from machine import Pin, ADC, I2C
import utime
from dht import DHT22
from ssd1306 import SSD1306_I2C
# Initialize components
adc_voltage = ADC(0) # Voltage potentiometer on ADC0 (GP26, Pin 31)
adc_current = ADC(1) # Current potentiometer on ADC1 (GP27, Pin 32)
led = Pin(15, Pin.OUT) # LED on GP15 (Pin 20)
button_battery = Pin(14, Pin.IN, Pin.PULL_DOWN) # Battery control button on GP14 (Pin 19)
button_stepper = Pin(13, Pin.IN, Pin.PULL_DOWN) # Stepper motor control button on GP13 (Pin 17)
dht = DHT22(Pin(16)) # DHT22 sensor on GP16 (Pin 21)
# Stepper Motor Pins connected to A4988 Driver
step_pin = Pin(18, Pin.OUT) # STEP pin on GP18 (Pin 24)
dir_pin = Pin(17, Pin.OUT) # DIR pin on GP17 (Pin 22)
ms1_pin = Pin(19, Pin.OUT) # MS1 pin on GP19 (Pin 25)
ms2_pin = Pin(20, Pin.OUT) # MS2 pin on GP20 (Pin 26)
# I2C and OLED
i2c = I2C(0, scl=Pin(21), sda=Pin(20)) # I2C0 on GP21 (Pin 29) for SCL and GP20 (Pin 28) for SDA
oled = SSD1306_I2C(128, 64, i2c)
# Global Variables
battery_connected = False
stepper_on = False
# Helper function to control stepper motor
def step_motor(steps):
dir_pin.value(1) # Set direction
for _ in range(steps):
step_pin.value(1)
utime.sleep_us(500)
step_pin.value(0)
utime.sleep_us(500)
# Main loop
while True:
# Read potentiometer values
voltage = adc_voltage.read_u16() * 3.3 / 65535 # Convert to voltage
current = adc_current.read_u16() * 3.3 / 65535 # Convert to current
# Read temperature from DHT22
dht.measure()
temperature = dht.temperature()
# Battery management
if button_battery.value() == 1:
battery_connected = not battery_connected
utime.sleep(0.5) # Debounce delay
if battery_connected:
led.value(1)
else:
led.value(0)
# Stepper motor control for cooling
if temperature > 30 or button_stepper.value() == 1: # 30°C threshold
stepper_on = True
step_motor(512) # Rotate 1 revolution for demonstration
else:
stepper_on = False
# Update OLED display
oled.fill(0)
oled.text("Battery: {}".format("On" if battery_connected else "Off"), 0, 0)
oled.text("Voltage: {:.2f}V".format(voltage), 0, 10)
oled.text("Current: {:.2f}A".format(current), 0, 20)
oled.text("Temp: {:.2f}C".format(temperature), 0, 30)
oled.text("Cooling: {}".format("On" if stepper_on else "Off"), 0, 40)
oled.show()
utime.sleep(1) # Delay before next reading