Python Forum

Full Version: Need help merging/embedding
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I cleaned up two scripts that I am trying to merge. You can see that there are common elements to this. The first script I got working was the "keg1.py" and it uses the variable "keg1" for the weight values. While this is running, I get appropriate LED activity and a scroll of values in the shell window. The "keg1scale.py" is demonstrated at https:/youtu.be/2Oh-E0u8Jko.

keg1scale.py is this
import time
import sys


from gpiozero import LED
#Define LED indicators - these are GPIO numbers
LED1 = LED(21)
LED2 = LED(26)
LED3 = LED(20)
LED4 = LED(19)
LED5 = LED(16)
LED6 = LED(13)

EMULATE_HX711=False

referenceUnit = 1

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!")
    sys.exit()

hx = HX711(5, 6)
hx.set_reading_format("MSB", "MSB")
hx.set_reference_unit(1)
hx.reset()
hx.tare()

print("Initialized, put the keg on...")
LED6.blink(2,3)

while True:
    try:        
        keg1 = hx.get_weight(5)
        print(keg1)
        if ( keg1 < 50000 ):
            LED1.blink(.2,.2)
        else:
            LED1.off()
        if ( keg1 < 115000 ):
            LED2.blink(.5,.5)
        else:
            LED2.off()
        if ( keg1 > 115000 ):
            LED3.on()
        else:
            LED3.off()
        if ( keg1 > 253000 ):
            LED4.on()
        else:
            LED4.off()
        if ( keg1 > 380000 ):
            LED5.on()
        else:
            LED5.off()
        if ( keg1 > 500000 ):
            LED6.on()
        else:
            LED6.off()
       
        hx.power_down()
        hx.power_up()
        time.sleep(0.1)

    except (KeyboardInterrupt, SystemExit):
        cleanAndExit()
Here is the cleaned up "compare_to_average.py" that I am trying to incorporate. I am getting bombarded with indention errors and it keeps stopping. What do I keep of this and where do I put it?

compare_to_average.py is this:

import time

def moving_average(prev_average, new_value, num_steps = 20.0):
   return (prev_average * (num_steps - 1) + new_value) / num_steps

average = weight = keg1
w_threshold = 100


while True:
   weight = keg1
   lost_weight = average - weight
    if lost_weight > w_threshold:
       print("You got served")
   average = moving_average(average, weight)
   time.sleep(30) 

The goal is to print "You got served" when the variable "keg1" decreases in value significantly within a few minutes of time. A pint of beer weighs about 9000 "units" on this scale system. How and where do I merge these two?
You can't simply merge them. The first one is looping continuously, allowing the LEDs to be updated as fast as the sensor can be read and the loop updated. There's no history that needs to be kept, so this is fine.

The second one is keeping an average, and that depends on how fast the updates happen. So it sleeps every 30 seconds. If it ran as fast as the LED loop, the average would be lost. If it caused the LED loop to pause every 30 seconds, the scale would be very non-responsive.

I would probably use datetime to pull a timestamp. Then in the LED loop if the timestamp is more than 30 seconds old, update the timestamp and call a function to update the moving average and print the text.
That sounds reasonable. In one attempt to embed this, my scale would stop after 30 seconds. Now I understand why. Can you share an example of how this timestamp can be incorporated in the keg1scale.py portion?

I think I see an opening here. This timestamp...if it happens every 120 seconds and checks the variable (keg1) against the last time it checked it, it could catch the difference. Seems we wouldn't really need to do the averaging.

For clarification, the scale does waver by a few hundred units during testing. An empty keg registers between 88200 and 89000 units, so it might be good to truncate the value after getting it. Rounding could be another way to smooth things out if necessary.
Something like...

import time
last_timecheck = time.time()
# initialize your rolling average here as well

# main loop
while True:
    # do your LED stuff
    if (time.time() - last_timecheck) > 30:
        last_timecheck = time.time()
        # update rolling average
import time
last_timecheck = time.time()
# initialize your rolling average here as well
# is this what you mean?
def moving_average(prev_average, new_value, num_steps = 20.0):
   return (prev_average * (num_steps - 1) + new_value) / num_steps
 
average = weight = keg1
w_threshold = 100

 
# main loop
while True:
    # do your LED stuff
    if (time.time() - last_timecheck) > 30:
        last_timecheck = time.time()
        # update rolling average
        # and like here too?
        
        weight = keg1
        lost_weight = average - weight
        if lost_weight > w_threshold:
           print("You got served")
        average = moving_average(average, weight)
        time.sleep(30)

http://tpcg.io/XUaKb8rj

Check my edits at http://tpcg.io/XUaKb8rj
What I meant by "initialize your rolling average", is you might want to set up your "prev_average" value. That way you don't have to special-case the first time you call it. (You've done exactly that).
Yeah ...this is new to me so I am not sure what all that should look like. Where would I find more documentation for this function?
What function are you looking for?
Checking a variable on a recurring cycle and simlply make LED6.blink() if the variable "keg1" has changed by more than 5000 since the last time it was checked. I think every 2 minutes should suffice.

If I could work that into the keg1scale.py it would be good. Once I get that to capture the event and blink the light, I will work in the other parts of the push notification, etc.
Right. The loop in keg1scale.py was what was intended by "main Loop" above. It will do all the LED stuff, then you put the bits after the LED comment at the bottom of that loop.

Don't put in the sleep though, it's not necessary.
Pages: 1 2