I'm working along the book "Python Programming for Arduino" written by Pratik Desai (annoyingly smart guy).
I got stuck in exercise where student is learning to implement a slider that changes intensity of LED that is connected to a pin. I marked where the code isn't working as it should.
Code is:
import tkinter
from pyfirmata import ArduinoMega
from time import sleep
port = '/dev/ttyACM0'
board = ArduinoMega(port)
sleep(5)
lenPin = board.get_pin('d:11:o')
top = tkinter.Tk()
top.title('Specify time using Entry')
top.minsize(300, 30)
timePeriodEntry = tkinter.Entry(top, bd=5, width=25)
brightnessScale = tkinter.Scale(top, from_=0, to=100,
orient=tkinter.HORIZONTAL)
brightnessScale.grid(column=2, row=2)
tkinter.Label(top, text='Time (seconds)').grid(column=1, row=1)
tkinter.Label(top, text='Brightness (%)').grid(column=1, row=2)
def onStartPress():
time_period = timePeriodEntry.get()
time_period = float(time_period)
ledBrightness = brightnessScale.get()
ledBrightness = float(ledBrightness)
startButton.config(state=tkinter.DISABLED)
lenPin.write(ledBrightness / 100.0) # this part of code ain't working
sleep(time_period)
lenPin.write(0)
startButton.config(state=tkinter.ACTIVE)
timePeriodEntry.grid(column=2, row=1)
timePeriodEntry.focus_set()
startButton = tkinter.Button(top, text='Lit Up', command=onStartPress)
startButton.grid(column=1, row=3)
exitButton = tkinter.Button(top, text='Exit', command=top.quit)
exitButton.grid(column=2, row=3)
top.mainloop()
According to the book this code should work. I did some basic checks such as printing out the variable ledBrightness
to see if it gets the correct value and it is getting the correct value. Problem is when I run the program it isn't working. The LED won't come on at all. It works only when I replace the variable with 1 (True) which turns the LED on or 0 (False) which turns it back off, however without any option to adjust intensity.
What I'm doing wrong here? If the write()
function can accept only 1 or 0 how come that this book says you can customize the input?
From the documentation:
write(value)
Output a voltage from the pin
Parameters: value – Uses value as a boolean if the pin is in output mode, or expects a float from 0 to 1 if the pin is in PWM mode. If the pin is in SERVO the value should be in degrees.
get_pin(pin_def)
Returns the activated pin given by the pin definition. May raise an
InvalidPinDefError
or aPinAlreadyTakenError
.Parameters: pin_def – Pin definition as described below, but without the arduino name. So for example
a:1:i
.‘a’ analog pin Pin number ‘i’ for input ‘d’ digital pin Pin number ‘o’ for output ‘p’ for pwm (Pulse-width modulation)
All seperated by
:
.
You need to define the pin as PWM not output.
lenPin = board.get_pin('d:11:p')
Then lenPin.write(value)
doesn't just accept 0 and 1, but any float number between 0 and 1.