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-controllerIn 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/test_knob_app.py
"""Exercise the real MicroPython adapter and entrypoint without attached hardware."""
import contextlib
import io
import types
import unittest
from unittest.mock import patch
from knob_app import Board, run
from knob_runtime import KnobRuntime
from mcf8329 import Mcf8329, CONFIG_REGISTERS
from test_knob_runtime import Hardware, fixture_profile
class Pin:
OUT, IN = 1, 0
def __init__(self, number, mode=None, value=0):
self.number, self.level = number, value
self.events = []
def value(self, value=None):
if value is None: return self.level
self.level = value
self.events.append(value)
def on(self): self.value(1)
def off(self): self.value(0)
def init(self, mode, value): self.value(value)
class PWM:
def __init__(self, pin, freq, duty_u16):
self.pin, self.freq, self.duty = pin, freq, duty_u16
self.closed = False
def duty_u16(self, value): self.duty = value
def deinit(self): self.closed = True
class AppTests(unittest.TestCase):
def test_board_pin_mapping_output_order_and_cleanup(self):
buses = []
def soft_bus(**kwargs):
buses.append(kwargs)
return object()
machine = types.SimpleNamespace(Pin=Pin, PWM=PWM, ADC=lambda n:n,
I2C=lambda *a, **k:None,
SoftI2C=soft_bus)
hw = Board(machine, None)
self.assertEqual(hw.arm.number, 3)
self.assertEqual(hw.pwm.pin.number, 2)
self.assertEqual(hw.pwm.freq, 20000)
self.assertEqual(hw.button.number, 8)
self.assertEqual(hw.adcs["knob_raw"], 29)
self.assertEqual((hw.arm.level, hw.pwm.duty), (0, 0))
self.assertIsInstance(hw.motor, Mcf8329)
self.assertEqual((buses[0]["sda"].number, buses[0]["scl"].number), (0, 1))
self.assertEqual(buses[0]["freq"], 100000)
self.assertEqual(buses[0]["timeout"], 1000)
events = []
hw.arm.on = lambda:events.append("enable")
hw.arm.off = lambda:events.append("disable")
hw.pwm.duty_u16 = lambda duty:events.append(("pwm", duty))
hw.drive(True, 10000)
hw.off()
self.assertEqual(events, [("pwm", 10000), "enable", "disable", ("pwm", 0)])
for duty in (-1, 65536, True, 1.5):
with self.assertRaises(ValueError): hw.drive(True, duty)
self.assertEqual(events[-2:], ["disable", ("pwm", 0)])
hw.close()
self.assertTrue(hw.pwm.closed)
self.assertEqual(hw.speed.level, 0)
def test_actual_board_and_mcf_bus_are_gated_by_runtime_profile(self):
# Real Board + Mcf8329 + KnobRuntime; only pins, ADCs and wire bus simulated.
class RegisterBus:
def __init__(self):
self.regs = dict(fixture_profile()["registers"])
self.packet, self.reads = [], []
self.fail = False
def start(self): pass
def stop(self): self.packet = []
def write(self, data):
if self.fail: return 0
self.packet.extend(data)
if len(self.packet) == 5:
self.reads.append(self.packet[3])
self.data = iter(self.regs[self.packet[3]].to_bytes(4, "little"))
return len(data)
def readinto(self, buf, nack): buf[0] = next(self.data)
class ADC:
def __init__(self, pin): self.pin = pin
def read_u16(self):
return raw[{26:"vbus_raw", 27:"vmotor_raw", 28:"current_raw", 29:"knob_raw"}[self.pin]]
for profile in (None, fixture_profile()):
with self.subTest(profile=profile is not None):
clock = Hardware()
clock.sleep_us = lambda _: None
raw = dict(clock.raw)
bus = RegisterBus()
machine = types.SimpleNamespace(Pin=Pin, PWM=PWM, ADC=ADC,
I2C=lambda *a, **k:None, SoftI2C=lambda **k:bus)
hw = Board(machine, clock)
hw.fault.level, hw.button.level = 1, 1
hw.verify_pd_boot = lambda:None
hw.pd_status = lambda _:dict(clock.pd)
runtime = KnobRuntime(hw, clock, profile)
for _ in range(20): runtime.tick(20)
hw.button.level = 0
for _ in range(5): runtime.tick(20)
raw["knob_raw"], hw.button.level = 50000, 1
for _ in range(10): runtime.tick(20)
if profile is None:
self.assertEqual((hw.arm.level, hw.pwm.duty), (0, 0))
self.assertEqual(bus.reads, [])
else:
self.assertEqual(bus.reads[:24], list(CONFIG_REGISTERS))
self.assertEqual(hw.arm.level, 1)
self.assertGreater(hw.pwm.duty, 0)
bus.fail = True
with self.assertRaises(OSError): runtime.tick(20)
self.assertEqual((hw.arm.level, hw.pwm.duty), (0, 0))
self.assertFalse(runtime.verified)
hw.close()
def exercise(self, profile, fail_once=False, command=""):
class RunningHardware(Hardware):
def __init__(self):
super().__init__()
self.history = []
self.closed = False
self.failed = False
self.feed_count = 0
def sample_raw(self):
self.raw.update(button_down=600 <= self.now < 720,
knob_raw=50000 if self.now >= 800 else 0)
if fail_once and self.now >= 900 and not self.failed:
self.failed = True
raise OSError("injected ADC failure")
return super().sample_raw()
def off(self):
super().off()
self.history.append((self.now, False, 0))
def drive(self, enabled, duty):
super().drive(enabled, duty)
self.history.append((self.now, enabled, duty))
def sleep_ms(self, delay):
self.now += delay
if self.now >= 1500: raise KeyboardInterrupt()
def close(self): self.off(); self.closed = True
def feed(self): self.feed_count += 1
hw = RunningHardware()
stdin = io.StringIO(command)
class Poll:
def register(self, *args): pass
def poll(self, *args):
return [1] if hw.now >= 1100 and stdin.tell() < len(command) else []
machine = types.SimpleNamespace(Pin=Pin, WDT=lambda **kwargs:hw)
select = types.SimpleNamespace(POLLIN=1, poll=Poll)
stdout = io.StringIO()
with patch.dict("sys.modules", {"machine":machine, "time":hw, "select":select}), \
patch("knob_app.Board", return_value=hw), \
patch("motor_setup.PROFILE", profile), patch("sys.stdin", stdin), \
contextlib.redirect_stdout(stdout):
with self.assertRaises(KeyboardInterrupt): run()
self.assertTrue(hw.closed)
self.assertFalse(hw.enabled)
self.assertGreater(hw.feed_count, 5)
return hw, stdout.getvalue()
def test_shipped_preview_entrypoint_cannot_enable(self):
hw, output = self.exercise(None, command="status\n")
self.assertFalse(any(enabled for _, enabled, _ in hw.history))
self.assertIn("PREVIEW ONLY", output)
self.assertIn("knob=", output)
def test_commissioned_entrypoint_drives_and_usb_stop_disarms(self):
hw, output = self.exercise(fixture_profile(), command="stop\n")
self.assertTrue(any(enabled for _, enabled, _ in hw.history))
self.assertFalse(any(enabled for t, enabled, _ in hw.history if t > 1100))
def test_fault_recovers_supervision_without_restart_or_timing_loop(self):
hw, output = self.exercise(fixture_profile(), fail_once=True)
self.assertTrue(any(enabled for _, enabled, _ in hw.history))
self.assertFalse(any(enabled for t, enabled, _ in hw.history if t >= 900))
self.assertEqual(output.count("injected ADC failure"), 1)
self.assertNotIn("sample is late", output)
if __name__ == "__main__": unittest.main()