struct timeval tv1;
struct timeval tv2;
long start;
long stop;
float Dis;
digitalWrite(Trig, LOW);
delayMicroseconds(2);
digitalWrite(Trig, HIGH);
delayMicroseconds(10);
digitalWrite(Trig, LOW);
while (!(digitalRead(Echo) == 1));
gettimeofday(&tv1, NULL);
while (!(digitalRead(Echo) == 0));
gettimeofday(&tv2, NULL);
start = tv1.tv_usec + tv1.tv_sec * 1000000;
stop = tv2.tv_sec * 1000000 + tv2.tv_usec;
Dis = (float)(stop - start) / 1000000 * 34000 / 2;
return Dis;
這個代碼是基于hC-sr04的超聲波在C或C++的編譯器下均可運行
|