我发现了这个漂亮的 Python 代码:
import asyncio
import serial_asyncio
async def main(loop):
reader, writer = await serial_asyncio.open_serial_connection(url='COM4', baudrate=9600)
messages = [b'foo\n', b'bar\n', b'baz\n', b'qux\n']
sent = send(writer, messages)
received = recv(reader)
await asyncio.wait([sent, received])
async def send(w, msgs):
for msg in msgs:
w.write(msg)
print(f'sent: {msg.decode().rstrip()}')
await asyncio.sleep(0.5)
w.write(b'DONE\n')
print('Done sending')
async def recv(r):
while True:
msg = await r.readuntil(b'\n')
if msg.rstrip() == b'DONE':
print('Done receiving')
break
print(f'received: {msg.rstrip().decode()}')
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
loop.close()
我有这个简单的 Arduino 代码:
String data;
void setup()
{
Serial.begin(9600);
}
void loop()
{
while(Serial.available())
{
data = Serial.readString();
Serial.print(data);
}
}
我不明白为什么 Python Send 不能正常工作,python 正在接收来自 arduino 的消息,我已经尝试过类似的事情:
Serial.println("Hello from Arduino");
delay(2000);
这个问题是当我使用异步方法时,当我使用简单的 import serial
而没有 async/await
时它工作正常,但我需要执行串行异步。
为什么python不能发送消息或为什么Arduino不能重新发送消息?
我在 Windows 10 上使用 COM 端口和 Arduino UNO。
谢谢!