I can communicate with a device over UART with the following command in the linux shell:
echo 'CMD' > /dev/ttyPS1
I tried to recreate this action in Python using the Pyserial module, but nothing happens. I have tried to use it in both a .py file as well as inside of 2.7 interpreter (in case of timing delay issues).
import serial
ser = serial.Serial('/dev/ttyPS1', 115200)
ser.write('CMD')
Interestingly enough... after running the snippet of python, I cannot write to the device using the linux shell. stty shows me that Pyserial has added a bunch of options to the device. If I clear these extra options, then I can use the linux shell to talk with my device again.
Before Python script:
>>> stty -F /dev/ttyPS1
speed 115200 baud; line = 0;
-brkint -imaxbel
After Python script:
>>> stty -F /dev/ttyPS1
speed 115200 baud; line = 0;
min = 0; time = 0;
-brkint -icrnl -imaxbel
-opost -onlcr
-isig -icanon -iexten -echo -echoe -echok -echoctl -echoke
Why is this behavior happening? Is there a way to make Pyserial act like the linux shell?
If you really want to make pyserial
open the device file without changing all those flags, or explicitly make it change the flags to exactly the values they already have, you can probably do that with a bunch of option arguments to the constructor, or maybe by setting some attributes or calling some methods after construction.
But why do you want to do that?
If you just want to do the equivalent of echo
, just do what the shell and echo
command are doing: open the device file as a file and write to it.
So, one of these:
with open('/dev/ttyPS1', 'wb') as ps1:
ps1.write(b'CMD')
with open('/dev/ttyPS1', 'wb', buffering=0) as ps1:
ps1.write(b'CMD')
with open('/dev/ttyPS1', 'wb') as ps1:
ps1.raw.write(b'CMD')
ps1 = os.open('/dev/ttyPS1', os.O_WRONLY)
os.write(ps1, b'CMD')
os.close(ps1)
If you're using Python 2.x, you don't need the b
prefixes, and there is no .raw
, but otherwise things are similar:
with open('/dev/ttyPS1', 'wb') as ps1:
ps1.write('CMD')
with open('/dev/ttyPS1', 'wb', 0) as ps1:
ps1.write('CMD')
ps1 = os.open('/dev/ttyPS1', os.O_WRONLY)
os.write(ps1, 'CMD')
os.close(ps1)