Raspberry Pi Ultrasonic Sensor (HC-SR04) Control
네오즈 · 2019-09-27 · 3
# 1. Ultrasonic Sensor Test Circuit Configuration

( HC-SR04 ultrasonic sensor 1EA, 1KΩ resistor 1EA Echo connection, 2KΩ resistor 1EA GND connection )
Trig: GPIO 17 connection, Echo: GPIO 18 connection
Caution: When a High level signal is generated on the echo pin, 5V is transmitted. However, since the Raspberry Pi operates at 3.3V, the voltage must be stepped down to 3.3V using 1KΩ and 2KΩ resistors to prevent Raspberry Pi damage.
For code writing and execution methods, refer to the "**Raspberry Pi GPIO Port (LED, Button) Control**" guide.
**2. Ultrasonic Sensor Test Python Code**
The distance to an object is calculated by measuring the time it takes for an ultrasonic wave to bounce off an object and return.
```python
import RPi.GPIO as GPIO # Use functions defined in RPi.GPIO as GPIO
import time # time module
GPIO.setmode(GPIO.BCM) # Use BCM nomenclature for GPIO names
GPIO.setup(17, GPIO.OUT) # Trig=17 ultrasonic signal transmission pin number designation and output specification
GPIO.setup(18, GPIO.IN) # Echo=18 ultrasonic reception pin number designation and input specification
print "Press SW or input Ctrl+C to quit" # Display message on screen
try:
while True:
GPIO.output(17, False)
time.sleep(0.5)
GPIO.output(17, True) # Output a 10us pulse.
time.sleep(0.00001) # This pulse in Python will actually be around 100us
GPIO.output(17, False) # However, the HC-SR04 sensor accepts this error
while GPIO.input(18) == 0: # Set the moment when pin 18 turns OFF as the start time
start = time.time()
while GPIO.input(18) == 1: # Set the moment when pin 18 turns ON again as the reflected wave reception time
stop = time.time()
time_interval = stop ? start # Calculate distance from ultrasonic reception time
distance = time_interval * 17000
distance = round(distance, 2)
print "Distance => ", distance, "cm"
except KeyboardInterrupt: # When Ctrl-C is input
GPIO.cleanup() # Clear GPIO related settings
Print "bye~"
```
# 3. Ultrasonic Sensor Test C Code
```c
#include // Include stdio.h file (to use printf())
#include // Include wiringPi.h file
int main(void )
{
Float distance, start, stop;
wiringPiSetup();
// GPIO pin numbering based on wiringPi standard
pinMode(0, OUTPUT); // wiringPi GPIO 0 = Python(BCM) 17
pinMode(1, INPUT); // wiringPi GPIO 1 = Python(BCM) 18
while(1)
{
digitalWrite(0,0); // Output wiringPi pin 0 to Low
digitalWrite(0,1); // Output wiringPi pin 0 to High
delayMicroseconds(10); // Pause for 10 microseconds
digitalWrite(0,0);
while(digitalRead(1) == 0) // When wiringPi pin 1 is Low
start = micros(); // Save microseconds
while(digitalRead(1) == 1) // When wiringPi pin 1 is High
stop = micros(); // Save microseconds
distance = (stop ? start) / 58; // Derive distance using the time difference
printf("Distance=> %2f cm \n",distance);
delay(1000);
}
return 0;
}
```
3
댓글 0개
등록된 댓글이 없습니다.