Wait on Arduino auto-reset using pySerial

前端 未结 3 1119
礼貌的吻别
礼貌的吻别 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:44

    I realize this is an old question, but hopefully this can be useful to somebody else out there with the same problem.

    I had an issue where if I used any baudrates other than 9600, the serial connection in python would just receive gibberish all the time, even if Serial.begin(...) is properly set on the arduino and matches the value used in the python code. I read online that the bootloader or watchdog may take a second to load (when the board is power-cycled) and it may send stuff over serial at some specific baudrate (for chip programming possibly). I'm guessing that this is what messes up the serial communication in python.

    Here's the piece of code that gives me reliable results:

    import serial
    from time import sleep
    arduino = serial.Serial('/dev/ttyACM0') # dummy connection to receive all the watchdog gibberish (unplug + replug) and properly reset the arduino
    with arduino: # the reset part is actually optional but the sleep is nice to have either way.
      arduino.setDTR(False)
      sleep(1)
      arduino.flushInput()
      arduino.setDTR(True)
    
    # reopen the serial, but this time with proper baudrate. This is the correct and working connection.
    arduino = serial.Serial('/dev/ttyACM0',baudrate=57600)
    
    with arduino:
        while True:
            print(arduino.readline())
    

    The code used on the arduino side for testing is as simple as this:

    void setup() {
      Serial.begin(57600);
      Serial.println("setup");
    }
    
    void loop() {
      Serial.println("hello");
      delay(200);
    }
    

提交回复
热议问题