Skip to content
 
📑标签
🏷stm32 🏷小项目 🏷大学

🗒初墨

🍊Hello,各位好,我是面包!

这篇文档集合了面包的蓝桥杯嵌入式组的竞赛经历与总结。

蓝桥杯比赛经历

2023-11
  • 参加了深圳大学物光学院的蓝桥杯校内赛->通过选拔
仅见

首先排查硬件问题,认为单片机有问题就直接申请替换,不要质疑自己浪费时间

2024-4
  • 本校考场试点->省赛->省一
2024-6
  • 哈工深考场试点->国赛->心态崩了,没发挥出正常水平->国优
仅见

从易到难,先把简易的可得分点写完,一步一步来;早上记得吃早饭,不然有可能肚子痛,亲身之鉴

蓝桥杯总结

  1. 熟练使用STM32HAL库配置单片机上的所有外设,驱动正常功能验证,进行模块封装;
  2. 熟练搭建基于滴答计时器的伪实时系统,用与多任务执行;
  3. 善于编写数据解析的代码;
  4. 早上比赛时一定要吃饱🥪;

答题步骤

  1. 选择题
  2. 速读程序题要求-了解需要使用什么模块
  3. 快速编写模板代码
  4. 细读题目要求
  5. 实现LED,KEY,LCD要求
  6. 题目细节实现,逐个模块突破

注意要点

  1. 多个数据需要循环递增索引赋值的话把递增变量单独取出来

反面案例

c
Value_A[i++]=Value;
Value_B[i++]=Value;

修改代码

c
Value_A[i]=Value;
Value_B[i]=Value;
i++;
  1. EEROM通过I2C读写数据时需要添加延时
c
I2CInit();
i2c_24c02_write(EEROM_String_1, 0x00, 5);
HAL_Delay(5);
i2c_24c02_read(EEROM_String_2, 0x00, 5);
  1. 随机数的N种生成方式
  • 通过时基uwTick获取
  1. 字符转换成整形数据并不一致

反面案例

c
int i=0;
char str[3]={'1','2','3'};
i=str[2];
//i=33

修改代码

c
int i=0;
char str[3]={'1','2','3'};
i=str[2]-'0';
//i=3
  1. 注意uint16_tuint8_t的数据范围

  2. 数据处理不要单独重写一个函数专门处理,要放在及时响应的代码后面

  3. 注意文本要求中的等号

  4. 对应用型代码尽可能的添加注释

  5. 修改main.c以外文件时要全局编译

  6. 清零时记得带上关联变量一起清零

  7. 注意调整参数的步长

  8. 注意要求显示变量的小数点后几位

  9. 浮点数不可以直接比较,会有误差

C标准库

<stdio.h>

1. int sprintf(char *str, const char *format, ...)

将format中包含的字符串赋值到str指向的字符数组

c
#include <stdio.h>
#include <math.h>

int main()
{
   char str[80];

   sprintf(str, "Pi 的值 = %f", M_PI);
   puts(str);
   
   return(0);
}

2. int snprintf ( char * str, size_t size, const char * format, ... );

将format中包含的前size个字符串赋值到str指向的字符数组

3. int sscanf(const char *str, const char *format, ...)

  • 从字符串读取格式化输入
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   int day, year;
   char weekday[20], month[20], dtm[100];

   strcpy( dtm, "Saturday March 25 1989" );
   sscanf( dtm, "%s %s %d  %d", weekday, month, &day, &year );

   printf("%s %d, %d = %s\n", month, day, year, weekday );
    
   return(0);
}
  • 从不定长字符串中提取整型数据
c
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "(12,23,34,32,1,32,677)";
    int num, count = 0;
    char *ptr = str;  // 指针用于跟踪解析位置
    int offset = 0;

    // 跳过开头的 '('
    if (*ptr == '(') ptr++;

    // 循环提取所有整数
    while (sscanf(ptr, "%d%n", &num, &offset) == 1) {
        printf("提取到第 %d 个数字:%d\n", ++count, num);
        ptr += offset;  // 移动指针到已解析的位置
        
        // 跳过逗号或结束符 ')'
        if (*ptr == ',' || *ptr == ')') ptr++;
        else break;  // 遇到非法字符终止
    }

    printf("共提取 %d 个整数\n", count);
    return 0;
}

<string.h>

1. int memcmp(const void *str1, const void *str2, size_t n)

把 str1 和 str2 的前 n 个字节进行比较

2. char *strcpy(char *dest, const char *src)

把 src 所指向的字符串复制到 dest

3. char *strncpy(char *dest, const char *src, size_t n)

把 src 所指向的字符串复制到 dest,最多复制 n 个字符

4. size_t strlen(const char *str)

计算字符串 str 的长度,直到空结束字符,但不包括空结束字符。

5. char *strtok(char *str, const char *delim)

分解字符串 str 为一组字符串,delim 为分隔符

<math.h>

1. double fabs(double x)

返回 x 的绝对值

2.double pow(double x, double y)

返回 x 的 y 次幂

<stdlib.h>

1. int abs(int x)

返回 x 的绝对值

2. int rand(void)

返回一个范围在 0 到 RAND_MAX 之间的伪随机数

3. void srand(unsigned int seed)

该函数播种由函数 rand 使用的随机数发生器

c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    srand(time(NULL));
    for (int i = 0; i < 10; i++) {
        printf("%d ", rand() % 100);
    }
    printf("\n");

    return 0;
}

<time.h>

1. time_t time(time_t *timer)

计算当前日历时间,并把它编码成 time_t 格式

c
#include <stdio.h>
#include <time.h>
 
int main ()
{
  time_t seconds;
 
  seconds = time(NULL);
  printf("自 1970-01-01 起的小时数 = %ld\n", seconds/3600);
  
  return(0);
}

STM32CUBEMX

时钟配置

STM32G431RBT6的晶振为24MHz

Led

引脚GPIO modeGPIO mode level
PC8GPIO_OutputHigh
PC9GPIO_OutputHigh
PC10GPIO_OutputHigh
PC11GPIO_OutputHigh
PC12GPIO_OutputHigh
PC13GPIO_OutputHigh
PC14GPIO_OutputHigh
PC15GPIO_OutputHigh
PD2GPIO_OutputLow

Key

引脚GPIO modeGPIO mode level
PA0GPIO_InputLow
PB0GPIO_InputLow
PB1GPIO_InputLow
PB2GPIO_InputLow

Adc

ADC1Mode->Asynchronous clock mode divided by 2

ADC2Mode->Asynchronous clock mode divided by 2

TIM

模式配置

参数设置

开启时钟中断

RTC

代码日记

main.c

c
/* 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 "rtc.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

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


__IO uint32_t uwTick_LED_Set_Point;
__IO uint32_t uwTick_KEY_Set_Point;
__IO uint32_t uwTick_LCD_Set_Point;

/*LED*/
uint16_t ucLed;

/*KEY*/
uint16_t Key_Val,Key_Down,Key_Up,Key_Old;

/*I2C*/
uint8_t EEROM_String_1[5]={11,22,33,44,55};
uint8_t EEROM_String_2[5]={0};
uint8_t RES_K;

/*LCD*/
uint8_t Lcd_String[21];

//UART
uint8_t Rx_String[10];
uint8_t Rx_Flag;
uint8_t Rx_Buff;

//信号发生器
uint16_t PWM_T_Point;
uint16_t PWM_D_Point;
float PWM_Duty;

//时钟
RTC_TimeTypeDef H_M_S;
RTC_DateTypeDef Y_M_D;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

void Led_Proc(void);
void Key_Proc(void);
void Lcd_Proc(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_USART1_UART_Init();
  MX_ADC1_Init();
  MX_ADC2_Init();
  MX_TIM2_Init();
  MX_TIM3_Init();
  MX_TIM6_Init();
  MX_TIM17_Init();
  MX_RTC_Init();
  /* USER CODE BEGIN 2 */
	
	LCD_Init();
	LCD_SetTextColor(White);
	LCD_SetBackColor(Black);	
	LCD_Clear(Black);
	
	I2CInit();
	i2c_24c02_write(EEROM_String_1, 0x00, 5);
	HAL_Delay(5);
	i2c_24c02_read(EEROM_String_2, 0x00, 5);
	
	i2c_4017_write(0x0e);
	RES_K = i2c_4017_read();
	
	HAL_UART_Receive_IT(&huart1, (uint8_t*)&Rx_Buff, 1);
	
	HAL_TIM_Base_Start(&htim2);
	HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_1);
	HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_2);
	
  /* USER CODE END 2 */

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

    /* USER CODE BEGIN 3 */
		Led_Proc();
		Key_Proc();
		Lcd_Proc();
  }
  /* 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 Led_Proc(void)
{
	if(uwTick-uwTick_LED_Set_Point<100)return;
	uwTick_LED_Set_Point=uwTick;
	
	Led_Disp(ucLed);
}
void Key_Proc(void)
{
	if(uwTick-uwTick_KEY_Set_Point<50)return;
	uwTick_KEY_Set_Point=uwTick;
	
	Key_Val=Key_Scan();
	Key_Down=Key_Val&(Key_Val^Key_Old);
	Key_Up=~Key_Val&(Key_Val^Key_Old);
	Key_Old=Key_Val;
	
	
	if(Key_Down==1)
	{
		ucLed=0x01;
	}
	else if(Key_Down==2)
	{
		ucLed=0x02;
	}
	else if(Key_Down==3)
	{
		ucLed=0x04;
	}
	else if(Key_Down==4)
	{
		ucLed=0x08;
	}
	
}
void Lcd_Proc(void)
{
	if(uwTick-uwTick_LCD_Set_Point<100)return;
	uwTick_LCD_Set_Point=uwTick;
	
	HAL_RTC_GetTime(&hrtc, &H_M_S, RTC_FORMAT_BIN);
	HAL_RTC_GetDate(&hrtc, &Y_M_D, RTC_FORMAT_BIN);
	
	sprintf((char*)Lcd_String,"Hello");
	LCD_DisplayStringLine(Line0,Lcd_String);
	sprintf((char*)Lcd_String,"R37:%3.2fV",get_ADC2()*3.3/4096);
	LCD_DisplayStringLine(Line1,Lcd_String);
	sprintf((char*)Lcd_String,"R38:%3.2fV",get_ADC1()*3.3/4096);
	LCD_DisplayStringLine(Line2,Lcd_String);
	sprintf((char*)Lcd_String,"ROM:%02d-%02d-%02d-%02d-%02d",EEROM_String_2[0],
		EEROM_String_2[1],EEROM_String_2[2],EEROM_String_2[3],EEROM_String_2[4]);
	LCD_DisplayStringLine(Line3,Lcd_String);
	sprintf((char*)Lcd_String,"RES_K:%d",RES_K);
	LCD_DisplayStringLine(Line4,Lcd_String);
	sprintf((char*)Lcd_String,"PWM_T:%05d",1000000/PWM_T_Point);
	LCD_DisplayStringLine(Line5,Lcd_String);
	sprintf((char*)Lcd_String,"PWM_Duty:%4.2f",PWM_Duty*100);
	LCD_DisplayStringLine(Line6,Lcd_String);
	sprintf((char*)Lcd_String,"Date:%02d-%02d-%02d",Y_M_D.Year,Y_M_D.Month,Y_M_D.Date);
	LCD_DisplayStringLine(Line7,Lcd_String);	
	sprintf((char*)Lcd_String,"Time:%02d-%02d-%02d",H_M_S.Hours,H_M_S.Minutes,H_M_S.Seconds);
	LCD_DisplayStringLine(Line8,Lcd_String);	
}


void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
	if(huart==&huart1)
	{
		Rx_String[Rx_Flag++]=Rx_Buff;
		if(Rx_String[Rx_Flag-1]==0x0A)
		{
			HAL_UART_Transmit(&huart1,(uint8_t*)&Rx_String,Rx_Flag,0xFFFF);
			while(HAL_UART_GetState(&huart1)==HAL_UART_STATE_BUSY_TX);
			memset(Rx_String,0x00,sizeof(Rx_String));
			Rx_Flag=0;
		}
	HAL_UART_Receive_IT(&huart1,(uint8_t*)&Rx_Buff,1);
	}

}

void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
	if(htim->Instance==TIM2)
	{
		if(htim->Channel==HAL_TIM_ACTIVE_CHANNEL_1)
		{
			PWM_T_Point = HAL_TIM_ReadCapturedValue(&htim2,TIM_CHANNEL_1);
			PWM_Duty = (float)PWM_D_Point/PWM_T_Point;
		}
		else if(htim->Channel==HAL_TIM_ACTIVE_CHANNEL_2)
		{
			PWM_D_Point = HAL_TIM_ReadCapturedValue(&htim2,TIM_CHANNEL_2);
		}
	}
}

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

gpio

c
/* USER CODE BEGIN 2 */

void Led_Disp(uint8_t ucLed)
{
	HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2 ,GPIO_PIN_SET);
	HAL_GPIO_WritePin(GPIOC, GPIO_PIN_All ,GPIO_PIN_SET);
	HAL_GPIO_WritePin(GPIOC, ucLed<<8 ,GPIO_PIN_RESET);
	HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2 ,GPIO_PIN_RESET);
	return;
}

uint8_t Key_Scan(void)
{
	uint8_t ucKey_Val;
	if(!HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0))ucKey_Val=4;
	else if(!HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_0))ucKey_Val=1;
	else if(!HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1))ucKey_Val=2;
	else if(!HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_2))ucKey_Val=3;
	return ucKey_Val;
}	



/* USER CODE END 2 */
h
/* USER CODE BEGIN Prototypes */
void Led_Disp(uint8_t ucLed);
uint8_t Key_Scan(void);
/* USER CODE END Prototypes */

adc

c
/* USER CODE BEGIN 1 */

float get_ADC1(void)
{
	float Voltage;
	HAL_ADC_Start(&hadc1);
	Voltage=HAL_ADC_GetValue(&hadc1);
	HAL_ADC_Stop(&hadc1);
	return Voltage;
}

float get_ADC2(void)
{
	float Voltage;
	HAL_ADC_Start(&hadc2);
	Voltage=HAL_ADC_GetValue(&hadc2);
	HAL_ADC_Stop(&hadc2);
	return Voltage;
}

/* USER CODE END 1 */
h
/* USER CODE BEGIN Prototypes */
float get_ADC1(void);
float get_ADC2(void);
/* USER CODE END Prototypes */

i2c

c
void i2c_24c02_write(uint8_t* pucBuf, uint8_t ucAddr, uint8_t ucNum)
{

  I2CStart();
  I2CSendByte(0xA0);
  I2CWaitAck();
  
  I2CSendByte(ucAddr);
  I2CWaitAck();
  
  
  while(ucNum--)
  {
    I2CSendByte(*pucBuf++);
    I2CWaitAck();
  }
  I2CStop();

}

void i2c_24c02_read(uint8_t* pucBuf, uint8_t ucAddr, uint8_t ucNum)
{
  I2CStart();
  I2CSendByte(0xA0);
  I2CWaitAck();
  
  I2CSendByte(ucAddr);
  I2CWaitAck();
  
  I2CStart();
  I2CSendByte(0xA1);
  I2CWaitAck();
  
  while(ucNum--)
  {
    *pucBuf++ = I2CReceiveByte();
    
    if(ucNum)
      I2CSendAck();
    else
      I2CSendNotAck();
  }
  I2CStop();
}

void i2c_4017_write(uint8_t RES_K)
{
  I2CStart();
  I2CSendByte(0x5E);
  I2CWaitAck();
  I2CSendByte(RES_K);
  I2CWaitAck();
  I2CStop();
}

uint8_t i2c_4017_read(void)
{
  uint8_t RES_K;
  I2CStart();
  I2CSendByte(0x5F);
  I2CWaitAck();
  RES_K=I2CReceiveByte();
  I2CWaitAck();
  I2CStop();
  return RES_K;

}
h
void i2c_24c02_write(uint8_t* pucBuf, uint8_t ucAddr, uint8_t ucNum);
void i2c_24c02_read(uint8_t* pucBuf, uint8_t ucAddr, uint8_t ucNum);
void i2c_4017_write(uint8_t RES_K);
uint8_t i2c_4017_read(void);