I'm trying to find the speed of remote control toy car passing by two ultrasonic sensors. I need help on my code and suggestion on max speed car should go to record time. Opposite direction not accounted for and ideally the car would pass by both sensors without stopping. I know laser reading is better for this simulation but I need it for a presentation in two weeks.
Here are the steps I was recommended to use:
- Get the duration of pulse for sensor 1 and convert to distance
- if the distance the object is within the desired threshold (you detected something) 2a. record the system time at which object was detected 2b. start a loop to for sensor 2
- Within the sensor 2 loop keep getting the duration/distance until an object is detected or too much time has passed
- If an object is detected record the system time
Subtract the two system times (from sensor 1 and 2) and use that to determine object speed
#define sensor_distance .111 //distance between two sensors in meters const int trigPin1 = 3; const int echoPin1 = 4; const int trigPin2 = 5; const int echoPin2 = 6; double first_time = 0; double second_time = 0; double final_time = 0; double vehicle_speed = 0; void setup() { pinMode(trigPin1, OUTPUT); pinMode(echoPin1, INPUT); pinMode(trigPin2, OUTPUT); pinMode(echoPin2, INPUT); Serial.begin(9600); } void loop() { double ping_time(int trig1, int echo1, double first_time); double ping_time(int trig2, int echo2, double second_time); final_time = second_time - first_time; vehicle_speed = sensor_distance/final_time; } double ping_time(int trig, int echo, double record_time) //function used to record time. { long duration, distance; digitalWrite(trig, LOW); delayMicroseconds(2); digitalWrite(trig, HIGH); delayMicroseconds(10); digitalWrite(trig, LOW); duration = pulseIn(echo, HIGH); distance = duration * 0.034 / 2; if (distance < 35) { Serial.print(distance); Serial.println(" cm"); record_time = millis(); record_time = record_time/100; //Divided by 100 to get time in seconds return record_time; } if (distance > 35) { Serial.println("OUT OF RANGE"); } delay(20); }