Created
June 18, 2020 14:37
-
-
Save pinae/2209e06eb2ea25655b00af750ab4cf40 to your computer and use it in GitHub Desktop.
Test program for GPIO (IN/OUT/PWM) on the Raspberry Pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import RPi.GPIO as GPIO | |
from threading import Thread | |
def setup(): | |
GPIO.setwarnings(False) | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(2, GPIO.OUT, | |
initial=GPIO.LOW) | |
GPIO.setup(22, GPIO.IN) | |
GPIO.setup(10, GPIO.IN) | |
GPIO.setup(26, GPIO.IN) | |
GPIO.setup(12, GPIO.OUT) | |
GPIO.setup(13, GPIO.OUT) | |
global red | |
global green | |
red = GPIO.PWM(12, 50) # 50Hz | |
green = GPIO.PWM(13, 50) | |
red.start(0) | |
green.start(0) | |
Thread(target=ck_btn_forevr).start() | |
GPIO.add_event_detect( | |
22, GPIO.RISING, | |
callback=lambda _: print( | |
"<- Switch to the left.")) | |
GPIO.add_event_detect( | |
10, GPIO.RISING, | |
callback=lambda _: print( | |
"-> Switch to the right.")) | |
def loop(): | |
for dc in range(0, 101, 5): | |
red.ChangeDutyCycle(dc) | |
time.sleep(0.1) | |
GPIO.output(2, GPIO.HIGH) | |
for dc in range(100, -1, -5): | |
red.ChangeDutyCycle(dc) | |
green.ChangeDutyCycle(100-dc) | |
time.sleep(0.1) | |
GPIO.output(2, GPIO.LOW) | |
for dc in range(100, -1, -5): | |
green.ChangeDutyCycle(dc) | |
time.sleep(0.1) | |
def ck_btn_forevr(): | |
while True: | |
GPIO.wait_for_edge(26,GPIO.RISING) | |
print("Button pressed") | |
time.sleep(0.1) | |
try: | |
setup() | |
while True: | |
loop() | |
except KeyboardInterrupt: | |
pass | |
finally: | |
red.stop() | |
green.stop() | |
GPIO.cleanup() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment