簡體   English   中英

解析使用Python從USB讀取的串行數據

[英]Parsing serial data read in from USB using Python

我對python完全陌生。

我正在使用以下代碼從USB設備提取數據,該設備正在使用printf()將數據打印到我的樹莓派上。 我正在使用以下python代碼讀取此數據並將其打印到屏幕上:

 #!/usr/bin/python
    import serial
    ser = serial.Serial(
    port='/dev/ttyUSB0',\
    baudrate=115200,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
    timeout=0)
    print("connected to: " + ser.portstr)
    ser.write("help\n");
    while True:
    line = ser.readline();
    if line:
        print(line),
    ser.close()

該代碼按預期輸出以下結果(這是我使用printf()的結果):

Received Ticks are: 380 and nodeID is: 1

如何解析行變量,以便將Ticks(380)和nodeID(1)的數量保存為兩個變量,以便可以將這些變量用於python中的HTTP POST請求?

分割字符串,然后取所需的部分:

>>> s = "Received Ticks are: 380 and nodeID is: 1"
>>> s.split()
['Received', 'Ticks', 'are:', '380', 'and', 'nodeID', 'is:', '1']
>>> words = s.split()
>>> words[3]
'380'
>>> words[7]
'1'
>>> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM