Hello everyone, I am a ruffian balance, is a serious technical ruffian. Today ruffian balance to introduce you is the serial port debugging tool Pzh-py-COM birth of the serial port function.
Serial port debugging assistant is the core of course is the serial port data transceiver and display function, pzh-py-com with the help of pySerial library to achieve serial transceiver function, today ruffian balance for everyone to introduce pySerial is how to play a function in pzh-py-com.
Introduction to pySerial
PySerial is a python library designed by Chris Liechti to implement serial port access. The library was launched in 2001 and has been continuously updated to date. Pzh-py-com uses pySerial 3.4. PySerial use is very simple and available on its website through the its API: pythonhosted.org/pyserial/py… , ruffian sorted out the more commonly used API as follows:
class Serial(SerialBase) :
Initialize serial port parameters
def __init__(self, *args, **kwargs) :
# Open serial port
def open(self) :
# Disable serial port
def close(self) :
Get serial port status
def isOpen(self) :
# set input_buffer/output_buffer size
def set_buffer_size(self, rx_size=4096, tx_size=None) :
Get the number of bytes in the input_buffer
def inWaiting(self) :
Read bytes from serial port
def read(self, size=1) :
# to empty input_buffer
def reset_input_buffer(self) :
Write all data in data to serial port
def write(self, data) :
Wait until all the data in the output_buffer is sent
def flush(self) :
# to empty output_buffer
def reset_output_buffer(self) :
Copy the code
PySerial uses a method with the same name as the parameter, and does not require a call to open() or close() to deactivate it. These methods are implemented by calling a method in Serial called _reconfigure_port().
Parameter names | Functional explanation | Note/Configurable value |
---|---|---|
port | The device name | /dev/ttyUSB0 on GNU/Linux or COM3 on Windows |
baudrate (int) | Baud rate | / |
bytesize | Data bit Number of bits | FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS |
stopbits | Stop bit | STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO |
parity | Parity bit | PARITY_NONE, PARITY_EVEN, PARITY_ODD PARITY_MARK, PARITY_SPACE |
timeout (float) | Receive a timeout | None: Blocking mode 0: non-blocking mode x: timeout period x seconds |
write_timeout (float) | Send timeout | With a timeout |
Two, JaysPyCOM serial port function realization
The serial port function code is mainly divided into three parts: configuration function realization, receiving function realization, sending function realization. To implement these functions, you need to import two modules, serial and threading. Serial is the pySerial library. Threading is python’s own threading library, whose functions are described in the following code. In addition, two global variables are defined, s_serialPort and s_recvInterval. S_serialPort is an object instance of the serial port device, and s_recvInterval is the thread interval.
import serial
import threading
s_serialPort = serial.Serial()
s_recvInterval = 0.5
Copy the code
2.1 Serial Port Configuration
OpenClosePort (), all available ports are closed by default when the software is started. If the user selects the configuration parameters (serial number, baud rate…) OpenClosePort () is executed. In openClosePort(), we need to configure s_serialPort and Open the specified serial port device.
class mainWin(win.com_win) :
def setPort ( self ) :
s_serialPort.port = self.m_textCtrl_comPort.GetLineText(0)
def setBaudrate ( self ) :
index = self.m_choice_baudrate.GetSelection()
s_serialPort.baudrate = int(self.m_choice_baudrate.GetString(index))
def setDatabits ( self ) :
#...
def setStopbits ( self ) :
#...
def setParitybits ( self ) :
#...
def openClosePort( self, event ) :
if s_serialPort.isOpen():
s_serialPort.close()
self.m_button_openClose.SetLabel('Open')
else:
Assign the input value from the GUI configuration panel to s_serialPort
self.setPort()
self.setBaudrate()
self.setDatabits()
self.setStopbits()
self.setParitybits()
Open the serial port device specified by s_serialPort
s_serialPort.open()
self.m_button_openClose.SetLabel('Close')
s_serialPort.reset_input_buffer()
s_serialPort.reset_output_buffer()
# Enable serial port receiving thread (execute periodically every 0.5 seconds)
threading.Timer(s_recvInterval, self.recvData).start()
Copy the code
PySerial will automatically store data to the input_buffer corresponding to s_serialPort once it is enabled on the RXD line. But they don’t actively inform us. How do we know if there is any data in input_buffer? In this case, we need to start a timed thread that will check the input_buffer to see if there is any data, so we need to create a serial port receiver thread recvData() while the serial port device is turned on.
2.2 Serial Port Reception Function
RecvData () is the threading.timer () thread. This is a software Timer that can only time out once to trigger the execution of a task. If you want the task loop to fire, add a call to threading.timer () in the task itself.
def clearRecvDisplay( self, event ) :
self.m_textCtrl_recv.Clear()
def setRecvFormat( self, event ) :
event.Skip()
def recvData( self ) :
if s_serialPort.isOpen():
Get the number of data in input_buffer
num = s_serialPort.inWaiting()
ifnum ! =0:
Get the data in input_buffer and display it in the receive display box on the GUI interface
data = s_serialPort.read(num)
self.m_textCtrl_recv.write(data)
# this sentence is the key to the thread being able to execute regularly
threading.Timer(s_recvInterval, self.recvData).start()
Copy the code
2.3 Serial Port Sending Function
The serial port sending function is much simpler than the serial port receiving function. The serial port sending function is mainly to implement the callback function of the “Send” button on the GUI interface, namely sendData(). The code implementation is relatively simple and will not be described.
def clearSendDisplay( self, event ) :
self.m_textCtrl_send.Clear()
def setSendFormat( self, event ) :
event.Skip()
def sendData( self, event ) :
if s_serialPort.isOpen():
Get the data in the send input box and send it through the serial port
lines = self.m_textCtrl_send.GetNumberOfLines()
for i in range(0, lines):
data = self.m_textCtrl_send.GetLineText(i)
s_serialPort.write(str(data))
else:
self.m_textCtrl_send.Clear()
self.m_textCtrl_send.write('Port is not open')
Copy the code
At present, the serial port transceiver and display implementation are based on characters, that is, only ASCII characters are supported in the sending input box and receiving display box. The Char/Hex display conversion function (setRecvFormat()/setSendFormat()) has not been added, which will be further optimized in the future.
At this point, serial port debugging tool pzh-py-com birth of serial port function to achieve riffrump balance will be introduced to the end, applause where ~~~
Welcome to subscribe to
The article will be published on my blog park homepage, CSDN homepage and wechat public account platform at the same time.
Wechat search “ruffian balance embedded” or scan the following two-dimensional code, you can see the first time on the phone oh.