Search code examples
pythonraspberry-piserial-portserial-communicationmbed

How to process a serial read value in Raspberry pi


I have been trying to have some serial communication between raspberry and my STM32 board (I use MBEDOS for the firmware).

Right now, I am able to do serial writing from my raspberry to the microcontroller, and succeed.

However, I wanted to try to write something from the microcontroller to the raspberry, and the raspberry should process it. But, it seems that it fails to do so.

The code of the raspberry is quite simple:

import time
import serial
ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate = 9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1
    )
while 1:
     x=ser.readline()
     if x[2] == "e":
         break         
     print x
print("stop")

A little explanation to my code, what I wanted to do is when my microcontroller send an "e", it should break from the loop. I used x[2] because I noticed when we print the serial data, it will print:

b'eeeeeee\n'

hence,I decided to use x[2].

In the microcontroller part, I used:

if(butn == 1) {
        // raspi.putc('e');
        raspi.printf("eeeeeee");
        swo.printf("e is printed");
    }

where butn is the user button. I already tried using .putc('e') but it is the same as well.

How can I deal with this problem?

Thank you!!


Solution

  • The problem in your code is that Serial.readline() return a bytes object, not a string. That's why you see the b when it gets printed.

    Now, indexing with bytes objects doesn't count the b and the ' that appear in its string representation; so if you want the first character, you should use x[0]. However, when you use indexing in the bytes object you won't get a character, you will get the number representation of the particular byte you requested.

    x = b'eeeee'
    print x[0]
    
    >>> 101
    

    Unsurpisingly, 101 is the ascii for 'e'.

    You need to cast x[0] to a character. The result would be:

    while 1:
         x=ser.readline()
         if chr(x[0]) == "e":
             break         
         print x