+motors, not crashing, ADC needs DMA fix to stop messing up other DMAs
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
#include "main.h"
|
||||
|
||||
ADC_HandleTypeDef hadc1;
|
||||
DMA_HandleTypeDef hdma_adc1;
|
||||
DMA_HandleTypeDef hdma_usart3_rx;
|
||||
DMA_HandleTypeDef hdma_usart3_tx;
|
||||
I2C_HandleTypeDef hi2c2;
|
||||
TIM_HandleTypeDef htim14;
|
||||
UART_HandleTypeDef huart3;
|
||||
|
||||
+38
-193
@@ -1,222 +1,67 @@
|
||||
/* USER CODE BEGIN Header */
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file : main.c
|
||||
* @brief : Main program body
|
||||
******************************************************************************
|
||||
* @attention
|
||||
*
|
||||
* Copyright (c) 2026 STMicroelectronics.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is licensed under terms that can be found in the LICENSE file
|
||||
* in the root directory of this software component.
|
||||
* If no LICENSE file comes with this software, it is provided AS-IS.
|
||||
*
|
||||
******************************************************************************
|
||||
*/
|
||||
/* USER CODE END Header */
|
||||
/* Includes ------------------------------------------------------------------*/
|
||||
#include "main.h"
|
||||
#include "cmsis_os.h"
|
||||
#include "KPIRover.h"
|
||||
|
||||
#if 0
|
||||
#include "adc.h"
|
||||
#include "dma.h"
|
||||
#include "i2c.h"
|
||||
#include "tim.h"
|
||||
#include "usart.h"
|
||||
#include "gpio.h"
|
||||
#endif
|
||||
|
||||
/* Private includes ----------------------------------------------------------*/
|
||||
/* USER CODE BEGIN Includes */
|
||||
|
||||
/* USER CODE END Includes */
|
||||
|
||||
/* Private typedef -----------------------------------------------------------*/
|
||||
/* USER CODE BEGIN PTD */
|
||||
|
||||
/* USER CODE END PTD */
|
||||
|
||||
/* Private define ------------------------------------------------------------*/
|
||||
/* USER CODE BEGIN PD */
|
||||
|
||||
/* USER CODE END PD */
|
||||
|
||||
/* Private macro -------------------------------------------------------------*/
|
||||
/* USER CODE BEGIN PM */
|
||||
|
||||
/* USER CODE END PM */
|
||||
|
||||
/* Private variables ---------------------------------------------------------*/
|
||||
|
||||
/* USER CODE BEGIN PV */
|
||||
|
||||
/* USER CODE END PV */
|
||||
|
||||
/* Private function prototypes -----------------------------------------------*/
|
||||
void SystemClock_Config(void);
|
||||
void MX_FREERTOS_Init(void);
|
||||
/* USER CODE BEGIN PFP */
|
||||
|
||||
/* USER CODE END PFP */
|
||||
|
||||
/* Private user code ---------------------------------------------------------*/
|
||||
/* USER CODE BEGIN 0 */
|
||||
|
||||
/* USER CODE END 0 */
|
||||
|
||||
/**
|
||||
* @brief The application entry point.
|
||||
* @retval int
|
||||
*/
|
||||
int main(void)
|
||||
{
|
||||
HAL_Init();
|
||||
SystemClock_Config();
|
||||
HAL_Init();
|
||||
SystemClock_Config();
|
||||
osKernelInitialize(); /* Call init function for freertos objects (in cmsis_os2.c) */
|
||||
|
||||
/* USER CODE BEGIN SysInit */
|
||||
KPIRover_Init();
|
||||
|
||||
/* USER CODE END SysInit */
|
||||
osKernelStart();
|
||||
|
||||
/* Initialize all configured peripherals */
|
||||
#if 0
|
||||
MX_GPIO_Init();
|
||||
MX_DMA_Init();
|
||||
MX_ADC1_Init();
|
||||
MX_TIM1_Init();
|
||||
MX_TIM2_Init();
|
||||
MX_TIM3_Init();
|
||||
MX_TIM4_Init();
|
||||
MX_I2C2_Init();
|
||||
MX_USART2_UART_Init();
|
||||
MX_USART3_UART_Init();
|
||||
#endif
|
||||
/* USER CODE BEGIN 2 */
|
||||
|
||||
/* USER CODE END 2 */
|
||||
|
||||
/* Init scheduler */
|
||||
osKernelInitialize(); /* Call init function for freertos objects (in cmsis_os2.c) */
|
||||
|
||||
KPIRover_Init();
|
||||
|
||||
/* Start scheduler */
|
||||
osKernelStart();
|
||||
|
||||
/* We should never get here as control is now taken by the scheduler */
|
||||
|
||||
/* Infinite loop */
|
||||
/* USER CODE BEGIN WHILE */
|
||||
while (1)
|
||||
{
|
||||
/* USER CODE END WHILE */
|
||||
|
||||
/* USER CODE BEGIN 3 */
|
||||
}
|
||||
/* USER CODE END 3 */
|
||||
while (1) { }
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief System Clock Configuration
|
||||
* @retval None
|
||||
*/
|
||||
void SystemClock_Config(void)
|
||||
{
|
||||
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
|
||||
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
|
||||
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
|
||||
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
|
||||
|
||||
/** Configure the main internal regulator output voltage
|
||||
*/
|
||||
__HAL_RCC_PWR_CLK_ENABLE();
|
||||
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
|
||||
__HAL_RCC_PWR_CLK_ENABLE();
|
||||
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
|
||||
|
||||
/** Initializes the RCC Oscillators according to the specified parameters
|
||||
* in the RCC_OscInitTypeDef structure.
|
||||
*/
|
||||
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
|
||||
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
|
||||
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
|
||||
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
|
||||
RCC_OscInitStruct.PLL.PLLM = 4;
|
||||
RCC_OscInitStruct.PLL.PLLN = 168;
|
||||
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
|
||||
RCC_OscInitStruct.PLL.PLLQ = 4;
|
||||
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
|
||||
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
|
||||
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
|
||||
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
|
||||
RCC_OscInitStruct.PLL.PLLM = 4;
|
||||
RCC_OscInitStruct.PLL.PLLN = 168;
|
||||
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
|
||||
RCC_OscInitStruct.PLL.PLLQ = 4;
|
||||
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
|
||||
/** Initializes the CPU, AHB and APB buses clocks
|
||||
*/
|
||||
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|
||||
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
|
||||
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
|
||||
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
|
||||
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
|
||||
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
|
||||
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|
||||
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
|
||||
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
|
||||
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
|
||||
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
|
||||
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
|
||||
|
||||
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
}
|
||||
|
||||
/* USER CODE BEGIN 4 */
|
||||
|
||||
/* USER CODE END 4 */
|
||||
|
||||
/**
|
||||
* @brief Period elapsed callback in non blocking mode
|
||||
* @note This function is called when TIM14 interrupt took place, inside
|
||||
* HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
|
||||
* a global variable "uwTick" used as application time base.
|
||||
* @param htim : TIM handle
|
||||
* @retval None
|
||||
*/
|
||||
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
|
||||
{
|
||||
/* USER CODE BEGIN Callback 0 */
|
||||
|
||||
/* USER CODE END Callback 0 */
|
||||
if (htim->Instance == TIM14)
|
||||
{
|
||||
HAL_IncTick();
|
||||
}
|
||||
/* USER CODE BEGIN Callback 1 */
|
||||
|
||||
/* USER CODE END Callback 1 */
|
||||
if (htim->Instance == TIM14)
|
||||
{
|
||||
HAL_IncTick();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief This function is executed in case of error occurrence.
|
||||
* @retval None
|
||||
*/
|
||||
void Error_Handler(void)
|
||||
{
|
||||
/* USER CODE BEGIN Error_Handler_Debug */
|
||||
/* User can add his own implementation to report the HAL error return state */
|
||||
__disable_irq();
|
||||
while (1)
|
||||
{
|
||||
}
|
||||
/* USER CODE END Error_Handler_Debug */
|
||||
__disable_irq();
|
||||
while (1) { }
|
||||
}
|
||||
#ifdef USE_FULL_ASSERT
|
||||
/**
|
||||
* @brief Reports the name of the source file and the source line number
|
||||
* where the assert_param error has occurred.
|
||||
* @param file: pointer to the source file name
|
||||
* @param line: assert_param error line source number
|
||||
* @retval None
|
||||
*/
|
||||
void assert_failed(uint8_t *file, uint32_t line)
|
||||
{
|
||||
/* USER CODE BEGIN 6 */
|
||||
/* User can add his own implementation to report the file name and line number,
|
||||
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
|
||||
/* USER CODE END 6 */
|
||||
}
|
||||
#endif /* USE_FULL_ASSERT */
|
||||
|
||||
@@ -154,7 +154,7 @@
|
||||
#define INSTRUCTION_CACHE_ENABLE 1U
|
||||
#define DATA_CACHE_ENABLE 1U
|
||||
|
||||
#define USE_HAL_ADC_REGISTER_CALLBACKS 0U /* ADC register callback disabled */
|
||||
#define USE_HAL_ADC_REGISTER_CALLBACKS 1U /* ADC register callback enabled */
|
||||
#define USE_HAL_CAN_REGISTER_CALLBACKS 0U /* CAN register callback disabled */
|
||||
#define USE_HAL_CEC_REGISTER_CALLBACKS 0U /* CEC register callback disabled */
|
||||
#define USE_HAL_CRYP_REGISTER_CALLBACKS 0U /* CRYP register callback disabled */
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
set(KPI_Rover_ADC_Inc
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
|
||||
set(KPI_Rover_ADC_Src
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/ulAdc.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/drvAdc.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/hwADC.c
|
||||
)
|
||||
|
||||
add_library(KPI_Rover_ADC STATIC)
|
||||
|
||||
target_include_directories(KPI_Rover_ADC PRIVATE
|
||||
${KPI_Rover_ADC_Inc}
|
||||
)
|
||||
|
||||
target_sources(KPI_Rover_ADC PRIVATE
|
||||
${KPI_Rover_ADC_Src}
|
||||
)
|
||||
|
||||
target_link_libraries(KPI_Rover_ADC PRIVATE
|
||||
FREERTOS_H
|
||||
HAL_H
|
||||
KPI_Rover_Database_H
|
||||
KPI_Rover_Logger_H
|
||||
)
|
||||
|
||||
add_library(KPI_Rover_ADC_H INTERFACE)
|
||||
target_include_directories(KPI_Rover_ADC_H INTERFACE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
@@ -0,0 +1,184 @@
|
||||
#include "drvAdc.h"
|
||||
#include "stm32f4xx_hal.h"
|
||||
#include "cmsis_os.h"
|
||||
#include <string.h>
|
||||
|
||||
extern ADC_HandleTypeDef hadc1;
|
||||
|
||||
#define DRV_ADC_FLAG_DMA_COMPLETE 0x01
|
||||
#define DRV_ADC_FLAG_TIMER_TRIG 0x02
|
||||
#define MEASUREMENT_PERIOD_MS 100
|
||||
|
||||
typedef enum { ADC_STATE_IDLE, ADC_STATE_BUSY } drv_adc_state_t;
|
||||
|
||||
static drv_adc_state_t current_state = ADC_STATE_IDLE;
|
||||
static uint8_t active_hw_channels[MAX_HW_ADC_ID];
|
||||
static size_t active_channel_count = 0;
|
||||
|
||||
static uint16_t dma_buffer[MAX_HW_ADC_ID * SAMPLES_PER_CYCLE];
|
||||
|
||||
static osThreadId_t drv_adc_thread_id = NULL;
|
||||
static osTimerId_t drv_adc_timer_id = NULL;
|
||||
|
||||
typedef struct {
|
||||
drvAdc_Callback cb;
|
||||
void* ctx;
|
||||
} adc_callback_entry_t;
|
||||
static adc_callback_entry_t callback_table[MAX_HW_ADC_ID];
|
||||
|
||||
|
||||
static uint16_t Filter_Algorithm_36Samples(uint16_t* data, size_t step) {
|
||||
uint32_t sum = 0;
|
||||
uint16_t min1 = 0xFFFF, min2 = 0xFFFF;
|
||||
uint16_t max1 = 0, max2 = 0;
|
||||
|
||||
for (int i = 0; i < SAMPLES_PER_CYCLE; i++) {
|
||||
uint16_t val = data[i * step];
|
||||
sum += val;
|
||||
|
||||
if (val < min1) {
|
||||
min2 = min1; min1 = val;
|
||||
} else if (val < min2) {
|
||||
min2 = val;
|
||||
}
|
||||
|
||||
if (val > max1) {
|
||||
max2 = max1; max1 = val;
|
||||
} else if (val > max2) {
|
||||
max2 = val;
|
||||
}
|
||||
}
|
||||
|
||||
sum -= (min1 + min2 + max1 + max2);
|
||||
return (uint16_t)(sum >> 5); // / 32
|
||||
}
|
||||
|
||||
static void drvAdc_WorkerTask(void *argument) {
|
||||
for (;;) {
|
||||
uint32_t flags = osThreadFlagsWait(DRV_ADC_FLAG_TIMER_TRIG | DRV_ADC_FLAG_DMA_COMPLETE, osFlagsWaitAny, osWaitForever);
|
||||
|
||||
switch (current_state) {
|
||||
|
||||
case ADC_STATE_IDLE:
|
||||
if (flags & DRV_ADC_FLAG_TIMER_TRIG) {
|
||||
HAL_StatusTypeDef status = HAL_ADC_Start_DMA(&hadc1,
|
||||
(uint32_t*)dma_buffer, active_channel_count * SAMPLES_PER_CYCLE);
|
||||
|
||||
if (status == HAL_OK) {
|
||||
current_state = ADC_STATE_BUSY;
|
||||
}
|
||||
else {
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case ADC_STATE_BUSY:
|
||||
if (flags & DRV_ADC_FLAG_DMA_COMPLETE) {
|
||||
|
||||
HAL_ADC_Stop_DMA(&hadc1);
|
||||
HAL_ADC_Stop(&hadc1);
|
||||
|
||||
for (size_t i = 0; i < active_channel_count; i++) {
|
||||
uint8_t hw_ch = active_hw_channels[i];
|
||||
|
||||
uint16_t filtered = Filter_Algorithm_36Samples(&dma_buffer[i], active_channel_count);
|
||||
|
||||
if (hw_ch < MAX_HW_ADC_ID && callback_table[hw_ch].cb != NULL) {
|
||||
callback_table[hw_ch].cb(hw_ch, (uint32_t)filtered, callback_table[hw_ch].ctx);
|
||||
}
|
||||
}
|
||||
|
||||
current_state = ADC_STATE_IDLE;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
HAL_ADC_Stop_DMA(&hadc1);
|
||||
current_state = ADC_STATE_IDLE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void drvAdc_TimerCallback(void *arg) {
|
||||
if (drv_adc_thread_id) {
|
||||
osThreadFlagsSet(drv_adc_thread_id, DRV_ADC_FLAG_TIMER_TRIG);
|
||||
}
|
||||
}
|
||||
|
||||
void drvAdc_init(uint32_t enabledChannels_mask) {
|
||||
active_channel_count = 0;
|
||||
memset(callback_table, 0, sizeof(callback_table));
|
||||
memset(dma_buffer, 0, sizeof(dma_buffer));
|
||||
|
||||
hadc1.Instance = ADC1;
|
||||
for (int i = 0; i < MAX_HW_ADC_ID; i++) {
|
||||
if (enabledChannels_mask & (1U << i)) {
|
||||
active_channel_count++;
|
||||
}
|
||||
}
|
||||
|
||||
hadc1.Init.NbrOfConversion = active_channel_count;
|
||||
hadc1.Init.ScanConvMode = ENABLE;
|
||||
hadc1.Init.ContinuousConvMode = ENABLE;
|
||||
hadc1.Init.DiscontinuousConvMode = DISABLE;
|
||||
hadc1.Init.DMAContinuousRequests = DISABLE;
|
||||
HAL_ADC_Init(&hadc1);
|
||||
|
||||
ADC_ChannelConfTypeDef sConfig = {0};
|
||||
uint8_t rank_counter = 1;
|
||||
active_channel_count = 0;
|
||||
|
||||
for (int i = 0; i < MAX_HW_ADC_ID; i++) {
|
||||
if (enabledChannels_mask & (1U << i)) {
|
||||
active_hw_channels[active_channel_count++] = i;
|
||||
sConfig.Channel = i;
|
||||
sConfig.Rank = rank_counter++;
|
||||
sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
|
||||
HAL_ADC_ConfigChannel(&hadc1, &sConfig);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
const osThreadAttr_t task_attrs = {
|
||||
.name = "DrvAdcTask",
|
||||
.stack_size = 512,
|
||||
.priority = osPriorityAboveNormal
|
||||
};
|
||||
|
||||
drv_adc_thread_id = osThreadNew(drvAdc_WorkerTask, NULL, &task_attrs);
|
||||
|
||||
const osTimerAttr_t timer_attrs = {
|
||||
.name = "DrvAdcTimer"
|
||||
};
|
||||
|
||||
drv_adc_timer_id = osTimerNew(drvAdc_TimerCallback, osTimerPeriodic, NULL, &timer_attrs);
|
||||
}
|
||||
|
||||
void drvAdc_startMeasurement(void) {
|
||||
if (drv_adc_timer_id) {
|
||||
osTimerStart(drv_adc_timer_id, MEASUREMENT_PERIOD_MS);
|
||||
}
|
||||
}
|
||||
|
||||
void drvAdc_stopMeasurement(void) {
|
||||
if (drv_adc_timer_id) {
|
||||
osTimerStop(drv_adc_timer_id);
|
||||
}
|
||||
HAL_ADC_Stop_DMA(&hadc1);
|
||||
}
|
||||
|
||||
void drvAdc_registerCallback(uint8_t channel, drvAdc_Callback cb, void* ctx) {
|
||||
if (channel < MAX_HW_ADC_ID) {
|
||||
callback_table[channel].cb = cb;
|
||||
callback_table[channel].ctx = ctx;
|
||||
}
|
||||
}
|
||||
|
||||
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) {
|
||||
if (hadc->Instance == ADC1) {
|
||||
if (drv_adc_thread_id) {
|
||||
osThreadFlagsSet(drv_adc_thread_id, DRV_ADC_FLAG_DMA_COMPLETE);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#ifndef DRV_ADC_H
|
||||
#define DRV_ADC_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#define SAMPLES_PER_CYCLE 36
|
||||
#define MAX_HW_ADC_ID 19
|
||||
|
||||
typedef void (*drvAdc_Callback)(uint8_t channel, uint32_t filteredRaw, void* ctx);
|
||||
|
||||
void drvAdc_init(uint32_t enabledChannels_mask);
|
||||
void drvAdc_startMeasurement(void);
|
||||
void drvAdc_stopMeasurement(void);
|
||||
void drvAdc_registerCallback(uint8_t channel, drvAdc_Callback cb, void* ctx);
|
||||
|
||||
#endif // DRV_ADC_H
|
||||
@@ -0,0 +1,83 @@
|
||||
#include "hwADC.h"
|
||||
#include "main.h"
|
||||
|
||||
extern ADC_HandleTypeDef hadc1;
|
||||
extern DMA_HandleTypeDef hdma_adc1;
|
||||
|
||||
void HW_ADC1_Init(void)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
|
||||
{
|
||||
|
||||
GPIO_InitTypeDef GPIO_InitStruct = {0};
|
||||
if(adcHandle->Instance==ADC1)
|
||||
{
|
||||
/* USER CODE BEGIN ADC1_MspInit 0 */
|
||||
|
||||
/* USER CODE END ADC1_MspInit 0 */
|
||||
/* ADC1 clock enable */
|
||||
__HAL_RCC_ADC1_CLK_ENABLE();
|
||||
|
||||
__HAL_RCC_GPIOC_CLK_ENABLE();
|
||||
/**ADC1 GPIO Configuration
|
||||
PC1 ------> ADC1_IN11
|
||||
*/
|
||||
GPIO_InitStruct.Pin = GPIO_PIN_1;
|
||||
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
|
||||
GPIO_InitStruct.Pull = GPIO_NOPULL;
|
||||
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
|
||||
|
||||
/* ADC1 DMA Init */
|
||||
/* ADC1 Init */
|
||||
hdma_adc1.Instance = DMA2_Stream0;
|
||||
hdma_adc1.Init.Channel = DMA_CHANNEL_0;
|
||||
hdma_adc1.Init.Direction = DMA_PERIPH_TO_MEMORY;
|
||||
hdma_adc1.Init.PeriphInc = DMA_PINC_DISABLE;
|
||||
hdma_adc1.Init.MemInc = DMA_MINC_ENABLE;
|
||||
hdma_adc1.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
|
||||
hdma_adc1.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD;
|
||||
hdma_adc1.Init.Mode = DMA_NORMAL;
|
||||
hdma_adc1.Init.Priority = DMA_PRIORITY_LOW;
|
||||
hdma_adc1.Init.FIFOMode = DMA_FIFOMODE_ENABLE;
|
||||
hdma_adc1.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL;
|
||||
hdma_adc1.Init.MemBurst = DMA_MBURST_SINGLE;
|
||||
hdma_adc1.Init.PeriphBurst = DMA_PBURST_SINGLE;
|
||||
if (HAL_DMA_Init(&hdma_adc1) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
|
||||
__HAL_LINKDMA(adcHandle,DMA_Handle,hdma_adc1);
|
||||
|
||||
/* USER CODE BEGIN ADC1_MspInit 1 */
|
||||
|
||||
/* USER CODE END ADC1_MspInit 1 */
|
||||
}
|
||||
}
|
||||
|
||||
void HAL_ADC_MspDeInit(ADC_HandleTypeDef* adcHandle)
|
||||
{
|
||||
|
||||
if(adcHandle->Instance==ADC1)
|
||||
{
|
||||
/* USER CODE BEGIN ADC1_MspDeInit 0 */
|
||||
|
||||
/* USER CODE END ADC1_MspDeInit 0 */
|
||||
/* Peripheral clock disable */
|
||||
__HAL_RCC_ADC1_CLK_DISABLE();
|
||||
|
||||
/**ADC1 GPIO Configuration
|
||||
PC1 ------> ADC1_IN11
|
||||
*/
|
||||
HAL_GPIO_DeInit(GPIOC, GPIO_PIN_1);
|
||||
|
||||
/* ADC1 DMA DeInit */
|
||||
HAL_DMA_DeInit(adcHandle->DMA_Handle);
|
||||
/* USER CODE BEGIN ADC1_MspDeInit 1 */
|
||||
|
||||
/* USER CODE END ADC1_MspDeInit 1 */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
#ifndef __HW_ADC1_H
|
||||
#define __HW_ADC1_H
|
||||
|
||||
void HW_ADC1_Init(void);
|
||||
|
||||
#endif /* __HW_ADC1_H */
|
||||
@@ -0,0 +1,279 @@
|
||||
#include <math.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include "ulAdc.h"
|
||||
#include "drvAdc.h"
|
||||
|
||||
#include "ulog.h"
|
||||
#include "ulDatabase.h"
|
||||
|
||||
#include "cmsis_os2.h"
|
||||
|
||||
#define HW_CH_BATTERY 11
|
||||
#define HW_CH_TEMP 16
|
||||
|
||||
#define ADC_MAX_VAL 4095.0f
|
||||
#define ADC_VREF 3.3f
|
||||
|
||||
/* 1. Battery: Voltage Divider (100k + 22k) / 22k */
|
||||
#define BAT_DEFAULT_SCALE ((ADC_VREF / ADC_MAX_VAL) * ((100.0f + 22.0f) / 22.0f))
|
||||
#define BAT_DEFAULT_OFFSET 0
|
||||
|
||||
/*
|
||||
* 2. Temp: T = (V - V25)/Slope + 25
|
||||
* V = Raw * (3.3/4095).
|
||||
* T = [Raw * (3.3/4095) - V25] / Slope + 25
|
||||
* T = Raw * [3.3 / (4095*Slope)] - [V25/Slope - 25]
|
||||
* T = Scale * (Raw - Offset_Raw)
|
||||
* if Scale = 3.3 / (4095*Slope) and Offset_Raw represents the zero-crossing.
|
||||
*/
|
||||
#define TEMP_V25 0.76f
|
||||
#define TEMP_SLOPE 0.0025f
|
||||
#define TEMP_DEFAULT_SCALE (ADC_VREF / (ADC_MAX_VAL * TEMP_SLOPE))
|
||||
|
||||
#define TEMP_DEFAULT_OFFSET (int32_t)(((TEMP_V25 - (25.0f * TEMP_SLOPE)) * ADC_MAX_VAL) / ADC_VREF)
|
||||
|
||||
#define ADC_CAL_STATUS_OK 0x00
|
||||
#define ADC_CAL_STATUS_IN_PROGRESS 0x01
|
||||
#define ADC_CAL_STATUS_ERROR 0xFF
|
||||
|
||||
#define LOG_INTERVAL_MS 1000
|
||||
typedef enum {
|
||||
CAL_STATE_IDLE = 0,
|
||||
CAL_STATE_WAIT_FOR_SAMPLE
|
||||
} adc_cal_state_t;
|
||||
|
||||
typedef struct {
|
||||
uint8_t hw_channel;
|
||||
|
||||
uint16_t db_id_val;
|
||||
uint16_t db_id_cal_offset;
|
||||
uint16_t db_id_cal_scale;
|
||||
|
||||
volatile int32_t active_offset;
|
||||
volatile float active_scale;
|
||||
|
||||
adc_cal_state_t cal_state;
|
||||
uint8_t pending_point;
|
||||
float pending_target;
|
||||
|
||||
volatile uint32_t last_raw;
|
||||
volatile float last_phys;
|
||||
} adc_channel_ctx_t;
|
||||
|
||||
adc_channel_ctx_t app_adc_ctx[] = {
|
||||
{
|
||||
.hw_channel = HW_CH_BATTERY,
|
||||
.db_id_val = PARAM_BATTERY_VOLTAGE,
|
||||
.db_id_cal_offset = ADC_CAL_CH_11_OFFSET,
|
||||
.db_id_cal_scale = ADC_CAL_CH_11_SCALE,
|
||||
.active_offset = BAT_DEFAULT_OFFSET,
|
||||
.active_scale = BAT_DEFAULT_SCALE,
|
||||
.cal_state = CAL_STATE_IDLE
|
||||
},
|
||||
{
|
||||
.hw_channel = HW_CH_TEMP,
|
||||
.db_id_val = PARAM_MCU_TEMPERATURE,
|
||||
.db_id_cal_offset = ADC_CAL_CH_TEMP_OFFSET,
|
||||
.db_id_cal_scale = ADC_CAL_CH_TEMP_SCALE,
|
||||
.active_offset = TEMP_DEFAULT_OFFSET,
|
||||
.active_scale = TEMP_DEFAULT_SCALE,
|
||||
.cal_state = CAL_STATE_IDLE
|
||||
}
|
||||
};
|
||||
|
||||
#define CTX_COUNT (sizeof(app_adc_ctx)/sizeof(app_adc_ctx[0]))
|
||||
|
||||
static void ulAdc_GetHardcodedDefaults_Bat(float* defScale, int32_t* defOffset) {
|
||||
const float Vref = 3.3f;
|
||||
const float MaxAdc = 4095.0f;
|
||||
const float DivFactor = (100.0f + 22.0f) / 22.0f; // (R1+R2)/R2
|
||||
|
||||
/*
|
||||
* Val = Scale * (Raw - Offset)
|
||||
* Offset = 0
|
||||
*/
|
||||
*defOffset = 0;
|
||||
/* Scale = (Vref / MaxAdc) * DivFactor */
|
||||
*defScale = (Vref / MaxAdc) * DivFactor;
|
||||
}
|
||||
|
||||
static void ulAdc_GetHardcodedDefaults_Temp(float* defScale, int32_t* defOffset) {
|
||||
const float Vref = 3.3f;
|
||||
const float MaxAdc = 4095.0f;
|
||||
const float V25 = 0.76f;
|
||||
const float Slope = 0.0025f;
|
||||
|
||||
/*
|
||||
* T = (Raw * (Vref/Max) - V25) / Slope + 25
|
||||
* T = (Raw * Vref/Max)/Slope - V25/Slope + 25
|
||||
* T = Raw * (Vref/(Max*Slope)) - (V25/Slope - 25)
|
||||
* T = Scale * (Raw - Offset_Raw)
|
||||
*/
|
||||
|
||||
float scale_val = Vref / (MaxAdc * Slope);
|
||||
float offset_val_phys = (V25 / Slope) - 25.0f;
|
||||
|
||||
/* Offset_Raw = offset_val_phys / scale_val */
|
||||
|
||||
*defScale = scale_val;
|
||||
*defOffset = (int32_t)(offset_val_phys / scale_val);
|
||||
}
|
||||
|
||||
static float ulAdc_applyCalibration(uint8_t channel, uint32_t rawValue) {
|
||||
adc_channel_ctx_t* ctx = NULL;
|
||||
for(size_t i=0; i<CTX_COUNT; i++) {
|
||||
if(app_adc_ctx[i].hw_channel == channel) {
|
||||
ctx = &app_adc_ctx[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!ctx) {
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
/* Y = Scale * (X - Offset) */
|
||||
int32_t raw_shifted = (int32_t)rawValue - ctx->active_offset;
|
||||
return (float)raw_shifted * ctx->active_scale;
|
||||
}
|
||||
|
||||
static void ulAdc_CallbackHandler(uint8_t channel, uint32_t filteredRaw, void* ctx_void) {
|
||||
adc_channel_ctx_t* ctx = (adc_channel_ctx_t*)ctx_void;
|
||||
if (!ctx) {
|
||||
return;
|
||||
}
|
||||
ctx->last_raw = filteredRaw;
|
||||
|
||||
switch (ctx->cal_state) {
|
||||
|
||||
case CAL_STATE_IDLE:
|
||||
{
|
||||
uint8_t start_cmd = 0;
|
||||
|
||||
if (ulDatabase_getUint8(ADC_CALIBRATION_START, &start_cmd) && start_cmd == 0xF1) {
|
||||
uint8_t target_ch = 0;
|
||||
ulDatabase_getUint8(ADC_CALIBRATION_CHANNEL_ID, &target_ch);
|
||||
if (target_ch == ctx->hw_channel) {
|
||||
ulDatabase_getUint8(ADC_CALIBRATION_POINT, &ctx->pending_point);
|
||||
ulDatabase_getFloat(ADC_CALIBRATION_POINT_VALUE, &ctx->pending_target);
|
||||
|
||||
ctx->cal_state = CAL_STATE_WAIT_FOR_SAMPLE;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case CAL_STATE_WAIT_FOR_SAMPLE:
|
||||
{
|
||||
bool cal_ok = true;
|
||||
|
||||
if (ctx->pending_point == 0) {
|
||||
/* OFFSET CALIBRATION --- */
|
||||
ctx->active_offset = (int32_t)filteredRaw;
|
||||
ulDatabase_setInt32(ctx->db_id_cal_offset, ctx->active_offset);
|
||||
}
|
||||
else if (ctx->pending_point == 1) {
|
||||
/* SCALE CALIBRATION --- */
|
||||
int32_t raw_shifted = (int32_t)filteredRaw - ctx->active_offset;
|
||||
|
||||
if (abs(raw_shifted) > 10) {
|
||||
ctx->active_scale = ctx->pending_target / (float)raw_shifted;
|
||||
ulDatabase_setFloat(ctx->db_id_cal_scale, ctx->active_scale);
|
||||
} else {
|
||||
cal_ok = false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
cal_ok = false;
|
||||
}
|
||||
|
||||
if (cal_ok) {
|
||||
ulDatabase_setUint8(ADC_CALIBRATION_START, ADC_CAL_STATUS_OK);
|
||||
} else {
|
||||
ulDatabase_setUint8(ADC_CALIBRATION_START, ADC_CAL_STATUS_ERROR);
|
||||
}
|
||||
ctx->cal_state = CAL_STATE_IDLE;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
ctx->cal_state = CAL_STATE_IDLE;
|
||||
break;
|
||||
}
|
||||
|
||||
float phys_val = ulAdc_applyCalibration(channel, filteredRaw);
|
||||
|
||||
ctx->last_phys = phys_val;
|
||||
ulDatabase_setFloat(ctx->db_id_val, phys_val);
|
||||
}
|
||||
|
||||
static void ulAdc_init_internal(void) {
|
||||
uint32_t adc_mask = 0;
|
||||
|
||||
for (size_t i = 0; i < CTX_COUNT; i++) {
|
||||
float def_scale;
|
||||
int32_t def_offset;
|
||||
|
||||
if (app_adc_ctx[i].hw_channel == HW_CH_BATTERY) {
|
||||
ulAdc_GetHardcodedDefaults_Bat(&def_scale, &def_offset);
|
||||
} else {
|
||||
ulAdc_GetHardcodedDefaults_Temp(&def_scale, &def_offset);
|
||||
}
|
||||
|
||||
adc_channel_ctx_t* ctx = &app_adc_ctx[i];
|
||||
adc_mask |= (1U << ctx->hw_channel);
|
||||
|
||||
int32_t stored_offset;
|
||||
float stored_scale;
|
||||
|
||||
if (ulDatabase_getInt32(ctx->db_id_cal_offset, &stored_offset) && stored_offset != 0) {
|
||||
ctx->active_offset = stored_offset;
|
||||
} else {
|
||||
ctx->active_offset = def_offset;
|
||||
}
|
||||
|
||||
if (ulDatabase_getFloat(ctx->db_id_cal_scale, &stored_scale) &&
|
||||
isfinite(stored_scale) && fabsf(stored_scale) > 1e-9f) {
|
||||
ctx->active_scale = stored_scale;
|
||||
} else {
|
||||
ctx->active_scale = def_scale;
|
||||
}
|
||||
}
|
||||
|
||||
drvAdc_init(adc_mask);
|
||||
|
||||
for (size_t i = 0; i < CTX_COUNT; i++) {
|
||||
drvAdc_registerCallback(app_adc_ctx[i].hw_channel, ulAdc_CallbackHandler, (void*)&app_adc_ctx[i]);
|
||||
}
|
||||
|
||||
drvAdc_startMeasurement();
|
||||
}
|
||||
|
||||
static void ulAdc_task(void *argument) {
|
||||
ulAdc_init_internal();
|
||||
|
||||
for (;;) {
|
||||
osDelay(LOG_INTERVAL_MS);
|
||||
|
||||
for (int i = 0; i < CTX_COUNT; i++) {
|
||||
adc_channel_ctx_t* ctx = &app_adc_ctx[i];
|
||||
|
||||
ULOG_INFO("[ADC CH%d] Raw: %lu | Phys: %.3f", ctx->hw_channel, ctx->last_raw, ctx->last_phys);
|
||||
osDelay(20);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ulAdc_init(void)
|
||||
{
|
||||
const osThreadAttr_t adcTask_attributes = {
|
||||
.name = "adcTask",
|
||||
.priority = (osPriority_t) osPriorityNormal,
|
||||
.stack_size = 256 * 4
|
||||
};
|
||||
|
||||
(void) osThreadNew(ulAdc_task, NULL, &adcTask_attributes);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#ifndef ADC_MANAGER_H
|
||||
#define ADC_MANAGER_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
void ulAdc_init(void);
|
||||
|
||||
#endif // ADC_MANAGER_H
|
||||
@@ -7,9 +7,11 @@ target_include_directories(KPI_Rover PRIVATE
|
||||
)
|
||||
|
||||
set(KPIROVER_COMPONENTS
|
||||
ADC
|
||||
Communication
|
||||
Database
|
||||
Logger
|
||||
Motors
|
||||
#Storage
|
||||
)
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
#include "KPIRover.h"
|
||||
|
||||
//#include "ADC/ulAdc.h"
|
||||
#include "Communication/ProtocolHandler.h"
|
||||
#include "Database/ulDatabase.h"
|
||||
#include "ulAdc.h"
|
||||
#include "ProtocolHandler.h"
|
||||
#include "ulDatabase.h"
|
||||
//#include "Encoders/ulEncoder.h"
|
||||
//#include "IMU/ulImu.h"
|
||||
//#include "Motors/ulMotorsController.h"
|
||||
#include "ulMotorsController.h"
|
||||
//#include "Storage/ulStorage.h"
|
||||
|
||||
#include "ulog.h"
|
||||
@@ -72,6 +72,9 @@ void KPIRover_Init(void) {
|
||||
ULOG_SUBSCRIBE(ul_ulog_send, ULOG_DEBUG_LEVEL);
|
||||
ulDatabase_init(ulDatabase_params, sizeof(ulDatabase_params) / sizeof(struct ulDatabase_ParamMetadata));
|
||||
ProtocolHandler_init();
|
||||
|
||||
//ulAdc_init();
|
||||
ulMotorsController_init();
|
||||
#if 0
|
||||
ulStorage_init();
|
||||
ulEncoder_Init();
|
||||
|
||||
@@ -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