i have a project to create speedometer using HC-SR04.
i’m already finishing the code but i think this code have a bug.
when i change the delay to 100, the output are not stable.
here is my code
can you help me?
const int pingPin = 4;
const int trigPin = 2;
int start = 0;
long durasi, cm;
long posisi[2];
long waktu[2];
void setup() {
Serial.begin(9600);
}
void loop()
{
for (int i=0; i <= 1; i++){
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(pingPin, INPUT);
durasi = pulseIn(pingPin, HIGH);
cm = mikrokecenti(durasi);
posisi[i]=cm;
waktu[i]=millis();
delay(1000);
// Serial.println(posisi[0]);
//Serial.println(posisi[1]);
}
//Serial.print(posisi[0]);Serial.print(" ");Serial.println(posisi[1]);
int speedd=((posisi[0]-posisi[1])*1000)/((waktu[1]-waktu[0]));
Serial.print(speedd);
Serial.println(" Cm/s");
}
long mikrokecenti(long microseconds)
{
return microseconds / 29 / 2;
}