Raspberry Pi 9: Raspberry Pi controls HC-SR04 ultrasonic module for distance measurement

The working principle of ultrasound (based on the explanation of wemos small project split)

1. Introduction to Ultrasonic Module

There are usually two ultrasonic components on the ultrasonic sensor module,One for transmitting and one for receiving.
There are 4 pins on the circuit board:
VCC (positive)
Trig (trigger)
Echo (response)
GND (ground)

Working voltage and current: 5V, 15mA

Sensing distance: 2—400cm

Sensing angle: 15° not allowed

The area of ​​the detected object should not be less than 50cm² and should be as flat as possible

With temperature compensation circuit

Input a high potential of more than 10 microseconds to the trigger pin of the ultrasonic module to generate ultrasonic waves. After the ultrasonic waves are emitted,Before receiving the returned ultrasound, the "response" pin is at a high point.
Therefore, the program can convert the distance of the measured object from the high potential pulse duration of the "response" pin.

Insert picture description here
Insert picture description here
We can see that it has a total of four pins:
      Vcc: connected to 5V power supply (connected to pin 1)
      Trig: output port (connected to pin 16)
      Echo: input port (connected to port 18)
      Gnd: ground terminal ( Connect to port 6)
Hardware connection
Insert picture description here
We will focus on introducing two kinds of pins used in this experiment:
①. Power supply pins: divided into 3.3V / 5V / 0V, among which 0V represents ground
②. GPIO input and output interface: this is a very important one Class pin, the GPIO is marked in the above picture is this kind of interface, the Raspberry Pi GPIO interface can only input and output digital signals (0&1, etc.)

Insert picture description here

Implementation code

#include <wiringPi.h>
#include <stdio.h> 
#include <sys/time.h>

#define Trig    4
#define Echo    5 

void ultraInit(void)  
{
    
      
     pinMode(Echo, INPUT);  //设置端口为输入
     pinMode(Trig, OUTPUT)/;  //设置端口为输出
} 
 float disMeasure(void)  
 {
    
      
     struct timeval tv1;  //timeval是time.h中的预定义结构体 其中包含两个一个是秒,一个是微秒
     /*
     struct timeval
     {
         time_t tv_sec;  //Seconds. 
         suseconds_t tv_usec;  //Microseconds. 
     };
     */
     
     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));  //如果不是1,则继续等待
     gettimeofday(&tv1, NULL);           //获取当前时间 开始接收到返回信号的时候 
   
     while(!(digitalRead(Echo) == 0));  //如果不是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){
    
     //如果初始化失败,就输出错误信息 程序初始化时务必进行
         printf("setup wiringPi failed !");  
         return 1;  
     }  
   
     ultraInit(); 
       
     while(1){
    
      
         dis = disMeasure();  
         printf("distance = %0.2f cm\n",dis);  
         delay(1000);  
     }  
   
     return 0;  
 }  

Compile and run

gcc demo1.c -lwiringPi
./a.out

distance = 170.74 cm
distance = 190.74 cm
distance = 150.04 cm
distance = 180.00 cm
.......

Code analysis:

1.wiringPiSetup(void):

When using the wiringPi.h library, the Raspberry Pi must be initialized before performing any operations, otherwise the program will not run normally.
When the initialization operation is not completed, the function returns a value of -1.
Other Raspberry Pi initialization functions include wiringPiSetupGpio(void). The method of this function is similar to wiringPiSetup(void). When the function fails to run normally, the return value is also -1. The difference is that wiringPiSetup(void) is used to initialize the Raspberry Pi pinswiringPi pin number tableThe number of pins is 0~16;
wiringPiSetupGpio(void) is used when initializing the Raspberry Pi pinsBCM GPIO pin number table.
  The other two functions are wiringPiSetupPhys(void) and wiringPiSetupSys (void), which are not introduced here because they are not commonly used.

2.void pinMode(uint8 pin, WiringPinMode mode)

This function is used to determine the function of a pin. If the function of this pin is not determined before using a pin or the pin setting mode is incorrect, some elusive errors will occur.
This function has two parameters. The first parameter pin is a positive integer, which is used to specify the pin number (0-16), and the second parameter is used to specify the IO mode of the pin. The available parameters are INPUT, OUTPUT, OUTPUT_OPEN_DRAIN, INPUT_ANALOG, INPUT_PULLUP, INPUT_PULLDOWN, INPUT_FLOATING, PWMPWM_OPEN_DRAIN

3.digitalWrite(uint8 pin, uint8 value)

This is another function that has been defined in wiringPi.h. Its function is to
output a specified level signal to a pin that has been configured as an output mode (OUTPUT or OUTPUT_OPEN_DRAIN) , where pin is a positive integer. To specify a pin that has been initialized, value can be a number or a parameter. The number means: 1 means high level, 0 means low level; parameter means: LOW means low level, HIGH means high level.

4.delayMicroseconds (unsigned int howLong)

Pause the thread for a specified number of microseconds (1000 microseconds = 1 millisecond = 0.001s). Because Linux is multi-threaded, the actual number of seconds to pause may be more than the set number

5.digitalRead (int pin)

Read the level value (LOW / HIGH) of a pin and return.
Where pin is the number of the pin, the initialization type of the pin must be an input type such as INPUT. The return value can also be 1/0 (the function returns 0 when the input signal voltage is between 0 and 1.16 V, and returns 1 when the input signal is between 1.83 and 3.3 V. If the input voltage is between 1.16 and 1.83 V, it will return. 0 or 1.)

6.gettimeofday(struct timeval *, struct timezone *);

The function returns the number of seconds that have elapsed since 0:00:00 in 1970 to the present, and two parameters are required when the function is passed in normally.
The first one has already been introduced, and the second one is not useful here, so I won’t list it for the time being, just use NULL when passing in the parameter. There is a little story about this issue here: tv_sec in timeval is of type time_t, The type of long. In 32 bits, it is 4 bytes. The largest positive integer that can be represented is 2147483647, and the time that can be represented is up to 2038-01-19 03:14:07. After exceeding it, it becomes -2147483648, which is linux2038 The question of the year. The time_t type under the 64-bit system, that is, the long type, has a length of 8 bytes and can be used for hundreds of billions of years. There is no need to worry about overflow for such a long time.

7. Calculate the number of microseconds based on the number of seconds returned

start = tv1.tv_sec * 1000000 + tv1.tv_usec ;
stop = tv2.tv_sec * 1000000 + tv2.tv_usec;
We know that the timeval structure contains two variables,
tv_sec represents the number of seconds, 1 second = 1000000 microseconds, and the second parameter tv_usec represents the number of microseconds, so we can get the start through these two formulas And the number of microseconds at the end, and then make a difference to get the time used for ultrasonic transmission

8. Calculate distance based on time

(stop - start) / 1000000 * 34000 / 2
Because stop and start are subtle originally, how many seconds are converted back to 1000000 after the difference.
Because the propagation of sound in the material is affected by the material material, we do not consider the type of the medium for the time being. The default is that the sound is transmitted in the air, so the speed of sound is 340m/s=34000cm/s, because the ultrasonic ranging The error range is 200-300cm, so we use cm to calculate the speed here.

Reference:
Raspberry Pi controls ultrasound

Guess you like

Origin blog.csdn.net/weixin_40734514/article/details/108676254