Monday, May 29, 2017

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

Python to generate PWM on GPIO of Raspberry Pi to control brightness of a LED, with tkinter GUI. Tested on Raspberry Pi 2 running Raspbian Jessie with PIXEL rel. 2017-04-10, work on both Python 2 (from Tkinter import *) and 3 (from Tkinter import * ).


pyGuiPwm.py
from Tkinter import *   #for Python 2
#from tkinter import *   #for Python 3

import platform
import RPi.GPIO as GPIO

def setPwm(newvalue):
    pwmValue.set(newvalue)
    pwmled.ChangeDutyCycle(float(newvalue))

def on_closing():
    print("Clean up")
    pwmled.stop()
    GPIO.cleanup()
    print("bye")
    master.destroy()

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

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))

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

master = Tk()

pwmValue = StringVar()
label = Label(master, textvariable=pwmValue, relief=RAISED )
label.pack()

slider = Scale(master, from_=0, to=100, orient=HORIZONTAL, command=setPwm)
slider.pack()

master.protocol("WM_DELETE_WINDOW", on_closing)
mainloop()



Next:
Python to control RGB LED, with tkinter colorchooser/tkColorChooser

No comments: