'python arduino usb communication
I'm trying to move data from Python to Arduino nano, but I can't see anything on the console on the Arduino side, but when I tried to move data from Arduino to python, it worked very well. Follow my codes below:
arduino code
void setup() {
Serial.begin(9600);
}
void loop() {
if(Serial.available() > 0) {
char data = Serial.read();
char str[2];
str[0] = data;
str[1] = '\0'
Serial.print(str);
}
}
python code
import serial, time
arduino = serial.Serial('COM3', 9600, timeout=.1)
time.sleep(1) # give the connection a second to settle
arduino.write("Hello from Python!")
while True:
data = arduino.readline()
if data:
print data.rstrip('\n') # strip out the new lines
Solution 1:[1]
The Arduino is using print, the Python is using readLINE.. Readline reads until it finds a '\n' the arduino is never sending a '\n'.'
Replace \0 in the sketch with \n and it should work.
It's always useful to test using the serial monitor and seeing what happens, if this doesn't work then please try sending some data using the serial monitor and let us know the results.
Solution 2:[2]
The problem may be that you have set too little time after connecting to the COM port.
try this
time.sleep(5) # give the connection 5 seconds to establish
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JeffUK |
| Solution 2 | vChuk |
