串行 python 到 arduino
Serial python to arduino
我想使用 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'
为假)。
我什么都试过了,还是解决不了这个问题。
Python代码:
import serial
ser = serial.Serial('/dev/ttyUSB0',9600)
ser.write('a')
编辑:ser.write(b'a')
也不起作用
你可以在这里看到我的决定=> 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)
当你看到 Rx 灯闪烁但 arduino 似乎没有收到数据时,我会检查两件事:
1) 在从 python 主机发送数据之前,确保 arduino 有足够的时间来设置和启动串行通信。您可以在 Serial.begin
语句中包含导致板载 LED 以独特模式 闪烁 的代码,然后在此之后启动 python 代码。 (LED 详细信息:how to make the LED blink)
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 主机,那么您就知道您的通信设置是正确的。
添加
ser.flush()
在ser.write('a')
之后的最后
或
ser.close()
引用 link 以确保数据已发送到端口。
感谢您的回复。但是,并没有解决我的问题。
在尝试了几乎所有可以想到的解决方案之后,我修复了它。在 打开 端口和 sending/reading 之间,需要延迟 - 至少对于我的树莓派而言。
所以这有效:
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
我想使用 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'
为假)。
我什么都试过了,还是解决不了这个问题。
Python代码:
import serial
ser = serial.Serial('/dev/ttyUSB0',9600)
ser.write('a')
编辑:ser.write(b'a')
也不起作用
你可以在这里看到我的决定=> 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)
当你看到 Rx 灯闪烁但 arduino 似乎没有收到数据时,我会检查两件事:
1) 在从 python 主机发送数据之前,确保 arduino 有足够的时间来设置和启动串行通信。您可以在 Serial.begin
语句中包含导致板载 LED 以独特模式 闪烁 的代码,然后在此之后启动 python 代码。 (LED 详细信息:how to make the LED blink)
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 主机,那么您就知道您的通信设置是正确的。
添加
ser.flush()
在ser.write('a')
或
ser.close()
引用 link 以确保数据已发送到端口。
感谢您的回复。但是,并没有解决我的问题。
在尝试了几乎所有可以想到的解决方案之后,我修复了它。在 打开 端口和 sending/reading 之间,需要延迟 - 至少对于我的树莓派而言。
所以这有效:
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