MicroPython on-device algorithms — PID controller, moving average, Kalman filter, state machine, task scheduler, data logger.
Pure MicroPython algorithm implementations that run on the device. These are Safe tier — no direct hardware side effects.
These algorithms are typically combined with sensor reads (input) and actuator control (output).
Upload as .py files via mpremote fs cp algorithm.py : for reuse.
Classic PID with anti-windup for control loops (e.g., temperature regulation):
import time, json
class PID:
def __init__(self, kp, ki, kd, setpoint=0, output_min=-100, output_max=100):
self.kp = kp
self.ki = ki
self.kd = kd
self.setpoint = setpoint
self.output_min = output_min
self.output_max = output_max
self._integral = 0
self._last_error = 0
self._last_time = time.ticks_ms()
def compute(self, measurement):
now = time.ticks_ms()
dt = time.ticks_diff(now, self._last_time) / 1000.0
if dt <= 0:
dt = 0.001
self._last_time = now
error = self.setpoint - measurement
self._integral += error * dt
derivative = (error - self._last_error) / dt
self._last_error = error
output = self.kp * error + self.ki * self._integral + self.kd * derivative
# Anti-windup: clamp output and freeze integral if saturated
if output > self.output_max:
output = self.output_max
self._integral -= error * dt
elif output < self.output_min:
output = self.output_min
self._integral -= error * dt
return output
# Example usage: temperature control