我有一个Python脚本,它将字符串test
写入Arduino串口。如果arduino收到test
字符串,它应该使用字符串ok
回复,并且LED 13应该喜欢...
问题:当使用Arduino串行监视器将test
写入串口时,Arduino会按预期回复ok
,并且LED#13亮起。
但是,当Python脚本将test
写入同一个串行端口时,没有任何反应。 Arduino不回复串口,LED#13不亮。
如何修复Python脚本以使Arduino和LED 13的ok
响应亮起来?
Arduino Sketch
int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
while(Serial.available() == 0) { }
if(Serial.readString() == "test\r\n") {
Serial.print("ok\r\n");
digitalWrite(ledPin, HIGH);
}
readString = ""; // Clear recieved buffer
delay(100);
}
Python脚本
port = 'COM5'
ser = serial.Serial(
port=port,
baudrate=9600,
timeout=5
)
serial.write("test\r\n")
response = serial.readline()
print response
答案 0 :(得分:2)
<script type="text/javascript">
function CalculateImageSize(id){
var image = document.getElementById(id);
var height = image.offsetHeight;
var width = image.offsetWidth;
...
// use height, width to resize image.
}
</script>
如果您不想等待固定的秒数,您可能需要等待port = 'COM5'
ser = serial.Serial(
port=port,
baudrate=9600,
timeout=5
)
# you need to sleep after opening the port for a few seconds
time.sleep(5) # arduino takes a few seconds to be ready ...
#also you should write to your instance
ser.write("test\r\n")
# and give arduino time to respond
time.sleep(0.5)
response = self.serial.readline()
print response
(清除发送)