Wait on Arduino auto-reset using pySerial

前端 未结 3 1194
礼貌的吻别
礼貌的吻别 2021-02-08 05:54

I\'m trying to read lines from an Arduino board with a very simple code (for the sake of showcasing the problem) on Linux.

Python code:

# arduino.py
impo         


        
3条回答
  •  广开言路
    2021-02-08 06:32

    The Arduino IDE's monitor toggle's the assigned DTR pin of the port when connected. Where this toggling causes a reset on the Arduino. Noting that the DTR is toggled after the Monitor has opened the Serial port and is ready to receive data. In your case the below example should do the same.

    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())
    

    I would also add the compliment to the DTR for the Arduino's with AVR's using built-in USB, such as the Leonoardo, Esplora and alike. The setup() should have the following while, to wait for the USB to be opened by the Host.

    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
      }
    }
    

    It will have no effect for FTDI's based UNO's and such.

提交回复
热议问题