Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PySerial not talking to Arduino

  • Python version: 2.6.6
  • PySerial version: 2.5
  • Arduino board: Duemilanove 328

I have written some code to simulate some hardware I'm working with and uploaded it to the Arduino board. This code works. I know this, because I get the expected response from HyperTerminal.

However, when I try to connect using PySerial the connection does not error, but I get no response to the commands I send.

Why might this be?

Python code

import serial

def main():
    sp = serial.Serial()
    sp.port = 'COM4'
    sp.baudrate = 19200
    sp.parity = serial.PARITY_NONE
    sp.bytesize = serial.EIGHTBITS
    sp.stopbits = serial.STOPBITS_ONE
    sp.timeout = 0.5
    sp.xonxoff = False
    sp.rtscts = False
    sp.dsrdtr = False

    sp.open()

    sp.write("GV\r\n".encode('ascii'))
    value = sp.readline()
    print value
    sp.write("GI\r\n".encode('ascii'))
    value = sp.readline()
    print value

    sp.close()
 
if __name__ == "__main__":
    main()

NB: the code on the Arduino sends back \r\n at the end of a response to a command.

HyperTerminal configuration:

COM4 configuration in HyperTerminal

Edit

I have found that if I increase the timeout to 10 seconds and add a sp.readline() before I send anything, then I get responses to both commands.

How long is the hardware handshake usually between PySerial and an Arduino or USB RS-232 ports?

like image 550
Matt Ellen Avatar asked Nov 16 '11 09:11

Matt Ellen


People also ask

How do I send a serial message to Arduino?

How? Using serial inputs is not much more complex than serial output. To send characters over serial from your computer to the Arduino just open the serial monitor and type something in the field next to the Send button. Press the Send button or the Enter key on your keyboard to send.

How do I know if PySerial is installed?

To check that it is installed, start Pyzo and at the command prompt type in: import serial If it just gives you another >>> prompt, all is good. Checking that it is really working.

Is PySerial read blocked?

Totally non-blocking.

Is serial the same as PySerial?

pySerial includes a small console based terminal program called serial. tools. miniterm.


1 Answers

Can not verify this but it could be that you try and read before there is any data there, thus you get no reply back.

To test this you could try and poll until there is data

value = None
while not value:
   value = sp.readline()
print value

Edit

The Arduino will reset when you open a serial connection, any data written during bootup will likely go to bit heaven. You could use a sleep for 2 seconds (could not find the exact time it takes, will likely vary anyway) before you do any reads/writes.

Alternatively you could write to it until you get a response back, after you get a return you start doing "real work".

like image 104
ib.lundgren Avatar answered Sep 27 '22 23:09

ib.lundgren