0

I am trying to communicate to a UART device using Raspberry Pi (Raspberry Pi 3B with Raspbian stretch) Header pins with pyserial. I have followed all the steps mentioned in https://www.raspberrypi.org/documentation/configuration/uart.md to activate the UART over Header pins (Like editing the /boot/cmdline.txt file, disabling the UART over bluetooth ) . I am able to communicate to the device and get the data but this is not working all time but on a cyclic basis. If I run the program for the first time it works fine. If I close the program and run it again , then I am receiving all the blank values. If I close the program and run it again , I am receiving the perfect output. This happens repeatedly. Is there anything I am doing wrong ?? Below is the code i am using.

import time
import serial
try:
    ser = serial.Serial()
    ser.port = '/dev/serial0'
    ser.baudrate = 115200
    ser.bytesize = serial.EIGHTBITS 
    ser.parity =serial.PARITY_NONE 
    ser.stopbits = serial.STOPBITS_ONE 
    ser.timeout = 1
except Exception as e:
    print(e)
    pass
print(ser)

while True:
    try:
        ser.open()
        data=str(ser.readline())
        ser.close()
        print(data)
    except Exception as e:
        print(e)
        pass

I am trying to figure out what's going wrong with this for 1.5 days now. Somebody please help :(

1 Answer 1

1

It is totally un-necessary (and counter-productive) to disable the UART over bluetooth. For all, but the most demanding tasks the mini UART functions perfectly well, any doesn't disable Bluetooth. In any event it is better to use raspi-config to change settings rather than editing files.

End of sermon - now to your problem, you have the following code which continually opens and closes the port, leaving you with an undefined state in the buffer.

while True:
    try:
        ser.open()
        …
        ser.close()
        …

Open the serial port ONCE at the start of your program and close it at the end.

Even then on initial run the buffer may contain data, you should flush or discard first read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.