python 讀取串口數(shù)據(jù)的示例
python3 讀取串口數(shù)據(jù) demo
最近在寫一個(gè)demo,zigbee串口連接樹莓派,樹莓派使用串口通信接受zigbee穿過來得值。其中我是用的樹莓派是3代B+,zigbee每隔三秒鐘從串口輸出數(shù)據(jù)。下面是python串口通信,但是不是linux的,是我在windows上寫的測試demo,python版本是3。
python串口讀取數(shù)據(jù)
# TODO 串口讀取數(shù)據(jù)# Auther wjwimport serial # 導(dǎo)入串口包import time # 導(dǎo)入時(shí)間包ser = serial.Serial('COM3',115200,timeout = 5) # 開啟com3口,波特率115200,超時(shí)5ser.flushInput() # 清空緩沖區(qū)def main(): while True: count = ser.inWaiting() # 獲取串口緩沖區(qū)數(shù)據(jù) if count !=0 : recv = ser.read(ser.in_waiting).decode('gbk') # 讀出串口數(shù)據(jù),數(shù)據(jù)采用gbk編碼 print(time.time(),' --- recv --> ', recv) # 打印一下子 time.sleep(0.1) # 延時(shí)0.1秒,免得CPU出問題if __name__ == ’__main__’: main()
上邊的代碼就已經(jīng)實(shí)現(xiàn)python串口讀數(shù)了,但大部分還需要寫入。
串口寫入數(shù)據(jù)
其實(shí)就是一個(gè)write方法,我開了一個(gè)線程,在線程里獲取串口出來的數(shù)據(jù),然后一個(gè)死循環(huán)每隔一秒發(fā)1,每隔一秒發(fā)0.
import serialimport timeimport _thread # 導(dǎo)入線程包data_ser = serial.Serial('COM3',115200,timeout = 5)data_ser.flushInput()def get_data(): while True: data_count = data_ser.inWaiting() if data_count !=0 : recv = data_ser.read(data_ser.in_waiting).decode('gbk') print(time.time(),' --- data_recv --> ', recv) time.sleep(0.1)if __name__ == ’__main__’: _thread.start_new_thread(get_data,()) # 開啟線程,執(zhí)行g(shù)et_data方法 while 1: time.sleep(20) data_ser.write(b’1’) # 發(fā)送二進(jìn)制1 time.sleep(20) data_ser.write(b’0’) # 發(fā)送二進(jìn)制0
完成了,應(yīng)該差不多就這樣!樹莓派自帶python,但是默認(rèn)是python2,可以兩行命令修改默認(rèn)python3
sudo rm /usr/bin/python
sudo ln -s /usr/bin/python3.4 /usr/bin/python
以上就是python 讀取串口數(shù)據(jù)的示例的詳細(xì)內(nèi)容,更多關(guān)于python 讀取串口數(shù)據(jù)的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Android table布局開發(fā)實(shí)現(xiàn)簡單計(jì)算器2. IntelliJ IDEA安裝插件的方法步驟3. 理解PHP5中static和const關(guān)鍵字4. php模擬實(shí)現(xiàn)斗地主發(fā)牌5. spring acegi security 1.0.0 發(fā)布6. MyBatis中的JdbcType映射使用詳解7. vue 使用localstorage實(shí)現(xiàn)面包屑的操作8. Python random庫使用方法及異常處理方案9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備