Search code examples
python-3.xserial-portpyserialuart

Received message differs from sent message over serial connection


I am trying to connect two raspberries over a serial connection with pyserial. I wrote two little scripts, for transmitting and receiving. While there is a communication happening between those two, the received message is completely different, than the sent message.

For example if I do

serial1.write(b'hello')

on raspi1, then raspi2 receives:

print(serial2.readline().hex())
fa9b9fff

which is the hex representation of ú›Ÿÿ.

EDIT: Here is the receive and send methods:

sender:

def send_msg(_ser, _msg):
    if _ser.isOpen():  # isOpen() is deprecated since version 3.0
        try:
            _ser.flushInput()  # flush input buffer, discarding all its contents
            _ser.flushOutput()  # flush output buffer, aborting current output 
            # and discard all that is in buffer

            _ser.write(_msg)
            _ser.flush()

        except IOError:
            print('error communicating...')

    else:
        print('cannot open serial port')
    return

receiver:

def read_line(_ser, _eol_character=b'\n', _timeout=1, _encoding='utf-8'):
    buffer = ""
    timer = time.time()
    while (time.time()-timer)<_timeout:
        one_byte = _ser.read(1)
        print(one_byte.hex())
        if one_byte == _eol_character:
            return buffer.encode(_encoding)
        else:
            buffer += str(one_byte, _encoding, errors='replace')
    raise TimeoutError("Timed out while read_line(), make sure there is an EOF!")

Solution

  • The kind of gibberish you're getting indicates three possible causes:

    -A mismatch of settings, most likely different baud rates

    -Noise on the bus: frequently originating from lacking a common ground reference. This happens when you have not connected only connect the TX and RX signals but leave the GND floating (on desktop computers you'll likely have a common ground even if you don't connect the GND signals because of the safety ground on your house's wiring but on laptops or other battery-powered devices this is a problem and you have to use a third cable to connect GND on both sides of the bus).

    -You're trying to communicate using different logic levels. This happens if one side of the bus is working on TTL levels (5V) and the other on 3.3V or when you have a real RS232 level (differential) combined with any of the others. Not to mention if you try to mix RS485 with RS232 or TTL, which, of course, won't work either.