如何从称重秤的输出中获取值

2024-10-01 07:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从称重机的输出中得到重量的值。我已使用RS232到USB转换器将称重机与windows PC连接。我正在使用python连接和获取数据。以下是用于获取的代码

import time
import serial
import Tkinter
import re

window = Tkinter.Tk()
 
def PrintWeight():
    ser = serial.Serial(
        port='COM6',
        baudrate=2400,
        timeout=None,
        parity=serial.PARITY_EVEN,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.SEVENBITS
    )
    ser.isOpen()
    while 1 :
            bytesToRead = ser.inWaiting()
            data = ser.read(bytesToRead)
            time.sleep(1)
            print(str(data))

MyTitle = Tkinter.Label(window, text="Weight Display",font="TimesRoman 16")
MyTitle.pack()

MyButton = Tkinter.Button(window, text="FETCH", command=PrintWeight)
MyButton.pack()
 
dice_thrown = Tkinter.Label(window, font="Helvetica 16 bold")
dice_thrown.pack()
 
window.mainloop()

我得到的输出是- enter image description here

如所附图片所示,方括号内的000050是重量值,即50 grms。如何从这一长系列数据中仅获取数值数据,即仅50

甚至我也使用以下代码从字符串中提取数字数据-

s = str(data)
m = re.search(r"\[([A-Za-z0-9_]+)\]", s)
print m.group(1)

但这是一个错误-- AttributeError: 'NoneType' object has no attribute 'group'

请帮帮我

谢谢


Tags: 代码importredatatimetkinterserialwindow