Monday, May 29, 2017

Python to generate PWM on GPIO of Raspberry Pi


Python to generate PWM on GPIO of Raspberry Pi to control brightness of a LED. Tested on Raspberry Pi 2 running Raspbian Jessie with PIXEL rel. 2017-04-10, work on both Python 2 and 3.


pyGPIO.py
import RPi.GPIO as GPIO
import time
import platform

print("Raspberry Pi board revision: "
      + str(GPIO.RPI_INFO['P1_REVISION']))
print("Machine: "
      + platform.machine())
print("Processor: "
      + platform.processor())
print("System: "
      + platform.system())
print("Version: "
      + platform.version())
print("Uname: "
      + str(platform.uname()))
print("Python version: "
      + platform.python_version())
print("RPi.GPIO version: "
      + str(GPIO.VERSION))
print("Ctrl-C to terminate and clean up GPIO")

#mode = GPIO.BCM
#led = 21
mode = GPIO.BOARD
led = 40

GPIO.setmode(mode)
GPIO.setup(led, GPIO.OUT)
pwmled = GPIO.PWM(led, 50)
pwmled.start(0)

try:
    while True:
        for dc in range(0, 101, 5):
            pwmled.ChangeDutyCycle(dc)
            time.sleep(0.1)
        for dc in range(100, -1, -5):
            pwmled.ChangeDutyCycle(dc)
            time.sleep(0.1)
finally:
    print("Clean up")
    pwmled.stop()
    GPIO.cleanup()


Reference:
raspberry-gpio-python - Using PWM in RPi.GPIO

Connection (same as in the post "Python to control GPIO of Raspberry Pi"):


Next:
Python to output PWM to control LED brightness, with tkinter GUI

No comments: