MustafaMulla29/rp2040-bldc-motor-controller

Hardware assembly metadata and PCB geometry for a controller board with a snap-off rotary-encoder section, plus four parallel 150 µF/50 V bulk electrolytic capacitors filtering the motor supply.

Version
2.0.40
License
unset
Stars
0

Use with the tscircuit CLI

tsci is the tscircuit CLI. Install it with npm install -g tscircuit.

tsci clone MustafaMulla29/rp2040-bldc-motor-controller  # download the package files into ./rp2040-bldc-motor-controller
tsci add MustafaMulla29/rp2040-bldc-motor-controller    # add it to your project as @tsci/MustafaMulla29.rp2040-bldc-motor-controller

In a cloned or new (tsci init) project: tsci dev starts a local preview, tsci build outputs Circuit JSON, and tsci push publishes to tscircuit.com.

firmware/knob_app.py

"""MicroPython knob/ARM application. See docs/knob-firmware.md before use.

The shipped motor_setup.PROFILE is None: ADC preview works, motor output does
not. MCF8329A performs sensorless FOC internally. The runtime verifies its
commissioned profile before permitting PWM/ARM; it never programs motor tuning.
Run this OR power_manager.py, never both; this file is not auto-installed as main.py.
"""
from knob_runtime import KnobRuntime
from mcf8329 import Mcf8329, PWM_HZ
from pd_profile import verify_runtime, nvm_is_9v
from pd_nvm import NVM
from power_policy import adc_millivolts
from motor_profile import calibrated_sample
from select_pd_voltage import VoltageSelector
from status_led import StatusLed


class Board:
    def __init__(self, machine, clock):
        Pin = machine.Pin
        self.arm = Pin(3, Pin.OUT, value=0)
        self.speed = Pin(2, Pin.OUT, value=0)
        self.pwm = machine.PWM(self.speed, freq=PWM_HZ, duty_u16=0)
        self.button = Pin(8, Pin.IN)
        self.fault = Pin(4, Pin.IN)
        self.pd_ok = Pin(6, Pin.IN)
        self.adcs = {key: machine.ADC(pin) for key, pin in
                     (("vbus_raw", 26), ("vmotor_raw", 27),
                      ("current_raw", 28), ("knob_raw", 29))}
        self.pd = machine.I2C(1, sda=Pin(22), scl=Pin(23), freq=100000)
        # GP0/1 and UI GP16/17 share hardware I2C0. Use a separate software bus
        # here, also allowing TI's mandatory 100 us spacing between each byte.
        self.motor = Mcf8329(machine.SoftI2C(sda=Pin(0), scl=Pin(1),
                                           freq=100000, timeout=1000), clock)
        self.clock = clock

    def off(self):
        self.arm.off()  # Q5 off => DRVOFF pulled high before changing PWM.
        self.pwm.duty_u16(0)

    def drive(self, enabled, duty):
        # Called only by KnobRuntime after profile, power and ARM checks.
        if type(duty) is not int or not 0 <= duty <= 65535:
            self.off()
            raise ValueError("Invalid motor PWM duty")
        if not enabled or duty == 0:
            self.off()
            return
        try:
            self.pwm.duty_u16(duty)  # Establish command before allowing gates.
            self.arm.on()
        except BaseException:
            self.off()
            raise

    def close(self):
        try:
            self.off()
        finally:
            self.pwm.deinit()
            self.speed.init(self.speed.OUT, value=0)

    def sample_raw(self):
        result = {name: adc.read_u16() for name, adc in self.adcs.items()}
        result.update(button_down=not self.button.value(),
                      fault_n=bool(self.fault.value()), pd_ok2_low=not self.pd_ok.value())
        return result

    def verify_pd_boot(self):
        if not nvm_is_9v(NVM(self.pd, clock=self.clock).read()):
            raise OSError("Provision and cold-boot verify the 9 V PD default first")

    def pd_status(self, selected_mv):
        verify_runtime(self.pd, selected_mv=selected_mv)
        return dict(rdo=int.from_bytes(self.pd.readfrom_mem(0x28, 0x91, 4), "little"),
                    pe_state=self.pd.readfrom_mem(0x28, 0x29, 1)[0])


def run():
    import machine
    import time
    import sys
    import select
    from motor_setup import PROFILE

    hw = Board(machine, time)
    try:
        led = StatusLed(machine.Pin)
        led.show("waiting")
        watchdog = machine.WDT(timeout=1000)
        runtime = KnobRuntime(hw, time, PROFILE)

        def selection_sample():
            raw = hw.sample_raw()
            if runtime.profile:
                s = calibrated_sample(raw, runtime.profile["calibration"])
            else:
                s = {"vbus_mv": adc_millivolts(raw["vbus_raw"]),
                     "vmotor_mv": adc_millivolts(raw["vmotor_raw"])}
            return dict(s, pd_ok2_low=raw["pd_ok2_low"])

        selector = VoltageSelector(hw.pd, lambda: runtime.stop("voltage change"),
                                   selection_sample, time, service=watchdog.feed)
        poll = select.poll()
        poll.register(sys.stdin, select.POLLIN)
        line = ""
        print("Knob/ARM: start at zero; release then press ARM. Press again to stop.")
        print("USB commands: status | stop | voltage 5/9/15/20 (POWER OFF)")
        if PROFILE is None:
            print("PREVIEW ONLY: motor profile/calibration absent; all drive outputs stay LOW.")
        previous = time.ticks_ms()
        while True:
            try:
                now = time.ticks_ms()
                dt = max(1, time.ticks_diff(now, previous))
                runtime.tick(dt)
                # tick includes its own execution time; exclude it from next dt.
                previous = time.ticks_ms()
                for _ in range(16):  # Bound console work so input cannot starve supervision.
                    if not poll.poll(0):
                        break
                    char = sys.stdin.read(1)
                    if char in ("\r", "\n"):
                        command, line = line.strip(), ""
                        if not command:
                            continue
                        if command == "stop":
                            runtime.stop("USB stop")
                        elif command == "status":
                            print(runtime.status())
                        elif command.startswith("voltage "):
                            words = command.split()
                            # Invalid voltage commands must also leave drive off.
                            runtime.stop("voltage command")
                            if len(words) != 2 or words[1] not in ("5", "9", "15", "20"):
                                raise ValueError("Use voltage 5/9/15/20")
                            runtime.select_voltage(int(words[1]) * 1000, selector)
                            previous = time.ticks_ms()
                            print(runtime.status())
                        else:
                            raise ValueError("Use status, stop or voltage 5/9/15/20")
                    elif len(line) < 64:
                        line += char
                    else:
                        line = ""
                        raise ValueError("Command too long")
                if runtime.control.fault_latched:
                    led.show("fault")
                elif runtime.control.duty:
                    led.show("commanding")
                else:
                    led.show("pd_ready" if runtime.verified else "waiting")
            except (OSError, ValueError) as error:
                runtime.stop(str(error), fault=True)
                runtime.verified = False
                led.show("fault")
                print(error)
                time.sleep_ms(100)  # Back off while disarmed; no repeated high outputs.
                previous = time.ticks_ms()
            watchdog.feed()
            time.sleep_ms(20)
    finally:
        hw.close()


if __name__ == "__main__":
    run()