- 继电器
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红、绿交替亮。

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()
通过按任意键让激光器交替亮、灭