I am trying to make a program which constantly reads data being sent from device using serial port to computer. In addition to this whenever I enter something it is sent to device.(My main aim is to make a serial terminal emulator).
I wrote following program but it waits for any input and does not constantly read data and display on screen sent by device as thought:
ser1 = serial.Serial(com_name_to_use, auto_baud, timeout=0, write_timeout=0)
while True:
try:
# Writing Section
inp_str1 = input() # + "\n"
str1 = inp_str1.encode(encoding="ascii")
ser1.write(str1)
time.sleep(0.03)
# Reading Section
bf = ser1.readline()
print(str(bf, encoding="utf-8"), end="")
except Exception as err1:
pass
Kindly, tell how to fix it.
Related
I am currently trying to use pyserial to read the values from my handheld tachometer, the specific model is the DT-2100.
I am using python 3 and my current code looks like this:
# Imports
import serial
import time
import io
# Coding section
# Setting Parameters
port = "COM3"
baud = 38400
data = []
info = 0
# Setting the port location, baudrate, and timeout value
ser = serial.Serial(port, baud, timeout=2)
# Ensuring that the port is open
if ser.isOpen():
print(ser.name + ' is open...')
# trying to read a single value from the display
#input("Ensure that the DT-2100 is turned on...")
info = ser.write(b'CSD')
ser.write(b'CSD')
info_real = ser.readlines()
print()
print("The current value on the screen is: ", info)
print()
print("The real value on the screen is: ", info_real)
This is what I get back after running the code:
COM3 is open...
The current value on the screen is: 3
The real value on the screen is: []
Process finished with exit code 0
The main issue is that I should be getting the value that is displayed by the tachometer, which for this test was 0, but between my two attempted methods I got 3 and nothing.
Any help is greatly appreciated.
The zip file you linked to contained an xls file which seemed to detail all the commands.
All the commands seem to be wrapped in: <STX> cmd <CR>, so you are missing those.
The CSD command would need to be like this: ser.write(b'\x02CSD\r')
Similarly the reply is also wrapped in the same way and you would need to remove those bytes and interpret the rest.
I needed to write and read data with pyserial.
I'm sending the output I want with write command
and then want to check and read arrival of new data.
when I'm calling the read command it's also printing the data i have sent.
this is the code below:
#on one script:
while 1:
serial.write(str.encode("blabla111"))
bytesToRead = serial.inWaiting()
if bytesToRead is not 0:
print(serial.read(bytesToRead))
time.sleep(1)
#on second script:
while 1:
serial.write(str.encode("hello222"))
bytesToRead = serial.inWaiting()
if bytesToRead is not 0:
print(serial.read(bytesToRead))
time.sleep(1)
#print result on first script (excepting to get only :hello222)
blabla111hello222
What am I missing here?
I tried to use the flush command didn't help
My raspberry pi is connected to microcontroller over serial pin. I am trying to read the data from the serial port. The script reads the data for few seconds. However, it terminates throwing following exception
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)
I have used following python code
#!/usr/bin/python
import serial
import time
serialport = serial.Serial("/dev/ttyAMA0", 115200, timeout=.5)
while 1:
response = serialport.readlines(None)
print response
time.sleep(.05)
serialport.close()
Here is the code you should be using if you are seriously trying to just transfer and print a file:
for line in serialport.readlines().split('\n'):
print line
------------------------------------------------------------
I believe you are having problems because you are using readlines(None) instead of readline() Readline() reads it a line at a time, and will wait for each one. If reading a whole file it will be slower than readlines. But readlines() expects a whole file all at once. It is obviously not waiting for your serial transfer speed.
--------------------------------------------------
My data-logging loop receives a line every two minutes and writes it to a file. It could easily just print each line like you show in the OP.
readine() waits for each line. I have tested it to wait up to 30 minutes between lines with no problems by altering the program on the Nano.
import datetime
import serial
ser = serial.Serial("/dev/ttyUSB0",9600) --/dev/ACM0 is fine
while True :
linein = ser.readline()
date = str(datetime.datetime.now().date())
date = date[:10]
time = str(datetime.datetime.now().time())
time = time[:8]
outline = date + tab + time + tab + linein
f = open("/home/pi/python/today.dat","a")
f.write(outline)
f.close()
Maybe changing to this approach would be better for you.
I have a small python example I got off another website. I am trying to understand how to read from serial using it.
I am sending a message from a FRDM K64f board over serial and the python program reads this but returns a strange values, below is an example of one of them:
YVkJ�ZC
My python code:
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.isOpen()
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
# Python 3 users
# input = input(">> ")
if input == 'exit':
ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
ser.write(input + '\r\n')
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + out
This is my code for the board:
int main(){
Serial pc(USBTX, USBRX);
pc.baud(9600);
while(1){
char c = pc.getc();
if((c == 'w')) {
pc.printf("Hello");
}
}
}
The exact return I get is this:
Enter your commands below.
Insert "exit" to leave the application.
>> w
>>YVkJ�ZC
>>
Managed to solve this.
My declaration of serial didn't seem to be working properly.
Went back to pyserial documentation and declaring my serial like below and using readline() solved the problem.
ser = serial.Serial('/dev/ttyACM0')
I have an embedded linux device and here's what I would like to do using python:
Get the device console over serial port. I can do it like this:
>>> ser = serial.Serial('/dev/ttyUSB-17', 115200, timeout=1)
Now I want to run a tail command on the embedded device command line, like this:
# tail -f /var/log/messages
and capture the o/p and display on my python >>> console.
How do I do that ?
Just open the file inside python and keep readign from it. If needed be, in another thread:
>>> ser = serial.Serial('/dev/ttyUSB-17', 115200, timeout=1)
>>> output = open("/var/log/messages", "rb")
And inside any program loop, just do:
data = output.read()
print(data)
If you want it to just go printing on the console as you keep doing other stuff, type
in something like:
from time import sleep
from threading import Thread
class Display(Thread):
def run(self):
while True:
data = self.output.read()
if data: print(data)
sleep(1)
t = Display()
t.output = output
t.start()
very first you need to get log-in into the device.
then you can run the specified command on that device.
note:command which you are going to run must be supported by that device.
Now after opening a serial port using open() you need to find the login prompt using Read() and then write the username using write(), same thing repeat for password.
once you have logged-in you can now run the commands you needed to execute