Python Forum
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
PySerial
#1
Hello everyone,
I am opening this thread because I need to retrieve numeric data from a serial port RS232.

This is what I would like to accomplish:
1- Read data from my device (Serial Port RS232)
2- Store data in some variables
3- Read more data
4- Repeat 2,3

The way I get data from my device is the following

cat /dev/ttyUSB0 > result.txt
The problem with the above solution is :
1- I need to open a terminal
2- I am not able to read data unless I terminate the cat /dev/ttyUSB0 > result.txt

So, my question is, is there a way to do everything from Python? Is so, could someone please help me out?
Reply
#2
If you've a regular serial device, you can use pyserial. If you're using something from FTDI, you'll find also Modules for it. But you can use also pyserial.


Pyserial, Threaded linereader, Asyncio linereader

import serial


def readlines(file):
    data = []
    while True:
        chunk = file.read(1)
        if not chunk:
            yield b''.join(data)
            break
        if chunk == b'\n':
            yield b''.join(data)
            data = []
        else:
            data.append(chunk)

ser = serial.Serial('/dev/ttyUSB0', 115200)
for line in readlines(ser):
    # here you can process the data
    print(line)
The example of readlines is not ideal. You should look into the threaded or asyncio line reader, which is also in pyserial.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020