2017年1月16日 星期一

樹莓派 Raspberry Pi 3 Simple GPIO Traffic Light


零件接駁圖:























Python 程式碼:
#!/usr/bin/python
import RPi.GPIO as GPIO
import time

# setup pin numbers for LED and Tact button
R_LED_PIN = 11
Y_LED_PIN = 13
G_LED_PIN = 15
BUTTON_PIN = 36

GPIO.setmode(GPIO.BOARD)
GPIO.setup(R_LED_PIN, GPIO.OUT)
GPIO.setup(Y_LED_PIN, GPIO.OUT)
GPIO.setup(G_LED_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN)

prev_input = 0
seq = 1

def changeLight(seq):
    if (seq == 1):
        GPIO.output(Y_LED_PIN,False)
        GPIO.output(G_LED_PIN,False)
        GPIO.output(R_LED_PIN,True)
    if (seq == 2):
        GPIO.output(Y_LED_PIN,True)
    if (seq == 3):
        GPIO.output(R_LED_PIN,False)
        GPIO.output(Y_LED_PIN,False)
        GPIO.output(G_LED_PIN,True)
    if (seq == 4):
        GPIO.output(G_LED_PIN,False)
        GPIO.output(Y_LED_PIN,True)

try:
    while True:
        # read button input
        input = GPIO.input(BUTTON_PIN)
        # if previous reading was low and this on high, turn on LED
        if ((not prev_input) and input):
           print "Button pressed: " + time.strftime("%H:%M:%S")
           changeLight(seq)
           seq = seq + 1
           if (seq > 4):
                seq = 1
        prev_input = input
        time.sleep(0.05)
except KeyboardInterrupt:
    pass

GPIO.cleanup()

沒有留言:

張貼留言