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.")