Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Manufacturing Technology >> Manufacturing process

Connecting HC‑SR04 Ultrasonic Sensor to Raspberry Pi 3 – A Complete Guide

Hardware Requirements

Wiring Diagram

Sensor pins connect to the Pi as follows:

  1. VCC → Pin 2 (5 V)
  2. GND → Pin 6 (ground)
  3. TRIG → Pin 12 (GPIO18)
  4. ECHO → 330 Ω resistor → Pin 18 (GPIO24); 470 Ω resistor → Pin 6 (ground)

The resistors limit the 5 V echo pulse to the Pi’s 3.3 V logic level.

Place the sensor on a breadboard and run jumper wires to the corresponding GPIO pins. To add a second sensor, duplicate the wiring on the other side of the board, connecting VCC and GND to the same power rails and choosing any two free GPIO pins for TRIG and ECHO.

Software – Python Example

Open your preferred IDE or the terminal, create a new file named ultrasonic_distance.py, and paste the following script. The code is written for a single sensor; duplicate the section and rename the variables (TRIG2, ECHO2, etc.) to support a second sensor.

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

TRIG1 = 18
ECHO1 = 24

GPIO.setup(TRIG1, GPIO.OUT)
GPIO.output(TRIG1, False)

GPIO.setup(ECHO1, GPIO.IN)

time.sleep(0.1)
GPIO.output(TRIG1, True)
time.sleep(0.00001)
GPIO.output(TRIG1, False)

while GPIO.input(ECHO1) == 0:
    pass
pulse_start1 = time.time()

while GPIO.input(ECHO1) == 1:
    pass
pulse_end1 = time.time()

pulse_duration1 = pulse_end1 - pulse_start1
distance1 = pulse_duration1 * 17150
distance1 = round(distance1, 2)

print(f'Distance: {distance1} cm')

time.sleep(10)
GPIO.cleanup()

Save the file, then run it from a terminal with:

python3 ultrasonic_distance.py

For additional sensors, mirror the wiring on the breadboard, update the TRIG and ECHO pin numbers in the code, and add a second measurement block.

Source: Ultrasonic Sensor (HC‑SR04) + Raspberry Pi

Manufacturing process

  1. How to Connect a DS1820 One‑Wire Temperature Sensor to a Raspberry Pi Using GPIO
  2. Control an LED with a PIR Motion Sensor on Raspberry Pi
  3. Build a Low‑Cost Raspberry Pi Soil Moisture Sensor for Smart Irrigation
  4. Testing the DS18B20 Temperature Sensor on Raspberry Pi
  5. Directly Connect a Lego Mindstorms NXT Ultrasonic Sensor to a Raspberry Pi
  6. Connecting an HC‑SR04 Ultrasonic Sensor to a Raspberry Pi – A Practical Guide
  7. Build a Raspberry Pi Home Temperature Monitor with MCP9808, InfluxDB & Grafana
  8. Master Raspberry Pi GPIO: Interfacing a PIR Motion Sensor on B+/Model 2
  9. How to Connect, Calibrate, and Program the HC‑SR501 PIR Motion Sensor with a Raspberry Pi
  10. Mastering the HC‑SR04 Ultrasonic Sensor with Arduino: A Complete Tutorial