[PYTHON] Weighing instrument using raspberry pi and hx711 (GUI display on Tkinter)

I also had a need for weight measurement and result display according to weight at work, so I made a prototype. IMG_20200418_151503.jpg

1. Touch panel display setup

For display only, an HDMI-connected display or an inorganic CLI can be used, but the target is not a programmer but an amateur like myself. Therefore, we will arrange a touch panel display so that you can perform simple operations using the GUI display and touch panel. 81BVrYzOaqL.AC_SL1500.jpg https://www.amazon.co.jp/dp/B075K56C12/ This does not occupy GPIO, so it is ideal for load cell connection!

The setup method is introduced by the ancestors in an easy-to-understand manner, so I will post a link.

Note of neural assembly: I received a small touch screen that GPIO of Raspberry Pi can pull out, so I tried using it for electronic work https://neuralassembly.blogspot.com/2017/12/raspberry-pigpio.html

2. Load cell amplifier for weight measurement

It seems that it is easy and common to use the hx711 of the A / D converter as a load cell amplifier to measure the weight with raspberry pi. (Since there is a lot of noise, there are places where it says that we do not recommend specifications if you can afford it ...)

This time, I also wanted a load cell, so I bought a kit with a set of weight measurement tables in addition to the following MAX 5 kg load cell hx711. 61qE+6hhiBL.AC_SL1000.jpg

https://www.amazon.co.jp/dp/B07JL7NP3F/

2.1. Connection between hx711 and raspbberry pi

Connect to the raspberry pi with the flat cable included in the hx711 kit.

hx711 raspberypi
GND GND(6pin)
DT GPIO5(29pin)
SCK GPIN6(31pin)
VCC 5V(4pin)

2.2. hx711 setup

Get the hx711 library for python from github.

$ git clone https://github.com/tatobari/hx711py
Cloning into 'hx711py'...
remote: Counting objects: 77, done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 77 (delta 3), reused 5 (delta 2), pack-reused 68
Unpacking objects: 100% (77/77), done.

I will actually run it.

$ python hx711/example.py
Tare done! Add weight now...
490
458
445
451
459
483
467
486
511
412
^CCleaning... ←ctrl+End with c
Bye!

If it is connected correctly, the numbers should come out like this. Now, since this number is just displaying the output of the load cell, it must be calibrated to a number equivalent to the weight.

For example, when a weight with a clear weight (or a weight whose weight is known on a kitchen scale, etc. is used as a weight) is placed on the load cell.

Tare done! Add weight now...
458
445
451 ← Place a weight here
4475
13929
212399
212419
212441
212402
212399
212460
212422
212385
212456
212424
212463
212451
212455
212379
212438
212457
212451
212390
^CCleaning...
Bye!

Suppose you get a result like this: In this case, the correction value is the average value of 212399 to 212390, which has stable values, divided by the actual weight. Assuming that the weight of the weight is 200g, 212417 (average value) / 200g (actual weight) = 1062 is the correction value. The correction value is assigned to referenceUnit in ʻexample.py`.

example.py


…
#referenceUnit = 1
referenceUnit = 1062
…

is not it. Now you can get the actual weight (apart from disturbances such as noise and temperature).

3. GUI display with Tkinter

For self-satisfaction, an inorganic CLI display is sufficient, but if you want to say "Wow!" To an amateur, you will need a GUI display (laughs). However, in fact, just by displaying the GUI, the degree of perfection of the program looks different, and the appeal from bosses and colleagues should change.

This time, I decided to display the GUI with Tkinter by referring to the following site.

Equipment enthusiasts: GUI monitoring of temperature with Raspberry Pi and Tkinter http://setsubi.no-mania.com/raspberry%20pi/%E3%83%A9%E3%82%BA%E3%83%91%E3%82%A4%E3%81%A8tkinter%E3%81%A7%E6%B8%A9%E5%BA%A6%E3%81%AEgui%E7%9B%A3%E8%A6%96

The full code is below. For the sake of clarity, the display is based on the weight and the number of 100-yen balls placed. Although it is redundant, I will leave the commented out part as it is for those who add / modify from ʻexample.py`.

weight_choose.py


#! /usr/bin/python3
# -*- coding: utf-8 -*-

import time
import sys
import math
import tkinter as tk

EMULATE_HX711=False

#referenceUnit = 1
referenceUnit = 1062

if not EMULATE_HX711:
    import RPi.GPIO as GPIO
    from hx711 import HX711
else:
    from emulated_hx711 import HX711

def cleanAndExit():
    print("Cleaning...")

    if not EMULATE_HX711:
        GPIO.cleanup()
        
    print("Bye!")
    root.destroy()
    root.quit()
    sys.exit()

hx = HX711(5, 6)

# I've found out that, for some reason, the order of the bytes is not always the same between versions of python, numpy and the hx711 itself.
# Still need to figure out why does it change.
# If you're experiencing super random values, change these values to MSB or LSB until to get more stable values.
# There is some code below to debug and log the order of the bits and the bytes.
# The first parameter is the order in which the bytes are used to build the "long" value.
# The second paramter is the order of the bits inside each byte.
# According to the HX711 Datasheet, the second parameter is MSB so you shouldn't need to modify it.
hx.set_reading_format("MSB", "MSB")

# HOW TO CALCULATE THE REFFERENCE UNIT
# To set the reference unit to 1. Put 1kg on your sensor or anything you have and know exactly how much it weights.
# In this case, 92 is 1 gram because, with 1 as a reference unit I got numbers near 0 without any weight
# and I got numbers around 184000 when I added 2kg. So, according to the rule of thirds:
# If 2000 grams is 184000 then 1000 grams is 184000 / 2000 = 92.
#hx.set_reference_unit(113)
hx.set_reference_unit(referenceUnit)

hx.reset()

hx.tare()

print("Tare done! Add weight now...")

# to use both channels, you'll need to tare them both
#hx.tare_A()
#hx.tare_B()

#while True:
#    try:
        # These three lines are usefull to debug wether to use MSB or LSB in the reading formats
        # for the first parameter of "hx.set_reading_format("LSB", "MSB")".
        # Comment the two lines "val = hx.get_weight(5)" and "print val" and uncomment these three lines to see what it prints.
        
        # np_arr8_string = hx.get_np_arr8_string()
        # binary_string = hx.get_binary_string()
        # print binary_string + " " + np_arr8_string
        
        # Prints the weight. Comment if you're debbuging the MSB and LSB issue
#        val = hx.get_weight(5)
#        print(val)


        # To get weight from both channels (if you have load cells hooked up 
        # to both channel A and B), do something like this
        #val_A = hx.get_weight_A(5)
        #val_B = hx.get_weight_B(5)
        #print "A: %s  B: %s" % ( val_A, val_B )

#        hx.power_down()
#        hx.power_up()
#        time.sleep(0.1)

#    except (KeyboardInterrupt, SystemExit):
#        cleanAndExit()

def zero():
    hx.reset()
    hx.tare()

root = tk.Tk()
root.geometry("800x500")
root.title(u"Weight scale")

sbtn = tk.Button(root, text='End',font = ('', 50), command=cleanAndExit)
sbtn.pack(side = 'bottom')

zbtn = tk.Button(root, text='Zero reset',font = ('', 30), command=zero)
zbtn.pack(side = 'bottom')

title = tk.Label(text='weight[g]',font = ('', 70))
title.pack()

while True:
    val = hx.get_weight(5)
    print(val)
    weight = tk.Label(text='{:.1f}'.format(val),font = ('', 70))
    weight.pack()
    
    txit = tk.Label(text='',font = ('', 70))
    if val >= 3.8 and val <= 5.8:
        txit = tk.Label(text='1 100 yen ball',font = ('', 70))
    elif val >= 8.1 and val <= 11.0:
        txit = tk.Label(text='Two 100-yen balls',font = ('', 70))
    elif  val >= 12.6 and val <= 16.1:
        txit = tk.Label(text='3 100-yen balls',font = ('', 70))
    elif  val >= 17.2 and val <= 21.2:
        txit = tk.Label(text='4 100-yen balls',font = ('', 70))
    elif  val >= 21.7 and val <= 26.2:
        txit = tk.Label(text='5 100-yen balls',font = ('', 70))

    txit.pack()
    
    weight.update()
    txit.update()
    weight.forget()
    txit.forget()
    hx.power_down()
    hx.power_up()
    time.sleep(0.5)

root.mainloop()

The zero reset button is used to reset 0g, and the end button is used to terminate the program. The result of the actual operation is as follows.

weight_choose.py.gif https://youtu.be/YzPybzAu_xk

After that, if you start it automatically with autostart, it looks more like a real measuring instrument and is cool! Thank you for your hard work.

Recommended Posts

Weighing instrument using raspberry pi and hx711 (GUI display on Tkinter)
MQTT on Raspberry Pi and Mac
Try using ArUco on Raspberry Pi
Input and output display images directly using the frame buffer (/ dev / fb0) on Raspberry Pi
Detect "brightness" using python on Raspberry Pi 3!
Run servomotor on Raspberry Pi 3 using python
Detect temperature using python on Raspberry Pi 3!
Initial settings for using GrovePi + starter kit and camera on Raspberry Pi
Detect slide switches using python on Raspberry Pi 3!
Try using a QR code on a Raspberry Pi
Detect magnet switches using python on Raspberry Pi 3!
Sound the buzzer using python on Raspberry Pi 3!
Display CPU temperature every 5 seconds on Raspberry Pi 4
I tried running Flask on Raspberry Pi 3 Model B + using Nginx and uWSGI
Record temperature and humidity with systemd on Raspberry Pi
Build an OpenCV4 environment on Raspberry Pi using Poetry
Create a color sensor using a Raspberry Pi and a camera
pigpio on Raspberry pi
Try using the temperature sensor (LM75B) on the Raspberry Pi.
Install PyCall on Raspberry PI and try using GPIO's library for Python from Ruby
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Installation of Docker on Raspberry Pi and L Chika
Install pyenv on Raspberry Pi and version control Python
Output to "7-segment LED" using python on Raspberry Pi 3!
Cython on Raspberry Pi
Troubleshoot with installing OpenCV on Raspberry Pi and capturing
Cross-compiling for Raspberry Pi Zero on Debian-Try using shared libraries
Detect "temperature (using A / D converter)" using python on Raspberry Pi 3!
[Python GUI] DICOM contrast adjustment and BMP conversion using Tkinter
Get the weather using the API and let the Raspberry Pi speak!
Indoor monitoring using Raspberry Pi
Display GUI messages on Ubuntu
Introduced pyenv on Raspberry Pi
Use NeoPixel on Raspberry Pi
Install OpenCV4 on Raspberry Pi 3
Install TensorFlow 1.15.0 on Raspberry Pi
Control the motor with a motor driver using python on Raspberry Pi 3!
Make a simple CO2 incubator using Raspberry PI and CO2 sensor (MH-Z14A)
Make a Kanji display compass with Raspberry Pi and Sense Hat
Graph display of household power consumption with 3GPI and Raspberry Pi
Create your own IoT platform using raspberry pi and ESP32 (Part 1)
[Ruby on Rails] Display and pinning of GoolgeMAP using Google API
Testing uart communication on Raspberry Pi
USB over ethernet using Raspberry pi
raspberry pi 4 centos7 install on docker
Create a python GUI using tkinter
Install ghoto2 on Raspberry Pi (memo)
Notes on using post-receive and post-merge
OpenCV installation procedure on Raspberry Pi
Power on / off Raspberry pi on Arduino
Detect switch status on Raspberry Pi 3
Install OpenMedia Vault 5 on Raspberry Pi 4
Using a webcam with Raspberry Pi
L Chika on Raspberry Pi C #
Build wxPython on Ubuntu 20.04 on raspberry pi 4
GUI creation in python using tkinter 2
Detect analog signals with A / D converter using python on Raspberry Pi 3!