How to read data from serial port? Python - python

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...

Related

Python connection with a Device through serial port

I need help with a python code to connect with a Router or a Switch via serial port. I use pycharm from a Windows terminal.
This is what I tried:
import keyboard
ser = serial.Serial(port="COM1", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE)
while True:
ser.write('You got connected\r\n'.encode('Ascii'))
receive = ser.readline()
print(receive.decode('Ascii'))
if keyboard.is_pressed('q'):
print('User need to quit the app.')
break
ser.close()
Tried and I got errors.
What error do you get ?
This would be very helpful if you could copy/paste your errors in here.

Communicate with a terminal using pySerial

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

python pyserial read data and respond

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

Receiving data from com port by pyserial

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.

Error in working with pyserial module of python

import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyS0',
#port='/dev/ttyACM0',
baudrate=115200,
parity=serial.PARITY_ODD,
#stopbits=serial.STOPBITS_TWO,
#bytesize=serial.SEVENBITS
)
ser.isOpen() # returns true
time.sleep(1);
ser.write("some_command \n")
ser.close()
I have a embedded board. It has a serial port which is connected to my computer. I am running above script to access this serial port and run some board specific commands.
My problem
I open my serial port (using minicom in linux) separately and then run above script, It works. If I don't open serial port separately, Script doesn't work.
try
ser.write("some_command \n".encode())
alternatively try
ser.write(bytes(b"some_command \n"))

Categories

Resources