#include <stm32f1xx_hal.h>
#include"string.h"
#include "stdio.h"
#define Seuil 2047
int exact_position[]={0, 0 , 0, 1, 0, 0, 0};
float error = 0;
float previous_error = 0;
float error_accum = 0;
char buffer[60];
uint16_t adc_values[7];
//uint16_t adc_values[] = {0, 0 , 0, 0, 0, 0, 0, 0};
/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;
TIM_HandleTypeDef htim2;
UART_HandleTypeDef huart1;
osThreadId Task_ConversionHandle;
osThreadId PWM_FunctionHandle;
osMessageQId Queue_CH0Handle;
osMessageQId Queue_CH1Handle;
osMessageQId Queue_CH2Handle;
osMessageQId Queue_CH3Handle;
osMessageQId Queue_CH4Handle;
osMessageQId Queue_CH5Handle;
osMessageQId Queue_CH6Handle;
osMutexId MutexHandle;
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_ADC1_Init(void);
static void MX_TIM2_Init(void);
static void MX_USART1_UART_Init(void);
void StartTask_Conversion(void const * argument);
void StartPWM_Function(void const * argument);
int Position (int *S){
int My_Position = 0;
for (int i = 0; i<=6 ; i++)
{
My_Position+=S[i]*10*(i+1);
}
return My_Position;
}
float PID(float kp, float kd,float ki) {
int Sensor_state[7];
for (int i = 0; i <=6; i++) {
// sprintf(buffer, "adc_values : %d\r\n",adc_values[i]); // Convert integer to string and add newline
// HAL_UART_Transmit(&huart1, (uint8_t*)buffer, strlen(buffer), portMAX_DELAY);
// osDelay(500);
if (adc_values[i] >= Seuil) {
Sensor_state[i] = 1; }
else {
Sensor_state[i]= 0;}
}
previous_error = error;
error = Position(Sensor_state) - Position(exact_position);
if(error== -40)
{
if(previous_error > 0) {
error= 30; }
else {
error= - 30; }
}
float P = kp * error;
float D = kd * (error - previous_error);
float I = ki * (previous_error + error);
float correction = P + I + D;
// sprintf(buffer, "correction: %d\r\n",(int)correction); // Convert integer to string and add newline
// HAL_UART_Transmit(&huart1, (uint8_t*)buffer, strlen(buffer), portMAX_DELAY);
return correction; }
int *Motor_Speed_V2(float kp, float kd,float ki){
static int Speed[2];
int Normal_Speed = 100;
int extrem_position[]={0, 0 , 0, 0, 0, 0, 1};
int Max_error_abs = Position(extrem_position) - Position(exact_position);
float Max_correction_abs = kp*Max_error_abs+ki*2*Max_error_abs+kd*Max_error_abs;
float correction = PID(kp,kd,ki);
correction = -100+200*(correction + Max_correction_abs)/(2*Max_correction_abs);
int Left_speed;
int Right_speed;
if(correction >= 0)
{
Left_speed = Normal_Speed;
Right_speed = Normal_Speed - (int)correction;
}
if(correction < 0)
{
Left_speed = Normal_Speed + (int)correction;
Right_speed = Normal_Speed;
}
Speed [0]= Left_speed;
Speed [1]= Right_speed;
// sprintf(buffer, "Left_speed: %d , Right_speed: %d \r\n", Left_speed ,Right_speed ); // Convert integer to string and add newline
// HAL_UART_Transmit(&huart1, (uint8_t*)buffer, strlen(buffer), portMAX_DELAY);
return Speed ;
}
void Robot_Go(float kp, float kd,float ki){
int *Speed_Value;
Speed_Value = Motor_Speed_V2(kp,kd,ki);
//Left motor_connected to GPIOB11&12 , enable at A0
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_11,GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12,GPIO_PIN_SET);
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, Speed_Value[0]);
//Right motor_connected to GPIOB13&14 , enable at A1
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_13,GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14,GPIO_PIN_SET);
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_2, Speed_Value[1]);
}
int main(void)
{
HAL_Init();
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_ADC1_Init();
MX_TIM2_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Create the mutex(es) */
/* definition and creation of Mutex */
osMutexDef(Mutex);
MutexHandle = osMutexCreate(osMutex(Mutex));
/* USER CODE BEGIN RTOS_MUTEX */
/* add mutexes, ... */
/* USER CODE END RTOS_MUTEX */
/* USER CODE BEGIN RTOS_SEMAPHORES */
/* add semaphores, ... */
/* USER CODE END RTOS_SEMAPHORES */
/* USER CODE BEGIN RTOS_TIMERS */
/* start timers, add new ones, ... */
/* USER CODE END RTOS_TIMERS */
/* Create the queue(s) */
/* definition and creation of Queue_CH0 */
osMessageQDef(Queue_CH0, 16, uint16_t);
Queue_CH0Handle = osMessageCreate(osMessageQ(Queue_CH0), NULL);
/* definition and creation of Queue_CH1 */
osMessageQDef(Queue_CH1, 16, uint16_t);
Queue_CH1Handle = osMessageCreate(osMessageQ(Queue_CH1), NULL);
/* definition and creation of Queue_CH2 */
osMessageQDef(Queue_CH2, 16, uint16_t);
Queue_CH2Handle = osMessageCreate(osMessageQ(Queue_CH2), NULL);
/* definition and creation of Queue_CH3 */
osMessageQDef(Queue_CH3, 16, uint16_t);
Queue_CH3Handle = osMessageCreate(osMessageQ(Queue_CH3), NULL);
/* definition and creation of Queue_CH4 */
osMessageQDef(Queue_CH4, 16, uint16_t);
Queue_CH4Handle = osMessageCreate(osMessageQ(Queue_CH4), NULL);
/* definition and creation of Queue_CH5 */
osMessageQDef(Queue_CH5, 16, uint16_t);
Queue_CH5Handle = osMessageCreate(osMessageQ(Queue_CH5), NULL);
/* definition and creation of Queue_CH6 */
osMessageQDef(Queue_CH6, 16, uint16_t);
Queue_CH6Handle = osMessageCreate(osMessageQ(Queue_CH6), NULL);
/* USER CODE BEGIN RTOS_QUEUES */
/* add queues, ... */
/* USER CODE END RTOS_QUEUES */
/* Create the thread(s) */
/* definition and creation of Task_Conversion */
osThreadDef(Task_Conversion, StartTask_Conversion, osPriorityHigh, 0, 128);
Task_ConversionHandle = osThreadCreate(osThread(Task_Conversion), NULL);
/* definition and creation of PWM_Function */
osThreadDef(PWM_Function, StartPWM_Function, osPriorityNormal, 0, 128);
PWM_FunctionHandle = osThreadCreate(osThread(PWM_Function), NULL);
HAL_ADC_Start_DMA(&hadc1, (uint32_t *) adc_values , 7);
HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); //A15
HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2); //B3
/* 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 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** 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.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
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_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief ADC1 Initialization Function
* @param None
* @retval None
*/
static void MX_ADC1_Init(void)
{
/* USER CODE BEGIN ADC1_Init 0 */
/* USER CODE END ADC1_Init 0 */
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC1_Init 1 */
/* USER CODE END ADC1_Init 1 */
/** Common config
*/
hadc1.Instance = ADC1;
hadc1.Init.ScanConvMode = ADC_SCAN_ENABLE;
hadc1.Init.ContinuousConvMode = ENABLE;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.NbrOfConversion = 7;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_0;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_1;
sConfig.Rank = ADC_REGULAR_RANK_2;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_2;
sConfig.Rank = ADC_REGULAR_RANK_3;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_3;
sConfig.Rank = ADC_REGULAR_RANK_4;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_4;
sConfig.Rank = ADC_REGULAR_RANK_5;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_5;
sConfig.Rank = ADC_REGULAR_RANK_6;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_6;
sConfig.Rank = ADC_REGULAR_RANK_7;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC1_Init 2 */
/* USER CODE END ADC1_Init 2 */
}
/**
* @brief TIM2 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM2_Init(void)
{
/* USER CODE BEGIN TIM2_Init 0 */
/* USER CODE END TIM2_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM2_Init 1 */
/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 0;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 100;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */
/* USER CODE END TIM2_Init 2 */
HAL_TIM_MspPostInit(&htim2);
}
/**
* @brief USART1 Initialization Function
* @param None
* @retval None
*/
static void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/**
* Enable DMA controller clock
*/
static void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/* USER CODE BEGIN Header_StartTask_Conversion */
/**
* @brief Function implementing the Task_Conversion thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTask_Conversion */
void StartTask_Conversion(void const * argument)
{
for(;;){
xQueueSend(Queue_CH0Handle, &adc_values[0], 100);
xQueueSend(Queue_CH1Handle, &adc_values[1], 100);
xQueueSend(Queue_CH2Handle, &adc_values[2], 100);
xQueueSend(Queue_CH3Handle, &adc_values[3], 100);
xQueueSend(Queue_CH4Handle, &adc_values[4], 100);
xQueueSend(Queue_CH5Handle, &adc_values[5], 100);
xQueueSend(Queue_CH6Handle, &adc_values[6], 100);
}
vTaskDelay(pdMS_TO_TICKS(100)); // Délai pour la prochaine exécution
}
/* USER CODE BEGIN Header_StartPWM_Function */
/**
* @brief Function implementing the PWM_Function thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartPWM_Function */
void StartPWM_Function(void const * argument)
{
for(;;)
{
if (osMutexWait(MutexHandle, osWaitForever) == osOK) {
if (
xQueueReceive(Queue_CH0Handle,&adc_values[0],portMAX_DELAY) == pdPASS &&
xQueueReceive(Queue_CH1Handle,&adc_values[1],portMAX_DELAY) == pdPASS &&
xQueueReceive(Queue_CH2Handle,&adc_values[2],portMAX_DELAY) == pdPASS &&
xQueueReceive(Queue_CH3Handle,&adc_values[3],portMAX_DELAY) == pdPASS &&
xQueueReceive(Queue_CH4Handle,&adc_values[4],portMAX_DELAY) == pdPASS &&
xQueueReceive(Queue_CH5Handle,&adc_values[5],portMAX_DELAY) == pdPASS &&
xQueueReceive(Queue_CH6Handle,&adc_values[6],portMAX_DELAY) == pdPASS ){
Robot_Go(1,0.1,0.1);
// float Correction_Value;
// Correction_Value = PID(1,0.1,0.1);
// sprintf(buffer, "correction: %f\r\n", Correction_Value); // Convert integer to string and add newline
// HAL_UART_Transmit(&huart1, (uint8_t*)buffer, strlen(buffer), portMAX_DELAY);
snprintf(buffer, 100, "QUEUE_CH3: %d\r\n", adc_values[3]);
HAL_UART_Transmit(&huart1, (uint8_t *) buffer, sizeof(buffer), portMAX_DELAY);
}
}
osMutexRelease(MutexHandle);
}
osDelay(100);
}
/**
* @brief Period elapsed callback in non blocking mode
* @note This function is called when TIM1 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 == TIM1) {
HAL_IncTick();
}
/* USER CODE BEGIN Callback 1 */
/* USER CODE END Callback 1 */
}
/**
* @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 */
}
#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 */