LoPy4 alarm callback not repeating periodically
-
I have a LoPy4 which I am trying to measure an ADC voltage on periodically. I have an alarm that I am trying to trigger interrupts every five seconds with. Here is what the code I am testing with looks like:
from machine import ADC from machine import Timer import utime adc = ADC(0) #ADC channels for baterry voltage monitoring adc_b1 = adc.channel(pin = 'P20', attn=ADC.ATTN_11DB) list = [] #Measures battery voltage def battery_voltage(): for i in range(0, 35): read = adc_b1.voltage() list.insert(i, read) avg_reading_b1 = sum(list)/len(list) list.clear() bat_1 = str(round(avg_reading_b1/1000, 2)) #String and round print(bat_1) battery_alarm = Timer.Alarm(battery_voltage(), s=5, periodic=True) def main(): while(1): continue main()
The functions battery_voltage() gets called once after the file has been successfully uploaded. After that, the program continues to loop but battery_voltage() does not get called again. Is there something wrong with how I am setting up the alarm?
-
@joshhulnz
a) write:Timer.Alarm(battery_voltage, s=5, periodic=True)
without the brackets.
Optimization:
b) in the main loop, I would use a short sleep instead of the continue statement
c) I you just need the average, you do not have to collect the values. Just add them up while reading, e.g.def battery_voltage(): avg = 0 for i in range(0, 35): avg += adc_b1.voltage() print(round(avg/35000, 2))