I am trying to use Raspberry Pi 4 to communicate to a RS485 chip for serial communication purposes. I need to use GPIO#3 from Pi for to control the nRE/DE PIN on the RS485 chip. when GPIO#3 is low, the RS485 chip is in Rx (reading) mode, HIGH in Tx (transmitting) mode. To transmit anything, I need to set the GPIO#3 to HIGH right before sending any data (this part works), and IDEALLY GPIO#3 should be HIGH for the same duration as the write process takes. So I did the following:
os.system("echo 1 > /sys/class/gpio/gpio3/value") #set GPIO#3 HIGH
n = ser.write(cmdHex)
os.system("echo 0 > /sys/class/gpio/gpio3/value") #set GPIO#3 LOW
#the rest of the code is read response back from the target device
However this structure of code does not work. I connected the oscilloscope, it shows GPIO#3 was set to HIGH for only very short (nearly noticeable length) and immediately turned to LOW while data has send through. Say the entire data takes 8ms to sent out, GPIO#3 was only set to HIGH for 0.2ms. After seeing this behaviour, I decided to add sleep function to let the program to wait until write finished then set the GPHI#3 to LOW. And the duration of the write process can be calculated based on the baudrate.
#each byte has 1 start bit, 8 data bit and 1 stop bit, so 10 bits total
sleeptime = 1/(baudrate*1.0) * dataLength * 10
os.system("echo 1 > /sys/class/gpio/gpio3/value") #set GPIO#3 HIGH
n = ser.write(cmdHex)
time.sleep(sleeptime)
os.system("echo 0 > /sys/class/gpio/gpio3/value") #set GPIO#3 LOW
#the rest of the code is for reading
However, the real issue comes. It doesn't sleep exactly for that amount of time. It is always sleep longer (sometimes a little bit longer, sometimes very long, very inconsistent). This unexpected behaviour results that sometimes the GPIO#3 pin stayed too long and it overlapped with the response so the chip cannot read it since it was still in writing mode...
Any help how to solve this issue? I have absolutely no idea what I did wrong.
Thank you for any thought/comments below.