imrishabh18/rp2040-motor-controller

This circuit module provides a microcontroller-based NEMA17 stepper motor driver with integrated USB-C Power Delivery, temperature sensing, and safety interlocks.

Version
1.0.16
License
unset
Stars
0

firmware/thermal_guard.py

"""MicroPython RP2040 adapter. No automatic start or automatic fault restart."""
from machine import Pin, I2C, disable_irq, enable_irq
from time import sleep_ms, ticks_ms
from tmp102 import TMP102, WARN_C
from thermal_policy import ThermalPolicy


class ThermalGuard:
    def __init__(self):
        self.enable = Pin(22, Pin.OUT, value=0)
        self.motor_inputs = [Pin(n, Pin.OUT, value=0) for n in (18, 19, 20, 21)]
        self.alert = Pin(24, Pin.IN)
        self.driver_fault = Pin(23, Pin.IN)
        self.led = Pin(25, Pin.OUT, value=0)
        self.policy = ThermalPolicy()
        self.irq_trip = 0
        self.configured = False
        self.sensor = TMP102(I2C(1, sda=Pin(26), scl=Pin(27), freq=100_000))
        self.alert.irq(handler=self._temperature_irq, trigger=Pin.IRQ_FALLING, hard=True)
        try:
            self.sensor.configure()
            # Exceed the 125 ms conversion interval plus conversion time.
            sleep_ms(300)
            self.configured = True
        except (OSError, ValueError):
            self.policy.trip("temperature sensor initialization failed")
        self.poll()

    def _temperature_irq(self, _pin):
        # Hardware gate already holds nSLEEP low; capture it until manual rearm.
        self.enable.value(0)
        self.irq_trip = 1

    def stop(self, reason="user stop"):
        self.enable.value(0)
        self.policy.trip(reason)
        for pin in self.motor_inputs:
            pin.value(0)

    def poll(self):
        try:
            if not self.configured:
                raise OSError("Sensor not configured; reboot to retry")
            temp = self.sensor.temperature()
            self.policy.sample(temp, bool(self.alert.value()),
                               driver_fault=self.policy.enabled and not self.driver_fault.value())
        except (OSError, ValueError):
            self.policy.sample(None, sensor_ok=False)
        if self.irq_trip:
            self.policy.trip("hardware overtemperature alert")
        if not self.policy.enabled:
            self.enable.value(0)
            for pin in self.motor_inputs:
                pin.value(0)
        # Fast blink = stopped/fault; slow blink = warm; solid = enabled/cool.
        period = 125 if self.policy.latched else 500
        blink = self.policy.latched or self.policy.temperature_c >= WARN_C
        self.led.value((ticks_ms() // period) % 2 if blink else 1)
        return self.policy.status()

    def arm(self):
        # Always take a fresh verified reading. A stale last sample cannot arm.
        self.poll()
        # Avoid an I2C transaction with interrupts disabled. The critical section
        # protects the final check and enable write against a concurrent alert.
        irq_state = disable_irq()
        try:
            if not self.alert.value() or not self.policy.arm():
                return False
            self.irq_trip = 0
            self.enable.value(1)
        finally:
            enable_irq(irq_state)
        sleep_ms(3)  # DRV8847 wake time is 1.5 ms; do not drive coils yet.
        self.poll()
        return self.policy.enabled