等待使用pySerial进行Arduino自动重置

ast*_*nlu 9 python arduino pyserial

我试图在Linux上用一个非常简单的代码(为了展示问题)从Arduino板读取行.

Python代码:

# arduino.py
import serial
arduino = serial.Serial('/dev/ttyACM0')

with arduino:
    while True:
        print(arduino.readline())
Run Code Online (Sandbox Code Playgroud)

Arduino代码:

// simpleWrite.ino
long ii = 0;

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
}

void loop() {
  Serial.println(ii);
  ii++;
}
Run Code Online (Sandbox Code Playgroud)

由于电路板在打开串行连接时自动复位,因此第一个字节可能是垃圾.一两秒后一切正常.

这是典型的输出:

$ python arduino.py 
b'09\r\n'
b'540\r\n'
b'541\r\n'
b'542\r\n'
b'543\r\n'
b'544\r\n'
b'545\r\n'
b'546\r\n'
b'547\r\n'
b'548\r\n'
b'549\r\n'
b'550\r\n'
b'551\r\n'
b'552\r\n'
b'553\r\n'
b'554\r\n'
b'555\r\n'
b'556\r\n'
b'557\r\n'
b'55\xfe0\r\n'  # <---- Here the board restarted
b'1\r\n'
b'2\r\n'
b'3\r\n'
b'4\r\n'
b'5\r\n'
b'6\r\n'
b'7\r\n'
b'8\r\n'
b'9\r\n'
b'10\r\n'
Run Code Online (Sandbox Code Playgroud)

但是,我看到Arduino IDE串行监视器没有这个问题,并正确显示延迟(重启时),然后打印从第一行开始的所有行.

有没有办法使用pySerial在Python中模拟这种行为?也就是说,在重新启动之前丢弃所有输出,仅此而已?也许是通过一些低级功能?

我尝试查看相关的Arduino源代码,但我不知道Java,它没有帮助.

注意:当然我可以睡三个小时,丢弃一切并从那里开始,但我也可能放弃一些第一行.

编辑:显然,Windows上不存在此问题,并且不需要接受的解决方案.

mpf*_*aga 14

连接时,Arduino IDE的监视器切换是指定端口的DTR引脚.此切换导致Arduino重置.注意到在监视器打开串行端口并准备接收数据后,DTR被切换.在您的情况下,下面的示例应该做同样的事情.

Import serial

arduino = serial.Serial('/dev/ttyS0',
                     baudrate=9600,
                     bytesize=serial.EIGHTBITS,
                     parity=serial.PARITY_NONE,
                     stopbits=serial.STOPBITS_ONE,
                     timeout=1,
                     xonxoff=0,
                     rtscts=0
                     )
# Toggle DTR to reset Arduino
arduino.setDTR(False)
sleep(1)
# toss any data already received, see
# http://pyserial.sourceforge.net/pyserial_api.html#serial.Serial.flushInput
arduino.flushInput()
arduino.setDTR(True)

with arduino:
    while True:
        print(arduino.readline())
Run Code Online (Sandbox Code Playgroud)

我还要使用内置USB,例如Leonoardo,Esplora等,为AVR的Arduino添加对DTR的赞美.setup()应该具有以下内容,等待主机打开USB.

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
}
Run Code Online (Sandbox Code Playgroud)

它对FTDI的UNO等没有任何影响.