In this lesson we strive to improve the precision of our distance measurements using an average of a large number of measurements. This builds on the work we did in the last few lessons.
We are building this with parts from our Elegoo Kit , and our actual build is using an Arduino Nano, which allows the project to be built on a single breadboard. You can get the neat jumper wires HERE.
This video takes you through the process step-by-step.
The code developed in this video is included below for your convenience.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | #include <LiquidCrystal.h> int rs=7; int en=8; int d4=9; int d5=10; int d6=11; int d7=12; int buttonPin=A0; int buttonVal; int numMeas=100; float avMeas; int j; float bucket=0; LiquidCrystal lcd(rs,en,d4,d5,d6,d7); int trigPin=2; int echoPin=3; int pingTravelTime; float pingTravelDistance; float distanceToTarget; int dt=5000; void setup() { // put your setup code here, to run once: lcd.begin(16,2); pinMode(trigPin,OUTPUT); pinMode(echoPin,INPUT); pinMode(buttonPin,INPUT); digitalWrite(buttonPin,HIGH); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: lcd.setCursor(0,0); lcd.print("Place the Target"); lcd.setCursor(0,1); lcd.print("Press to Measure"); buttonVal=digitalRead(buttonPin); while (buttonVal==1){ buttonVal=digitalRead(buttonPin); } lcd.setCursor(0,0); lcd.clear(); lcd.print("Measureing . . ."); for (j=1;j<=numMeas;j=j+1){ digitalWrite(trigPin,LOW); delayMicroseconds(10); digitalWrite(trigPin,HIGH); delayMicroseconds(10); digitalWrite(trigPin,LOW); pingTravelTime=pulseIn(echoPin,HIGH); delay(25); pingTravelDistance=(pingTravelTime*765.*5280.*12)/(3600.*1000000); distanceToTarget=pingTravelDistance/2; bucket=bucket+distanceToTarget; } avMeas=bucket/numMeas; Serial.print("Av. Dist. to Target is: "); Serial.print(avMeas); Serial.println(" in."); lcd.clear(); lcd.setCursor(0,0); lcd.print("Target Distance"); lcd.setCursor(0,1); lcd.print(distanceToTarget); lcd.print(" Inches"); delay(dt); } |