我正在尝试通过 OS X 上的 Pyserial 与我的 Arduino 进行交互。我正在通过发送 0 到 9 之间的数字来控制 LED。 代码如
import serial
arduino = serial.Serial('/dev/tty.usbserial', 9600)
arduino.write('5')
工作得很好,但我试图让这个例子中的 5 作为一个可变变量,但是类似
arduino.write('%d') % 5
不会工作。我不知道如何格式化输出等于工作示例的变量?
最佳答案
您没有格式化字符串 %d
而是函数调用:
arduino.write('%d' % 5)
%
符号应该紧跟在 '
之后。
这会起作用,但最好使用带有格式字符串的元组:
arduino.write('%d' % (5,))
因为当你有多个参数时,无论如何你都必须这样使用它:
arduino.write('%d.%d' % (2, 3))
关于python - PySerial 与变量的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11310347/