import sys
import time
import select
import gc
import dht
from machine import Pin, PWM, I2C
from pico_i2c_lcd import I2cLcd
# GPIO Setup
led = Pin(15, Pin.OUT)
pwm_led = PWM(Pin(16))
pwm_led.freq(1000)
buzzer = Pin(17, Pin.OUT)
sensor = dht.DHT22(Pin(18))
# LCD Setup
i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
# CLI Variables
input_buffer = ""
history = [""] * 5
hist_index = 0
lcd.clear()
lcd.putstr("Console Ready")
print("Pico UART Console Ready")
print("> ", end="")
while True:
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
c = sys.stdin.read(1)
if c == '\x08' or c == '\x7f':
if len(input_buffer) > 0:
input_buffer = input_buffer[:-1]
print("\b \b", end="")
elif c == '\n':
print()
cmd = input_buffer.strip()
history[hist_index] = cmd
hist_index = (hist_index + 1) % 5
lcd.clear()
if cmd == "HELP":
print("Commands:")
print("HELP")
print("UPTIME")
print("SET LED 1 ON")
print("SET LED 1 OFF")
print("SET PWM <0-255>")
print("BEEP")
print("READ SENSOR")
print("HISTORY")
lcd.putstr("HELP MENU")
elif cmd == "UPTIME":
uptime = int(time.ticks_ms()/1000)
print("Uptime:", uptime)
lcd.putstr("Time:")
lcd.putstr(str(uptime))
elif cmd == "SET LED 1 ON":
led.value(1)
print("LED ON")
lcd.putstr("LED ON")
elif cmd == "SET LED 1 OFF":
led.value(0)
print("LED OFF")
lcd.putstr("LED OFF")
elif cmd.startswith("SET PWM"):
try:
val = int(cmd.split()[2])
if 0 <= val <= 255:
pwm_led.duty_u16(val * 257)
print("PWM:", val)
lcd.putstr("PWM:")
lcd.putstr(str(val))
else:
print("PWM Range 0-255")
lcd.putstr("PWM ERROR")
except:
print("Invalid PWM")
lcd.putstr("PWM ERROR")
elif cmd == "BEEP":
buzzer.value(1)
time.sleep(0.5)
buzzer.value(0)
print("BEEP")
lcd.putstr("BEEP")
elif cmd == "READ SENSOR":
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
print("Temp:", temp, "C")
print("Humidity:", hum, "%")
lcd.putstr("T:")
lcd.putstr(str(temp))
lcd.putstr("C ")
lcd.putstr("H:")
lcd.putstr(str(hum))
lcd.putstr("%")
except Exception as e:
print("Sensor Error")
lcd.putstr("SENSOR ERR")
elif cmd == "MEM":
free_mem = gc.mem_free()
print("Free Memory:", free_mem, "bytes")
lcd.putstr("MEM:")
lcd.putstr(str(free_mem))
elif cmd == "HISTORY":
print("History:")
for h in history:
print(h)
lcd.putstr("HISTORY")
else:
print("Unknown Command")
lcd.putstr("UNKNOWN")
input_buffer = ""
print("> ", end="")
else:
input_buffer += c
print(c, end="")