65 lines
1.8 KiB
Python
65 lines
1.8 KiB
Python
import serial
|
|
import tkinter as tk
|
|
|
|
def map_analog_to_weight(analog_value):
|
|
if analog_value >= 920:
|
|
return 0
|
|
elif analog_value >= 830:
|
|
return 10
|
|
elif analog_value >= 720:
|
|
return 20
|
|
elif analog_value >= 360:
|
|
weight = (analog_value - 360) * (20 - 50) / (720 - 360) + 50
|
|
return round(weight, 2)
|
|
elif analog_value >= 280:
|
|
weight = (analog_value - 280) * (50 - 100) / (360 - 280) + 100
|
|
return round(weight, 2)
|
|
elif analog_value >= 180:
|
|
weight = (analog_value - 180) * (100 - 200) / (280 - 180) + 200
|
|
return round(weight, 2)
|
|
else:
|
|
weight = (analog_value - 60) * (200 - 500) / (180 - 60) + 500
|
|
return round(weight, 2)
|
|
|
|
# Configure the COM port settings
|
|
com_port = 'COM12'
|
|
baud_rate = 9600
|
|
|
|
# Open the serial connection
|
|
ser = serial.Serial(com_port, baud_rate)
|
|
|
|
# Create the Tkinter window
|
|
window = tk.Tk()
|
|
window.title("Weight Display")
|
|
window.geometry("200x100")
|
|
|
|
# Create a label to display the weight
|
|
weight_label = tk.Label(window, text="Weight: -- g", font=("Arial", 16))
|
|
weight_label.pack(pady=20)
|
|
|
|
def update_weight_label(weight):
|
|
weight_label.config(text=f"Weight: {weight} g")
|
|
|
|
try:
|
|
while True:
|
|
# Read a line of data from the serial port
|
|
line = ser.readline().decode().strip()
|
|
|
|
# Convert the received data to a numeric value
|
|
try:
|
|
analog_value = int(line)
|
|
weight = map_analog_to_weight(analog_value)
|
|
update_weight_label(weight)
|
|
except ValueError:
|
|
print("Invalid data received")
|
|
|
|
# Update the Tkinter window
|
|
window.update()
|
|
|
|
except KeyboardInterrupt:
|
|
# Close the serial connection when the program is interrupted
|
|
ser.close()
|
|
|
|
# Close the Tkinter window
|
|
window.destroy()
|