我想使用python将串行数据('a'
)发送到我的arduino。
arduino 上的接收代码如下:
char inChar = (char)Serial.read();
if(inChar=='a'){
//do stuff
}
从 arduino 串行终端发送字符"a"时,它可以工作。但是,当从python 2.7发送时(代码见下文),rx led闪烁,但to stuff
未执行(即 inChar=='a'
是错误的)。我尝试了一切,但我无法解决这个问题。
蟒蛇代码:
import serial
ser = serial.Serial('/dev/ttyUSB0',9600)
ser.write('a')
编辑:ser.write(b'a')
也不起作用
当您看到 Rx 灯闪烁但 arduino 似乎没有接收数据时,我会检查两件事:
1) 在从 python 主机发送数据之前,请确保 arduino 有足够的时间来设置和启动串行通信。您可以包含导致板载 LED 在 Serial.begin
语句后以独特模式闪烁的代码,然后启动 python 代码。(LED细节:如何使LED闪烁)
2) 确保通信设置正确。您可能需要显式设置所有参数,以便知道它们是什么,并确保它们在电缆的两端相同。例如,在 arduino 上:
// set up Serial comm with standard settings
Serial.begin(9600,SERIAL_8N1);
Serial.flush();
然后在 python 代码中:
bytesize=8
parity='N'
stopbits=1
timeout=3
ser = serial.Serial(port_name, baudrate=9600, bytesize=bytesize, parity=parity, stopbits=stopbits, timeout=timeout)
此外,如果您可以将数据从arduino发送到python主机,那么您就知道您的通信设置是正确的。
add
ser.flush()
在ser.write('a')
之后的最后
或
ser.close()
从链接引用以确保数据已发送到端口。
感谢您的回复。但是,它并没有解决我的问题。
在尝试了几乎所有可以想象的解决方案后,我修复了它。在打开端口和发送/读取之间,需要延迟 - 至少对于我的覆盆子。
所以这有效:
import serial
import time
ser = serial.Serial('/dev/ttyUSB0',9600) #opening the port
time.sleep(1) #wait 1s
ser.write('a') #write to the port
你可以在这里看到我的决定=> https://github.com/thisroot/firebox
import firebox as fb
serPort = fb.findDevice('stimulator')
if(serPort):
data = []
data.append("<fire,200,5>")
fb.sendMessage(serPort,data)