pyFirmata 的 write() 函数

pyFirmata's write() function

我正在研究 Pratik Desai(烦人的聪明人)写的 "Python Programming for Arduino" 书。

我被困在练习中,学生正在学习实现一个滑块来改变连接到引脚的 LED 的强度。我标记了代码无法正常工作的地方。

代码是:

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

根据本书,这段代码应该可以工作。我做了一些基本检查,例如打印出变量 ledBrightness 以查看它是否获得了正确的值,并且正在获得正确的值。问题是当我 运行 程序无法运行时。 LED 根本不会亮起。仅当我将变量替换为打开 LED 的 1 (True) 或将其关闭的 0 (False) 替换为变量时,它才起作用,但是没有任何选项来调整强度。

我做错了什么?如果write()函数只能接受1或0为什么这本书说你可以自定义输入?

来自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 a PinAlreadyTakenError.

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 :.

需要定义引脚为PWM不输出

lenPin = board.get_pin('d:11:p')

那么 lenPin.write(value) 不仅接受 0 和 1,还接受 0 到 1 之间的任何浮点数。