Search code examples
pythonarduinopyserialarduino-uno

Arduino Serial programming issue


I'm sending an integer from python using pySerial.

import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600);
ser.write(b'5');

When i compile,the receiver LED on arduino blinks.However I want to cross check if the integer is received by arduino. I cannot use Serial.println() because the port is busy. I cannot run serial monitor first on arduino and then run the python script because the port is busy. How can i achieve this?


Solution

  • You could listen for the Arduino's reply with some additional code.

    import serial
    ser = serial.Serial('/dev/cu.usbmodem1421', 9600); # timeout after a second
    
    while ser.isOpen():
        try:
            ser.write(b'5');
            while not ser.inWaiting():  # wait till something's received
                pass
            print(str(ser.read(), encoding='ascii'))  #decode and print
        except KeyboardInterrupt:  # close the port with ctrl+c
            ser.close()
    

    Use Serial.print() to print what the Arduino receives to the serial port, where your Python code is also listening.