HC-SR04
HC-SR04接线图
树莓派GPIO
Rpi.GPIO库官方网站:https://pypi.python.org/pypi/RPi.GPIO
作业1
结合1602LCD,将HC-SR04超声波传感器收集的距离数据显示到LCD上。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import RPi.GPIO as GPIO from time import sleep, time import Adafruit_CharLCD as LCD
lcd = LCD.Adafruit_CharLCDPlate()
TRIG = 17 ECHO = 27
def checkdist(): GPIO.output(TRIG, GPIO.HIGH) sleep(0.000015) GPIO.output(TRIG, GPIO.LOW) while not GPIO.input(ECHO): pass t1 = time() while GPIO.input(ECHO): pass t2 = time() return (t2 - t1) * 34000 / 2
GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(ECHO, GPIO.IN)
try: while True: print('distance:%0.2fcm' % checkdist()) lcd.clear() lcd.message('distance:\n%0.2fcm' % checkdist()) sleep(1) except KeyboardInterrupt: GPIO.cleanup()
|
完整代码见:test_hcsr04_lcd.py
作业2
利用HC-SR04超声波传感器和1602LCD液晶显示屏,做一个小小的障碍报警装置(当前方50cm内有物体时,LCD显示警报信息,并将LED显示红色;否则显示安全,并将LED显示为绿色)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import RPi.GPIO as GPIO from time import sleep, time import Adafruit_CharLCD as LCD
lcd = LCD.Adafruit_CharLCDPlate()
TRIG = 17 ECHO = 27
def checkdist(): GPIO.output(TRIG, GPIO.HIGH) sleep(0.000015) GPIO.output(TRIG, GPIO.LOW) while not GPIO.input(ECHO): pass t1 = time() while GPIO.input(ECHO): pass t2 = time() return (t2 - t1) * 34000 / 2
GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(ECHO, GPIO.IN)
try: while True: dist = checkdist() print(dist) if dist < 50: lcd.clear() lcd.message('Dangerous!!!') lcd.set_color(1, 0, 0) else: lcd.clear() lcd.message('Safety!!!') lcd.set_color(0, 1, 0) sleep(0.5) except KeyboardInterrupt: GPIO.cleanup()
|
完整代码见:test_hcsr04_lcd_ring.py