简体   繁体   中英

Python serial.write doing nothing

Basically, what I am trying to do is input a string to the Arduino from Python, and the Arduino should print it back, and again it is read from Python. But when I run this code nothing happens.

I have tried the Arduino code separately and it works well with the serial monitor. I checked if the problem was with readline() with a different problem and it was running perfectly, so I guess the problem is with write() .

This is my Arduino code:

void setup() {
  Serial.begin(9600);
}

char rx_byte = 0;

void loop() {
  if(Serial.available() > 0) {
    rx_byte = Serial.read();
    Serial.println(rx_byte);
  }
}

This is my Python code:

import time
import serial

ser = serial.Serial('COM5', 9600)
ser.write(b's')
ser.flush()
time.sleep(1)    
message = ser.readline()
print(message)    
ser.close()

I think the ser.flush() might be killing the response. When I run your code without it my code works fine.

I tried changing

message = ser.readline()

to

message = ser.read()

and everything worked for me. Try using read() instead of readline()

您应该检查Arduino-Available ,因为如果Serial.available() > 0您错过了()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM