Create C firmware for a PWM motor driver with a PID controller that has anti-windup protection for the integral term. The controller needs to run at exactly 1kHz using a hardware timer interrupt.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Producing detailed Atmega328P PID motor driver code
The chunk outlines a complete Atmega328P C firmware plan: Timer1 set for 20kHz PWM controlling motor duty, Timer2 configured for a 1kHz control-loop ISR running a PID with integral anti-windup via clamping, plus global volatile variables, setpoint, dummy speed reading, and saturation logic. The next step is creating the full final C code implementing these specifics.
Below is a minimal example of C firmware for an 8‑bit AVR (e.g. ATmega328P @ 16 MHz) that:
Generates a hardware PWM on OC1A to drive a motor (Timer1 in Fast‑PWM mode, ~20 kHz switching).
Runs a PID controller at exactly 1 kHz in a hardware timer interrupt (Timer2 in CTC mode).
Implements anti‑windup on the integral term (conditional integration and clamping).
Exposes placeholders for obtaining a speed measurement (e.g. from an encoder or ADC).
You can adapt the pin mappings, clock, and constants to your specific microcontroller and hardware.
c
/*
* Simple PWM motor driver with PID (anti-windup), 1 kHz loop.
* Target: ATmega328P @ 16 MHz (e.g. Arduino Uno)
*
* PWM pin: OC1A (PB1 / Arduino D9)
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdint.h>
#define F_CPU 16000000UL
/* ======= PWM (Timer1) configuration ======= */
#define PWM_PRESCALER 8
#define PWM_TOP_VALUE 99 // Fast-PWM with ICR1, -> 16MHz/(8*(99+1)) ≈ 20 kHz
#define PWM_MAX_DUTY PWM_TOP_VALUE
/* ======= PID gains (tune for your system) ======= */
volatile float Kp = 0.8f;
volatile float Ki = 0.2f;
volatile float Kd = 0.01f;
/* ======= PID state ======= */
volatile float setpoint = 0.0f; // Desired speed (units: e.g. ticks/s)
volatile float measured_speed = 0.0f; // Actual speed feedback (update from encoder/ADC)
volatile float integral_term = 0.0f;
volatile float prev_error = 0.0f;
volatile float dt_sec = 0.001f; // 1 kHz => 1 ms => 0.001 s
/* Clamp limits for anti-windup */
volatile float integral_min = -1000.0f;
volatile float integral_max = 1000.0f;
/* ======= Function prototypes ======= */
static void init_pwm(void);
static void init_control_timer(void);
static inline void set_pwm_duty(uint16_t duty);
static inline float read_speed_sensor(void);
/* ======= Main ======= */
int main(void)
{
/* Example setpoint (tune in your application) */
setpoint = 500.0f; // Example target speed in "units"
init_pwm();
init_control_timer();
sei(); // Enable global interrupts
/* Main loop: update measured_speed from your sensor/encoder here */
while (1) {
// For a real application, update measured_speed from encoder pulses
// or an ADC reading. This example just leaves it as-is.
// Example: measured_speed = read_speed_sensor();
}
return 0;
}
/* ======= Hardware setup ======= */
static void init_pwm(void)
{
/* Set OC1A (PB1) as output */
DDRB |= (1 << PB1);
/*
* Timer1 Fast PWM, mode 14: WGM13:0 = 14 (0b1110)
* Non-inverting on OC1A: COM1A1 = 1, COM1A0 = 0
*/
TCCR1A = (1 << COM1A1); // Clear OC1A on compare match, set at BOTTOM
TCCR1B = (1 << WGM13) | (1 << WGM12); // Mode 14 part
TCCR1A |= (1 << WGM11); // Mode 14 part
TCCR1A &= ~(1 << WGM10);
/* Set TOP value for desired PWM frequency */
ICR1 = PWM_TOP_VALUE;
/* Start Timer1 with prescaler = 8 */
TCCR1B |= (1 << CS11);
/* Initialize duty to 0 */
OCR1A = 0;
}
static void init_control_timer(void)
{
/*
* Timer2 in CTC mode to fire interrupt at 1 kHz:
* f = F_CPU / (prescaler * (OCR2A + 1))
*
* Choose prescaler = 64:
* f = 16 MHz / (64 * (OCR2A + 1)) => OCR2A = 249 for 1 kHz
*/
TCCR2A = (1 << WGM21); // CTC mode, OCR2A as TOP
TCCR2B = 0; // Stop timer to set OCR2A first
OCR2A = 249; // 1 kHz
TIMSK2 = (1 << OCIE2A); // Enable compare match interrupt
TCCR2B |= (1 << CS22); // Start timer with prescaler 64
}
/* ======= PID computation ISR (1 kHz) ======= */
ISR(TIMER2_COMPA_vect)
{
/* Read current speed (updated externally, or call read_speed_sensor()) */
float current_speed = measured_speed; // or call read_speed_sensor()
/* PID error */
float error = setpoint - current_speed;
/* Derivative term */
float derivative = (error - prev_error) / dt_sec;
/* Propose new integral */
float new_integral = integral_term + (error * dt_sec);
/* Anti-windup: clamp integral to limits */
if (new_integral > integral_max) new_integral = integral_max;
if (new_integral < integral_min) new_integral = integral_min;
/* Compute the raw (unsaturated) control effort */
float u = (Kp * error) + (Ki * new_integral) + (Kd * derivative);
/* Saturate output to valid PWM range */
if (u > PWM_MAX_DUTY) u = PWM_MAX_DUTY;
if (u < 0.0f) u = 0.0f;
/*
* Optional conditional integration:
* Only accept the new integral if we're not driving further into saturation.
*/
if ((u >= PWM_MAX_DUTY && error > 0.0f) ||
(u <= 0.0f && error < 0.0f)) {
// Do not update integral to avoid windup
} else {
integral_term = new_integral;
}
/* Apply control effort to PWM */
set_pwm_duty((uint16_t)u);
/* Store for next iteration */
prev_error = error;
}
/* ======= Helper functions ======= */
static inline void set_pwm_duty(uint16_t duty)
{
if (duty > PWM_MAX_DUTY) duty = PWM_MAX_DUTY;
OCR1A = duty;
}
/* Stub for sensor reading: implement as needed (encoder, ADC, etc.) */
static inline float read_speed_sensor(void)
{
// Example placeholder: return some ADC/encoder-derived speed value
return 0.0f;
}
Notes and adaptation tips:
Timer2 is configured for a 1 kHz interrupt (OCR2A = 249, prescaler = 64). If you change F_CPU, recalculate OCR2A or choose a different prescaler.
Timer1 is used for PWM on OC1A at ~20 kHz (ICR1 = 99, prescaler = 8). Adjust to your motor/driver requirements.
Replace the read_speed_sensor() stub and the measured_speed assignment with your actual speed feedback (e.g. from an encoder ISR or ADC).
Tune Kp, Ki, and Kd to your motor and load. Also adjust integral_min/integral_max to prevent windup.
If you need more sophisticated anti‑windup, you can implement back‑calculation (integral_term += Kw*(u_sat - u_raw)) instead of clamping/conditional integration.