2016/09/18

UP board:簡單試用GPIO

照著RPi.GPIO - UpWiki的範例,運用RPi.GPIO模組、撰寫Python程式來控制UP board的GPIO腳位。

UP board的腳位功能圖,其中Pin欄是板子的實體針腳編號,UP pinout則是UP板子SoC的腳位編號,Linux GPIO是Raspberry Pi板子的SoC腳位編號。底下範例一律使用Pin欄的編號。
首先更新套件:
$ sudo apt-get update
$ sudo apt-get install python-rpi.gpio

接下來三個範例,閃爍LED,LED明暗度,開關控制LED亮滅。

範例,閃爍LED,讓LED亮一秒、滅一秒,不斷重複。電路圖如下:
程式碼:
import RPi.GPIO as GPIO
import time

LED_PIN = 16

GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED_PIN, GPIO.OUT)

try:
    while True:
        GPIO.output(LED_PIN, GPIO.HIGH)
        time.sleep(1)
        GPIO.output(LED_PIN, GPIO.LOW)
        time.sleep(1)
except:
    GPIO.cleanup()

範例,LED明暗度,以軟體PWM控制LED的亮度,LED會從全暗漸漸到全亮,再漸漸回到全暗。電路圖同前。

程式碼:
import RPi.GPIO as GPIO
import time

LED_PIN = 16

GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED_PIN, GPIO.OUT)
p = GPIO.PWM(LED_PIN, 50)
p.start(0)

try:
    while True:
        for dc in range(0, 101, 5):
            p.ChangeDutyCycle(dc)
            time.sleep(0.1)
        for dc in range(100, -1, -5):
            p.ChangeDutyCycle(dc)
            time.sleep(0.1)
except:
    pass

p.stop()
GPIO.cleanup()

範例,開關控制LED亮滅,不按下開關時LED熄滅,按下時才亮起。電路圖如下:
程式碼:
import RPi.GPIO as GPIO
import time

LED_PIN = 16
BUTTON_PIN = 13

GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN)

try:
    while True:
        print(GPIO.input(BUTTON_PIN))
        if GPIO.input(BUTTON_PIN):
            GPIO.output(LED_PIN, GPIO.HIGH)
        else:
            GPIO.output(LED_PIN, GPIO.LOW)
except:
    GPIO.cleanup()


參考資料:

No comments:

Post a Comment