Serial communication issue with python

I tried to receive data from my computer through a USB cable with Python.
However, the Arduino IDE serial monitor could not receive data.
Please help me!
My computer is Windows. When I used putty, the data was coming up, so I believe not a USB port problem.

The codes are these.

void setup() {
  Serial.begin(9600);
  Serial.println("Arduino is ready");
}

void loop() {
  if (Serial.available()) {
    String received = Serial.readStringUntil('\n');  // Read incoming message
    Serial.println("Arduino received: " + received);  // Send back confirmation
  }
}

python,terminal on Windows
import serial
import time

serPort = "COM6"
baudRate = 9600

try:
    ser = serial.Serial(serPort, baudRate)
    print("Serial port " + serPort + " opened. Baudrate: " + str(baudRate))
    
    time.sleep(2)  # Wait for Arduino to reset
    
    ser.write(b'Hello Arduino\n')  # Send a test message to Arduino
    print("Sent: Hello Arduino")
    
    while ser.inWaiting() == 0:
        pass
    
    received_data = ser.readline().decode('utf-8').strip()  # Read response
    print("Received from Arduino: " + received_data)

except serial.SerialException as e:
    print(f"Serial error: {e}")
finally:
    ser.close()
    print("Serial port closed.")

I've written a small tutorial on interfacing with Python. See Two ways communication between Python3 and Arduino

1 Like

After doing your tutorial, Can I get Arduino to receive text file data from the computer?

if you understand the tutorial, you'll know how to send data from the computer to the Arduino. It's not difficult to switch from a keyboard input to a file but you'll have to handle some sort of protocol to tell the arduino what's coming (a file can hold binary data and so you won't have an easy end marker).

If you open the Serial Monitor, no other devices will be connected to the Arduino. So either Python will talk to the Arduino and read from it, or you type and send text to the Arduino and it will respond via the Serial Monitor.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.