Sending serial message in python - python

I am trying to send this command ":01050801FF00F2" over serial in python 2.7 , with no success.
The code that i use is :
import serial, sys ,socket
from time import sleep
port = "COM9"
baudRate = 9600
try:
ser = serial.Serial(port, baudRate, timeout=1)
if not ser.isOpen():
ser.open()
except Exception, e:
print("Error opening com port. Quitting."+str(e))
sys.exit(0)
print("Opening " + ser.portstr)
#this is few ways i am trying to send with
c = '01050801FF00F2'
ser.write(c.encode('utf-8'))
sleep(3)
ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output
#and discard all that is in buffer
c = ':01050801FF00F2'
ser.write(c.encode('hex'))
sleep(3)
ser.write(':01050801FF00F2')

If those are hex values, this should work:
c = '\x01\x05\x08\x01\xFF\x00\xF2'
ser.write(c)

Have you tried sending the command using bytearray?
Perhaps you could try:
ser.write(b':01050801FF00F2')
or
ser.write(':01050801FF00F2'.encode())

Related

How to open the serial device exclusively in pyserial?

I want to open the serial device exclusively by pyserial in ubuntu 20.04. I tried the following two approaches.
To use the exclusive flag in pyserial.
ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2, exclusive=True)
To use fcntl as below.
try:
ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2)
if ser.isOpen():
try:
fcntl.flock(ser.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except Exception as e:
print(e)
except Exception a e:
print(e)
Both approaches do not work. There is no any lock file generated under /var/lock.
Finally, I can only created the lock file manually under /var/lock as below.
try:
device_name = serialdevice.split("/")[2]
lock_file_name = "/var/lock/LCK.."+device_name
ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2)
if ser.isOpen():
open(lock_file_name, 'w').write(str(os.getpid()))
else:
print("port not open")
except Exception as e:
print("Failed to open serial port exclusively. Pls check if the serial port is already used by other tools")
print(e)
return
May I ask what could be wrong in the first two approaches? Is the manual method used generally in opening the serial port exclusively? Do I need to delete the lock file manually when the python script quit?
Thanks!

Python Serial Read all Output (cant break out of while loop)

I have this code which im using to connect to a printer and send it commands. It works perfectly until it gets to the while loop, it just cant get out of it. The output prints the first few lines expected in serial than just waits until while loop goes false. how do i get out of the loop?
import serial
import os
import time
ser = serial.Serial('/dev/ttyUSB0', 115200) # open serial port
print("Device Name: " + ser.name)
while True:
response = ser.readline().decode('utf-8')
print(response)
time.sleep(1)
The whole point of a while True: loop is that there is no stop condition. This means that it will keep going until you manually stop your program.
What you can do is add a break statement when you don't read anything anymore.
And don't forget to use a timeout on your serial so it doesn't hang forever waiting for new data:
import serial
import os
import time
ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=10) # open serial port
print("Device Name: " + ser.name)
counter = 0
while counter < 10:
response = ser.readline().decode('utf-8')
print(response)
if response == "":
break
time.sleep(1)
With this, it will read everything available then wait 10 seconds for additional data.
If there is no more data, it will return an empty string (no bytes read) and break from the loop.

Continuosly Read/Monitor Serial Port(if port not opened continuously run script) using python

Im newbie for python and serial port. I want to monitor serial port continuously. If port not opened or access denied, need to run the python script without stop.
I had done something, But that script has stopped when the PORT not opened or access denied. kindly, help someone to close this issue.
import serial
z1baudrate = 9600
z1port = 'COM4'
z1serial = serial.Serial(port=z1port, baudrate=z1baudrate,timeout=1)
try:
if z1serial.is_open:
while True:
size = z1serial.inWaiting()
if size:
data = z1serial.read(size)
res= data.decode("utf-8")
print(res)
else:
print("Data not reading")
time.sleep(1)
else:
z1serial.close()
print('z1serial not open or Already in use')
except serial.SerialException as e:
z1serial.close()
print('COM4 not open')
You need to include the z1serial assignment inside the try block as
import serial
import time
z1baudrate = 9600
z1port = 'COM4'
while True:
try:
z1serial = serial.Serial(port=z1port, baudrate=z1baudrate,timeout=1)
if z1serial.is_open:
while True:
size = z1serial.inWaiting()
if size:
data = z1serial.read(size)
res= data.decode("utf-8")
print(res)
else:
print("Data not reading")
time.sleep(1)
else:
z1serial.close()
print('z1serial not open or Already in use')
except serial.SerialException:
print('COM4 not open')
time.sleep(1)
This worked for me, running on Python 3.7

Unable to close file after writing it with data stream from Com port using python

I am trying to open a serial port via Python, write the incoming data stream into a file and close the file when the data stream stops.
My program is unable to detect that the port is no longer receiving any data. So the file remains open. What do I do?
import serial
ser = serial.Serial(port='COM8', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
print("Connected to Audio(COM8) port")
try:
f = open('C:\Users\user\Desktop\final.raw', 'w')
while 1:
ser_bytes = ser.readline()
if ser_bytes:
f.write(ser_bytes)
else:
break
finally:
f.close()
print("output file closed")
ser.close()
Specify timeout while using ser.readline()

pySerial: port only works the first I use it after I power it on

I have trouble reading an arbitrary port with pySerial. I can only read the port when the port hasn't been used by any program after it's turned on. Otherwise, I can open the port but ser.inWaiting() returns 0, telling me there is no data in the port buffer. Actually, I can see data in a port monitor, so why does pySerial gets no data? I am using os x 10.9.5., python 2.7.8 and pySerial 2.7
Here is the code:
def usb():
ser = serial.Serial('/dev/tty.usbmodem422651', 115200)
try:
while True:
print ser.read(1000)
except KeyboardInterrupt:
ser.close()
exit
if __name__ == "__main__":
testUSB()
Thank you for your help!
You need to understand how serial works.
If you already opened some terminal and read the data, then it's the input buffer of the serial port is now empty.
while True:
print ser.read(1000)
It's not a good practice, you can try the following using inWating:
if ser.inWaiting:
ser.read(len(ser.inWaiting()))
You cannot open the port from 2 different apps or software.
A good code will look like:
import serial
def my_usb():
s_handle = serial.Serial('/dev/tty.usbmodem422651', 115200)
# or any other end condition
while True:
try:
if s_handle.inWaiting():
print s_handle.read(s_handle.inWaiting())
except KeyboardInterrupt:
print "exiting...."
finally:
s_handle.close()
if __name__ == "__main__":
my_usb()

Categories

Resources