简体   繁体   中英

PySerial has problems reading Arduino

I want to dump a ROM. The Arduino waits until it receives the key which is one digit. I use this digit as the starting command and as a parameter to tell the Arduino how big the ROM is. This is my Arduino code (simplified for testing):

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

void loop() {
  uint8_t key = 10;

  while(key > 2){
    key = Serial.read();
    key -= '0';
  }

  Serial.print("75 A E8 98 D4 E8 8A E4 E8 EB E4 F9 C3 60 3C 55");
  Serial.println("");
  Serial.print("74 C E8 35 3 E8 79 E1 88 96 9F 0 EB F E8");
  Serial.println("");
  Serial.print("0 E8 9 1 FF 76 19 E8 4F DC 8F 46 19 61 F8 C3");
  Serial.println("");
  Serial.print("E8 5E E1 33 C0 EB 29 B8 1 0 81 BE A0 0 0 51");
  Serial.println("");

  Serial.println("EOF");
}

And this is my Python code to tell the Arduino to start dumping and to read the response:

line = " "

ser = serial.Serial("COM10", 115200, timeout=1)
ser.write("1")
ser.flush()

while line != "EOF":
    line = ser.readline().strip
    print line

ser.close()

The problem: its printing nothing.

PS: already tried different values for timeout but neither 0 or None worked.

EDIT: Everyone else is invited to awnser! I'm using Python 2.7.6 - Anaconda 1.9.2 32bit @ Win7x64

EDIT2 The solution is to add a delay of 2secs ( time.speep(2) ) before the first write in python. More details here: pySerial works fine in Python interpreter, but not standalone

Pyserial certainly has no problem reading arduino serial ... I have done it many many times

try this

ser = serial.Serial("COM10", 115200, timeout=5)
ser.flush()
ser.write("1")
print ser.read(1000)
ser.close()

or abstract it further

class MySerial:
    def __init__(self,*args,**kwargs):
       kwargs["timeout"] = kwargs.get("timeout",5) #ensure timeout set
       self.ser = serial.Serial(*args,**kwargs)

    def query(self,cmd):
       self.ser.flush()
       self.ser.write(cmd)
       return self.ser.read(100000)

ser = MySerial("COM10", 115200, timeout=5)
print ser.query("1")

also I am a little curious why you are writing hex to a string all space separated like that instead of just writing in bytes...

you can verify that you can get reads as follows

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

void loop() {
    Serial.read();
    Serial.println("Hello World!\r");
}

this will wait for anything then send the hello world string ... make sure you see that at least then continue tweaking it to behave as you want (EG. get a specific value from the read before continuing ,send a message other than hello world ... my guess is that its not getting past your Serial.read() for whatever reason

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