通过 pySerial 向端口发送字符串出错
Sending string to port via pySerial went wrong
我刚开始学习 Arduino 编程,我在使用 pySerial 库的 write() 命令时遇到了一些问题。
我有一个 arduino 程序,使用 arduino IDE 的串行终端可以正常工作。
我可以编写命令,它 return 给我一些文本并使用 blackmagic 3g-SDI shell 更改摄像机的参数。
每次发送东西时,它应该 return 给我一条确认消息或一条错误消息,这证明我没有用 pySerial write() 函数发送任何东西。
我也知道有一个实际的通信,因为当我使用 readline() 时,我可以在程序的开头看到 'begin' 消息。
我已经尝试过使用 putty,并按照完整的教程一步一步直接在命令行中进行操作,但同样的情况发生了,我真的不知道我还能做什么,我已经访问过方法许多论坛和主题并尝试了不同的东西。
import serial
import time
arduino = serial.Serial("COM3",baudrate = 9600, timeout = 2)
#arduino.open()
print(arduino.is_open)
time.sleep(2)
def sendCommand(command):
arduino.write(bytes(b"command"))
done = arduino.readline()
doneDecoded = done.decode('ascii')
print(doneDecoded)
print(done)
print('done')
pass
while True:
command =input(" Write your command : ")
sendCommand(command)
我期待 arduino 对我的输入做出任何类型的响应,但现在响应只是空白,就好像他没有收到任何数据一样。
首先,您的 sendCommand 函数会在您每次调用它时发送字符串 "command",因此您从未向 Arduino 发送任何它会响应的命令。
其次,您的 python 代码正在您的计算机上运行,其时钟频率可能为 1.2 至 2.8 GHz,而 Arduino 的时钟速度为 16 MHz,(这几乎慢了 100 倍)
当你向Arduino发送命令时,你需要给Arduino时间来处理命令并响应它。我建议在串行写入和串行读取之间添加大约 100 毫秒的延迟,如下所示
def sendCommand(command):
arduino.write(bytes(command))
time.sleep(100)
done = arduino.readline()
这应该对你有用。
很可能 Arduino 只是在等待 EOL(行尾)字符(或序列)开始处理您的可变长度命令。
EOL 通常是 \r
或 \n
或两者的组合。尝试在 arduino.write(bytes(b"command"))
之后发送
我刚开始学习 Arduino 编程,我在使用 pySerial 库的 write() 命令时遇到了一些问题。 我有一个 arduino 程序,使用 arduino IDE 的串行终端可以正常工作。 我可以编写命令,它 return 给我一些文本并使用 blackmagic 3g-SDI shell 更改摄像机的参数。 每次发送东西时,它应该 return 给我一条确认消息或一条错误消息,这证明我没有用 pySerial write() 函数发送任何东西。 我也知道有一个实际的通信,因为当我使用 readline() 时,我可以在程序的开头看到 'begin' 消息。
我已经尝试过使用 putty,并按照完整的教程一步一步直接在命令行中进行操作,但同样的情况发生了,我真的不知道我还能做什么,我已经访问过方法许多论坛和主题并尝试了不同的东西。
import serial
import time
arduino = serial.Serial("COM3",baudrate = 9600, timeout = 2)
#arduino.open()
print(arduino.is_open)
time.sleep(2)
def sendCommand(command):
arduino.write(bytes(b"command"))
done = arduino.readline()
doneDecoded = done.decode('ascii')
print(doneDecoded)
print(done)
print('done')
pass
while True:
command =input(" Write your command : ")
sendCommand(command)
我期待 arduino 对我的输入做出任何类型的响应,但现在响应只是空白,就好像他没有收到任何数据一样。
首先,您的 sendCommand 函数会在您每次调用它时发送字符串 "command",因此您从未向 Arduino 发送任何它会响应的命令。
其次,您的 python 代码正在您的计算机上运行,其时钟频率可能为 1.2 至 2.8 GHz,而 Arduino 的时钟速度为 16 MHz,(这几乎慢了 100 倍)
当你向Arduino发送命令时,你需要给Arduino时间来处理命令并响应它。我建议在串行写入和串行读取之间添加大约 100 毫秒的延迟,如下所示
def sendCommand(command):
arduino.write(bytes(command))
time.sleep(100)
done = arduino.readline()
这应该对你有用。
很可能 Arduino 只是在等待 EOL(行尾)字符(或序列)开始处理您的可变长度命令。
EOL 通常是 \r
或 \n
或两者的组合。尝试在 arduino.write(bytes(b"command"))