日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

【实例记录】在ubuntu上运行python实现与单片机多线程串口通信

發(fā)布時(shí)間:2024/9/30 56 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【实例记录】在ubuntu上运行python实现与单片机多线程串口通信 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

  • 工具
    • 步驟

工具

工具:自己電腦雙系統(tǒng)的ubuntu18.04,單片機(jī)esp8266,一個(gè)usb轉(zhuǎn)ttl模塊,ubuntu上已經(jīng)下載了python的3.6和pip,還需要pip install serial
首先在windows下測(cè)試板子是否能順利收發(fā)數(shù)據(jù):
打開串口調(diào)試助手
這里不需要用usb轉(zhuǎn)ttl插windows的usb口,直接把esp8266連安卓線插上就好

板子里的程序是發(fā)1亮燈,發(fā)0關(guān)燈,發(fā)其他的則原樣返回,可見結(jié)果是對(duì)的,亮燈也如預(yù)期。

步驟

模塊和單片機(jī)連接:
G-GND
5V-VIN
TXD-RX
RXD-TX
需要知識(shí):串口通信 多線程 線程鎖
打開串口權(quán)限
sudo chmod 777 /dev/ttyUSB0

注意杜邦線一定要接對(duì),不然可能單片機(jī)沒有上電都不知道
寫代碼:

import threading import serial import time from time import sleep from threading import Lock from datetime import datetime loops=[2, 4] lock=Lock() date_time_format='%y-%M-%d %H:%M:%S' serial = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.5) def date_time_str(date_time):return datetime.strftime(date_time, date_time_format)def loop(n_loop, n_sec):lock.acquire(blocking=True,timeout=2)serial.write("1".encode())sleep(n_sec)print(f'線程({n_loop})開始執(zhí)行:{date_time_str(datetime.now())},先休眠({n_sec})秒')serial.write("0".encode())sleep(n_sec)lock.release()print(f'線程({n_loop})休眠結(jié)束,結(jié)束于:{date_time_str(datetime.now())}')def begin(n_loop,sec):sleep(sec)serial.write("yes".encode())data = serial.read(20)print(data.decode())# 為線程定義一個(gè)函數(shù)def print_time(threadName, delay):serial.write("1".encode())sleep(delay)serial.write("0".encode())sleep(delay)def receive(threadName,delay):serial.write("999".encode())data = serial.read(20)print('this is'+str(data))sleep(delay)# 創(chuàng)建兩個(gè)線程def main():print(f'---所有線程開始執(zhí)行:{date_time_str(datetime.now())}')threads=[]n_loops=range(len(loops))t=threading.Thread(target=loop, args=(1, loops[0]))threads.append(t)m=threading.Thread(target=begin,args=(2,loops[1]))threads.append(m)for i in n_loops: # start threadsthreads[i].start()for i in n_loops: # wait for allthreads[i].join() # threads to finishprint(f'---所有線程執(zhí)行結(jié)束于:{date_time_str(datetime.now())}')if __name__ == '__main__':main()

結(jié)果:

亮燈也成功了。

然后記錄一下關(guān)于python的將字典轉(zhuǎn)化為json:

import jsonprint(json.dumps(list('abcde'))) dict = {"time":1,"localtion":9.8} ni = json.dumps(dict) print(dict) print(ni)

總結(jié)

以上是生活随笔為你收集整理的【实例记录】在ubuntu上运行python实现与单片机多线程串口通信的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。