溫馨提示×

Ubuntu串口如何實現(xiàn)多線程通信

小樊
89
2024-07-12 02:14:35
欄目: 智能運維

在Ubuntu系統(tǒng)中,可以使用多種方式來實現(xiàn)串口的多線程通信,其中一種比較常見且簡單的方法是使用Python編程語言結(jié)合pySerial庫來實現(xiàn)。

以下是一個示例代碼,演示了如何在Ubuntu系統(tǒng)中使用Python和pySerial庫實現(xiàn)串口的多線程通信:

import serial
import threading

# 串口配置
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)

# 讀取串口數(shù)據(jù)的線程
def read_serial():
    while True:
        data = ser.readline().decode().strip()
        if data:
            print(f"Received data: {data}")

# 寫入串口數(shù)據(jù)的線程
def write_serial():
    while True:
        data = input("Enter data to send: ")
        ser.write(data.encode())

# 創(chuàng)建并啟動讀取串口數(shù)據(jù)的線程
read_thread = threading.Thread(target=read_serial)
read_thread.start()

# 創(chuàng)建并啟動寫入串口數(shù)據(jù)的線程
write_thread = threading.Thread(target=write_serial)
write_thread.start()

在上面的代碼中,首先配置了串口(/dev/ttyUSB0),然后創(chuàng)建了兩個線程,一個用于讀取串口數(shù)據(jù),另一個用于寫入串口數(shù)據(jù)。read_serial函數(shù)通過ser.readline()方法讀取串口數(shù)據(jù),write_serial函數(shù)通過ser.write()方法向串口寫入數(shù)據(jù)。

通過這種方式,我們可以實現(xiàn)串口的收發(fā)數(shù)據(jù)功能,并且讀取和寫入串口數(shù)據(jù)的操作是在不同的線程中進行,保證了并發(fā)性和實時性。

0