I was not happy with original code for Ultrasonic sensor and decided to write my own implementation.
I managed to do this, but it still looks weird. Could you help me to improve it?
#include <wiringPi.h>
#include <stdio.h>
#include <sys/time.h>
#define Trig 0
#define Echo 1
double raw_ultrasonic_measure(int trig, int echo) {
digitalWrite(Trig, LOW);
delayMicroseconds(1);
digitalWrite(Trig, HIGH);
delayMicroseconds(10);
digitalWrite(Trig, LOW);
while(!(digitalRead(Echo) == 1));
int time1 = micros();
while(!(digitalRead(Echo) == 0));
int time2 = micros();
return (double)(time2 - time1) / 100;
}
double ultrasonic_measure(int trig, int echo) {
double value1 = raw_ultrasonic_measure(trig, echo);
delay(1);
double value2 = raw_ultrasonic_measure(trig, echo);
delay(1);
double value3 = raw_ultrasonic_measure(trig, echo);
delay(1);
double value4 = raw_ultrasonic_measure(trig, echo);
delay(1);
double value5 = raw_ultrasonic_measure(trig, echo);
return (value1 + value2 + value3 + value4 + value5) / 5;
}
int main(void) {
wiringPiSetup();
pinMode(Echo, INPUT);
pinMode(Trig, OUTPUT);
while(1){
double value = raw_ultrasonic_measure(Trig, Echo);
printf("%0.1f cm\n", value);
delay(1000);
}
return 0;
}