Conceptualizing Firmware Design
I'm focused on the fundamental aspects of the firmware architecture. I've begun to zero in on how PWM and PID will work together to control the motor. Now, the main challenge is to figure out the best way to handle the essential control aspects.
Outlining the Core Elements
I'm now prioritizing the foundational components. I'm moving from a general code base plan to structuring the motor control firmware, and I've focused on the main pieces that need the HAL (Hardware Abstraction Layer) and motor drivers. I also started building a basic framework for the PID logic and the initial structs that need to be defined.
Designing the PID Implementation
I'm deep in the implementation details of the PID controller now. Focusing on anti-windup strategies and struct definitions to hold gains and state variables. The goal is to make the PID_Compute function robust for use in the main control loop. I've also begun to consider how to handle negative output values from the PID in relation to motor direction.
Developing the System's Components
I'm expanding the code now, I've got the motor driver functions laid out, along with the beginnings of the encoder interface, aiming to track pulses for velocity calculations. Also, I'm working to refine the PID controller structure. I will focus on implementing the pseudo-HAL to ensure portability across different microcontrollers.
Structuring the Code Framework
I am now structuring the firmware components based on the identified core elements. I've designed the pid.h, pid.c, motor.h, motor.c, encoder.h and encoder.c files. The control loop structure is now defined inside of main.c, and I'm developing a rudimentary timer setup for the PID's sample time. I also started implementing pseudo-HAL functions to ensure code portability, focusing on essential functions like HAL_GPIO_Write and HAL_PWM_SetDuty.
This allows for a modular design suitable for most microcontrollers (STM32, AVR/Arduino, ESP32, PIC).
The solution is divided into three parts:
- The PID Library (Generic math).
- The Hardware Abstraction (Placeholders for your specific MCU).
- The Main Logic (Integrating sensor, math, and actuator).
1. PID Controller Struct and Logic (pid.h / pid.c)
This is a robust implementation including Integral Windup protection (essential for motor drivers to prevent the math from accumulating values beyond what the physical motor can output).
/* pid.h */
#ifndef PID_H
#define PID_H
typedef struct {
// Gains
float Kp;
float Ki;
float Kd;
// Output limits
float outputMin;
float outputMax;
// State variables
float integralErr;
float prevErr;
} PID_Config;
void PID_Init(PID_Config *pid, float kp, float ki, float kd, float min, float max);
float PID_Compute(PID_Config *pid, float setpoint, float measured, float dt);
#endif
/* pid.c */
#include "pid.h"
void PID_Init(PID_Config *pid, float kp, float ki, float kd, float min, float max) {
pid->Kp = kp;
pid->Ki = ki;
pid->Kd = kd;
pid->outputMin = min;
pid->outputMax = max;
pid->integralErr = 0.0f;
pid->prevErr = 0.0f;
}
float PID_Compute(PID_Config *pid, float setpoint, float measured, float dt) {
float error = setpoint - measured;
// Proportional term
float P = pid->Kp * error;
// Integral term with discrete integration
pid->integralErr += error * dt;
float I = pid->Ki * pid->integralErr;
// Derivative term
float derivative = (error - pid->prevErr) / dt;
float D = pid->Kd * derivative;
// Calculate total output
float output = P + I + D;
// Save error for next loop
pid->prevErr = error;
// --- Clamping / Anti-Windup ---
// If output exceeds limits, clamp it and stop integration to prevent windup
if (output > pid->outputMax) {
output = pid->outputMax;
// Optional: Back-calculate integral to prevent stickiness
pid->integralErr -= error * dt;
} else if (output < pid->outputMin) {
output = pid->outputMin;
pid->integralErr -= error * dt;
}
return output;
}
2. Hardware Abstraction Layer
Since I don't know your specific microcontroller (MSP430, STM32, Arduino), I have defined these as "stub" functions. You must fill these with your specific register writes.
/* hardware_driver.c */
#include <stdint.h>
#include <stdbool.h>
// Hardware Pins (Example definition)
#define MAX_PWM_DUTY 1000 // 100% duty cycle value of your timer
// --- Encoder Reading ---
// This should ideally be an atomic read from a hardware timer in Encoder Mode
volatile int32_t encoder_count = 0;
int32_t HARWARE_GetEncoderCount(void) {
// Return the current pulse count from your Quadrature Encoder
return encoder_count;
}
// --- Motor PWM Control ---
void HARDWARE_SetMotorPWM(float pwm_value) {
// 1. Determine Direction
if (pwm_value >= 0) {
// Set GPIO Pin for Forward
// HAL_GPIO_WritePin(DIR_PORT, DIR_PIN, HIGH);
} else {
// Set GPIO Pin for Reverse
// HAL_GPIO_WritePin(DIR_PORT, DIR_PIN, LOW);
pwm_value = -pwm_value; // Make positive for duty cycle
}
// 2. Cap at Max Duty Cycle (Safety)
if (pwm_value > MAX_PWM_DUTY) pwm_value = MAX_PWM_DUTY;
// 3. Write to Hardware Timer
// TIM->CCR1 = (uint32_t)pwm_value;
}
3. Main Application (main.c)
The key to stable PID is a fixed time step (dt). We use a while loop that waits for a specific time duration to pass before calculating.
#include <stdio.h>
#include "pid.h"
#include <stdint.h>
// --- Configuration ---
#define PID_LOOP_FREQUENCY_HZ 100.0f // Run PID at 100Hz
#define PID_DT (1.0f / PID_LOOP_FREQUENCY_HZ) // 0.01 seconds
// Global PID Instance
PID_Config motorPID;
// Helper to simulate 'millis' or generic system tick
extern uint32_t GetSystemTimeMs(void);
int main(void) {
// 1. Hardware Setup
// Init_GPIO();
// Init_PWM();
// Init_Encoder();
// 2. Initialize PID
// Kp=2.0, Ki=0.5, Kd=0.1 (These must be tuned manually!)
// Limits: -1000 to 1000 (PWM Timer Range)
PID_Init(&motorPID, 2.0f, 0.5f, 0.1f, -1000.0f, 1000.0f);
// 3. Variables
float targetSpeedRPMs = 150.0f; // Goal: 150 RPM
float currentSpeedRPMs = 0.0f;
int32_t prevEncoderPos = 0;
int32_t currentEncoderPos = 0;
uint32_t lastTime = GetSystemTimeMs();
while (1) {
uint32_t now = GetSystemTimeMs();
// Check if dt (10ms) has passed
if ((now - lastTime) >= (1000 / PID_LOOP_FREQUENCY_HZ)) {
// --- A. READ SENSORS ---
currentEncoderPos = HARWARE_GetEncoderCount();
// Calculate movement delta
int32_t deltaTicks = currentEncoderPos - prevEncoderPos;
prevEncoderPos = currentEncoderPos;
// Convert Ticks/Time to RPM (Formula depends on your Encoder Resolution)
// Example: (DeltaTicks / dt) * (60 sec / 1 min) / (Ticks per Revolution)
// Assuming 600 ticks per rev:
currentSpeedRPMs = ((float)deltaTicks / PID_DT) * 60.0f / 600.0f;
// --- B. COMPUTE PID ---
float motorOutput = PID_Compute(&motorPID, targetSpeedRPMs, currentSpeedRPMs, PID_DT);
// --- C. ACTUATE MOTOR ---
HARDWARE_SetMotorPWM(motorOutput);
// Update time tracker
lastTime = now;
}
}
}
4. How to Tune (Step-by-Step)
Before running the code, you must tune the values passed to PID_Init.
- Set Ki and Kd to 0. Set K to a small number.
Implementation Notes
- Data Types: This example uses
float for clarity. If you are using a low-power MCU without an FPU (Floating Point Unit), rewrite the math using int32_t Fixed Point arithmetic (Control = error * 1000 / Kp) to improve performance by 10x-50x.
- Input Filtering: If
currentSpeedRPMs is jittery (common with encoders), apply a simple Low Pass Filter (moving average) to the speed variable before passing it into PID_Compute, or the D-term will cause the motor to spasm.
- Sample Time:
dt must be accurate. If your GetSystemTimeMs() loop varies wildly, the integration math will be wrong. For production systems, run the PID calculation inside a hardware Timer Interrupt rather than the main while loop.