[PYTHON] Serial communication with Raspberry Pi + PySerial

Introduction

I wanted to communicate serially with Raspberry Pi, so I tried communication using USB serial conversion. I referred to "I tried serial communication with Raspberry Pi". A reception timeout has been added to the reception processing on the assumption that the processing will be performed in the order of command transmission → command reception.

environment

Installation

--Enter the following command to install pySerial. --Installation of pipenv is omitted.

$ pipenv install pyserial

USB serial conversion

I used FT232 USB serial conversion cable. If it is equipped with the FT232 chip, it seems to be recognized without adding a driver.

Check the connection destination with the following command.

$ ls -la /dev/ttyUSB*

If it is the first unit, the connection destination will be'/ dev / ttyUSB0'.

note: When communicating with Rasberry Pi on a PC (Windows / Mac / Linux), use a crossover cable. Since the Rasberry Pi is also a PC, there is a cross cable between the PCs, and the connection with communication equipment is straight (often).

code

Serial communication class

--It is assumed that processing is performed in the order of command transmission → command reception. (With timeout) --You can explicitly open / close the serial port. (Because it was necessary for personal implementation)

sample.py


# -*- coding: utf-8 -*-

import serial
import time
import threading

"""
Serial communication class
"""
class SampleComm:
    #Initialization
    def __init__(self):
        #Open flag
        self.isPortOpen = False
        #received data
        self.recvData = bytearray()
        #Event generation
        self.event = threading.Event()

    #Waiting for data reception(With timeout[sec])
    def recv(self, timeout=3):
        #Get time for timeout
        time_start = time.time()
        time_end = time_start
        #Clear thread waiting event
        self.event.clear()
        #Clear received data
        self.recvData.clear()
        #Received result True:Success False:Failure(time out)
        result = False

        #Waiting for data reception
        while not self.event.is_set():
            #Time-out check
            time_end = time.time()
            if (time_end - time_start > timeout):
                #Data transmission / reception stopped and failed(time out)To
                result = False
                self.stop()
                print("timeout:{0}sec".format(timeout))
                break

            #Read received data
            buff = self.comm.read()

            #Received data judgment
            if len(buff) > 0:
                #Add received data
                self.recvData.extend(buff)
                # (Temporary)Success if \ n has been received
                if (self.recvData.find(b'\n')) >= 0:
                    #Stop sending and receiving data and make it successful
                    result = True
                    self.stop()
                    break

        #Returns the result
        return (result, self.recvData)

    #Data transmission
    def send(self, data):
        self.comm.write(data)

    #Stop data transmission / reception
    def stop(self):
        self.event.set()

    #Cyril port open
    def open(self, tty, baud='115200'):
        try:
            self.comm = serial.Serial(tty, baud, timeout=0.1)
            self.isPortOpen = True
        except Exception as e:
            self.isPortOpen = False

        return self.isPortOpen

    #Serial port closed(Explicitly close)
    def close(self):
        self.stop()
        if (self.isPortOpen):
            self.comm.close()
        self.isPortOpen = False

if __name__ == "__main__":
    #Open serial
    comm = SampleComm()
    comm.open('/dev/ttyUSB0', '115200')

    #Data transmission
    comm.send('test'.encode())
    #Data reception(time out=10sec)
    result, data = comm.recv(10)
    print(result)
    print(data)

    #Close serial
    comm.close();

how to use

In pySerial version 2.5 and above, the argument of write () is bytearray (). If you want to send a string, do the appropriate encode (). str.encode () defaults to'utf-8'.

#Open serial
comm = SampleComm()
comm.open('/dev/ttyUSB0', '115200')

#Data transmission
comm.send('sample'.encode())
#Data reception(time out=10sec)
result, data = comm.recv(10)
print(result)
print(data)

#Close serial
comm.close();

You can also check the operation by executing sample.py.

$ python sample.py

in conclusion

Communication with the device is often processed in the order of command transmission → command reception, and I made it because I wanted to execute the reception processing with a timeout. It is necessary to change the judgment of reception completion as appropriate. I hope it will be helpful for similar cases in serial communication.

Recommended Posts

Serial communication with Raspberry Pi + PySerial
Enable UART + serial communication on Raspberry Pi
Serial communication with Python
GPGPU with Raspberry Pi
DigitalSignage with Raspberry Pi
Serial communication between Raspberry pi --Arduino Uno (Python)
Mutter plants with Raspberry Pi
[Raspberry Pi] Stepping motor control with Raspberry Pi
Testing uart communication on Raspberry Pi
Servo motor control with Raspberry Pi
OS setup with Raspberry Pi Imager
Try L Chika with raspberry pi
Just check serial communication with tk
VPN server construction with Raspberry Pi
Try moving 3 servos with Raspberry Pi
Using a webcam with Raspberry Pi
Measure SIM signal strength with Raspberry Pi
Hello World with Raspberry Pi + Minecraft Pi Edition
Build a Tensorflow environment with Raspberry Pi [2020]
Get BITCOIN LTP information with Raspberry PI
Try fishing for smelt with Raspberry Pi
Programming normally with Node-RED programming on Raspberry Pi 3
Improved motion sensor made with Raspberry Pi
Try Object detection with Raspberry Pi 4 + Coral
Power SG-90 servo motor with raspberry pi
Working with sensors on Mathematica on Raspberry Pi
Use PIR motion sensor with raspberry Pi
Make a wash-drying timer with a Raspberry Pi
Infer Custom Vision model with Raspberry Pi
Operate an oscilloscope with a Raspberry Pi
Create a car meter with raspberry pi
Inkbird IBS-TH1 value logged with Raspberry Pi
Working with GPS on Raspberry Pi 3 Python
Raspberry Pi backup
Discord bot with python raspberry pi zero with [Notes]
I tried L-Chika with Raspberry Pi 4 (Python edition)
Enjoy electronic work with GPIO on Raspberry Pi
MQTT RC car with Arduino and Raspberry Pi
Power on / off your PC with raspberry pi
Use Majoca Iris elongated LCD with Raspberry Pi
CSV output of pulse data with Raspberry Pi (CSV output)
Observe the Geminids meteor shower with Raspberry Pi 4
Get CPU information of Raspberry Pi with Python
Play with your Ubuntu desktop on your Raspberry Pi 4
Get temperature and humidity with DHT11 and Raspberry Pi
Stock investment analysis app made with Raspberry Pi
Logging Inkbird IBS-TH1 mini values with Raspberry Pi
Connect to MySQL with Python on Raspberry Pi
GPS tracking with Raspberry Pi 4B + BU-353S4 (Python)
Measure CPU temperature of Raspberry Pi with Python
Record temperature and humidity with systemd on Raspberry Pi
Socket communication with Python
Machine learning with Raspberry Pi 4 and Coral USB Accelerator
Run LEDmatrix interactively with Raspberry Pi 3B + on Slackbot
Using the digital illuminance sensor TSL2561 with Raspberry Pi
What is Raspberry Pi?
Easy IoT to start with Raspberry Pi and MESH
Display images taken with the Raspberry Pi camera module
Using Akizuki Denshi's 4WD car FT-MC-004 with Raspberry Pi
Try to visualize the room with Raspberry Pi, part 1
pigpio on Raspberry pi