業務上是 有兩個按鈕 一個是打開 一個是關閉
記得先看儀器的說明說調成一直循環向電腦發送數據
誤區:一開始在關閉的時候總想着殺死線程也找到了方案. 後來看殺死線程處理不太友好.
所以加了off來控制線程的存活
沒寫註釋是英文起的都非常通俗易懂 比較難看懂的英語已經用拼音來了.
我也建議. 如果開發時候碰到一些自己都不明白的單詞 建議用拼接吧.
變量名的存在就是讓人看起來通俗易懂 如果你自己都不明白什麼意思反而用了不恰當的單詞還不如拼音
import serial
import serial.tools.list_ports
import threading
from time import sleep
class EletronicScale(object):
"""
稱重儀
"""
def __init__(self):
self.com = None
self.serial = None
self.off = None
def open_port(self):
if self.off != None and self.off != False:
print("已連接請勿重複連接")
return
try:
self.port_list = list(serial.tools.list_ports.comports())
for prot in self.port_list:
if prot.vid == 6790:
self.com = prot.device
if self.com != None:
self.serial = serial.Serial(self.com, 9600, timeout=0.5)
self.off = True
t = threading.Thread(target=self.xunhuanjieshoushuju)
t.start()
print("連接成功")
else:
print("請連接稱重儀")
except Exception as e:
raise e
def xunhuanjieshoushuju(self):
while True:
if self.off == False:
break
data = self.serial.read_all()
if len(data) > 10:
print("Weight%d" % (float(data.decode("utf8")[1:8]))
sleep(0.02)
def threading_data(self):
t = threading.Thread(target=self.xunhuanjieshoushuju)
t.start()
def close_port(self):
self.off = False
sleep(0.3)
self.serial.close()
print("關閉成功")
if __name__ == '__main__':
ele = EletronicScale()
ele.open_port()
ele.serial.isOpen()
t = threading.Thread(target=ele.xunhuanjieshoushuju)
t.start()
while True:
cur = int(input("1111"))
if cur == 2:
ele.off = False
sleep(0.3)
ele.close_prot()
print("關閉端口")
print(t.is_alive())
if cur == 1:
ele.off = True
ele.open_port()
t = threading.Thread(target=ele.xunhuanjieshoushuju)
t.start()
print("開啓線程")
print(t.is_alive())
python對接稱重儀(獲取串口數據)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.