The Raspberry Pi excels as a gateway into the world of physical computing, allowing you to sense and interact with the environment. One of the most practical and engaging sensors you can integrate is a датчик приближения. Wouldn’t it be cool if your Pi project could react when something approaches? That’s exactly the power proximity sensing unlocks – ideal for security systems, interactive displays, automation tasks, or simply as a fascinating learning experience. This guide will walk you through understanding proximity sensors and connecting them effectively to your Raspberry Pi using simple circuitry and Python code.
Proximity sensors encompass a range of technologies, all designed to detect the presence or absence of a nearby object without requiring physical contact. For Raspberry Pi projects, two common and accessible types are:
For our hands-on example, we’ll focus on the widely available and cost-effective HC-SR04 ultrasonic sensor, demonstrating its connection and programming with the Raspberry Pi.
The HC-SR04 ultrasonic sensor has four pins: VCC
(Power), Trig
(Trigger), Echo
, and GND
(Ground). While the sensor operates at 5V logic, the Raspberry Pi’s GPIO pins are only safe at 3.3V. Connecting the Echo
pin directly to a GPIO pin risks damaging your Pi. Therefore, we need a simple voltage divider circuit to reduce the 5V Echo signal down to 3.3V. This is crucial!
Hardware You’ll Need:
Circuit Connection Guide:
VCC
pin to a 5V pin on your Raspberry Pi (e.g., physical pin 2).GND
pin to a Ground (GND) pin on your Raspberry Pi (e.g., physical pin 6).Trig
pin directly to a free GPIO pin on the Raspberry Pi configured as an Экспорт (e.g., GPIO 23, physical pin 16).Echo
pin to a column on your breadboard.Echo
pin.Once the hardware is correctly wired, the magic happens in software. We’ll use Python with the RPi.GPIO
library (or gpiozero
) to control the Raspberry Pi’s GPIO pins. The core logic involves:
Trig
pin HIGH for a short duration (typically 10 microseconds) to initiate an ultrasonic pulse.Echo
pin. The Echo
pin will go HIGH and stay HIGH for the duration it takes the sound pulse to travel to the object and back to the sensor.Echo
pin remains HIGH.Distance = (Speed of Sound * Time Elapsed) / 2
. We divide by 2 because the sound travels to the object and back (round trip). The speed of sound is approximately 343 meters per second (or 34,300 cm/s) at room temperature (20°C).Sample Python Code (using RPi.GPIO):
”`python import RPi.GPIO as GPIO import time
GPIO.setmode(GPIO.BCM) # Using Broadcom chip numbering
TRIG_PIN = 23 # OUTPUT Pin (Trigger) ECHO_PIN = 24 # INPUT Pin (Echo - via voltage divider)
GPIO.setup(TRIG_PIN, GPIO.OUT) GPIO.setup(ECHO_PIN, GPIO.IN)
GPIO.output(TRIG_PIN, False) time.sleep(0.5) # Let sensor settle
try: while True:
GPIO.output(TRIG_PIN, True) time.sleep(0.00001) # 10 microseconds GPIO.output(TRIG_PIN, False)
pulse_start = time.time() while GPIO.input(ECHO_PIN) == 0: pulse_start = time.time