【STM32G431RBTx】备战蓝桥杯嵌入式→省赛试题→第十四届

本文提供了一个基于STM32的嵌入式系统代码实现,涉及LCD初始化、按键IO配置、LED控制、多个定时器(TIM3,TIM2,TIM4,TIM6,TIM7,TIM8,TIM17)的中断服务函数,用于按键消抖、PWM频率调整、ADC采样等。此外,代码中还实现了对按键状态的判断和处理,以及显示和LED灯的控制逻辑。
摘要由CSDN通过智能技术生成

前言

一、题目

请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述

二、模块初始化

1.LCD这里不用配置,直接使用提供的资源包就行
2.KEY, 四个按键IO口都要配置,分别是PB0, PB1,PB2,PA0依次是B0,B1,B2,B3不要弄错了
3.LED:开启PC8-15,PD2输出模式就行了。
4.定时器:TIM3(按键消抖定时器):PSC:80-1,ARR:10000-1,TIM2CH2:
PWM模式,PSC:200-1,ARR:100-1, TIM4:PSC:80-1,ARR:999,TIM6:PSC:80-1,ARR:9999, TIM7:PSC:80-1, ARR:999,TIM8:PSC:80-1, ARR:999,TIM17CH1:PSC:80-1, ARR:65535
5.ADC2IN15:single-ended模式开了就行

三、代码实现

bsp组中共有:
在这里插入图片描述

interrupt.h:

#ifndef __INTERRUPT_H__
#define __INTERRUPT_H__

#include "main.h"
#include "stdbool.h"

struct keys
{
    unsigned char key_judge;
    bool key_sta;
    bool single_flag;
    unsigned int key_time;
    bool long_flag;
};

#endif

interrupt.c:

#include "interrupt.h"
#include "tim.h"

struct keys key[4] = {0, 0, 0, 0, 0};

extern unsigned char B2_should_wait5s;
extern unsigned int B2WaitTick;
extern unsigned char Fre_should_change;
extern unsigned int Fre_now;
extern unsigned char PWMode;
extern unsigned int N;
extern unsigned char IntheCompareTimeH;
unsigned int CompareTimeH = 0;
unsigned char CompareTimeisOverH;
extern unsigned char IntheCompareTimeL;
unsigned int CompareTimeL = 0;
unsigned char CompareTimeisOverL;
extern unsigned char LED;
unsigned char LedTick = 0;
unsigned char LedType = 0;

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef * htim)
{
    if(htim->Instance == TIM3)
    {
        key[0].key_sta = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_0);
        key[1].key_sta = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1);
        key[2].key_sta = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_2);
        key[3].key_sta = HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0);
        for(unsigned char i = 0; i < 4; i++)
        {
            switch (key[i].key_judge)
            {
                case 0:
                {
                    if(key[i].key_sta == 0)
                    {
                        key[i].key_judge = 1;
                        key[i].key_time = 0;
                    }
                    break;
                }
                case 1:
                {
                    if(key[i].key_sta == 0)
                    {
                        key[i].key_judge = 2;
                    }
                    else
                    {
                        key[i].key_judge = 0;
                    }
                    break;
                }
                case 2:
                {
                    if(key[i].key_sta == 1)
                    {
                        key[i].key_judge = 0;
                        if(key[i].key_time <= 200)
                        {
                            key[i].single_flag = 1;
                        }
                        if(key[i].key_time > 200)
                        {
                            key[i].long_flag = 1;
                        }
                    }
                    else
                    {
                        key[i].key_time++;

                    }
                    break;
                }
            }
        }
    }
    if(htim->Instance == TIM4)
    {
        B2WaitTick++;
        LedTick++;
        if(LedTick == 100)
        {
            LedTick = 0;
            LedType = !LedType;
            LED = LED & 0xfd | (LedType << 1);
        }
        if(B2WaitTick == 5000)
        {
            B2_should_wait5s = 0;
            B2WaitTick = 0;
            HAL_TIM_Base_Stop_IT(&htim4);
        }
    }
    if(htim->Instance == TIM6)
    {
        if(Fre_should_change)
        {
            if(PWMode == LOW)
            {
                Fre_now += 8;
                __HAL_TIM_SET_PRESCALER(&htim2, 80000000 / 100 / Fre_now - 1);
                if(Fre_now == 8000)
                {
                    Fre_should_change = 0;
                    PWMode = HIGH;
                    HAL_TIM_Base_Stop_IT(&htim6);
                    LED = LED & 0xfd;
                    N++;
                }
            }
            else if(PWMode == HIGH)
            {
                Fre_now -= 8;
                __HAL_TIM_SET_PRESCALER(&htim2, 80000000 / 100 / Fre_now - 1);
                if(Fre_now == 4000)
                {
                    Fre_should_change = 0;
                    PWMode = LOW;
                    HAL_TIM_Base_Stop_IT(&htim6);
                    LED = LED & 0xfd;
                    N++;
                }
            }
        }
    }
    if(htim->Instance == TIM7)
    {
        if(IntheCompareTimeH == 1)
        {
            CompareTimeH++;
            if(CompareTimeH == 2000)
            {
                CompareTimeisOverH = 1;
                CompareTimeH = 0;
                HAL_TIM_Base_Stop_IT(&htim7);
            }
        }
    }
    if(htim->Instance == TIM8)
    {
        if(IntheCompareTimeL == 1)
        {
            CompareTimeL++;
            if(CompareTimeL == 2000)
            {
                CompareTimeisOverL = 1;
                CompareTimeL = 0;
                HAL_TIM_Base_Stop_IT(&htim8);
            }
        }
    }
}
/* Captured Values */
uint32_t uwIC1Value1_T17CH1 = 0;
uint32_t uwIC1Value2_T17CH1 = 0;
uint32_t uwDiffCapture_T17CH1 = 0;

/* Capture index */
uint16_t uhCaptureIndex_T17CH1 = 0;

/* Frequency Value */
uint32_t uwFrequency_T17CH1 = 0;

void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
    if(htim->Instance == TIM17)
    {
        if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1)
        {
            if(uhCaptureIndex_T17CH1 == 0)
            {
                /* Get the 1st Input Capture value */
                uwIC1Value1_T17CH1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);
                uhCaptureIndex_T17CH1 = 1;
            }
            else if(uhCaptureIndex_T17CH1 == 1)
            {
                /* Get the 2nd Input Capture value */
                uwIC1Value2_T17CH1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);

                /* Capture computation */
                if (uwIC1Value2_T17CH1 > uwIC1Value1_T17CH1)
                {
                    uwDiffCapture_T17CH1 = (uwIC1Value2_T17CH1 - uwIC1Value1_T17CH1);
                }
                else if (uwIC1Value2_T17CH1 < uwIC1Value1_T17CH1)
                {
                    /* 0xFFFF is max TIM1_CCRx value */
                    uwDiffCapture_T17CH1 = ((0xFFFF - uwIC1Value1_T17CH1) + uwIC1Value2_T17CH1) + 1;
                }
                else
                {
                    /* If capture values are equal, we have reached the limit of frequency
                       measures */
                    Error_Handler();
                }

                /* Frequency computation: for this example TIMx (TIM1) is clocked by
                   APB2Clk */
                uwFrequency_T17CH1 = 1000000 / uwDiffCapture_T17CH1;
                uhCaptureIndex_T17CH1 = 0;
            }
        }
    }
}

main.h:

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.h
  * @brief          : Header for main.c file.
  *                   This file contains the common defines of the application.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 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 */

/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H

#ifdef __cplusplus
extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */

/* USER CODE END ET */

/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */

/* USER CODE END EC */

/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */

/* USER CODE END EM */

/* Exported functions prototypes ---------------------------------------------*/
void Error_Handler(void);

/* USER CODE BEGIN EFP */

/* USER CODE END EFP */

/* Private defines -----------------------------------------------------------*/

/* USER CODE BEGIN Private defines */
#define PI 3.14
#define DATA 0
#define PARA 1
#define RECD 2
#define LOW 0
#define HIGH 1
/* USER CODE END Private defines */

#ifdef __cplusplus
}
#endif

#endif /* __MAIN_H */

main.c:

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 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 "led.h"
#include "badc.h"
#include "interrupt.h"
#include "lcd.h"
#include "stdio.h"
#include "led.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 */
extern struct keys key[4];
extern uint32_t uwFrequency_T17CH1;
char text[30];
float volt;
unsigned char Duty;
float v;
unsigned int R = 1, K = 1, N = 0;
unsigned char DisplayMode;
unsigned char PWMode;
unsigned char ModelChangeIsOk;
float MaxVinHighMode, MaxVinLowMode;
float temp1MaxVinHighMode, temp1MaxVinLowMode;
float temp2MaxVinHighMode, temp2MaxVinLowMode;
unsigned char B2_should_wait5s;
unsigned int B2WaitTick;
unsigned char SettingIndex;
unsigned int Ktemp = 1, Rtemp = 1;
unsigned char LockType;
unsigned char Fre_should_change;
unsigned int Fre_now = 4000;
unsigned char IntheCompareTimeH;
extern unsigned char CompareTimeisOverH;
unsigned char IntheCompareTimeL;
extern unsigned char CompareTimeisOverL;
unsigned char LED = 0x00;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void DisposeKey(void);
void DutyControl_Process(void);
void LCD_Disp(void);
void LED_Control(void);
/* 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)
{
  /* 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_TIM2_Init();
  MX_TIM3_Init();
  MX_TIM4_Init();
  MX_TIM6_Init();
  MX_TIM7_Init();
  MX_TIM8_Init();
  MX_TIM17_Init();
  MX_ADC2_Init();
  /* USER CODE BEGIN 2 */
  HAL_TIM_Base_Start_IT(&htim3);
  HAL_TIM_IC_Start_IT(&htim17, TIM_CHANNEL_1);
  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);
  LCD_Init();
  LCD_Clear(Black);
  LCD_SetBackColor(Black);
  LCD_SetTextColor(White);
  LED_Disp(0x00);
  /* USER CODE END 2 */

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

    /* USER CODE BEGIN 3 */
    volt = getADC(&hadc2) * 3.3 / 4096.0;
    DutyControl_Process();
    DisposeKey();
    v = uwFrequency_T17CH1 * 2 * PI * R / (100.0 * K);
    if(PWMode == HIGH)
    {
        if(v > MaxVinHighMode)
        {
            temp2MaxVinHighMode = v;
            if(IntheCompareTimeH == 0)
            {
                temp1MaxVinHighMode = v;
                IntheCompareTimeH = 1;
                HAL_TIM_Base_Start_IT(&htim7);
            }
            if(CompareTimeisOverH == 1)
            {
                IntheCompareTimeH = 0;
                if(temp2MaxVinHighMode == temp1MaxVinHighMode)
                {
                    MaxVinHighMode = temp1MaxVinHighMode;
                }
                CompareTimeisOverH = 0;
            }
        }
    }
      if(PWMode == LOW)
      {
          if(v > MaxVinLowMode)
          {
              temp2MaxVinLowMode = v;
              if(IntheCompareTimeL == 0)
              {
                  temp1MaxVinLowMode = v;
                  IntheCompareTimeL = 1;
                  HAL_TIM_Base_Start_IT(&htim8);
              }
              if(CompareTimeisOverL == 1)
              {
                  IntheCompareTimeL = 0;
                  if(temp2MaxVinLowMode == temp1MaxVinLowMode)
                  {
                      MaxVinLowMode = temp1MaxVinLowMode;
                  }
                  CompareTimeisOverL = 0;
              }
          }
      }
    LCD_Disp();
      LED_Control();
      LED_Disp(LED);
  }
  /* 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 */
void DisposeKey(void)
{
    if(key[0].single_flag)
    {
        DisplayMode++;
        DisplayMode %= 3;
        LCD_Clear(Black);
        key[0].single_flag = 0;
    }
    if(key[1].single_flag)
    {
        if(DisplayMode == DATA)
        {
            if((!B2_should_wait5s) && Fre_should_change == 0)
            {
                Fre_should_change = 1;
                B2_should_wait5s = 1;
                B2WaitTick = 0;
                HAL_TIM_Base_Start_IT(&htim4);
                HAL_TIM_Base_Start_IT(&htim6);
            }
        }
        if(DisplayMode == PARA)
        {
            SettingIndex = !SettingIndex;
        }
        key[1].single_flag = 0;
    }
    if(key[2].single_flag)
    {
        if(DisplayMode == PARA)
        {
            if(SettingIndex == 0)
            {
                Rtemp++;
                if(Rtemp == 11)
                {
                    Rtemp = 1;
                }
            }
            else
            {
                Ktemp++;
                if(Ktemp == 11)
                {
                    Ktemp = 1;
                }
            }
        }
        key[2].single_flag = 0;
    }
    if(key[3].single_flag)
    {
        if(DisplayMode == PARA)
        {
            if(SettingIndex == 0)
            {
                Rtemp--;
                if(Rtemp == 0)
                {
                    Rtemp = 10;
                }
            }
            else
            {
                Ktemp--;
                if(Ktemp == 0)
                {
                    Ktemp = 10;
                }
            }
        }
        if(DisplayMode == DATA)
        {
            if(LockType == 1)
            {
                LockType = 0;
            }
        }
        key[3].single_flag = 0;
    }
    if(key[3].long_flag)
    {
        LockType = 1;
        key[3].long_flag = 0;
    }
}

void DutyControl_Process(void)
{
    if(LockType == 0)
    {
        if(volt <= 1.0)
        {
            Duty = 10;
        }
        else if(volt > 1.0 && volt <= 3.0)
        {
            Duty =  (unsigned char)(-27.5 + 37.5 * volt);
        }
        else
        {
            Duty = 85;
        }
        __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_2, Duty);
    }
}

void LCD_Disp(void)
{
    if(DisplayMode == DATA)
    {
        LCD_DisplayStringLine(Line1, "        DATA");
        if(PWMode == LOW)
        {
            LCD_DisplayStringLine(Line3, "     M=L");
        }
        else if(PWMode == HIGH)
        {
            LCD_DisplayStringLine(Line3, "     M=H");
        }
        sprintf(text, "     P:%02d%%", Duty);
        LCD_DisplayStringLine(Line4, text);
        sprintf(text, "     V=%.1f", v);
        LCD_DisplayStringLine(Line5, text);
        SettingIndex = 0;
    }
    else if(DisplayMode == PARA)
    {
        LCD_DisplayStringLine(Line1, "        PARA");
        sprintf(text, "     R=%d ", Rtemp);
        LCD_DisplayStringLine(Line3, text);
        sprintf(text, "     K=%d ", Ktemp);
        LCD_DisplayStringLine(Line4, text);
    }
    else if(DisplayMode == RECD)
    {
        R = Rtemp;
        K = Ktemp;
        LCD_DisplayStringLine(Line1, "        RECD");
        sprintf(text, "     N=%d         ", N);
        LCD_DisplayStringLine(Line3, text);
        sprintf(text, "     MH=%.1f", MaxVinHighMode);
        LCD_DisplayStringLine(Line4, text);
        sprintf(text, "     ML=%.1f", MaxVinLowMode);
        LCD_DisplayStringLine(Line5, text);

    }
}

void LED_Control(void)
{
    if(DisplayMode == DATA)
    {
        LED = LED & 0xfe | 0x01;
    }
    else
    {
        LED = LED & 0xfe;
    }
    if(LockType)
    {
        LED = LED & 0Xfb | 0x04;
    }
    else
    {
        LED = LED & 0Xfb;
    }
}
/* 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 */

四、完成效果

蓝桥杯嵌入式第十四届省赛试题实现效果

五、总结

其实说本篇文章只是为了存放我的代码,所以看不懂很正常,如果需要代码可以找我私信。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值