2

I'm using an Arduino Mega to send data via serial communication to a Raspberry Pi 5. The connection is made through a TTL-232R cable (TTL serial on the Arduino side, USB on the Raspberry Pi side). On the Raspberry Pi, I'm using Python with the PySerial library to handle the communication.

Although I can successfully send data, I receive the following unexpected string immediately after opening the serial port:

\x00\x00267

Interestingly, this issue does not occur when I connect the Arduino to a Windows PC instead of the Raspberry Pi. My suspicion is that the serial communication parameters (parity, stop bits, xon/xoff flow control, etc.) might be configured differently on Windows compared to Raspbian. I have played with the number of stop bits with no success.

These parameters are set in Python using serial module:

    import serial
    import serial.tools.list_ports
class Serial_comm:

    EstadoPuerto = False

    def __init__(self):
        self.initialize()

    def initialize(self):

        self.port = serial.Serial()
        self.port.stopbits = 1
        self.port.parity = serial.PARITY_NONE
        self.port.xonxoff = False
        self.port.rtscts = False


    def serieOpen(self,port, baud):
        self.port.port = port
        self.port.baudrate = baud
        try:
            self.port.open()
            if self.port.isOpen():
                msg = "Puerto abierto con Exito"
                self.EstadoPuerto = True
        except Exception as e:
            msg = "Puerto no disponible: " + str(e)
        return msg

    # Read the port until the end of the line
    def rdv(self): 
    try:
        msg = self.port.readline()
    except Exception as e:
        msg = "Error de lectura en el puerto: " + str(e)
    return msg

Regarding the OS installed, I need to check, but I think it is Raspberry Pi OS with desktop version 12 (bookworm). serial module was installed using pip.

I’m wondering: how can I prevent receiving these extra or malformed characters when opening the serial port? Or, in other words, how can I check and compare the serial port configuration between Windows and Raspberry Pi OS to ensure consistency?

bardulia
  • 131
  • 5

1 Answers1

1

After reading the comments, my decision has been to just discard any received string from the serial port that has this '\x00' sequence inside of it.

This is the function I have used in the code and works nicely:

def verify_string(self,texto_var):
    flag = 0
    if '\x00' in texto_var:
        flag = 1
        print("Invalid string received:", repr(texto_var))
        self.tiempo_valor = 0
    elif texto_var == "" or texto_var =='\n':
        print("do nothing")
    else:
        print("Valid string:", repr(texto_var))
        # Do the convertion to int
        self.tiempo_valor = int(self.tiempo_texto.get())
return flag

bardulia
  • 131
  • 5