简体   繁体   English

Python串行写入不起作用第一次运行

[英]Python serial write doesn't work FIRST run

I have 2 programs to test serial communication, an simple arduino program that echoes whatever is on the serial port and a python program that writes to the serial port and prints the reply.我有 2 个程序来测试串行通信,一个简单的 arduino 程序,它回显串行端口上的任何内容,以及一个写入串行端口并打印回复的 python 程序。

I'm having an issue where whenever I upload the arduino program and try to run the python the first time after I uploaded, it would be stuck on print ser.readline() which I'm assuming means for some reason python is not writing to the serial port.我有一个问题,每当我上传 arduino 程序并在我上传后第一次尝试运行 python 时,它会卡在print ser.readline() ,我假设这意味着由于某种原因 python 没有写到串口。 I would have to quit the python program and run it again to get it to get a reply from arduino.我必须退出 python 程序并再次运行它才能得到 arduino 的回复。 The program would continue to work until I re-upload the arduino then once again python wouldn't work on first run.该程序将继续工作,直到我重新上传 arduino 然后再次 python 在第一次运行时无法工作。 Also if I open and close the serial monitor before I run the python program it will work the first run.此外,如果我在运行 python 程序之前打开和关闭串行监视器,它将在第一次运行时工作。 Does anyone know what is the issue?有谁知道是什么问题? This is on Ubuntu.这是在 Ubuntu 上。

arduino阿杜伊诺

String str;

void setup() {                
// Turn the Serial Protocol ON
  Serial.begin(115200);
}

void loop() {
  if (Serial.available()) {
      str = Serial.readStringUntil('\n');     // Read the serial input
      Serial.println(str);             // sends ascii code

  }
}

Python蟒蛇

import serial


ser = serial.Serial('/dev/ttyACM1', 115200)

for i in range(0,4):
    str = "test string\n"
    ser.write(str)
    print ser.readline()

The issue is likely related to many Arduinos resetting when a new serial connection is made.该问题可能与许多 Arduino 在建立新的串行连接时重置有关。

The solution is to either add a delay (about 2 seconds works) to the python program between the serial connection being created and the first data being sent or modifying the hardware to prevent a reset on serial connect.解决方案是在创建串行连接和发送第一个数据之间的 python 程序中添加延迟(大约 2 秒),或者修改硬件以防止串行连接重置。

By default python Serial might be blocking by default try removing the timeout:默认情况下,python Serial 可能会在默认情况下阻塞,请尝试删除超时:

ser = serial.Serial('/dev/ttyACM1', 115200,timeout=0)

additionally have a peek at the serial.threaded in the docs另外看看文档中的serial.threaded

I added我加了

time.sleep(1)
ser.setDTR(level=0)
time.sleep(1)

after opening the serial port and the issue was fixed.打开串口后问题就解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM