蓝桥杯嵌入式组第十四届省赛题目解析+STM32G431RBT6实现源码


前言:STM32G431RBT6实现嵌入式组第十四届题目解析+源码,本文默认读者具备基础的stm32知识。文章末尾附有第十四届题目。

1.题目解析

1.1 分而治之,藕断丝连

还是那句话,将不同模块进行封装,通过变量进行模块间的合作。
函数将模块分而治之,变量使模块间藕断丝连。

1.2 模块化思维导图

下图根据题目梳理。还是使用思维导图。
在这里插入图片描述

1.3 模块解析

1.3.1 KEY模块

还是控制按一次处理一次。老朋友了我们就不多说了,题目限制了按键消抖和单次处理,所以我们要加上消抖,和第前几届的处理一模一样。
正常按键逻辑:
开始按下—>按下—>释放;
但是题目要求得按一次处理一次,根据代码逻辑加了一种等待释放状态
根据机械按键的特性开始和结束都得消抖,加上按一次执行一次,所以我们的处理逻辑是:
开始按下—>按下消抖—>短按—>等待弹起—>长按—>弹起—>弹起消抖—>释放;
为了实现按一次执行一次,中间加了一个等待弹起状态(key_state_gain()函数获取到按键状态,key_state_set()设置按键对应按键涉及标志位,下一次进入到key_state_gain()函数中,按键状态就变成了等待弹起状态,这就保证了,短按长按只执行key_state_set()一次)
这里主要说逻辑,具体看源码

if(按键按下){
	if(是否是释放状态){					//开始按下
		进入消抖状态,开始消抖计时
	}
	else if(是否是消抖状态){    			//按下消抖
		if(当前时间-消抖计时>=消抖时长){
			消抖完成,进入按下状态
		}
	}
	else if(是否是短按状态 || 是否是长按状态){				//等待弹起状态
		等待释放状态
		记录长按2s开始时间
	}
	else if(是否是等待状态){              //长按实现
		if(时间达到2s) 长按状态
	}
}
else{//没有按下
	if(是否是等待释放或者按下状态){		//弹起
		进入消抖状态,开始消抖计时
	}
	else if(是否是消抖状态){				//弹起消抖
		if(当前时间-消抖计时>=消抖时长){
			消抖完成,按键释放
		}
	}
}

1.3.2 LED模块

ld1:数据界面亮,否则灭;
ld2:频率切换期间,以0.1s间隔闪烁;
ld3:占空比锁定亮,否则灭;
其他led保持熄灭状态。
解决办法,设置一个标志位代表ld1~ld8,改变对应位的的值,再将标志位写入ODR寄存器中来控制led的亮灭。
具体实现看源码

1.3.3 LCD模块

lcd显示三个界面,注意首次切换的时候得清屏。
根据B1进行三个界面的切换;
状态0:DATA;
在这里插入图片描述

状态1:PARA;
在这里插入图片描述
状态1:RECD。
在这里插入图片描述

具体实现看源码

1.3.4 TIM模块

TIM4产生0.1s时基。PSC:1699,ARR:9999;
TIM2,chn2: 16, 2499 , 4KHzPWM;
TIM3,chn2: 169, 9999, 捕获范围T<=10ms。
PSC和ARR计算公式(计算周期就是频率的倒数):
在这里插入图片描述

1.3.4.1 频率变化处理
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)   //pa1
{
    static uint32_t current_freq = 4000;
    if(HL_5s_run_flag == 1){
        if(HAL_GetTick() - tim_100ms >= 100){
            tim_100ms = HAL_GetTick();
            if(HL_conv_flag == 0){
                current_freq = current_freq <8000 ? current_freq+80 : 8000;
                TIM2->ARR = TIM2->ARR > 499 ? (uint32_t)4000000.0/current_freq-1 : 499;
            }
            else{
                current_freq = current_freq >4000 ? current_freq-80 : 4000;
                TIM2->ARR = TIM2->ARR < 999 ? (uint32_t)4000000.0/current_freq-1 : 999;
            }
        }
    }
    TIM2->CCR2 = (uint32_t)1.0*current_duty*TIM2->ARR/100.0;
}
1.3.4.1 占空比计算

看图可以知道这是一个分段函数。
在这里插入图片描述
我们可以这样解决

float caculate_duty()
{
    if(adc_smp_volt<=1.0){
        return 0.1;
    }
    else if(adc_smp_volt>1.0 && adc_smp_volt<=3.0){
        return (0.375*adc_smp_volt - 0.275);
    }
    else return 0.85;
}

1.3.5 ADC模块

这里adc采集R37电位器电压,这里就不多说。
具体请看源码

2.源码

我所有的实现都在main.c文件中。

2.1cubemx配置

在这里插入图片描述

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 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 "adc.h"
#include "tim.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "lcd.h"
/* 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);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
enum{    //按键状态
    key_released = 0U,
    key_reduction,
    key_short_pressed,
    key_short_wait,
    key_long_pressed,
    key_long_wait,
};

//按键状态,按键电平状态
uint8_t key_state[4] = {0}, key_volt[4] = {0};
uint32_t key_redu_tim = 0, key_2s_tim = 0;   //记录时间戳
float adc_smp_volt = 0.0f;   //adc采集电压
struct{
    uint16_t old_ccr;
    uint16_t new_ccr;
    float freq;
}PA7freq;           //输入捕获频率

float v_val = 0.0;  //v = f*2*PI*R / 100K
float H_max_val = 0.0, L_max_val = 0.0;   //高低速最大值记录

#define PI 3.14

void gain_key_state()   //获取按键状态
{
    key_volt[0] = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_0);
    key_volt[1] = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1);
    key_volt[2] = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_2);
    key_volt[3] = HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0);
    for(uint8_t i=0;i<4;i++)
    {
        if(!key_volt[i])
        {
            if(key_state[i] == key_released){
                key_state[i] = key_reduction;
                key_redu_tim = HAL_GetTick();
            }
            else if(key_state[i] == key_reduction){
                if(HAL_GetTick() - key_redu_tim >= 10){
                    key_state[i] = key_short_pressed;
                }
            }
            else if(key_state[i] == key_short_pressed){
                key_state[i] = key_short_wait;
                key_2s_tim = HAL_GetTick();
            }
            else if(key_state[i] == key_short_wait){
                if(HAL_GetTick()- key_2s_tim >= 2000){
                    key_state[i] = key_long_pressed;
                }
            }
            else if(key_state[i] == key_long_pressed){
                key_state[i] = key_long_wait;
            }  
        }
        else{
            if(key_state[i] != key_reduction && key_state[i] != key_released){
                key_state[i] = key_reduction;
                key_redu_tim = HAL_GetTick();
            }
            else if(key_state[i] == key_reduction){
                if(HAL_GetTick() - key_redu_tim >= 10){
                    key_state[i] = key_released;
                }
            }
        }
    }
}

//lcd转换,HL转换,HL切换运行态, RK切换, 锁定
uint8_t lcd_conv_flag = 0, HL_conv_flag = 0, HL_5s_run_flag = 0, RK_conv_flag = 0, lock_flag = 0;
uint8_t RK_set[2] = {1,1}, RK[2] = {1,1};   //RK数组
uint32_t HL_conv_5s = 0, N_cnt = 0;   //HL转换态时间戳, N计数

void key_process()   //按键状态设置对应标志位
{
    if(key_state[0] == key_short_pressed){
        lcd_conv_flag = lcd_conv_flag!=2 ? lcd_conv_flag+1 : 0;
        RK_conv_flag = 0;
        if(lcd_conv_flag == 2){
            RK[0] = RK_set[0];
            RK[1] = RK_set[1];
        }
    }
    else if(key_state[1] == key_short_pressed){
        if(lcd_conv_flag == 0){ //数据界面
            if(HL_5s_run_flag == 0){
                HL_conv_5s = HAL_GetTick();
                HL_5s_run_flag = 1;
            }
        }
        else if(lcd_conv_flag == 1){   //参数界面
            RK_conv_flag ^= 1;
        }
    }
    
    else if(key_state[2] == key_short_pressed){   //+
        if(lcd_conv_flag==1) RK_set[RK_conv_flag] = RK_set[RK_conv_flag] !=10 ? RK_set[RK_conv_flag]+1 : 1;
    }
    else if(key_state[3] == key_short_pressed){
        lock_flag = 0;
        if(lcd_conv_flag==1) RK_set[RK_conv_flag] = RK_set[RK_conv_flag] != 1 ? RK_set[RK_conv_flag]-1 : 10;
    }
    else if(key_state[3] == key_long_pressed){
        if(!lcd_conv_flag) lock_flag = 1;
    }
    
    if(HAL_GetTick() - HL_conv_5s >=5000 && HL_5s_run_flag == 1){
        HL_conv_flag ^= 1;
        HL_5s_run_flag = 0;
        N_cnt++;
    }
}

uint8_t caculate_duty()   //计算占空比
{
    if(adc_smp_volt <= 1.0) return 10;
    else if(adc_smp_volt>1.0 && adc_smp_volt <= 3.0) return (uint8_t)(35.0*adc_smp_volt - 25.0);
    else return 80;
}

uint8_t lcd_clear_flag = 0;  //lcd清屏
char lcd_str[21] = {0};   //lcd显示
void lcd_process()    //lcd处理
{ 
    switch(lcd_conv_flag){
        case 0:
            if(lcd_clear_flag == 2){
                LCD_Clear(Black);
                lcd_clear_flag = 0;
            }
            LCD_DisplayStringLine(Line1, (uint8_t*)"        DATA  ");
            if(HL_conv_flag == 0) sprintf(lcd_str, "     M=L     ");
            else sprintf(lcd_str, "     M=H     ");
            LCD_DisplayStringLine(Line3, (uint8_t*)lcd_str);
            sprintf(lcd_str, "     P=%hhu%%   ", caculate_duty());
            LCD_DisplayStringLine(Line4, (uint8_t*)lcd_str);
            sprintf(lcd_str, "     V=%.1f     ", v_val);
            LCD_DisplayStringLine(Line5, (uint8_t*)lcd_str);
            break;
        case 1:
            if(lcd_clear_flag == 0){
                LCD_Clear(Black);
                lcd_clear_flag = 1;
            }
            LCD_DisplayStringLine(Line1, (uint8_t*)"        PARA  ");
            sprintf(lcd_str, "     R=%hhu     ", RK_set[0]);
            LCD_DisplayStringLine(Line3, (uint8_t*)lcd_str);
            sprintf(lcd_str, "     K=%hhu     ", RK_set[1]);
            LCD_DisplayStringLine(Line4, (uint8_t*)lcd_str);
            break;
        case 2:
            if(lcd_clear_flag == 1){
                LCD_Clear(Black);
                lcd_clear_flag = 2;
            }
            LCD_DisplayStringLine(Line1, (uint8_t*)"        RECD  ");
            sprintf(lcd_str, "     N=%u     ", N_cnt);
            LCD_DisplayStringLine(Line3, (uint8_t*)lcd_str);
            sprintf(lcd_str, "     MH=%.1f     ", H_max_val);
            LCD_DisplayStringLine(Line4, (uint8_t*)lcd_str);
            sprintf(lcd_str, "     ML=%.1f     ", L_max_val);
            LCD_DisplayStringLine(Line5, (uint8_t*)lcd_str);
            break;
    }
}

uint8_t led_flag = 0, ld2_flag = 0;    //ld标志
uint32_t led_100ms_tim = 0;    //led100ms记录时间戳
void led_process()
{
    if(lcd_conv_flag == 0) led_flag = 1;
    else led_flag = 0;
    if(HL_5s_run_flag == 1){
        if(HAL_GetTick()-led_100ms_tim >= 100){
            led_100ms_tim = HAL_GetTick();
            ld2_flag ^=1;
            led_flag += ld2_flag << 1;
        }
    }
    if(lock_flag == 1) led_flag += 1 << 2;
    HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, 1);
    GPIOC->ODR = 0xffff ^ led_flag << 8;
    HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, 0);
}


uint32_t period_start_adc = 0;    //周期开启adc
uint8_t current_duty = 0;          //当前占空比

void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
    if(lock_flag == 0) adc_smp_volt = HAL_ADC_GetValue(hadc)*3.3/4096.0;
    current_duty = caculate_duty();
    period_start_adc = HAL_GetTick();
}

uint32_t max_recd_2s = 0;   //记录最大值时间戳
float detect_freq = 0;    //监测频率

void caculate_max(float *max)    //计算最大值
{
    if(PA7freq.freq > detect_freq){
        detect_freq = PA7freq.freq;
        max_recd_2s = HAL_GetTick();
    }
    else if(HAL_GetTick() - max_recd_2s >= 2000){
         *max = detect_freq*2*PI*RK[0] / (100.0*RK[1]);
    }
}

void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)  //pa7 tim3_chn2
{
    PA7freq.new_ccr = TIM3->CCR2;
    if(PA7freq.new_ccr > PA7freq.old_ccr){
        PA7freq.freq = 40000.0*100.0/(PA7freq.new_ccr-PA7freq.old_ccr);
    }
    else{
        PA7freq.freq = 40000.0*100.0/(PA7freq.new_ccr+40000-PA7freq.old_ccr);
    }
    PA7freq.old_ccr = PA7freq.new_ccr;
}

uint32_t tim_100ms = 0;
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)   //pa1
{
    static uint32_t current_freq = 4000;
    if(HL_5s_run_flag == 1){
        if(HAL_GetTick() - tim_100ms >= 100){
            tim_100ms = HAL_GetTick();
            if(HL_conv_flag == 0){
                current_freq = current_freq <8000 ? current_freq+80 : 8000;
                TIM2->ARR = TIM2->ARR > 499 ? (uint32_t)4000000.0/current_freq-1 : 499;
            }
            else{
                current_freq = current_freq >4000 ? current_freq-80 : 4000;
                TIM2->ARR = TIM2->ARR < 999 ? (uint32_t)4000000.0/current_freq-1 : 999;
            }
        }
    }
    TIM2->CCR2 = (uint32_t)1.0*current_duty*TIM2->ARR/100.0;
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
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 */
    LCD_Init();
    LCD_SetBackColor(Black);
    LCD_SetTextColor(White);
    LCD_Clear(Black);
  /* 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_TIM2_Init();
  MX_TIM3_Init();
  MX_ADC2_Init();
  MX_TIM8_Init();
  /* USER CODE BEGIN 2 */
    HAL_ADCEx_Calibration_Start(&hadc2, ADC_SINGLE_ENDED);
    HAL_ADC_Start_IT(&hadc2);
    HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_2);
    HAL_TIM_IC_Start_IT(&htim3, TIM_CHANNEL_2);
    
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
      gain_key_state();
      key_process();
      v_val =  PA7freq.freq*2*PI*RK[0] / (100.0*RK[1]);
      lcd_process();
      if(HAL_GetTick() - period_start_adc >= 10){
        HAL_ADC_Start_IT(&hadc2);
      }
      if(HL_conv_flag == 1)caculate_max(&H_max_val);
      else caculate_max(&L_max_val);
      led_process();
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(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 = RCC_PLLM_DIV3;
  RCC_OscInitStruct.PLL.PLLN = 20;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  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_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @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 */


3.第十四届题目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值