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.
--Enter the following command to install pySerial. --Installation of pipenv is omitted.
$ pipenv install pyserial
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).
--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();
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
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