Raspberry Pi 3b + HC-SR04 ultrasonic module drive (C speech written, wiringPi)

Ultrasonic Module Description:

Signal connection:

Vcc -- 5v

Trig -- Pin 15 (Broadcom GPIO 22)

Echo -- Pin 16 (Broadcom GPIO 23)

Gnd -- Gnd

The main logic introduced:

Use wiringPi interrupt function, wiringPiISR (23, INT_EDGE_BOTH, & EchoCac); rise and fall double edge.

Interrupt service function: EchoCac () record rising, falling time.

 

Broadcom GPIO 22 disposed emitting 10us high, then low, then wait for interrupt trigger.

 

The working code, return detection distance, in units of cm.

 1 #include "wiringPi.h"
 2 #include "stdio.h"
 3 #include "stdlib.h"
 4 
 5 void EchoCac(void);
 6 
 7 
 8 int t, t_start,t_end;
 9 int Dist;
10     
11 
12 int main(int argc, char * argv[])
13 {
14     int i, cnt;
15     
16     wiringPiSetupGpio ();   // use BCM GPIO mapping
17     
18     pinMode (22, OUTPUT);
19     
20     pinMode (23, INPUT);
21     
22     i = wiringPiISR (23, INT_EDGE_BOTH, &EchoCac);
23                 
24     digitalWrite(22, HIGH);
25     delayMicroseconds(10);
26     digitalWrite(22, LOW);    
27     printf("Ultrasonic Wave fire out!!!\n");    
28             
29 
30     while(1)
31     {
32         cnt++;
33     }
34 
35 }
36 
37 void EchoCac(void)
38 {
39     
40     if(digitalRead (23) == HIGH)
41     {
42     
43     t_start = micros();
44     
45     printf("Wave start:%d us\n",t_start);
46     
47     }    
48     
49     if(digitalRead (23) == LOW)
50     {
51     t_end = micros();
52     
53     printf("Echo got:%d us\n",t_end);
54     
55     t = t_end - t_start;
56     
57     Dist = (t*100*340)/2/1000000;
58     
59     printf("Target distance: %d cm\n",Dist);    
60     
61     exit(-1);
62     
63     }    
64     
65  
66 }
View Code

 

Guess you like

Origin www.cnblogs.com/winhaus/p/12240888.html