I am working on a project in which I want to calculate the speed of a toy car using an ultrasonic sensor by measuring the distance and once it reaches the end. We see the time that has passed from when the programme has started. However I have discovered that the sensor I am using is accurate only till 20cm. Any suggestions?
#include <NewPing.h>
int i=0;
float distance;
long duration;
int trigpin = 9;
int echopin = 10;
int s;
boolean warrant=true;
unsigned long time;
void setup() {
// put your setup code here, to run once:
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
// put your main code here, to run repeatedly:
time=millis();
if(warrant==true){
s=distance;
digitalWrite(trigpin, LOW);
delay(2);
digitalWrite(trigpin, HIGH);
delay(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
distance = duration * 0.034 / 2;
if((distance-s)>1){
Serial.println(distance);
}
delay(200);
if(distance>30){
Serial.println(distance/time);
Serial.println("done");
delay(10);
warrant=false;
}}}
Ideally it should measure the speed easily. The code is working perfectly but it breaks down after 20cm. Probably due to the sensor's limitations