import gc
from machine import Pin, ADC, unique_id, UART, reset_cause, RTC, Timer, reset, lightsleep, idle
from utime import sleep, sleep_ms
from dht import DHT22
class UARTmain:
def __init__(self):
gc.enable()
gc.collect()
self.ledpin1 = Pin("LED", Pin.OUT) # Initialize onboard LED
self.ledpin1.value(0)
self.red = Pin(12, Pin.OUT) # Initialize onboard LED red
self.red.value(0)
self.green = Pin(11, Pin.OUT) # Initialize onboard LED green
self.green.value(0)
# INITIALIZE READ/WRITE PINS & SETTINGS
# =======================================================
self.sensor = DHT22(Pin(19, Pin.IN, Pin.PULL_UP)) # Address the DHT22 Module
#Interrupt pin configs
self.interrupt_flag=0
self.debounce_time=0
self.pin = Pin(5, Pin.IN, Pin.PULL_UP)
#opening the UART for reading TwinDos
self.uart = UART(0, baudrate=38400, tx=Pin(16), rx=Pin(17))
#self.uart.init(bits=8, parity=None, stop=2)
self.tx_en_pin = Pin(18, Pin.OUT)
self.tx_en_pin.value(0) #enable reception mode
#------------------------------------
def red_blink(self, times, dt):
for x in range(times):
self.red.value(1)
sleep_ms(dt)
self.red.value(0)
sleep_ms(dt)
def green_blink(self, times, dt):
for x in range(times):
self.green.value(1)
sleep_ms(dt)
self.green.value(0)
sleep_ms(dt)
def toggle_board_led(self):
sleep_ms(100)
self.ledpin1.value(not self.ledpin1.value()) # toggling
sleep_ms(200)
self.ledpin1.value(not self.ledpin1.value()) # toggling
def get_uart_data(self):
data = "nan"
txData = b'get'
rxData = bytes()
for i in range(5):
try:
self.tx_en_pin.value(1) #enable transmission mode
self.uart.write(txData) #sending uart data
sleep(0.2)
print("\n*Reading UART")
self.tx_en_pin.value(0) #enable reception mode
while self.uart.any() > 0:
rxData += self.uart.read(10)
data=(rxData.decode('utf-8'))
#print("twindos_data: ", twindos_data)
result = data[:-1].split("#")
instantaneous_power_used =int(result[1])
total_power_used =int(result[2])
return instantaneous_power_used, total_power_used
except Exception as e:
print("\n*Error reading uart, ", e, "\nRetrying: ", i)
sleep(1)
continue
return "nan", "nan"
def read_and_blink(self):
instantaneous_power_used, total_power_used = self.get_uart_data()
print("\n*Power used: ", instantaneous_power_used, "\nTotal power used: ", total_power_used)
self.green_blink(self, 2, 300)
self.toggle_board_led()
if instantaneous_power_used > 1000:
self.red_blink(self, 4, 100)
#self.red_blink(self, 4, instantaneous_power_used*0.1)
else:
self.green_blink(self, 6, 100)
#self.green_blink(self, 4, instantaneous_power_used)
data_read_timer = Timer()
uart_data = UARTmain()
data_read_timer.init(period=(2000), mode=Timer.PERIODIC, callback=lambda t: uart_data.read_and_blink())