+motors, not crashing, ADC needs DMA fix to stop messing up other DMAs
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
set(KPI_Rover_Motors_Inc
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
|
||||
set(KPI_Rover_Motors_Src
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/drvMotors.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/PCA9685.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/ulGD.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/ulMotorsController.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/ulPID.c
|
||||
)
|
||||
|
||||
add_library(KPI_Rover_Motors STATIC)
|
||||
|
||||
target_include_directories(KPI_Rover_Motors PRIVATE
|
||||
${KPI_Rover_Motors_Inc}
|
||||
)
|
||||
|
||||
target_sources(KPI_Rover_Motors PRIVATE
|
||||
${KPI_Rover_Motors_Src}
|
||||
)
|
||||
|
||||
target_link_libraries(KPI_Rover_Motors PRIVATE
|
||||
FREERTOS_H
|
||||
HAL_H
|
||||
KPI_Rover_Database_H
|
||||
KPI_Rover_Logger_H
|
||||
)
|
||||
|
||||
add_library(KPI_Rover_Motors_H INTERFACE)
|
||||
target_include_directories(KPI_Rover_Motors_H INTERFACE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
@@ -0,0 +1,122 @@
|
||||
#include "PCA9685.h"
|
||||
#include "stm32f4xx_hal.h"
|
||||
#include "hwI2C2.h"
|
||||
|
||||
/* PCA9685 I2C address */
|
||||
/* 0x40 is the 7-bit address. HAL requires it shifted left by 1 (0x80) */
|
||||
#define PCA9685_ADDR (0x40 << 1)
|
||||
|
||||
/* Register Addresses */
|
||||
#define MODE1 0x00
|
||||
#define PRESCALE 0xFE
|
||||
#define LED0_ON_L 0x06
|
||||
|
||||
/**
|
||||
* Helper: Write a single byte to a register.
|
||||
*/
|
||||
#define pca9685_write(reg, data) do \
|
||||
{ \
|
||||
if (pca9685_write_i2c(reg, data) == false) \
|
||||
{ \
|
||||
return false; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
static bool pca9685_write_i2c(uint8_t reg, uint8_t data)
|
||||
{
|
||||
return HAL_I2C_Mem_Write(&hi2c2,
|
||||
PCA9685_ADDR,
|
||||
reg,
|
||||
I2C_MEMADD_SIZE_8BIT,
|
||||
&data,
|
||||
1,
|
||||
10) == HAL_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: Write 4 bytes consecutively (Burst Write).
|
||||
* Used to update all PWM registers (ON_L, ON_H, OFF_L, OFF_H) in one go.
|
||||
*/
|
||||
static void pca9685_write4(uint8_t reg, uint16_t on, uint16_t off)
|
||||
{
|
||||
uint8_t buf[4];
|
||||
/* Split 12-bit values into Low and High bytes */
|
||||
buf[0] = on & 0xFF; // ON_L
|
||||
buf[1] = on >> 8; // ON_H
|
||||
buf[2] = off & 0xFF; // OFF_L
|
||||
buf[3] = off >> 8; // OFF_H
|
||||
|
||||
HAL_I2C_Mem_Write(&hi2c2,
|
||||
PCA9685_ADDR,
|
||||
reg,
|
||||
I2C_MEMADD_SIZE_8BIT,
|
||||
buf,
|
||||
4,
|
||||
10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the PCA9685 chip.
|
||||
* Setup frequency and enable auto-increment mode.
|
||||
*/
|
||||
bool PCA9685_Init(void)
|
||||
{
|
||||
/* 1. Reset device (Wake up) */
|
||||
pca9685_write(MODE1, 0x00);
|
||||
HAL_Delay(10);
|
||||
|
||||
/* 2. Setup PWM Frequency ~1000Hz */
|
||||
/* Formula: prescale = 25MHz / (4096 * update_rate) - 1 */
|
||||
/* For 1000Hz: 25000000 / (4096 * 1000) - 1 ~= 5 */
|
||||
uint8_t prescale = 5;
|
||||
|
||||
/* To change pre-scaler, we must be in SLEEP mode */
|
||||
pca9685_write(MODE1, 0x10); // Sleep mode
|
||||
HAL_Delay(1);
|
||||
|
||||
pca9685_write(PRESCALE, prescale); // Write pre-scaler
|
||||
|
||||
/* 3. Wake up and set Auto-Increment */
|
||||
/* 0xA1: 1010 0001
|
||||
* Bit 5 (0x20): Auto-Increment enabled (allows writing 4 bytes at once)
|
||||
* Bit 0 (0x01): ALLCALL enabled
|
||||
*/
|
||||
pca9685_write(MODE1, 0xA1);
|
||||
HAL_Delay(5);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set PWM duty cycle for a specific channel.
|
||||
* @param channel: 0 to 15
|
||||
* @param on: Step number to turn ON (usually 0)
|
||||
* @param off: Step number to turn OFF (0 to 4095) - This acts as Duty Cycle
|
||||
*/
|
||||
void PCA9685_SetPWM(uint8_t channel, uint16_t on, uint16_t off)
|
||||
{
|
||||
/* Safety check */
|
||||
if (channel > 15)
|
||||
return;
|
||||
|
||||
/* 12-bit limit check (4095 is max) */
|
||||
if (off > 4095)
|
||||
off = 4095;
|
||||
|
||||
/* Calculate register address for this channel */
|
||||
/* Each channel has 4 registers, starting at LED0_ON_L (0x06) */
|
||||
pca9685_write4(LED0_ON_L + 4 * channel, on, off);
|
||||
}
|
||||
|
||||
void PCA9685_SetPin(uint8_t channel, uint8_t val)
|
||||
{
|
||||
if (channel > 15) return;
|
||||
|
||||
if (val) {
|
||||
// Full ON: Bit 4 в ON_H 1 - 4096, OFF в 0
|
||||
pca9685_write4(LED0_ON_L + 4 * channel, 0x1000, 0x0000);
|
||||
} else {
|
||||
// Full OFF: ON в 0, Bit 4 в OFF_H 1 - 4096
|
||||
pca9685_write4(LED0_ON_L + 4 * channel, 0x0000, 0x1000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
#ifndef PCA_9685_H_
|
||||
#define PCA_9685_H_
|
||||
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
bool PCA9685_Init(void);
|
||||
void PCA9685_SetPWM(uint8_t channel, uint16_t on, uint16_t off);
|
||||
void PCA9685_SetPin(uint8_t channel, uint8_t val);
|
||||
|
||||
#endif // PCA_9685_H_
|
||||
@@ -0,0 +1,74 @@
|
||||
#include "drvMotors.h"
|
||||
#include "PCA9685.h"
|
||||
//#include "ulog.h"
|
||||
|
||||
void DriverMotor_Init(drvMotor_t* motor)
|
||||
{
|
||||
if (motor->pwm_src == PWM_SRC_TIM) {
|
||||
HAL_TIM_PWM_Start(motor->pwm.tim.htim, motor->pwm.tim.channel);
|
||||
__HAL_TIM_MOE_ENABLE(motor->pwm.tim.htim);
|
||||
}
|
||||
else if (motor->pwm_src == PWM_SRC_PCA9685) {
|
||||
PCA9685_SetPWM(motor->pwm.pca.channel, 0, 0);
|
||||
PCA9685_SetPin(motor->in1_pca_channel, 0);
|
||||
PCA9685_SetPin(motor->in2_pca_channel, 0);
|
||||
}
|
||||
|
||||
motor->enabled = false;
|
||||
motor->last_forward = false;
|
||||
DriverMotor_setDirection(motor, true);
|
||||
}
|
||||
|
||||
void DriverMotor_Enable(drvMotor_t* motor)
|
||||
{
|
||||
motor->enabled = true;
|
||||
DriverMotor_setPwm(motor, 0);
|
||||
}
|
||||
|
||||
void DriverMotor_Disable(drvMotor_t* motor)
|
||||
{
|
||||
motor->enabled = false;
|
||||
DriverMotor_setPwm(motor, 0);
|
||||
}
|
||||
|
||||
void DriverMotor_setDirection(drvMotor_t* motor, bool forward){
|
||||
if (motor->pwm_src == PWM_SRC_PCA9685 && motor->last_forward == forward) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (motor->pwm_src == PWM_SRC_TIM) {
|
||||
HAL_GPIO_WritePin(motor->IN1_port, motor->IN1_pin, forward ? GPIO_PIN_SET : GPIO_PIN_RESET);
|
||||
HAL_GPIO_WritePin(motor->IN2_port, motor->IN2_pin, forward ? GPIO_PIN_RESET : GPIO_PIN_SET);
|
||||
}
|
||||
else if (motor->pwm_src == PWM_SRC_PCA9685) {
|
||||
if (forward) {
|
||||
PCA9685_SetPin(motor->in1_pca_channel, 1); // IN1 = HIGH
|
||||
PCA9685_SetPin(motor->in2_pca_channel, 0); // IN2 = LOW
|
||||
} else {
|
||||
PCA9685_SetPin(motor->in1_pca_channel, 0); // IN1 = LOW
|
||||
PCA9685_SetPin(motor->in2_pca_channel, 1); // IN2 = HIGH
|
||||
}
|
||||
|
||||
motor->last_forward = forward;
|
||||
}
|
||||
}
|
||||
|
||||
void DriverMotor_setPwm(drvMotor_t* motor, uint16_t pwm)
|
||||
{
|
||||
if (!motor->enabled)
|
||||
pwm = 0;
|
||||
|
||||
if (motor->pwm_src == PWM_SRC_TIM) {
|
||||
__HAL_TIM_SET_COMPARE(
|
||||
motor->pwm.tim.htim,
|
||||
motor->pwm.tim.channel,
|
||||
pwm
|
||||
);
|
||||
}
|
||||
else if (motor->pwm_src == PWM_SRC_PCA9685) {
|
||||
if (pwm > 4095) pwm = 4095;
|
||||
PCA9685_SetPWM(motor->pwm.pca.channel, 0, pwm);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
#ifndef MOTORS_DRIVER_H
|
||||
#define MOTORS_DRIVER_H
|
||||
|
||||
#include "stm32f4xx_hal.h"
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef enum {
|
||||
PWM_SRC_TIM,
|
||||
PWM_SRC_PCA9685
|
||||
} pwm_source_t;
|
||||
|
||||
typedef struct {
|
||||
GPIO_TypeDef* IN1_port;
|
||||
uint16_t IN1_pin;
|
||||
|
||||
GPIO_TypeDef* IN2_port;
|
||||
uint16_t IN2_pin;
|
||||
|
||||
pwm_source_t pwm_src;
|
||||
|
||||
uint8_t in1_pca_channel;
|
||||
uint8_t in2_pca_channel;
|
||||
|
||||
bool last_forward;
|
||||
|
||||
|
||||
union {
|
||||
struct {
|
||||
TIM_HandleTypeDef* htim;
|
||||
uint32_t channel;
|
||||
} tim;
|
||||
|
||||
struct {
|
||||
uint8_t channel;
|
||||
} pca;
|
||||
} pwm;
|
||||
|
||||
bool enabled;
|
||||
} drvMotor_t;
|
||||
|
||||
void DriverMotor_Init(drvMotor_t* motor);
|
||||
void DriverMotor_Enable(drvMotor_t* motor);
|
||||
void DriverMotor_Disable(drvMotor_t* motor);
|
||||
void DriverMotor_setDirection(drvMotor_t* motor, bool forward);
|
||||
void DriverMotor_setPwm(drvMotor_t* motor, uint16_t pwm);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,48 @@
|
||||
#include "main.h"
|
||||
|
||||
extern I2C_HandleTypeDef hi2c2;
|
||||
|
||||
void HW_I2C2_Init(void)
|
||||
{
|
||||
hi2c2.Instance = I2C2;
|
||||
hi2c2.Init.ClockSpeed = 100000;
|
||||
hi2c2.Init.DutyCycle = I2C_DUTYCYCLE_2;
|
||||
hi2c2.Init.OwnAddress1 = 0;
|
||||
hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
|
||||
hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
|
||||
hi2c2.Init.OwnAddress2 = 0;
|
||||
hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
|
||||
hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
|
||||
if (HAL_I2C_Init(&hi2c2) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
}
|
||||
|
||||
void HAL_I2C_MspInit(I2C_HandleTypeDef* i2cHandle)
|
||||
{
|
||||
|
||||
GPIO_InitTypeDef GPIO_InitStruct = {0};
|
||||
if(i2cHandle->Instance==I2C2)
|
||||
{
|
||||
__HAL_RCC_GPIOB_CLK_ENABLE();
|
||||
GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11;
|
||||
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
|
||||
GPIO_InitStruct.Pull = GPIO_NOPULL;
|
||||
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
|
||||
GPIO_InitStruct.Alternate = GPIO_AF4_I2C2;
|
||||
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
|
||||
__HAL_RCC_I2C2_CLK_ENABLE();
|
||||
}
|
||||
}
|
||||
|
||||
void HAL_I2C_MspDeInit(I2C_HandleTypeDef* i2cHandle)
|
||||
{
|
||||
|
||||
if(i2cHandle->Instance==I2C2)
|
||||
{
|
||||
__HAL_RCC_I2C2_CLK_DISABLE();
|
||||
HAL_GPIO_DeInit(GPIOB, GPIO_PIN_10);
|
||||
HAL_GPIO_DeInit(GPIOB, GPIO_PIN_11);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#include "main.h"
|
||||
|
||||
extern I2C_HandleTypeDef hi2c2;
|
||||
|
||||
void HW_I2C2_Init(void);
|
||||
void HAL_I2C_MspInit(I2C_HandleTypeDef* i2cHandle);
|
||||
void HAL_I2C_MspDeInit(I2C_HandleTypeDef* i2cHandle);
|
||||
@@ -0,0 +1,85 @@
|
||||
#include "ulGD.h"
|
||||
#include <math.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
/**
|
||||
* @file ulGD.c
|
||||
* @brief Online Gradient Descent (GD) Auto-tuner for PID Controllers.
|
||||
*
|
||||
* This module implements an adaptive learning algorithm based on the MIT Rule / Gradient Descent.
|
||||
* It automatically adjusts PID gains (Kp, Ki) in real-time to minimize error.
|
||||
*/
|
||||
|
||||
void ulGD_Init(ulGD_t* gd)
|
||||
{
|
||||
/* Tuning Speed */
|
||||
gd->alpha_p = 0.001f; // Kp learning rate
|
||||
gd->alpha_i = 0.0001f; // Ki learning rate
|
||||
|
||||
/* Safety Limits */
|
||||
gd->kp_min = 0.040f;
|
||||
gd->kp_max = 0.080f;
|
||||
|
||||
gd->ki_min = 0.010f;
|
||||
gd->ki_max = 0.020f;
|
||||
|
||||
/* Stability Settings */
|
||||
gd->max_delta = 0.0001f; // Max step size per cycle
|
||||
gd->deadzone = 0.02f; // Ignore small errors
|
||||
|
||||
/* Anti-Drift (Leakage) */
|
||||
gd->kp_anchor = 0.046f; // Target Kp (Base value)
|
||||
gd->ki_anchor = 0.013f; // Target Ki (Base value)
|
||||
gd->leakage_rate = 0.01f;// Return-to-base force
|
||||
}
|
||||
|
||||
void ulGD_Update(ulGD_t* gd, float error, float error_integral, float pwm_norm, float* kp, float* ki)
|
||||
{
|
||||
/* Validation */
|
||||
if (isnan(error) || isnan(error_integral)) return;
|
||||
if (isnan(*kp) || isnan(*ki)) return;
|
||||
|
||||
/* Skip if error is negligible */
|
||||
bool inside_deadzone = fabsf(error) < gd->deadzone;
|
||||
|
||||
/* Skip if motor is saturated (0% or 100%) */
|
||||
if (pwm_norm < 0.05f || pwm_norm > 0.95f) return;
|
||||
|
||||
float dKp = 0.0f;
|
||||
float dKi = 0.0f;
|
||||
|
||||
/* Calculate Gradients */
|
||||
if (!inside_deadzone) {
|
||||
// P-term gradient
|
||||
dKp = gd->alpha_p * error * fabsf(error);
|
||||
|
||||
// I-term gradient (with integral windup protection)
|
||||
float learning_integral = error_integral;
|
||||
if (learning_integral > 50.0f) learning_integral = 50.0f;
|
||||
if (learning_integral < -50.0f) learning_integral = -50.0f;
|
||||
|
||||
dKi = gd->alpha_i * error * learning_integral;
|
||||
|
||||
// Clamp step size
|
||||
if (dKp > gd->max_delta) dKp = gd->max_delta;
|
||||
if (dKp < -gd->max_delta) dKp = -gd->max_delta;
|
||||
|
||||
if (dKi > gd->max_delta) dKi = gd->max_delta;
|
||||
if (dKi < -gd->max_delta) dKi = -gd->max_delta;
|
||||
}
|
||||
|
||||
/* Calculate Leakage (Pull towards anchor) */
|
||||
float leak_p = (*kp - gd->kp_anchor) * gd->leakage_rate;
|
||||
float leak_i = (*ki - gd->ki_anchor) * gd->leakage_rate;
|
||||
|
||||
/* Update Gains */
|
||||
*kp = *kp + dKp - leak_p;
|
||||
*ki = *ki + dKi - leak_i;
|
||||
|
||||
/* Apply Hard Limits */
|
||||
if (*kp < gd->kp_min) *kp = gd->kp_min;
|
||||
if (*kp > gd->kp_max) *kp = gd->kp_max;
|
||||
|
||||
if (*ki < gd->ki_min) *ki = gd->ki_min;
|
||||
if (*ki > gd->ki_max) *ki = gd->ki_max;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#ifndef MOTORS_ULGD_H_
|
||||
#define MOTORS_ULGD_H_
|
||||
|
||||
#include <stdint.h>
|
||||
#include <math.h>
|
||||
|
||||
typedef struct {
|
||||
float alpha_p;
|
||||
float alpha_i;
|
||||
float kp_min, kp_max;
|
||||
float ki_min, ki_max;
|
||||
float max_delta;
|
||||
float deadzone;
|
||||
float kp_anchor;
|
||||
float ki_anchor;
|
||||
float leakage_rate;
|
||||
|
||||
} ulGD_t;
|
||||
|
||||
void ulGD_Init(ulGD_t* gd);
|
||||
void ulGD_Update(ulGD_t* gd, float error, float error_integral, float pwm_norm, float* kp, float* ki);
|
||||
|
||||
#endif /* MOTORS_ULGD_H_ */
|
||||
@@ -0,0 +1,373 @@
|
||||
#include "PCA9685.h"
|
||||
#include "cmsis_os.h"
|
||||
#include "drvMotors.h"
|
||||
#include "ulDatabase.h"
|
||||
#include "ulGD.h"
|
||||
#include "ulMotorsController.h"
|
||||
#include "ulPID.h"
|
||||
#include "ulog.h"
|
||||
#include <math.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MOTORS_CONTROL_PERIOD_MS 5
|
||||
#define ULMOTORS_NUM_MOTORS 4
|
||||
|
||||
typedef struct {
|
||||
drvMotor_t motors[ULMOTORS_NUM_MOTORS];
|
||||
ulPID_t pids[ULMOTORS_NUM_MOTORS];
|
||||
ulGD_t gd[ULMOTORS_NUM_MOTORS];
|
||||
|
||||
float last_pwm[ULMOTORS_NUM_MOTORS];
|
||||
uint16_t adapt_counter[ULMOTORS_NUM_MOTORS];
|
||||
|
||||
float pwm_max[ULMOTORS_NUM_MOTORS];
|
||||
|
||||
uint16_t period_ms;
|
||||
|
||||
float measured_rpm[ULMOTORS_NUM_MOTORS];
|
||||
float setpoint_rpm[ULMOTORS_NUM_MOTORS];
|
||||
float scale_filtered[ULMOTORS_NUM_MOTORS];
|
||||
} ulMotorsController_t;
|
||||
|
||||
typedef enum
|
||||
{
|
||||
MOTORS_STATE_INIT = 0,
|
||||
MOTORS_STATE_IDLE,
|
||||
MOTORS_STATE_RUN,
|
||||
MOTORS_STATE_TEST, // TEST
|
||||
MOTORS_STATE_ERROR
|
||||
} MotorsCtrlState_t;
|
||||
|
||||
extern ulMotorsController_t g_motors_ctrl;
|
||||
|
||||
extern MotorsCtrlState_t g_motors_state;
|
||||
|
||||
static osTimerId_t motors_timer_handle;
|
||||
|
||||
|
||||
const float dt_sec = MOTORS_CONTROL_PERIOD_MS / 1000.0f;
|
||||
|
||||
ulMotorsController_t g_motors_ctrl;
|
||||
MotorsCtrlState_t g_motors_state = MOTORS_STATE_INIT;
|
||||
|
||||
static const uint16_t key_rpm[ULMOTORS_NUM_MOTORS] = {
|
||||
MOTOR_FL_RPM,
|
||||
MOTOR_RL_RPM,
|
||||
MOTOR_FR_RPM,
|
||||
MOTOR_RR_RPM
|
||||
};
|
||||
|
||||
static const uint16_t key_kp[ULMOTORS_NUM_MOTORS] = {
|
||||
MOTOR_FL_KP,
|
||||
MOTOR_RL_KP,
|
||||
MOTOR_FR_KP,
|
||||
MOTOR_RR_KP
|
||||
};
|
||||
|
||||
static const uint16_t key_ki[ULMOTORS_NUM_MOTORS] = {
|
||||
MOTOR_FL_KI,
|
||||
MOTOR_RL_KI,
|
||||
MOTOR_FR_KI,
|
||||
MOTOR_RR_KI
|
||||
};
|
||||
|
||||
static const uint16_t key_kd[ULMOTORS_NUM_MOTORS] = {
|
||||
MOTOR_FL_KD,
|
||||
MOTOR_RL_KD,
|
||||
MOTOR_FR_KD,
|
||||
MOTOR_RR_KD
|
||||
};
|
||||
|
||||
static const uint16_t key_setpoint[ULMOTORS_NUM_MOTORS] = {
|
||||
MOTOR_FL_SETPOINT,
|
||||
MOTOR_RL_SETPOINT,
|
||||
MOTOR_FR_SETPOINT,
|
||||
MOTOR_RR_SETPOINT
|
||||
};
|
||||
|
||||
static void Motors_UpdateFromDB_FloatArray(const uint16_t* keys, float* dst, int count)
|
||||
{
|
||||
for (int i = 0; i < count; i++) {
|
||||
int32_t val = 0;
|
||||
if (ulDatabase_getInt32(keys[i], &val)) {
|
||||
dst[i] = (float)val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void ulMotorsController_UpdateFeedback(ulMotorsController_t* ctrl)
|
||||
{
|
||||
Motors_UpdateFromDB_FloatArray(key_rpm, ctrl->measured_rpm, ULMOTORS_NUM_MOTORS);
|
||||
}
|
||||
|
||||
static void ulMotorsController_UpdateFromDB(ulMotorsController_t* ctrl)
|
||||
{
|
||||
Motors_UpdateFromDB_FloatArray(key_setpoint, ctrl->setpoint_rpm, ULMOTORS_NUM_MOTORS);
|
||||
}
|
||||
|
||||
|
||||
static void init_motors_hw_mapping(ulMotorsController_t* ctrl)
|
||||
{
|
||||
// MOTOR_1_FL
|
||||
ctrl->motors[0].pwm_src = PWM_SRC_PCA9685;
|
||||
ctrl->motors[0].pwm.pca.channel = 0; // MOTOR_1_PWM
|
||||
ctrl->motors[0].in1_pca_channel = 1; // MOTOR_1_FWD
|
||||
ctrl->motors[0].in2_pca_channel = 2; // MOTOR_1_RVR
|
||||
|
||||
// MOTOR_2_FR
|
||||
ctrl->motors[1].pwm_src = PWM_SRC_PCA9685;
|
||||
ctrl->motors[1].pwm.pca.channel = 4; // MOTOR_2_PWM
|
||||
ctrl->motors[1].in1_pca_channel = 5; // MOTOR_2_FWD
|
||||
ctrl->motors[1].in2_pca_channel = 6; // MOTOR_2_RVR
|
||||
|
||||
// MOTOR_3_RL
|
||||
ctrl->motors[2].pwm_src = PWM_SRC_PCA9685;
|
||||
ctrl->motors[2].pwm.pca.channel = 15; // MOTOR_3_PWM
|
||||
ctrl->motors[2].in1_pca_channel = 14; // MOTOR_3_FWD
|
||||
ctrl->motors[2].in2_pca_channel = 13; // MOTOR_3_RVR
|
||||
|
||||
// MOTOR_4_RR
|
||||
ctrl->motors[3].pwm_src = PWM_SRC_PCA9685;
|
||||
ctrl->motors[3].pwm.pca.channel = 11; // MOTOR_4_PWM
|
||||
ctrl->motors[3].in1_pca_channel = 10; // MOTOR_4_FWD
|
||||
ctrl->motors[3].in2_pca_channel = 9; // MOTOR_4_RVR
|
||||
|
||||
}
|
||||
|
||||
|
||||
void ulMotorsController_Init(ulMotorsController_t* ctrl)
|
||||
{
|
||||
ULOG_INFO("MotorsController init");
|
||||
|
||||
init_motors_hw_mapping(ctrl);
|
||||
|
||||
for (int i = 0; i < ULMOTORS_NUM_MOTORS; i++) {
|
||||
|
||||
float kp = 0.0f;
|
||||
float ki = 0.0f;
|
||||
float kd = 0.0f;
|
||||
|
||||
if (!ulDatabase_getFloat(key_kp[i], &kp)) {
|
||||
ULOG_ERROR("Failed to load Kp for motor %d! Using default.", i);
|
||||
kp = 0.046f;
|
||||
}
|
||||
|
||||
if (!ulDatabase_getFloat(key_ki[i], &ki)) {
|
||||
ULOG_ERROR("Failed to load Ki for motor %d!", i);
|
||||
ki = 0.013f;
|
||||
}
|
||||
|
||||
if (!ulDatabase_getFloat(key_kd[i], &kd)) {
|
||||
kd = 0.0001f;
|
||||
}
|
||||
|
||||
ulPID_Init(&ctrl->pids[i], kp, ki, kd);
|
||||
|
||||
ctrl->pids[i].deadzone = 0.05f;
|
||||
ctrl->pids[i].slew_rate = 25.0f;
|
||||
ctrl->pids[i].d_alpha = 0.05f;
|
||||
|
||||
ulGD_Init(&ctrl->gd[i]);
|
||||
|
||||
ulPID_SetOutputLimits(&ctrl->pids[i], 0.0f, 1.0f);
|
||||
ulPID_SetIntegralLimits(&ctrl->pids[i], -50.0f, 50.0f);
|
||||
|
||||
ctrl->last_pwm[i] = 0.0f;
|
||||
ctrl->setpoint_rpm[i] = 0.0f;
|
||||
ctrl->measured_rpm[i] = 0.0f;
|
||||
|
||||
|
||||
if (ctrl->motors[i].pwm_src == PWM_SRC_TIM) {
|
||||
ctrl->pwm_max[i] =
|
||||
(float)__HAL_TIM_GET_AUTORELOAD(
|
||||
ctrl->motors[i].pwm.tim.htim);
|
||||
}
|
||||
else {
|
||||
ctrl->pwm_max[i] = 4095.0f;
|
||||
}
|
||||
|
||||
ULOG_INFO("Motor[%d] pwm_max=%.0f", i, ctrl->pwm_max[i]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void ulMotorsController_Run(ulMotorsController_t* ctrl)
|
||||
{
|
||||
const float MAX_RPM_CONST = 250.0f;
|
||||
|
||||
for (int i = 0; i < ULMOTORS_NUM_MOTORS; i++) {
|
||||
|
||||
if (isnan(ctrl->pids[i].kp) || ctrl->pids[i].kp < 0.001f) ctrl->pids[i].kp = 0.046f;
|
||||
if (isnan(ctrl->pids[i].ki) || ctrl->pids[i].ki < 0.0f) ctrl->pids[i].ki = 0.013f;
|
||||
|
||||
float sp = ctrl->setpoint_rpm[i];
|
||||
float rpm = ctrl->measured_rpm[i];
|
||||
|
||||
if (isnan(rpm)) rpm = 0.0f;
|
||||
|
||||
bool forward = (sp >= 0.0f);
|
||||
DriverMotor_setDirection(&ctrl->motors[i], forward);
|
||||
|
||||
float pwm_norm = ulPID_Compute(&ctrl->pids[i], fabsf(sp), fabsf(rpm), dt_sec);
|
||||
|
||||
if (isnan(pwm_norm)) {
|
||||
pwm_norm = 0.0f;
|
||||
}
|
||||
|
||||
if (pwm_norm < 0.0f) pwm_norm = 0.0f;
|
||||
if (pwm_norm > 1.0f) pwm_norm = 1.0f;
|
||||
|
||||
float max_val = ctrl->pwm_max[i];
|
||||
if (max_val < 1.0f) max_val = 4095.0f;
|
||||
|
||||
uint32_t pwm_hw = (uint32_t)(pwm_norm * max_val);
|
||||
|
||||
if (pwm_hw > (uint32_t)max_val) pwm_hw = (uint32_t)max_val;
|
||||
|
||||
DriverMotor_setPwm(&ctrl->motors[i], pwm_hw);
|
||||
ctrl->last_pwm[i] = pwm_norm;
|
||||
|
||||
|
||||
// ADAPTIVE PI (GRADIENT DESCENT)
|
||||
|
||||
float error = sp - rpm;
|
||||
float error_norm = error / MAX_RPM_CONST;
|
||||
|
||||
ulGD_Update(
|
||||
&ctrl->gd[i],
|
||||
error_norm,
|
||||
ctrl->pids[i].integral,
|
||||
pwm_norm,
|
||||
&ctrl->pids[i].kp,
|
||||
&ctrl->pids[i].ki
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void MotorsTimerCallback(void *argument)
|
||||
{
|
||||
(void)argument;
|
||||
|
||||
switch (g_motors_state)
|
||||
{
|
||||
case MOTORS_STATE_INIT:
|
||||
ULOG_INFO("Motors state: INIT -> initializing HW");
|
||||
|
||||
for (int i = 0; i < ULMOTORS_NUM_MOTORS; i++) {
|
||||
DriverMotor_Init(&g_motors_ctrl.motors[i]);
|
||||
}
|
||||
|
||||
g_motors_state = MOTORS_STATE_IDLE;
|
||||
ULOG_INFO("Motors state: INIT -> IDLE");
|
||||
break;
|
||||
|
||||
case MOTORS_STATE_IDLE:
|
||||
{
|
||||
ulMotorsController_UpdateFromDB(&g_motors_ctrl);
|
||||
bool need_run = false;
|
||||
for (int i = 0; i < ULMOTORS_NUM_MOTORS; i++) {
|
||||
if (fabsf(g_motors_ctrl.setpoint_rpm[i]) > 1.0f) {
|
||||
need_run = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (need_run) {
|
||||
ULOG_INFO("Motors state: IDLE -> RUN");
|
||||
|
||||
for (int i = 0; i < ULMOTORS_NUM_MOTORS; i++) {
|
||||
DriverMotor_Enable(&g_motors_ctrl.motors[i]);
|
||||
ulPID_Reset(&g_motors_ctrl.pids[i]);
|
||||
}
|
||||
|
||||
g_motors_state = MOTORS_STATE_RUN;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case MOTORS_STATE_RUN:
|
||||
{
|
||||
static uint8_t sp_div = 0;
|
||||
|
||||
if (++sp_div >= 4) {
|
||||
sp_div = 0;
|
||||
ulMotorsController_UpdateFromDB(&g_motors_ctrl);
|
||||
}
|
||||
ulMotorsController_UpdateFeedback(&g_motors_ctrl);
|
||||
ulMotorsController_Run(&g_motors_ctrl);
|
||||
|
||||
bool all_zero = true;
|
||||
for (int i = 0; i < ULMOTORS_NUM_MOTORS; i++) {
|
||||
if (fabsf(g_motors_ctrl.setpoint_rpm[i]) > 1.0f) {
|
||||
all_zero = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (all_zero) {
|
||||
ULOG_INFO("Motors state: RUN -> IDLE (all setpoints ~0)");
|
||||
for (int i = 0; i < ULMOTORS_NUM_MOTORS; i++) {
|
||||
DriverMotor_setPwm(&g_motors_ctrl.motors[i], 0);
|
||||
g_motors_ctrl.last_pwm[i] = 0.0f;
|
||||
}
|
||||
g_motors_state = MOTORS_STATE_IDLE;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case MOTORS_STATE_ERROR:
|
||||
default:
|
||||
for (int i = 0; i < ULMOTORS_NUM_MOTORS; i++) {
|
||||
DriverMotor_setPwm(&g_motors_ctrl.motors[i], 0);
|
||||
g_motors_ctrl.last_pwm[i] = 0.0f;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void ulMotorsController_Task(void* argument)
|
||||
{
|
||||
(void)argument;
|
||||
|
||||
ulMotorsController_Init(&g_motors_ctrl);
|
||||
|
||||
if (!PCA9685_Init()) {
|
||||
ULOG_ERROR("Failed to initialize PCA9685");
|
||||
osThreadExit();
|
||||
}
|
||||
|
||||
const osTimerAttr_t timer_attrs = {
|
||||
.name = "Motors_Timer"
|
||||
};
|
||||
|
||||
motors_timer_handle = osTimerNew(MotorsTimerCallback, osTimerPeriodic, NULL, &timer_attrs);
|
||||
if (!motors_timer_handle) {
|
||||
ULOG_ERROR("Failed to create Motors timer");
|
||||
osThreadExit();
|
||||
}
|
||||
|
||||
osDelay(5);
|
||||
|
||||
if (osTimerStart(motors_timer_handle, MOTORS_CONTROL_PERIOD_MS) != osOK) {
|
||||
ULOG_ERROR("Failed to start Motors timer");
|
||||
osThreadExit();
|
||||
}
|
||||
|
||||
|
||||
for (;;) {
|
||||
|
||||
osDelay(5);
|
||||
}
|
||||
}
|
||||
|
||||
void ulMotorsController_init(void)
|
||||
{
|
||||
static const osThreadAttr_t MotorsCtrlTask_attributes = {
|
||||
.name = "MotorsCtrlTask",
|
||||
.priority = (osPriority_t) osPriorityNormal,
|
||||
.stack_size = 1024 * 4
|
||||
};
|
||||
(void) osThreadNew(ulMotorsController_Task, NULL, &MotorsCtrlTask_attributes);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#ifndef UL_MOTORS_CONTROLLER_H
|
||||
#define UL_MOTORS_CONTROLLER_H
|
||||
|
||||
//#include "ulGD.h"
|
||||
//#include "ulPID.h"
|
||||
//#include <stdint.h>
|
||||
|
||||
void ulMotorsController_init(void);
|
||||
//void ulMotorsController_Init(ulMotorsController_t* ctrl);
|
||||
//void ulMotorsController_Run(ulMotorsController_t* ctrl);
|
||||
//void ulMotorsController_Task(void* argument);
|
||||
|
||||
//void ulMotorsController_RetunePid(ulMotorsController_t* ctrl, int i);
|
||||
|
||||
#endif // UL_MOTORS_CONTROLLER_H
|
||||
@@ -0,0 +1,171 @@
|
||||
#include "stm32f4xx_hal.h"
|
||||
#include "ulPID.h"
|
||||
#include <math.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
// Gain for dynamic anti-windup (how fast to reduce integral when saturated)
|
||||
#define PID_AW_GAIN 0.5f
|
||||
|
||||
void ulPID_Init(ulPID_t* pid, float kp, float ki, float kd){
|
||||
pid->kp = kp;
|
||||
pid->ki = ki;
|
||||
pid->kd = kd;
|
||||
|
||||
pid->integral = 0.0f;
|
||||
pid->prev_meas = 0.0f;
|
||||
pid->d_filtered = 0.0f;
|
||||
|
||||
/* Output limits (usually 0.0 to 1.0 for PWM) */
|
||||
pid->out_min = 0.0f;
|
||||
pid->out_max = 1.0f;
|
||||
|
||||
/* Integral limits (prevent indefinite error accumulation) */
|
||||
pid->int_min = -1.0f;
|
||||
pid->int_max = 1.0f;
|
||||
|
||||
/* Setpoint filter (1.0 = no filtering, lower = smoother target) */
|
||||
pid->sp_filtered = 0.0f;
|
||||
pid->sp_alpha = 1.0f;
|
||||
|
||||
/* Derivative filter (CRITICAL for noisy encoders, 0.05-0.2 is good) */
|
||||
pid->d_alpha = 0.2f;
|
||||
|
||||
/* Max change of output per second (Soft Start) */
|
||||
pid->slew_rate = 100.0f;
|
||||
|
||||
/* Static friction compensation */
|
||||
pid->deadzone = 0.0f;
|
||||
|
||||
pid->last_output = 0.0f;
|
||||
|
||||
// pid->last_time is not used inside Compute anymore, but good to init
|
||||
pid->last_time = HAL_GetTick();
|
||||
pid->initialized = false;
|
||||
}
|
||||
|
||||
void ulPID_Reset(ulPID_t* pid){
|
||||
pid->integral = 0.0f;
|
||||
pid->prev_meas = 0.0f;
|
||||
pid->d_filtered = 0.0f;
|
||||
pid->last_output = 0.0f;
|
||||
pid->sp_filtered = 0.0f;
|
||||
pid->initialized = false;
|
||||
}
|
||||
|
||||
void ulPID_ResetI(ulPID_t* pid){
|
||||
pid->integral = 0.0f;
|
||||
}
|
||||
|
||||
void ulPID_SetParams(ulPID_t* pid, float kp, float ki, float kd){
|
||||
pid->kp = kp;
|
||||
pid->ki = ki;
|
||||
pid->kd = kd;
|
||||
}
|
||||
|
||||
void ulPID_SetOutputLimits(ulPID_t* pid, float out_min, float out_max){
|
||||
pid->out_min = out_min;
|
||||
pid->out_max = out_max;
|
||||
}
|
||||
|
||||
void ulPID_SetIntegralLimits(ulPID_t* pid, float int_min, float int_max){
|
||||
pid->int_min = int_min;
|
||||
pid->int_max = int_max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main PID calculation loop.
|
||||
* @param dt: Delta time in seconds (must be constant for stability!)
|
||||
*/
|
||||
float ulPID_Compute(ulPID_t* pid, float setpoint, float measured, float dt)
|
||||
{
|
||||
/* Safety: Avoid division by zero */
|
||||
if (dt <= 0.000001f) {
|
||||
return pid->last_output;
|
||||
}
|
||||
|
||||
/* Initialization (Bumpless Transfer) */
|
||||
/* Prevents "jumps" when PID is called for the first time */
|
||||
if (!pid->initialized)
|
||||
{
|
||||
pid->sp_filtered = setpoint;
|
||||
pid->prev_meas = measured;
|
||||
pid->d_filtered = 0.0f;
|
||||
pid->last_output = 0.0f;
|
||||
pid->initialized = true;
|
||||
}
|
||||
|
||||
/* Setpoint Filtering (Low Pass Filter) */
|
||||
/* Smooths out jerky changes in target speed */
|
||||
pid->sp_filtered += pid->sp_alpha * (setpoint - pid->sp_filtered);
|
||||
float sp = pid->sp_filtered;
|
||||
|
||||
/* Error Calculation */
|
||||
float error = sp - measured;
|
||||
|
||||
/* Integral Term (Accumulate Error) */
|
||||
pid->integral += error * dt;
|
||||
|
||||
// Hard clamp for integral to prevent overflow
|
||||
if (pid->integral > pid->int_max) pid->integral = pid->int_max;
|
||||
if (pid->integral < pid->int_min) pid->integral = pid->int_min;
|
||||
|
||||
/* Derivative Term (Derivative on Measurement) */
|
||||
/* We calculate slope of Sensor data, NOT Error. Prevents spikes when Setpoint changes. */
|
||||
float d_meas = (measured - pid->prev_meas) / dt;
|
||||
pid->prev_meas = measured;
|
||||
|
||||
// Note the minus sign: d(Error)/dt = -d(Measured)/dt (assuming constant setpoint)
|
||||
float d_raw = -d_meas;
|
||||
|
||||
// Filter the noisy D-term (Low Pass Filter)
|
||||
pid->d_filtered += pid->d_alpha * (d_raw - pid->d_filtered);
|
||||
|
||||
/* PID Sum */
|
||||
float out_unsat =
|
||||
pid->kp * error +
|
||||
pid->ki * pid->integral +
|
||||
pid->kd * pid->d_filtered;
|
||||
|
||||
/* Saturation (Clamping) */
|
||||
float out_clamped = out_unsat;
|
||||
if (out_clamped > pid->out_max) out_clamped = pid->out_max;
|
||||
if (out_clamped < pid->out_min) out_clamped = pid->out_min;
|
||||
|
||||
/* Dynamic Anti-Windup */
|
||||
/* If output is clamped, reduce Integral to stop it from growing uselessly */
|
||||
if (pid->ki != 0.0f && out_clamped != out_unsat)
|
||||
{
|
||||
float aw = out_clamped - out_unsat;
|
||||
pid->integral += (PID_AW_GAIN * aw * dt);
|
||||
}
|
||||
|
||||
float actuator = out_clamped;
|
||||
|
||||
/* Deadzone Compensation (Static Friction) */
|
||||
/* Adds a minimum power to overcome motor friction */
|
||||
if (fabsf(actuator) > 0.001f)
|
||||
{
|
||||
if (actuator > 0.0f)
|
||||
actuator += pid->deadzone;
|
||||
else
|
||||
actuator -= pid->deadzone;
|
||||
|
||||
// Re-clamp after adding deadzone
|
||||
if (actuator > pid->out_max) actuator = pid->out_max;
|
||||
if (actuator < pid->out_min) actuator = pid->out_min;
|
||||
}
|
||||
|
||||
/* Slew Rate Limiter (Soft Start / Anti-Shock) */
|
||||
/* Limits how fast the output can change to protect gears/electronics */
|
||||
float diff = actuator - pid->last_output;
|
||||
float max_change = pid->slew_rate * dt;
|
||||
|
||||
if (diff > max_change)
|
||||
actuator = pid->last_output + max_change;
|
||||
else if (diff < -max_change)
|
||||
actuator = pid->last_output - max_change;
|
||||
|
||||
pid->last_output = actuator;
|
||||
|
||||
return actuator;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#ifndef UL_PID_H
|
||||
#define UL_PID_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include "stm32f4xx_hal.h"
|
||||
|
||||
struct ulRLS_s;
|
||||
typedef struct ulRLS_s ulRLS_t;
|
||||
|
||||
typedef struct {
|
||||
float kp;
|
||||
float ki;
|
||||
float kd;
|
||||
|
||||
float integral;
|
||||
float prev_meas;
|
||||
float d_filtered;
|
||||
|
||||
float out_min;
|
||||
float out_max;
|
||||
|
||||
float int_min;
|
||||
float int_max;
|
||||
|
||||
float sp_filtered;
|
||||
float sp_alpha;
|
||||
|
||||
float d_alpha;
|
||||
float last_output;
|
||||
float slew_rate;
|
||||
|
||||
float deadzone;
|
||||
|
||||
uint32_t last_time;
|
||||
|
||||
bool initialized;
|
||||
} ulPID_t;
|
||||
|
||||
void ulPID_Init(ulPID_t* pid, float kp, float ki, float kd);
|
||||
void ulPID_Reset(ulPID_t* pid);
|
||||
void ulPID_SetParams(ulPID_t* pid, float kp, float ki, float kd);
|
||||
void ulPID_SetOutputLimits(ulPID_t* pid, float out_min, float out_max);
|
||||
void ulPID_SetIntegralLimits(ulPID_t* pid, float int_min, float int_max);
|
||||
float ulPID_Compute(ulPID_t* pid, float setpoint, float measured, float dt);
|
||||
void ulPID_AutoTune_FromRLS(ulPID_t* pid, const ulRLS_t* rls, float Ts);
|
||||
void ulPID_ResetI(ulPID_t* pid);
|
||||
#endif // UL_PID_H
|
||||
Reference in New Issue
Block a user