I am trying to open a serial port connection and keep it open as long as data if communicating. I also want to respond if certain data is received. Below is an example of the python script. I am able to open the serial port send data and the script responds, it will not respond with the elif data.
I am new to pyserial and have been working on python lately but not great by any means.
Thank you
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', timeout=10) # open serial port
print(ser.name) # check which port was really used
response = ser.read()
if response == (b'\r'):
ser.write (b'ID=')
elif response == (b'\r\r\x1bPG1\r'):
ser.write (b'110 1.8<CR><ACK><CR><ESC>[p<CR>')
#time.sleep(5)
#print ()
#ser.close() # close port
Related
I have a terminal which I connect to with serial communication, and I want to read from it and write to it some commands I prepared in advance in a string array
Using pySerial, I need to write a code that will read the lines with a stop condition which is a wait from the console for input from the user, and then write the commands from the array
Just want to clarify, it's like an automatic PuTTY, and no I can't connect to the terminal through ssh, and no I can't bood the machine's terminal since it's not a pc
here is what i tried:
import serial
Baud_Rate = 9600
Ser = serial.Serial('COM4', Baud_Rate)
while Ser.isOpen():
input('Error: Ser is already open, please close it manually. if the port is
closed, press enter\n')
try:
Ser.close()
except serial.serialutil.PortNotOpenError:
pass
Ser.open()
Serial_com = [] #a str array with the relevant commands
for i in range(len(Serial_com)):
ter = Ser.readline()
while ter != 0xaf:
#print(str(ter))
print(str(ter.decode('utf-8').rstrip('\r\n')))
ter = Ser.readline()
sleep(1)
if i == 0:
print('login: root')
Ser.write(bytes("root", encoding='utf-8'))
else:
print('\n\n\n\n\nroot # Ser: ~ # ' + str(Serial_com[i]))
Ser.write(bytes(Serial_com[i], encoding='utf8'))
I realized that once the serial port is waiting for the python code (or the user) to write commands, that it sends the character 0xaf. It might be a coincidence, but still I wrote that as a stop condition for the reading from the terminal
the code can read from the serial port, but once it needs to write to the serial port it won't proceed
I can't share the rest because it's confedencial for a project
I have Python 3.6.1 and PySerial Installed. I am trying the
I am able to get the list of comports connected. I now want to be able to send data to the COM port and receive responses back. How can I do that? I am not sure of the command to try next.
Code:
import serial.tools.list_ports as port_list
ports = list(port_list.comports())
for p in ports:
print (p)
Output:
COM7 - Prolific USB-to-Serial Comm Port (COM7)
COM1 - Communications Port (COM1)
I see from the PySerial Documentation that the way to open a COM Port is as below:
import serial
>>> ser = serial.Serial('/dev/ttyUSB0') # open serial port
>>> print(ser.name) # check which port was really used
>>> ser.write(b'hello') # write a string
>>> ser.close() # close port
I am running on Windows and I get an error for the following line:
ser = serial.Serial('/dev/ttyUSB0')
This is because '/dev/ttyUSB0' makes no sense in Windows. What can I do in Windows?
This could be what you want. I'll have a look at the docs on writing.
In windows use COM1 and COM2 etc without /dev/tty/ as that is for unix based systems. To read just use s.read() which waits for data, to write use s.write().
import serial
s = serial.Serial('COM7')
res = s.read()
print(res)
you may need to decode in to get integer values if thats whats being sent.
On Windows, you need to install pyserial by running
pip install pyserial
then your code would be
import serial
import time
serialPort = serial.Serial(
port="COM4", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE
)
serialString = "" # Used to hold data coming over UART
while 1:
# Wait until there is data waiting in the serial buffer
if serialPort.in_waiting > 0:
# Read data out of the buffer until a carraige return / new line is found
serialString = serialPort.readline()
# Print the contents of the serial data
try:
print(serialString.decode("Ascii"))
except:
pass
to write data to the port use the following method
serialPort.write(b"Hi How are you \r\n")
note:b"" indicate that you are sending bytes
Hi please bear my basic question as I am new to python.
I am trying to read data from serial port. Basically serial port is a USB port converted to serial port virtually. I am using arduino.
First i tried this code:
while(True):
ser=serial.Serial('COM6',9600)
bytoread=ser.inWaiting()
val=ser.read(bytoread)
But it gave me error.
Permission Error(13,Access is denied, none 5)
But when i changed my code to
while(True):
ser=serial.Serial()
ser.baudrate=19600
ser.port='COM6'
ser
ser.open()
bytoread=ser.inWaiting()
val=ser.read(bytoread)
Permission error did not come but program is always busy connecting the port. I waited for many minutes but it never moved forward. What I am doing wrong here?
you can do something like :
import serial
ser = serial.Serial('COM6', 9600, timeout=None)
while True:
data = ser.readline()
you can't put ser = serial.Serial('COM5', 9600, timeout=None) in your while loop because it will permanently (re)create the connection...
I can't receive data from com port by pyserial! I have compiled program that send data and receive answer from controller correctly! I used comport monitor program to spy request and answer from controller:correct send and answer
But when I send the same request i get nothing((my request without answer
My Python prog:
#!/usr/bin/env python
import sys, os
import serial, time
from serial import *
ser = serial.Serial(
port='COM7',
baudrate=4800,
bytesize=5,#18,
parity='N',
stopbits=1,
timeout=5,
xonxoff=0,#
rtscts=0,#
writeTimeout = 1#1
myz= '\x10\x02\x00\x00\x01\x4e\xf0\x04\x01\xff\x10\x17\x02\x4e\xf0\x04\x02\xff\x10\x17\x10\x03\xff'
while True:
ser.write(myz) #send data
ser.readline()
I was trying different speeds(4800,9600) and got nothing(((
Can anybody tell me where I get mistayke?
You'll not receive your own message on the com port you write it to. Either connect the other side of the cable to a different port, or communicate with a device that will answer you.
I have two Xbee Pro 900's, each attached to a Raspberry Pi. Both are updated to version 1061 and are set to API Enable with escapes. They also have the same Modem VID of 7FFF. Both Pi's have PySerial and the python-xbee library installed.
Xbee 1(Receiver) has a serial number of 0013A200409A1BB8
Xbee 2(Sender) has a serial number of 0013A200709A1BE9
I've included my code below, which is just sample code I've found online. My issue is that I'm not receiving anything on the appropriate Xbee. I have absolutely no idea what is wrong, I've triple checked the destination address, and both of the Xbee's configuration settings.
Xbee 2 Code(Sender):
#! /usr/bin/python
import time
from xbee import XBee
import serial
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
# Create API object
xbee = XBee(ser,escaped=True)
import pprint
pprint.pprint(xbee.api_commands)
DEST_ADDR_LONG = "\x00\x13\xA2\x00\x40\x9A\x1B\xB8"
# Continuously read and print packets
while True:
try:
print "send data"
xbee.tx_long_addr(frame='0x1', dest_addr=DEST_ADDR_LONG, data='AB')
time.sleep(1)
except KeyboardInterrupt:
break
ser.close()
Xbee 1 Code(Receiver):
#! /usr/bin/python
from xbee import XBee
import serial
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
# Create API object
xbee = XBee(ser,escaped=True)
# Continuously read and print packets
while True:
try:
print "waiting"
response = xbee.wait_read_frame()
print response
except KeyboardInterrupt:
break
ser.close()
When both programs are running, the Tx light on the sending Xbee blinks, but I receive nothing on the receiving Xbee. Is there something I'm missing? Thanks for your time!
Are you using XBee or XBeePro? I had the same problem and this post helped me a lot.
Try to modify the Receiver Code the following way:
import config
import serial
import time
from xbee import ZigBee
def toHex(s):
lst = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
hv = '0'+hv
hv = '0x' + hv
lst.append(hv)
def decodeReceivedFrame(data):
source_addr_long = toHex(data['source_addr_long'])
source_addr = toHex(data['source_addr'])
id = data['id']
samples = data['samples']
options = toHex(data['options'])
return [source_addr_long, source_addr, id, samples]
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
zb = ZigBee(ser, escaped = True)
while True:
try:
data = zb.wait_read_frame()
decodedData = decodeReceivedFrame(data)
print decodedData
except KeyboardInterrupt:
break
In my case the code above outputs the following:
[['0x00', '0x13', '0xa2', '0x00', '0x40', '0x9b', '0xaf', '0x4e'], ['0x68', '0x3f'], 'rx_io_data_long_addr', [{'adc-0': 524}]]
Here I shared configuration settings for Controller Node (compatible with X-CTU)
Are you sure the XBee modules are in escaped API mode (ATAP=2)? And 9600 baud?
Can you enable a mode in python-xbee to dump all characters in and out?
Have you confirmed the serial wiring is correct? (I see you're using USB, so that's not an issue.)
If you don't have hardware flow control hooked up, make sure the XBee modules have ATD6=0 and ATD7=0 set (disable RTS and CTS) and that python-xbee isn't expecting handshaking.
If you do have hardware flow control configured on the XBee, make sure you've told python-xbee to use it.
Can you use minicom or another serial terminal on the RaspPi to confirm that serial is working? Use minicom on the receiving end to see if you're getting anything at all?
Can you try sending and receiving with the radios connected to a PC instead of the Pi? Sending from the PC to the Pi, or vice-versa?