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 :(