Python learning threading

import threading
import time
import random
import serial.tools.list_ports

def thread1():
	global num
	while True:
		if num >= 0:
			lock2.acquire()
			num -= 1
			a = str(random.randint(100,299))
			c = str(random.randint(300,599))
			e = str(random.randint(600,999))
			b = ";motorspeed:{0};carspeed:{1};watertemp:{2};".format(a,c,e)
			uart_fd.write(b.encode())
			uart_fd.flushInput()
			time.sleep(0.1)
			lock1.release()
		else:
			exit()


def thread2():
	global num
	while True:
		if num >= 0:
			lock1.acquire()
			read_data = uart_fd.readline()
			print(read_data)
			uart_fd.flushOutput()
			time.sleep(0.1)
			lock2.release()
		else:
			print("end")
			uart_fd.close()
			exit()


if __name__ == "__main__":
	global num
	num = random.randint(100, 200)
	global count
	count = 0
	uartlist = list(serial.tools.list_ports.comports())
	if len(uartlist) <= 0:
		print("can't find the uart")
	else:
		uart_name = str(uartlist[0])
		my_uart = uart_name.split()
		uart_fd = serial.Serial(my_uart[0], int(115200), timeout=2, parity=serial.PARITY_NONE, stopbits=1)


	lock1 = threading.Lock()
	lock2 =threading.Lock()
	th1 = threading.Thread(None, target=thread1)
	th2 = threading.Thread(None, target=thread2)
	lock1.acquire()
	th1.start()
	th2.start()
	print("start")

Operate the serial port of the pc through python to communicate with the stm32 serial port, one thread only sends, and the other thread is read-only, and then try to add crc verification

Guess you like

Origin blog.csdn.net/cp_srd/article/details/104656297