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)defdate_time_str(date_time):return datetime.strftime(date_time, date_time_format)defloop(n_loop, n_sec):lock.acquire(blocking=True,timeout=2)serial.write("1".encode())sleep(n_sec)print(f'線程({n_loop})開始執行:{date_time_str(datetime.now())},先休眠({n_sec})秒')serial.write("0".encode())sleep(n_sec)lock.release()print(f'線程({n_loop})休眠結束,結束于:{date_time_str(datetime.now())}')defbegin(n_loop,sec):sleep(sec)serial.write("yes".encode())data = serial.read(20)print(data.decode())# 為線程定義一個函數defprint_time(threadName, delay):serial.write("1".encode())sleep(delay)serial.write("0".encode())sleep(delay)defreceive(threadName,delay):serial.write("999".encode())data = serial.read(20)print('this is'+str(data))sleep(delay)# 創建兩個線程defmain():print(f'---所有線程開始執行:{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'---所有線程執行結束于:{date_time_str(datetime.now())}')if __name__ =='__main__':main()
結果:
亮燈也成功了。
然后記錄一下關于python的將字典轉化為json:
import jsonprint(json.dumps(list('abcde')))dict={"time":1,"localtion":9.8}
ni = json.dumps(dict)print(dict)print(ni)