要在 Ubuntu 上使用 /dev/ttyUSB0
設備編寫一個簡單的串口收發程序,你可以使用 Python,結合 pyserial
庫來實現。這種方法相對簡單,適用于各種串行通信任務。以下是如何在 Python 中編寫串口收發程序的步驟及代碼示例:
步驟 1: 安裝 PySerial
首先確保安裝了 pyserial
,這是一個流行的 Python 庫,用于處理串行通信:
pip install pyserial
步驟 2: 編寫串口收發代碼
以下是一個簡單的 Python 腳本,用于打開 /dev/ttyUSB0
串口,配置波特率和其他參數,然后接收和發送數據。
import serial
import timedef open_serial(port, baud_rate):"""打開串口并配置基本參數"""try:ser = serial.Serial(port, baud_rate, timeout=1,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS)if ser.is_open:print(f"Serial port {port} opened successfully")return serexcept Exception as e:print(f"Failed to open serial port: {e}")return Nonedef read_from_serial(ser):"""從串口讀取數據"""try:data = ser.readline() # 讀取一行數據if data:print(f"Received: {data.decode().strip()}")except Exception as e:print(f"Failed to read data: {e}")def write_to_serial(ser, data):"""向串口發送數據"""try:ser.write(data.encode())print(f"Sent: {data}")except Exception as e:print(f"Failed to send data: {e}")def main():port = "/dev/ttyUSB0"baud_rate = 9600# 打開串口ser = open_serial(port, baud_rate)if ser and ser.is_open:try:# 循環接收和發送數據while True:read_from_serial(ser)time.sleep(1)write_to_serial(ser, "Hello from Python!")time.sleep(1)finally:ser.close()print("Serial port closed")if __name__ == "__main__":main()
程序說明
- 打開串口:
open_serial
函數嘗試打開指定的串口并配置波特率等參數。 - 讀取數據:
read_from_serial
函數從串口讀取一行數據,并將其解碼并打印。 - 發送數據:
write_to_serial
函數向串口發送字符串。 - 主循環:
main
函數中的循環演示了如何連續讀取和發送數據。
注意事項
- 確保你有足夠的權限訪問
/dev/ttyUSB0
。如果沒有,你可能需要使用sudo
來運行你的腳本,或將用戶添加到dialout
組。 - 波特率和其他串口參數應該與你要通信的設備相匹配。
這個簡單的示例提供了使用 Python 和 PySerial 進行串口通信的基礎。