-
Notifications
You must be signed in to change notification settings - Fork 0
/
cj.c
60 lines (45 loc) · 1.16 KB
/
cj.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <wiringPi.h>
#include <stdio.h>
#include <sys/time.h>
#define Trig 28
#define Echo 29
void ultraInit(void)
{
pinMode(Echo, INPUT);
pinMode(Trig, OUTPUT);
}
float disMeasure(void)
{
struct timeval tv1;
struct timeval tv2;
long start, 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_sec * 1000000 + tv1.tv_usec; //微秒级的时间
stop = tv2.tv_sec * 1000000 + tv2.tv_usec;
dis = (float)(stop - start) / 1000000 * 34000 / 2; //求出距离
return dis;
}
int main(void)
{
float dis;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
ultraInit();
while(1){
dis = disMeasure();
printf("distance = %0.2f cm\n",dis);
delay(1000);
}
return 0;
}