Ticker

6/recent/ticker-posts

Control RPi.GPIO PWM, using Python on Raspberry Pi 2

Example show how to control PWM of RPi.GPIO using Python (work on both Python 2 and 3), run on Raspberry Pi 2.


Connection:


testGPIO.py
import sys
import RPi.GPIO as GPIO
import time

print("sys.version:")
print(sys.version + "\n")

print("GPIO.VERSION: " + GPIO.VERSION)
print("GPIO.RPI_INFO['P1_REVISION'] = " + str(GPIO.RPI_INFO['P1_REVISION']));

io20 = 20
io21 = 21

GPIO.setmode(GPIO.BCM)
GPIO.setup(io20, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(io21, GPIO.OUT)
#config GPIO 21 as PWM, frequency = 50 cycle/sec
pwm21 = GPIO.PWM(io21, 50)
pwm21.start(10)

print("Press button to change PWM");
try:
while(True):
if (GPIO.input(io20)):
#duty cycle = 10%
pwm21.ChangeDutyCycle(10)
else:
#duty cycle = 90%
pwm21.ChangeDutyCycle(90)

except KeyboardInterrupt:
print ("\n")
print ("Exit by KeyboardInterrupt\n")

except:
print ("\n")
print ("Exit by Other case!\n")

finally:
pwm21.stop()
GPIO.cleanup()
print ("Clean up GPIO\n")


إرسال تعليق

0 تعليقات