adxl345采样频率太低stm23f4

时间:2018-08-23 17:58:38

标签: stm32 freertos

嗨,我正在尝试构建一个自平衡机器人,因此我需要加速度计和陀螺仪,但无法设置加速度计的最大输出频率。目前,在我的代码中,获取角度所需的时间几乎为28ms,我认为这太多了。您有什么建议要解决吗? 我附加的代码是我用来控制机器人的代码,这就是为什么代码很长的原因,但是用于与传感器通信的功能在文件的开头,而在文件的结尾使用这些功能的任务(StartSampler)。我正在使用带有FreeRtos的核stm32f401re板。

https://pastebin.com/suuePCrK

/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * This notice applies to any and all portions of this file
  * that are not between comment pairs USER CODE BEGIN and
  * USER CODE END. Other portions of this file, whether 
  * inserted by the user or by software development tools
  * are owned by their respective copyright owners.
  *
  * Copyright (c) 2018 STMicroelectronics International N.V. 
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without 
  * modification, are permitted, provided that the following conditions are met:
  *
  * 1. Redistribution of source code must retain the above copyright notice, 
  *    this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright notice,
  *    this list of conditions and the following disclaimer in the documentation
  *    and/or other materials provided with the distribution.
  * 3. Neither the name of STMicroelectronics nor the names of other 
  *    contributors to this software may be used to endorse or promote products 
  *    derived from this software without specific written permission.
  * 4. This software, including modifications and/or derivative works of this 
  *    software, must execute solely and exclusively on microcontroller or
  *    microprocessor devices manufactured by or for STMicroelectronics.
  * 5. Redistribution and use of this software other than as permitted under 
  *    this license is void and will automatically terminate your rights under 
  *    this license. 
  *
  * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" 
  * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT 
  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
  * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
  * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT 
  * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f4xx_hal.h"
#include "cmsis_os.h"

/* USER CODE BEGIN Includes */
#include "math.h"
#include "string.h"
#include "stdlib.h"
/* USER CODE END Includes */

/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c1;

TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim3;

UART_HandleTypeDef huart1;
UART_HandleTypeDef huart6;
DMA_HandleTypeDef hdma_usart1_rx;
DMA_HandleTypeDef hdma_usart6_rx;

osThreadId FilterHandle;
osThreadId ControllerHandle;
osThreadId ActuatorHandle;
osThreadId StampaHandle;
osThreadId SetPIDHandle;
osThreadId SamplerHandle;
osMutexId i2c_mutexHandle;
osMutexId uart_mutexHandle;
osMutexId sample_mutexHandle;
osMutexId pid_mutexHandle;
osMutexId angle_mutexHandle;
osMutexId voltage_mutexHandle;
osMutexId controller_mutexHandle;

/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
#define T                                       3                       //period 3 ms
#define T_control                       0.003               //period expressed in seconds 
#define N                                       1                       //number of samples 
#define adxl_address                0x53<<1
#define ITG3205_ADDRESS         0x68<<1

#define GRADSEC_TO_RAD          0.0174533       //°/s to radiant
#define RANGE                               0.0                 //range 
#define MAX_CONTROL                 6                       //max voltage to motors
#define CYCLE_CALIB                 2000
#define SOFT_START                  50
float OFFSET=0;

uint8_t acc_id, gyro_id;
int cnt=0; 

float OFFSET_ADX=-0.00196964317;
float OFFSET_GYRO=2.62438679;
float X_OFF=0;
float Y_OFF=0;
float Z_OFF=0;
float Y_GYR_OFF=-9.64649963;
int16_t x_u, y_u, z_u;
float x, y, z, y_g; 
int16_t y_gyro; 
int16_t y_gyro_old; 
uint8_t uart_buff[1]; 

uint8_t lsm6ds0_id; 
float acc_pitch, gyr_pitch;

char x_bt[4]; 
char y_bt[4]; 
char z_bt[4];
char yg_bt[4];

int m=0; 
int fine_pid=0;
int cr[4]={0,0,0,0};


//////WCET///////////
long unsigned int time[4]; 
long unsigned int time_sampler[4]; 
long unsigned int time_controller[4]; 
long unsigned int time_actuator[4]; 
long unsigned int time_stampa[4]; 


float adxl_pitch[N], itg3205_pitch[N];
float avg_adxl_pitch, avg_itg3205_pitch; 
float send_to_controller[2]; 
float send_to_actuator[2]; 


//CONTROLLER VARIABLE
double error, error_der, error_int, error_old; 
double control; 
double position=0, position_old=0; 
double KP=0;
double KI=0; 
double KD=0; 

double p_off=0;//0.072;
double n_off=0;//0.00085;

    double local_avg_adxl_pitch, local_avg_itg3205_pitch; 

//BLUETOOTH COMMUNICATION
uint8_t buff_rec[14+6+3];   //14 se il pid è costituito da 3 cifre intere 20 se p,i e d hanno due cifre decimali + 3 per i punti da saltare delle cifre decimali
char stamp[3];
uint8_t pid_vector[100];

int count=0;
uint32_t temp[10]; 

//CHECK SAMPLING TIME
float sensor_time;
TickType_t start_time=0;
TickType_t finish_time=0;


/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_USART6_UART_Init(void);
static void MX_I2C1_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_TIM2_Init(void);
static void MX_TIM3_Init(void);
void StarFilter(void const * argument);
void StartController(void const * argument);
void StartActuator(void const * argument);
void StartStampa(void const * argument);
void StartSetPID(void const * argument);
void StartSampler(void const * argument);

void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim);


/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
uint8_t data_reg[22]; 
uint8_t data_gyro; 

void adxl_write(uint8_t reg, uint8_t value){
    uint8_t data[2]; 
    data[0]=reg; 
    data[1]=value; 
    HAL_I2C_Master_Transmit(&hi2c1, adxl_address, data, 2, 10); 
        temp[0]=temp[0]+1; 
}

void adxl_read(uint8_t reg, uint8_t numberOfByte){
    HAL_I2C_Mem_Read(&hi2c1, adxl_address, reg, 1, data_reg, numberOfByte, 100);
temp[1]=temp[1]+1; 
}

void adxl_init(void ){
    adxl_read(0x00, 1); 
    acc_id=data_reg[0];
    adxl_write(0x2d, 0x00); //reset all bits
    //aggiunto per problemi sui registri alti dei sensori 
    adxl_write(0x2c, 0x0F);
    adxl_write(0x2d, 0x08); //measure bit-1, wake up 0, 0 at 8Mhz
    adxl_write(0x31, 0x03); //+-16g range  0x01 come secondo parametro per 4g range
    adxl_write(0x38, 0x80); //bypass filter fifo
}

void adxl_get_values(void){
        temp[2]=temp[2]+1; 
        adxl_read(0x32,6); 
        //l'aggiunta del -0.04 o -0.08 è per l'offset del sensore
        x_u=((data_reg[1]<<8) | data_reg[0])-0.04;//+1.74;      
        y_u=((data_reg[3]<<8) | data_reg[2])-0.04;//+1.74; 
        z_u=((data_reg[5]<<8) | data_reg[4])-0.08;//-3.73; 

        x=x_u*0.0312;                                                                                                                               //31.2/1000(mg) to scale to g
        y=y_u*0.0312;                                                                                                                               //31.2/1000(mg) to scale to g
        z=z_u*0.0312;                                                                                                                               //31.2/1000(mg) to scale to g

        sprintf(x_bt, "%f", x);             
        sprintf(y_bt, "%f", y); 
        sprintf(y_bt, "%f", z); 
}

float adxl_get_roll(void){
    adxl_get_values();
    return atan2(y, sqrt(x*x+z*z))*57.32484;
}

float adxl_get_pitch_rad(void){
    adxl_get_values();
    return atan2(x, sqrt(y*y+z*z));
}

float adxl_get_pitch(void){
    return (adxl_get_pitch_rad()-OFFSET)*57.32484;
}

void adxl_calib(void){
        for(int i=0; i<CYCLE_CALIB; i++){
            OFFSET=adxl_get_pitch_rad();
            HAL_Delay(T/N);
        }
    OFFSET/=CYCLE_CALIB;
}

void itg3205_write(uint8_t reg, uint8_t value){
    uint8_t data[2]; 
    data[0]=reg; 
    data[1]=value;
    HAL_I2C_Master_Transmit(&hi2c1, ITG3205_ADDRESS, data, 2, 10); 
}

void itg3205_read(uint8_t reg, uint8_t numberOfByte){
HAL_I2C_Mem_Read(&hi2c1, ITG3205_ADDRESS, reg, 1, &data_gyro, numberOfByte, 100);
}


void itg3205_init(void){
    uint8_t value[2];
    itg3205_read(0x00, 1); 
    gyro_id=data_gyro; 

    //SET FULL SCALE +- 2000°/s
    itg3205_write(0x16, 0x18);
}

float itg3205_get_pitch(void){
    itg3205_read(0x20, 1); 
    y_gyro=data_gyro;
    itg3205_read(0x1F, 1); 
    y_gyro |=(data_gyro<<8);
    return (y_gyro/14.375); 
}

void itg3205_calib(void){
    for(int i=0; i<CYCLE_CALIB; i++){
        OFFSET_GYRO+=itg3205_get_pitch();
        HAL_Delay(20);
    }
    OFFSET_GYRO/=CYCLE_CALIB;
}


void acc_calib(void){
      OFFSET_ADX=0;
        for(int i=0; i<CYCLE_CALIB; i++){
            OFFSET_ADX+=adxl_get_pitch_rad();
            HAL_Delay(T/N);
        }
    OFFSET_ADX/=CYCLE_CALIB;
}
void gyr_calib(void){
    OFFSET_GYRO=0; 
    for(int i=0; i<CYCLE_CALIB; i++){
        OFFSET_GYRO+=itg3205_get_pitch();
        HAL_Delay(20);
    }
    OFFSET_GYRO/=CYCLE_CALIB;
}
/* USER CODE END PFP */

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  *
  * @retval None
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USART6_UART_Init();
  MX_I2C1_Init();
  MX_USART1_UART_Init();
  MX_TIM2_Init();
  MX_TIM3_Init();
  /* USER CODE BEGIN 2 */
    //HAL_UART_Receive_DMA(&huart6,buff_rec,14+6+3);    //struttura predefinita con 5 valori + punto piu lettere + spazio es 'p100.20 i0.0000 d0.0000'
    HAL_UART_Receive_DMA(&huart6,buff_rec, 1); 
    adxl_init();
    itg3205_init();
    //acc_axis_calib();
    //gyr_axis_calib();
    //acc_calib();
    //gyr_calib();
    HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2); 
    __HAL_TIM_SetCompare(&htim2, TIM_CHANNEL_2, 250);
    HAL_TIM_Base_Start(&htim3);
  /* USER CODE END 2 */

  /* Create the mutex(es) */
  /* definition and creation of i2c_mutex */
  osMutexDef(i2c_mutex);
  i2c_mutexHandle = osMutexCreate(osMutex(i2c_mutex));

  /* definition and creation of uart_mutex */
  osMutexDef(uart_mutex);
  uart_mutexHandle = osMutexCreate(osMutex(uart_mutex));

  /* definition and creation of sample_mutex */
  osMutexDef(sample_mutex);
  sample_mutexHandle = osMutexCreate(osMutex(sample_mutex));

  /* definition and creation of pid_mutex */
  osMutexDef(pid_mutex);
  pid_mutexHandle = osMutexCreate(osMutex(pid_mutex));

  /* definition and creation of angle_mutex */
  osMutexDef(angle_mutex);
  angle_mutexHandle = osMutexCreate(osMutex(angle_mutex));

  /* definition and creation of voltage_mutex */
  osMutexDef(voltage_mutex);
  voltage_mutexHandle = osMutexCreate(osMutex(voltage_mutex));

  /* definition and creation of controller_mutex */
  osMutexDef(controller_mutex);
  controller_mutexHandle = osMutexCreate(osMutex(controller_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 thread(s) */
  /* definition and creation of Filter */
  //osThreadDef(Filter, StarFilter, osPriorityRealtime, 0, 128);
  //FilterHandle = osThreadCreate(osThread(Filter), NULL);

  /* definition and creation of Controller */
  osThreadDef(Controller, StartController, osPriorityRealtime, 0, 128);
  ControllerHandle = osThreadCreate(osThread(Controller), NULL);

  /* definition and creation of Actuator */
  osThreadDef(Actuator, StartActuator, osPriorityRealtime, 0, 128);
  ActuatorHandle = osThreadCreate(osThread(Actuator), NULL);

  /* definition and creation of Stampa */
  //osThreadDef(Stampa, StartStampa, osPriorityLow, 0, 128);
  //StampaHandle = osThreadCreate(osThread(Stampa), NULL);

  /* definition and creation of SetPID */
  //osThreadDef(SetPID, StartSetPID, osPriorityLow, 0, 128);
  //SetPIDHandle = osThreadCreate(osThread(SetPID), NULL);

  /* definition and creation of Sampler */
  osThreadDef(Sampler, StartSampler, osPriorityRealtime, 0, 128);
  SamplerHandle = osThreadCreate(osThread(Sampler), NULL);

  /* USER CODE BEGIN RTOS_THREADS */
  /* add threads, ... */
  /* USER CODE END RTOS_THREADS */

  /* USER CODE BEGIN RTOS_QUEUES */
  /* add queues, ... */
  /* USER CODE END RTOS_QUEUES */


  /* 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;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;

    /**Configure the main internal regulator output voltage 
    */
  __HAL_RCC_PWR_CLK_ENABLE();

  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);

    /**Initializes the CPU, AHB and APB busses clocks 
    */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = 16;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 84;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

    /**Initializes the CPU, AHB and APB busses 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(__FILE__, __LINE__);
  }

    /**Configure the Systick interrupt time 
    */
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

    /**Configure the Systick 
    */
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 15, 0);
}

/* I2C1 init function */
static void MX_I2C1_Init(void)
{

  hi2c1.Instance = I2C1;
  hi2c1.Init.ClockSpeed = 400000;
  hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
  hi2c1.Init.OwnAddress1 = 0;
  hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
  hi2c1.Init.OwnAddress2 = 0;
  hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
  if (HAL_I2C_Init(&hi2c1) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

}

/* TIM2 init function */
static void MX_TIM2_Init(void)
{

  TIM_MasterConfigTypeDef sMasterConfig;
  TIM_OC_InitTypeDef sConfigOC;

  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 84;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 1000;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  if (HAL_TIM_PWM_Init(&htim2) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 500;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

  HAL_TIM_MspPostInit(&htim2);

}

/* TIM3 init function */
static void MX_TIM3_Init(void)
{

  TIM_ClockConfigTypeDef sClockSourceConfig;
  TIM_MasterConfigTypeDef sMasterConfig;

  htim3.Instance = TIM3;
  htim3.Init.Prescaler = 0;
  htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim3.Init.Period = 65535;
  htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

}

/* USART1 init function */
static void MX_USART1_UART_Init(void)
{

  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(__FILE__, __LINE__);
  }

}

/* USART6 init function */
static void MX_USART6_UART_Init(void)
{

  huart6.Instance = USART6;
  huart6.Init.BaudRate = 9600;
  huart6.Init.WordLength = UART_WORDLENGTH_8B;
  huart6.Init.StopBits = UART_STOPBITS_1;
  huart6.Init.Parity = UART_PARITY_NONE;
  huart6.Init.Mode = UART_MODE_TX_RX;
  huart6.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart6.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart6) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

}

/** 
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void) 
{
  /* DMA controller clock enable */
  __HAL_RCC_DMA2_CLK_ENABLE();

  /* DMA interrupt init */
  /* DMA2_Stream1_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA2_Stream1_IRQn, 5, 0);
  HAL_NVIC_EnableIRQ(DMA2_Stream1_IRQn);
  /* DMA2_Stream2_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA2_Stream2_IRQn, 5, 0);
  HAL_NVIC_EnableIRQ(DMA2_Stream2_IRQn);

}

/** Configure pins as 
        * Analog 
        * Input 
        * Output
        * EVENT_OUT
        * EXTI
*/
static void MX_GPIO_Init(void)
{

  GPIO_InitTypeDef GPIO_InitStruct;

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4|GPIO_PIN_5, GPIO_PIN_RESET);

  /*Configure GPIO pins : PA4 PA5 */
  GPIO_InitStruct.Pin = GPIO_PIN_4|GPIO_PIN_5;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(huart);
  /* NOTE: This function Should not be modified, when the callback is needed,
           the HAL_UART_TxCpltCallback could be implemented in the user file
   */
            ///da un'array di numeri sotto forma di caratteri mi porto a un intero a 3cifre
            /*
            KP=(double)(100*(buff_rec[1]-48)+10*(buff_rec[2]-48)+1*(buff_rec[3]-48)+0.01*(buff_rec[5]-48)+0.001*(buff_rec[6]-48));
            KI=(double)(1*(buff_rec[9]-48)+0.1*(buff_rec[11]-48)+0.01*(buff_rec[12]-48)+0.001*(buff_rec[13]-48)+0.0001*(buff_rec[14]-48));
            KD=(double)(1*(buff_rec[17]-48)+0.1*(buff_rec[19]-48)+0.01*(buff_rec[20]-48)+0.001*(buff_rec[21]-48)+0.0001*(buff_rec[22]-48));
        */
        char delim[]=" ";
        if(buff_rec[0]!='\n'){
            //ancora devo ricevere l'ultimo carattere
            pid_vector[m]=buff_rec[0];
            m++;}
            else {
                //ultimo carattere ricevuto 

                //creo vettore di pari dimensione e lo riempio 
                uint8_t *tempo_buffer=malloc(m*sizeof(uint8_t));
                strcpy((char *)tempo_buffer,(const char *) pid_vector);
                char *ptr = strtok((char *)tempo_buffer, delim);
                KP = atof(ptr);
                ptr = strtok(NULL, delim);
                KI = atof(ptr);
                ptr = strtok(NULL, delim);
                KD = atof(ptr);

                //pulisco i puntatori
                free(ptr);
                free(tempo_buffer);
                for (int k=0; k<=m; k++)
                    pid_vector[k]=0; 
                m=0;
                        }



    /*
    //per trasformare l'intero p in un arrai di char cosi da stamparlo
            if(uart_mutexHandle !=NULL){
                if(xSemaphoreTake(uart_mutexHandle, (TickType_t) 5) == pdTRUE){
                    sprintf(stamp, "%f", KP);
                    HAL_UART_Transmit(&huart6, (uint8_t *)"P: ", 3,10);
                    HAL_UART_Transmit(&huart6, (uint8_t *) stamp, 3, 10); 
                    HAL_UART_Transmit(&huart6, (uint8_t *)"\n\r", 2, 10);

                    sprintf(stamp, "%f", KI);
                    HAL_UART_Transmit(&huart6, (uint8_t *)"I: ", 3,10);
                    HAL_UART_Transmit(&huart6, (uint8_t *)stamp, 3, 10); 
                    HAL_UART_Transmit(&huart6, (uint8_t *)"\n\r", 2, 10);

                    sprintf(stamp, "%f", KD);
                    HAL_UART_Transmit(&huart6, (uint8_t *)"D: ", 3,10);
                    HAL_UART_Transmit(&huart6, (uint8_t *)stamp, 3, 10); 
                    HAL_UART_Transmit(&huart6, (uint8_t *)"\n\r", 2, 10);
                    xSemaphoreGive(uart_mutexHandle);
                }
            }
    vTaskResume(SetPIDHandle);
    */
}
/* USER CODE END 4 */

/* StarFilter function */
void StarFilter(void const * argument)
{

感谢您的帮助

0 个答案:

没有答案