gpt4 book ai didi

python - Arduino 和 Python 之间的 Echo 程序

转载 作者:太空狗 更新时间:2023-10-30 02:35:32 24 4
gpt4 key购买 nike

我想通过 Python 中的 pyserial 将一些数据发送到 Arduino。我想让 Arduino 做的就是从串行端口读取可变长度的字符串数据,然后将其写回,以便 Python 可以读取它。由于我无法做到这一点,下面的代码只有 Python 发送字符。这是 Python 代码:

import serial
import sys
import pywapi
import time

def main():
ser = serial.Serial(3, 9600, timeout=1)
print "Conn established"
print "Sending: %s" % "z".__repr__()
print ser.write('z'.encode("ascii"))
time.sleep(2)
print "Received: %s" % ser.read(10).__repr__()
ser.close()

这是 Arduino 代码:

void setup(){
analogReference(DEFAULT);
Serial.begin(9600);
}

void loop(){
if(Serial.available() > 0)
Serial.println("x");
while(Serial.available() > 0){
Serial.print(Serial.read(), BYTE);
}
}

输出:

Conn established
Sending: 'z'
1
Received: ''

我知道 Arduino 的代码是有效的,因为它在从 Arduino 终端发送数据时有效。但是,当我尝试从 Python 发送任何内容时,它失败了。我整天都在为此苦苦挣扎。任何帮助将不胜感激。

最佳答案

尝试增加或删除超时,并将读取的大小设置为 1。您可能还想增加 sleep 延迟,甚至实现一个简单的读取循环。

类似于:

try:
while True:
data = ser.read(1).__repr__()
if data:
print "Received: %s." % data
else:
print "Looping."
except KeyboardInterrupt:
print "Done."
except:
raise
finally:
ser.close()
print "Closed port."

然后只需使用 ctrl-c 即可停止它。

关于python - Arduino 和 Python 之间的 Echo 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2330531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com