Jan-22-2025, 01:20 PM
I am running this code to measure the weight of a water jug. All is working but I expect that I might have issues if the internet is interrupted when it tries to send the requests.post. Is there a way I can run the calibration part (lines 21-26) one time (saving anything important) and then just run it on a cronjob or SSH command?
Here is the whole thing...
Here is the whole thing...
import time import sys import RPi.GPIO as GPIO from hx711 import HX711 import requests from ShaneKeys import ARKEY1 from gpiozero import LED LED2 = LED(12) # Red LED to indicate low level. LED1 = LED(16) # Green LED to indicate high level. def cleanAndExit(): print("Cleaning...") print("Bye!") sys.exit() LED1.on() # Indication that the program has started and that LED indications are functional. LED2.on() # Indication that the program has started and that LED indications are functional. hx = HX711(20, 21) hx.set_reading_format("MSB", "MSB") referenceUnit = 114 hx.set_reference_unit(referenceUnit) hx.reset() hx.tare() LED2.off() # Indication that reset and tare functions are complete. time.sleep(5) # Take a moment to reflect. LED1.off() # Indication that reset and tare functions are complete. print("Scale has been set to zero, add weight now...") # This is when I know that the "zero" or "calibration" is done. If not using VNC, I use the LEDs to tell me when to load the load. while True: try: val = hx.get_weight(5) wholeval = (val * -1) # For some reason the "val" was reporting a negative value. This makes it positive. newval = wholeval / 100 # This makes the value in a unit of whole pounds (2154 becomes 21.54 pounds). roundedval = round(newval, 2) # This ensures that the pound value is limited to two decimal places. print(roundedval) # This displays the measured weight in pounds. weight = str(roundedval) if roundedval > 10: # If the volume is greater than 25%, then power on the green LED on GPIO16. LED2.off() LED1.on() else: # If the volume is less than 25%, then power the red LED on GPIO12. LED2.on() LED1.off() r = requests.post(ARKEY1 + "|water|" + str(roundedval)) #This is where the script sends the weight to my phone - the variable "roundedval" is the weight of the keg in pounds. hx.power_down() hx.power_up() time.sleep(1800) #Sleep for 30 minutes then recheck the weight of the water. except (KeyboardInterrupt, SystemExit): cleanAndExit()