Mostly the results are constant, as they should be but occasionally I get two readings in series that are double what they should be.
Could Garbage collection be the problem?
Code: Select all
from umqtt.robust import MQTTClient
from machine import Pin
import ubinascii
import machine
import micropython
import utime
import time
micropython.alloc_emergency_exception_buf(100)
meter = Pin(12, Pin.IN)
now_ms = utime.ticks_ms()
last_ms = utime.ticks_ms()
# Default MQTT server to connect to
server = "192.168.1.2"
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
c = MQTTClient(CLIENT_ID, server)
c.connect()
def calc(a):
global now_ms
global last_ms
last_ms = now_ms
now_ms = utime.ticks_ms()
watts = utime.ticks_diff(now_ms, last_ms)
watts = 3600 / (watts * 0.004 )
WATTS = str(watts)
c.publish("current_usage", WATTS)
print(WATTS)
def trigger(p):
micropython.schedule(calc, 1)
meter.irq(trigger=Pin.IRQ_FALLING, handler=trigger, hard = True)