The user wants firmware in C to control a PWM motor driver using PID control.
This is a broad request, as the specific hardware (microcontroller, motor driver chip, encoder type) isn't specified.
To provide a useful answer, I need to:
- Abstract the hardware: Use generic C code but define clear interfaces (HAL - Hardware Abstraction Layer) so the user knows where to put their specific hardware code.
- Implement a PID algorithm: This is the core logic.
- Implement a control loop: How often does the PID run? How are setpoints updated?
- Structure the code: Good practice suggests separating the PID logic from the hardware driver.
Key components of the solution:
- PID Struct: To hold gains (Kp,Ki,Kd), limits (min/max output), integral term state, and previous error.
- PID Calculation Function: Takes the setpoint and current measurement, returns the control output (PWM duty cycle).
- Hardware Interface:
- Read Encoder: Function to get current speed or position.
- Set PWM: Function to update the motor driver duty cycle and direction.
- Timer/Interrupt: A steady "tick" to run the control loop at a fixed frequency.
- Main Loop: Demonstrates how to tie it all together.
Drafting the PID Logic:
- Error = Setpoint - Measurement.
- Proportional = Kp×Error.
- Integral = Integral + (Ki).
Refining the PID Logic:
- Derivative on Measurement vs Error: Usually better to do d(Input)/dt to avoid "derivative kick" on setpoint changes, but for a simple example, d(Error)/dt is standard and easier to understand. I'll stick to the standard error-based for simplicity but maybe add a comment.
- Time (): It's crucial to handle time correctly. Assuming a fixed timestep (e.g., called in a timer ISR) makes the math easier (multiply gains by or absorb into and ). I will assume a fixed timestep passed to the function or pre-calculated constants.
Hardware Assumptions:
- STM32 is a very common platform for this, but Arduino is more accessible to beginners. However, writing purely generic C is best for a "firmware" request. I will create a
hardware.h and hardware.c mock-up.
Structure of the Response:
- Overview: Explain the approach (Hardware Abstraction + PID Algorithm).
- PID Module (
pid.c/h): The reusable math.
- Hardware Interface (
motor_driver.c/h): Where the user puts pin manipulation code.
- Main/Application (
main.c): The loop/ISR.
- Tuning Tips: PID isn't just code; it's tuning.
Code details:
PIDController struct.
PID_Update function.
- Anti-windup clamping logic.
Self-Correction during drafting:
- Issue: Floating point math can be slow on some microcontrollers.
- Decision: I'll use
float for readability. It's fine on STM32/ESP32. If they need fixed-point, that's a specific optimization request. I'll stick to float for clarity.
- Issue: Direction control.
- Decision: The PID output can be signed. The PWM driver needs to interpret negative numbers as reverse (using an H-bridge).
Final Code Plan:
- pid.h: Struct definition and API.
- pid.c: The math.
- main.c: Example usage with a timer ISR simulation.
Let's write the code.
- PID Struct:
Kp, Ki, Kd, integrator, prevError, limMin, limMax, dt.
- Update Function:
error = setpoint - measurement
proportional = Kp * error
integrator += Ki * error * dt (Clamp integrator immediately to prevent windup? Or clamp total output? Standard approach: Calculate output, clamp output, if clamped && sign same as error, stop integrating. Simpler approach for basic tutorial: Clamp output, use back-calculation or just clamping). I will use a standard clamping approach on the integrator or total output. Let's clamp the total output.
Let's refine the "Main" loop. It needs to show a Timer Interrupt Service Routine (ISR).
Safety Note: Motors can be dangerous. Mention enabling limits and watchdogs.
Let's assemble the response.
Here is a complete, modular C firmware implementation for a PID motor controller.
This solution is designed to be hardware agnostic (portable). It separates the PID logic from the hardware-specific code (Timers, GPIOs) so you can adapt it to STM32, AVR (Arduino), ESP32, or PIC microcontrollers.
1. The PID Module (pid_controller.h & .c)
This handles the math.
pid_controller.h
#ifndef PID_CONTROLLER_H
#define PID_CONTROLLER_H
typedef struct {
// Tuning parameters
float Kp;
float Ki;
float Kd;
// Limits
float integral_limit; // Anti-windup limit for integral term
float output_limit; // Max PWM duty cycle (e.g., 100.0 or 255.0)
// State variables (internal)
float integral;
float prev_error;
float prev_measurement; // Used for Derivative on Measurement
} PID_Controller;
void PID_Init(PID_Controller *pid, float Kp, float Ki, float Kd, float integral_lim, float out_lim);
float PID_Compute(PID_Controller *pid, float setpoint, float measurement, float dt);
#endif
pid_controller.c
#include "pid_controller.h"
#include <math.h>
void PID_Init(PID_Controller *pid, float Kp, float Ki, float Kd, float integral_lim, float out_lim) {
pid->Kp = Kp;
pid->Ki = Ki;
pid->Kd = Kd;
pid->integral_limit = integral_lim;
pid->output_limit = out_lim;
pid->integral = 0.0f;
pid->prev_error = 0.0f;
pid->prev_measurement = 0.0f;
}
float PID_Compute(PID_Controller *pid, float setpoint, float measurement, float dt) {
float error = setpoint - measurement;
/*
* Proportional Term
*/
float proportional = pid->Kp * error;
/*
* Integral Term
* Accumulate error scaled by dt
*/
pid->integral += error * dt;
// Anti-windup: Clamp the integral term
if (pid->integral > pid->integral_limit) {
pid->integral = pid->integral_limit;
} else if (pid->integral < -pid->integral_limit) {
pid->integral = -pid->integral_limit;
}
float integral = pid->Ki * pid->integral;
/*
* Derivative Term
* Using "Derivative on Measurement" to avoid "Derivative Kick"
* when setpoint changes suddenly.
* Formula: -Kd * (d(measurement)/dt)
*/
float derivative = pid->Kd * ((measurement - pid->prev_measurement) / dt);
/*
* Calculate Total Output
*/
float output = proportional + integral - derivative;
// Output Clamping (Saturation)
if (output > pid->output_limit) {
output = pid->output_limit;
} else if (output < -pid->output_limit) {
output = -pid->output_limit;
}
// Store state for next iteration
pid->prev_error = error;
pid->prev_measurement = measurement;
return output;
}
2. The Hardware Abstraction Layer (motor_driver.h)
This is where you map the C logic to your specific microcontroller pins and timers.
motor_driver.h
#ifndef MOTOR_DRIVER_H
#define MOTOR_DRIVER_H
// 1. Hardware Setup Functions
void Motor_HW_Init(void); // Configures PWM Timer and GPIO
void Encoder_HW_Init(void); // Configures Encoder Timer/Interrupts
// 2. Control Functions
void Motor_SetPWM(float pwm_value); // Takes signed float (-100 to 100)
float Motor_GetSpeed(void); // Returns current speed (RPM or counts/s)
// 3. Timing
uint32_t Get_SystemTick(void); // Returns milliseconds since boot
#endif
motor_driver.c (Example Implementation)
Note: This contains pseudo-code for common MCUs (like STM32 HAL or Arduino). You must uncomment the section matching your hardware.
#include "motor_driver.h"
#include "pid_controller.h"
#include <stdlib.h>
// --- Hardware Specific Implementations ---
// Example: Global counter for encoder ticks (volatile for interrupts)
volatile int32_t encoder_ticks = 0;
void Motor_HW_Init(void) {
// TODO: Initialize PWM Timer
// Example STM32: HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
// Example Arduino: pinMode(9, OUTPUT);
}
void Encoder_HW_Init(void) {
// TODO: Initialize Encoder Interrupts or Hardware Quadrature Encoder
}
// PWM Value: -100.0 to 100.0 (assuming 100% duty cycle is max)
void Motor_SetPWM(float pwm_value) {
// 1. Determine Direction
if (pwm_value > 0) {
// Set GPIO A High, GPIO B Low (Forward)
} else {
// Set GPIO A Low, GPIO B High (Reverse)
pwm_value = -pwm_value; // Make magnitude positive
}
// 2. Clamp Duty Cycle
if (pwm_value > 100.0f) pwm_value = 100.0f;
// 3. Write to Hardware Register
uint32_t duty_register = (uint32_t)pwm_value; // Scale to timer resolution
// Pseudo-code:
// __HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_1, duty_register);
}
// Reads encoder and calculates speed (must be called at fixed intervals)
float Motor_GetSpeed(void) {
// This logic depends on if you are counting pulses per second
// or measuring pulse width.
// Here is a simple "Counts per Loop" approach:
static int32_t last_ticks = 0;
int32_t current_ticks = encoder_ticks; // Read volatile var
int32_t delta = current_ticks - last_ticks;
last_ticks = current_ticks;
// Convert ticks to standard units (e.g., RPM) if you have conversion factor
// For PID, raw "ticks per sample" is often sufficient.
return (float)delta;
}
uint32_t Get_SystemTick(void) {
// Return system timer
// STM32: return HAL_GetTick();
// Arduino: return millis();
return 0;
}
// --- Interrupt Service Routines (ISR) ---
// If using software interrupts for encoder:
// void EXTI_Handler() { if(pin_high) encoder_ticks++; else encoder_ticks--; }
3. Main Application Logic (main.c)
This ties everything together in a control loop.
#include "motor_driver.h"
#include "pid_controller.h"
// Configuration
#define PID_SAMPLE_TIME_MS 10 // Run PID loop every 10ms (100Hz)
// Global Objects
PID_Controller motorPID;
float target_speed = 50.0f; // Target setpoint (units match GetSpeed)
int main(void) {
// 1. Init Hardware
Motor_HW_Init();
Encoder_HW_Init();
// 2. Init PID
// Kp=2.0, Ki=0.5, Kd=0.1, IntLim=100, OutLim=100
PID_Init(&motorPID, 2.0f, 0.5f, 0.1f, 100.0f, 100.0f);
uint32_t last_tick = Get_SystemTick();
// 3. Super Loop
while (1) {
uint32_t now = Get_SystemTick();
// Check if it's time to run the control loop
if (now - last_tick >= PID_SAMPLE_TIME_MS) {
float dt = (float)(now - last_tick) / 1000.0f; // Convert ms to seconds
last_tick = now;
// A. Read Sensor
float current_speed = Motor_GetSpeed();
// B. Compute PID
// Note: Pass 'dt' explicitly to handle jitter in loop timing
float control_signal = PID_Compute(&motorPID, target_speed, current_speed, dt);
// C. Apply Output
Motor_SetPWM(control_signal);
}
// Other tasks (UI, Comms) can go here
}
}
How to Tune the System
- Set all gains to zero.
- Increase Kp: Until the motor starts oscillating (overshooting) the target speed, then back it off slightly.
- Increase Kd: If the motor is oscillating too much, add Kd to dampen the "springiness". This resists rapid changes.
- Increase Ki: If the motor settles at a speed below your target (due to friction or gravity), add Ki. This will slowly build up force to eliminate the error. Warning: Too much Ki causes instability.
Critical Implementation Details
- Integral Windup: If your motor is stalled (physically blocked), the Integral term will grow massive (
windup). When you unblock it, the motor will spin at max speed for a long time. The integral_limit in the struct prevents this.
- Derivative Kick: The code uses "Derivative on Measurement" (subtracting the change in measurement rather than the change in error). This prevents the motor from jerking violently if you suddenly change the
target_speed variable.
- Timing: The loop must run at a fixed interval (e.g., 10ms). The
dt calculation inside the loop accounts for small timing errors.