Pregunta

I use pyserial to write and read between two Raspberry pi(s) via UART

Raspberry pi 1 : send data to Raspberry pi 2

    while 1:
        ser=serial.Serial('/dev/ttyAMA0')
        if not ser.isOpen():
            ser.open()
        msg=raw_input('RPi 1 send:')
        ser.write(msg)
        ser.close()

Raspberry pi 2 : receive data from Raspberry pi 1

    while 1:
        ser=serial.Serial('/dev/ttyAMA0' ,timeout=0)
        if not ser.isOpen():
            ser.open()
        data=ser.read(1024)
        if data.__len__()>0:
            print 'RPi 2 receive:',data
        ser.close()

I run both code.

and send data

    RPi 1 send : Hello

and receive data

    RPi 2 receive : Hello

But if RPi 1 send data more than 8 characters

for example

    RPi 1 send : Hello Raspberry pi NO.2

The result is

    RPi 2 receive: Hello Ra
    RPi 2 receive: spberry 
    RPi 2 receive: pi NO.2

This is my problem. Because I want it to receive like this

(RPi 2 receive: Hello Raspberry pi NO.2) #show only one line.

and if send (more 8 char) again, it show in a new line.

What code to join it in one line? or other way to do this? :)

¿Fue útil?

Solución 2

I like to do this

sender.py

delim = "\x00"
ser.write(msg+delim)

reciever.py

delim = "\x00"
recvd = "".join(iter(lambda:ser.read(1),delim))
print recvd

Otros consejos

When reading using ser.read, you're just reading what is already in the buffer, or waiting for chars to arrive in the buffer. The size you specify is a maximum number of chars to receive, but it can be much less as you experienced.

You have 2 easy solutions:

  1. use ser.readline and put a terminator in your strings (like \n)
  2. if you know in advance how many characters to read, repeat reading until you've received them all

In both cases, specify a timeout (for example 1 second) when opening the serial line, to get back control on your code if the remote end doesn't send anything for whatever reason.

Hope it helps.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top