Commit e05c49ee authored by Gilles MARCKMANN's avatar Gilles MARCKMANN
Browse files

First implementation of a standalone raspi GUI for Load Cell HX711:

- default values set on raspberry Pi4
- a calibration procedure allows to reset parameters
- a tare button allows to reset value to zero
- figure_raspi_HX711.png gives the way to connect the load cell to the raspberry
parents
CREDITS:
This code is base on based on https://github.com/tatobari/hx711py, based on https://gist.github.com/underdoeg/98a38b54f889fce2b237
RASPBERRY PI GENERALITIES:
- update your rapsberry before all:
> sudo aptitude update -y
> sudo aptitude upgrade -y
> sudo reboot
- install Pixel (X11 Desktop), if any:
> sudo dpkg –configure –a
> sudo apt-get install lightdm
> sudo apt –fix-broken install
> sudo apt install lxde lxde-core lxterminal lxappearance
> sudo apt install xinit
> sudo apt install raspberrypi-ui-mods
> sudo apt-get install xutils
or:
> sudo apt-get update
> sudo apt-get dist-upgrade
> sudo reboot
> sudo apt-get install --no-install-recommends xserver-xorg
> sudo apt-get install raspberrypi-ui-mods
> sudo apt-get install lightdm
> sudo startx
HX711 PREREQUIREMENT:
- install GPIO:
> sudo pip install RPi.GPIO
> sudo pip install statistics
- install tkinter python module (GUI library for python)
> sudo apt-get install python-tk
- install matplotlib python module:
> sudo pip install matplotlib
> sudo pip2 uninstall backports.functools-lru-cache
> sudo apt install python-backports.functools-lru-cache
#! /usr/bin/python2
import time
import sys
import RPi.GPIO as GPIO
import csv
from tkinter import *
import tkinter.font as tkFont
import numpy
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
# import class definition
from tatobari.hx711 import HX711
def callback_cleanAndExit():
global _main_window_
global GPIO
GPIO.cleanup()
sys.exit()
_main_window_.quit()
def callback_tare():
print("Please wait...")
hx.reset()
hx.tare()
hx.tare_A()
hx.tare_B()
print("Tare done! Add weight now...")
def callback_CalSet(_parent_window_, text_value, text_unity):
global hx
global referenceUnit
global _WEIGHT_
global _UNITY_
val=0.
try:
val=float(text_value)
except:
print('Bad balue, no calibration done !')
val=0.
if(val!=0.):
print("reference="+_WEIGHT_.get())
referenceUnit = float(_WEIGHT_.get())/val
hx.set_reference_unit(referenceUnit)
_UNITY_.set(text_unity)
_parent_window_.destroy()
def callback_reset():
global hx
global time
global _UNITY_
print("No weight on scale!")
hx.set_reference_unit(1.)
hx.tare()
_UNITY_.set("")
print("Go to step 2.")
return
def callback_calibrate():
global hx
global _space_
global _calibration_window_
global _UNITY_
_calibration_window_ = Tk()
_calibration_window_['bg']='white'
_cal_frame_=Frame(_calibration_window_, padx=_space_, pady=_space_ ,relief=GROOVE, background="white")
_cal_frame_.pack()
_indication1_=Label(_cal_frame_, text="1. Remove all weight and click on 'Reset' button", background="white")
_indication1_.grid(row=0,column=0,columnspan=2)
_reset_button_=Button(_cal_frame_, text="Reset", command=lambda: callback_reset())
_reset_button_.grid(row=1, column=0 ,columnspan=2, padx=_space_, pady=_space_)
_indication2_=Label(_cal_frame_, text="2. Place a known weight on the scale, indicate the value and click on 'Calibrate' button", background="white")
_indication2_.grid(row=2,column=0,columnspan=2)
_val_frame_=Frame(_cal_frame_, padx=_space_,pady=_space_,borderwidth=0, background="white")
_val_frame_.grid(row=3,column=0)
_val_label_=Label(_val_frame_,text="Refrence weight:", background="white")
_val_label_.pack(side=LEFT)
_val_entry_=Entry(_val_frame_,width=10,relief=SUNKEN,takefocus=1,justify=RIGHT)
_val_entry_.pack(side=LEFT)
_unity_frame_=Frame(_cal_frame_, padx=_space_,pady=_space_,borderwidth=0, background="white")
_unity_frame_.grid(row=3,column=1)
_unity_label_=Label(_unity_frame_,text=" Unity symbol:", background="white")
_unity_label_.pack(side=LEFT)
_unity_entry_=Entry(_unity_frame_,width=10,relief=SUNKEN,takefocus=1,justify=RIGHT)
_unity_entry_.delete(0, END)
_unity_entry_.insert(0,_UNITY_.get())
_unity_entry_.pack(side=LEFT)
_cancel_button_=Button(_cal_frame_, text="Cancel", command=_calibration_window_.destroy)
_cancel_button_.grid(row=4, column=0, padx=_space_, pady=_space_)
_cal_button_=Button(_cal_frame_, text="Calibrate", command=lambda: callback_CalSet(_calibration_window_,_val_entry_.get(),_unity_entry_.get()))
_cal_button_.grid(row=4, column=1, padx=_space_, pady=_space_)
_calibration_window_.mainloop()
def callback_inbetween_mainloop():
global _WEIGHT_
global hx
global _main_window_
try:
val=hx.get_weight(1)
#_WEIGHT_.set( val )
_WEIGHT_.set( 1.*int(val*1000)/1000. )
#print(_WEIGHT_.get())
# 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(1)
#val_B = hx.get_weight_B(1)
#print "A: %s B: %s" % ( val_A, val_B )
hx.power_down()
hx.power_up()
time.sleep(.1)
except (KeyboardInterrupt, SystemExit):
cleanAndExit()
_main_window_.after(1, callback_inbetween_mainloop)
#-------------------------------------------------
# MAIN
#-------------------------------------------------
_main_window_ = Tk()
_main_window_['bg']='white'
_space_=3
#-----------------
# TITLE FRAME
#-----------------
_FrameTitle_=Frame(_main_window_, borderwidth=0)
_FrameTitle_.grid(row=0, column=0, columnspan=3, padx=_space_, pady=_space_)
_font_style_title_ = tkFont.Font(family="Lucida Grande", size=14)
_label_title_ = Label(_FrameTitle_, text="Scale",bg="white",font=_font_style_title_).pack(side=LEFT,fill=BOTH)
_font_style_title_ = tkFont.Font(family="Lucida Grande", size=14)
_label_title_red_ = Label(_FrameTitle_, text="HX711 load cell",bg="white",font=_font_style_title_,foreground="red").pack(side=LEFT,fill=BOTH)
hx = HX711(5, 6)
# If you're experiencing super random values, change these values to MSB or LSB until to get more stable values.
# 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.
# set this number divided by the real weight.
referenceUnit = int(1464009/2015)
hx.set_reference_unit(referenceUnit)
hx.reset()
hx.tare()
print("Tare done! Add weight now...")
_space_=3
#-----------------
# Main Label
#-----------------
_UNITY_=StringVar()
_UNITY_.set("g")
_WEIGHT_=StringVar()
_WEIGHT_.set(str(0.0))
_font_style_weight_ = tkFont.Font(family="Lucida Grande", size=20)
_weight_frame_=Frame(_main_window_,padx=_space_,pady=_space_, relief=GROOVE)
_weight_frame_.grid(row=1,column=1)
_weight_label_ = Label(_weight_frame_,padx=_space_,pady=_space_, width=10,textvariable=_WEIGHT_, borderwidth=2,
font=_font_style_weight_,relief=SUNKEN, background="white", anchor=E)
_weight_label_.pack(side=LEFT)
_unity_label_=Label(_main_window_,padx=_space_,pady=_space_, width=5,textvariable=_UNITY_, borderwidth=2,
font=_font_style_weight_, background="white", anchor=W)
_unity_label_.grid(row=1,column=2)
#-----------------
# button tare
#-----------------
_buttonTare_=Button(_main_window_, text="Tare", command=callback_tare)
_buttonTare_.grid(row=1, column=3, padx=_space_, pady=_space_)
#-----------------
# button calibrate
#-----------------
_buttonTare_=Button(_main_window_, text="Calibration", command=callback_calibrate)
_buttonTare_.grid(row=1, column=0, padx=_space_, pady=_space_)
#-----------------
# button quit
#-----------------
_buttonQuit_=Button(_main_window_, text="Quit", command=callback_cleanAndExit)
_buttonQuit_.grid(row=3, column=0, padx=_space_, pady=_space_)
#-----------------
# button prendre une mesure
#-----------------
#_buttonMeasure_=Button(_main_window_, text="Record Data", command=callback_add_measure)
#_buttonMeasure_=Button(_main_window_, text="Record Data")
#_buttonMeasure_.grid(row=3, column=1, padx=_space_, pady=_space_)
#-----------------
# button export
#-----------------
#_buttonExport_=Button(_main_window_, text="Export CSV", command=callback_export)
#_buttonExport_=Button(_main_window_, text="Export CSV")
#_buttonExport_.grid(row=3, column=2, padx=_space_, pady=_space_)
_main_window_.after(10, callback_inbetween_mainloop)
_main_window_.mainloop()
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
import time
import random
import math
import threading
class HX711:
def __init__(self, dout, pd_sck, gain=128):
self.PD_SCK = pd_sck
self.DOUT = dout
# Last time we've been read.
self.lastReadTime = time.time()
self.sampleRateHz = 80.0
self.resetTimeStamp = time.time()
self.sampleCount = 0
self.simulateTare = False
# Mutex for reading from the HX711, in case multiple threads in client
# software try to access get values from the class at the same time.
self.readLock = threading.Lock()
self.GAIN = 0
self.REFERENCE_UNIT = 1 # The value returned by the hx711 that corresponds to your reference unit AFTER dividing by the SCALE.
self.OFFSET = 1
self.lastVal = long(0)
self.DEBUG_PRINTING = False
self.byte_format = 'MSB'
self.bit_format = 'MSB'
self.set_gain(gain)
# Think about whether this is necessary.
time.sleep(1)
def convertToTwosComplement24bit(self, inputValue):
# HX711 has saturating logic.
if inputValue >= 0x7fffff:
return 0x7fffff
# If it's a positive value, just return it, masked with our max value.
if inputValue >= 0:
return inputValue & 0x7fffff
if inputValue < 0:
# HX711 has saturating logic.
if inputValue < -0x800000:
inputValue = -0x800000
diff = inputValue + 0x800000
return 0x800000 + diff
def convertFromTwosComplement24bit(self, inputValue):
return -(inputValue & 0x800000) + (inputValue & 0x7fffff)
def is_ready(self):
# Calculate how long we should be waiting between samples, given the
# sample rate.
sampleDelaySeconds = 1.0 / self.sampleRateHz
return time.time() >= self.lastReadTime + sampleDelaySeconds
def set_gain(self, gain):
if gain is 128:
self.GAIN = 1
elif gain is 64:
self.GAIN = 3
elif gain is 32:
self.GAIN = 2
# Read out a set of raw bytes and throw it away.
self.readRawBytes()
def get_gain(self):
if self.GAIN == 1:
return 128
if self.GAIN == 3:
return 64
if self.GAIN == 2:
return 32
# Shouldn't get here.
return 0
def readRawBytes(self):
# Wait for and get the Read Lock, incase another thread is already
# driving the virtual HX711 serial interface.
self.readLock.acquire()
# Wait until HX711 is ready for us to read a sample.
while not self.is_ready():
pass
self.lastReadTime = time.time()
# Generate a 24bit 2s complement sample for the virtual HX711.
rawSample = self.convertToTwosComplement24bit(self.generateFakeSample())
# Read three bytes of data from the HX711.
firstByte = (rawSample >> 16) & 0xFF
secondByte = (rawSample >> 8) & 0xFF
thirdByte = rawSample & 0xFF
# Release the Read Lock, now that we've finished driving the virtual HX711
# serial interface.
self.readLock.release()
# Depending on how we're configured, return an orderd list of raw byte
# values.
if self.byte_format == 'LSB':
return [thirdByte, secondByte, firstByte]
else: