python学习之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")

通过python操作pc机的串口与stm32串口通信,一个线程只发,另一个线程只读,之后加入crc校验试试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值