天天看點

raspberry pi (4) 繼電器,雷射傳感器

  1. 繼電器
import RPi.GPIO as GPIO 
import time

RelayPin = 11    # pin11 

def setup():
    GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
    GPIO.setup(RelayPin, GPIO.OUT)
    GPIO.output(RelayPin, GPIO.HIGH)

def loop(): 
    while True:
        print('...relayd on')
        GPIO.output(RelayPin, GPIO.LOW)
        time.sleep(0.5)

        print('relay off...')
        GPIO.output(RelayPin, GPIO.HIGH)
        time.sleep(0.5)

def destroy():
    GPIO.output(RelayPin, GPIO.HIGH)
    GPIO.cleanup()                     # Release resource

if __name__ == '__main__':     # Program start from here
    setup() 
    try:    
        loop()
    except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
        destroy()

           

雙色LED的R接到繼電器的常開,G接到繼電器的常閉,執行程式後,可以發現LED紅、綠交替亮。

raspberry pi (4) 繼電器,雷射傳感器

2. 雷射器

import RPi.GPIO as GPIO
import time

LedPin = 11    # pin11

def setup():
    GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
    GPIO.setup(LedPin, GPIO.OUT)   # Set LedPin's mode is output
    GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led

def loop():
    while True:
        input("any key to open laser:")
        print('...Laser on')
        GPIO.output(LedPin, GPIO.LOW)  # led on

        input("any key to close laser:")
        print('Laser off...')
        GPIO.output(LedPin, GPIO.HIGH) # led off

def destroy():
    GPIO.output(LedPin, GPIO.HIGH)     # led off
    GPIO.cleanup()                     # Release resource

if __name__ == '__main__':
    setup()
    try:
        loop()
    except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
        destroy()

           

通過按任意鍵讓雷射器交替亮、滅

raspberry pi (4) 繼電器,雷射傳感器

繼續閱讀