computers suck

python + Arduino + Tk: Toggling an LED

Whoa! This is so old I don’t even know where to start!

  • It’s using Python 2, so if it works at all it probably won’t for much longer, and Tkinter is something completely different under Python 3
    (grrreat planning there, Python guys …)
  • pyfirmata is likely ancient history too.

Phil sent me a note last week asking how to turn an LED on or off using Python talking through Firmata to an Arduino. This was harder than it looked.

It turns out the hard part is getting the value from the Tkinter Checkbutton itself. It seems that some widgets don’t return values directly, so you must read the widget’s value with a get() method. This appears to work:

# turn an LED on/off with a Tk Checkbutton - scruss 2012/11/13
# Connection:
# - small LED connected from D3, through a resistor, to GND

import pyfirmata
from Tkinter import *

# Create a new board, specifying serial port
# board = pyfirmata.Arduino('/dev/ttyACM0') # Raspberry Pi
board = pyfirmata.Arduino('/dev/tty.usbmodem411') # Mac

root = Tk()
var = BooleanVar()

# set up pins
pin3 = board.get_pin('d:3:o') # D3 On/Off Output (LED)

def set_led():  # set LED on/off
    ledval = var.get()
    print "Toggled", ledval

# now set up GUI
b = Checkbutton(root, text = "LED", command = set_led,
                variable = var)
b.pack(anchor = CENTER)


This is explained quite well here: Tkinter Checkbutton doesn’t change my variable – Stack Overflow. I also learnt a couple of things about my previous programs:

  • You don’t really need to set up an Iterator unless you’re reading analogue inputs
  • My “clever” cleanup-on-exit code actually made the script hang on Mac OS.

4 replies on “python + Arduino + Tk: Toggling an LED”

Thanks that works great – any idea how read an Arduino digital input and then set a digital output, so if input switch is on – the output turns on.

Again thanks for your efforts

it’s come with an Error “could not open port ‘COM6’. PERMISSION ERROR.

This piece of code is ancient history, Shibaram. I don’t think any part of it will work with Python 3.

COM6 means you’re likely running on Windows and it can’t find your Arduino

Leave a Reply

Your email address will not be published. Required fields are marked *