python - PySerial 与变量的通信

标签 python serial-port arduino pyserial

我正在尝试通过 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/

相关文章:

c++ - I2C通信树莓派3和Arduino

python - 如何在Python代码中比较peewee日期

python - PyMySQL executemany with ON DUPLICATE

python - numpy.unique 为集合列表提供错误的输出

c - 如何在c中通过串口连接编写二进制表示

microcontroller - 如何使用arduino从LM335Z获得摄氏度作为输出?

python - pySerial 程序无法正确读取串行

python - 更改一个列表中的元素会更改多个列表

C# SerialPort WriteLine 可以工作但不能写入

JAVA读写COM口