蓝桥杯嵌入式第9届真题(完成) STM32G431

蓝桥杯嵌入式第9届真题(完成) STM32G431

题目

image-20240212223046453

image-20240212223055564

image-20240212223105664

分析和代码

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** <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.* All rights reserved.</center></h2>** This software component is licensed by ST under BSD 3-Clause license,* the "License"; You may not use this file except in compliance with the* License. You may obtain a copy of the License at:*                        opensource.org/licenses/BSD-3-Clause********************************************************************************/
/* 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 */
#include "lcd.h"
/* USER CODE END Includes *//* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
struct Time{uint8_t hours;uint8_t minutes;uint8_t seconds;
};typedef enum {COUNTDOWN_STOPPED,COUNTDOWN_RUNNING,COUNTDOWN_PAUSED
} CountdownStatus;
/* 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 *//* USER CODE END Private defines */#ifdef __cplusplus
}
#endif#endif /* __MAIN_H *//************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

Time结构体定义了时间的数据类型,CountdownStatus是一个枚举类型,表示了定时器的三种状态

main.c

/* USER CODE BEGIN Header */
/********************************************************************************* @file           : main.c* @brief          : Main program body******************************************************************************* @attention** <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.* All rights reserved.</center></h2>** This software component is licensed by ST under BSD 3-Clause license,* the "License"; You may not use this file except in compliance with the* License. You may obtain a copy of the License at:*                        opensource.org/licenses/BSD-3-Clause********************************************************************************/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "tim.h"
#include "gpio.h"/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "key.h"
#include "led.h"
#include "stdio.h"
#include "i2c_hal.h"
/* USER CODE END Includes *//* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
extern struct Key key[4];
uint8_t lcdtext[30];
uint8_t timerstatus[20]= "Standby";
uint8_t timernum = 0;
uint8_t view = 1;
CountdownStatus countdownStatus = COUNTDOWN_STOPPED; // 初始状态为停止
uint32_t ledtime;
/* USER CODE END PTD *//* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD *//* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */struct Time time; //当前计时的时间
struct Time times[5];//存储五个准备好的定时时间
struct EeromAddr{uint8_t addr1;uint8_t addr2;uint8_t addr3;
} addr[5] = {{0x01, 0x02, 0x03},  // 第一个结构体的初值{0x04, 0x05, 0x06},  // 第二个结构体的初值{0x07, 0x08, 0x09},  // 第三个结构体的初值{0x0A, 0x0B, 0x0C},  // 第四个结构体的初值{0x0D, 0x0E, 0x0F}   // 第五个结构体的初值
};
/* 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 */
void key_process(void);
void lcd_process(void);
void pwmAndLed_process(void);
/* USER CODE END PFP *//* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void StartCountdown(void) {if (countdownStatus != COUNTDOWN_RUNNING) {countdownStatus = COUNTDOWN_RUNNING;sprintf((char *)timerstatus, "Running");}
}void PauseCountdown(void) {if (countdownStatus == COUNTDOWN_RUNNING) {countdownStatus = COUNTDOWN_PAUSED;sprintf((char *)timerstatus, "Pause");}
}void StopCountdown(void) {countdownStatus = COUNTDOWN_STOPPED;sprintf((char *)timerstatus, "Standby");
}void ReadFromEeprom(void)
{for (int i = 0; i < 5; i++) {times[i].hours = EEROM_Read(addr[i].addr1);HAL_Delay(5);times[i].minutes = EEROM_Read(addr[i].addr2);HAL_Delay(5);times[i].seconds = EEROM_Read(addr[i].addr3);HAL_Delay(5);}}
/* 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_TIM16_Init();/* USER CODE BEGIN 2 */LCD_Init();HAL_TIM_Base_Start_IT(&htim2);/* USER CODE END 2 *//* Infinite loop *//* USER CODE BEGIN WHILE */LCD_Clear(Black);LCD_SetBackColor(Black);LCD_SetTextColor(White);LED_display(0x00);// 假设EEROM_Read是您用来读取EEPROM数据的函数ReadFromEeprom();time = times[timernum];//默认是第一个while (1){pwmAndLed_process();lcd_process();key_process();/* 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};/** 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_HSI;RCC_OscInitStruct.HSIState = RCC_HSI_ON;RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV2;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 key_process(void)
{// 按键0:切换计时器编号并读取时间if (key[0].key_single_flag && view == 1) {key[0].key_single_flag = 0; // 清除标志位timernum = (timernum + 1) % 5; // 循环通过计时器编号LCD_Clear(Black);LCD_SetBackColor(Black); LCD_SetTextColor(White); // 从EEPROM读取时间ReadFromEeprom();time = times[timernum]; //加载存储的时间为当前时间}// 按键1(短按):在主视图切换到设置视图,或在设置视图中切换设置项if (key[1].key_single_flag) {key[1].key_single_flag = 0; // 清除标志位LCD_Clear(Black);LCD_SetBackColor(Black); // 根据需要设置背景色LCD_SetTextColor(White); // 根据需要设置文字色if (view == 1) {// 如果在主视图,进入设置模式view = 2; // 进入设置视图sprintf((char *)timerstatus, "Setting");time = times[timernum];} else if (view >= 2 && view < 5) {// 在设置模式下,循环切换设置项view++;} else if (view == 5) {// 如果已经在设置秒的视图,回到设置小时视图view = 3;}}// 按键1(长按):保存设置并返回主视图if (key[1].key_long_flag && (view >= 3 && view <= 5)) {key[1].key_long_flag = 0; // 清除标志位// 将当前时间写入EEPROMEEROM_Write(addr[timernum].addr1, time.hours);HAL_Delay(10);EEROM_Write(addr[timernum].addr2, time.minutes);HAL_Delay(10);EEROM_Write(addr[timernum].addr3, time.seconds);HAL_Delay(10);ReadFromEeprom();// 更新显示状态并返回主视图sprintf((char *)timerstatus, "Standby");// 清屏并准备显示主视图的信息LCD_Clear(Black);LCD_SetBackColor(Black); // 根据需要设置背景色LCD_SetTextColor(White); // 根据需要设置文字色view = 1;}// 按键2:根据当前视图调整时间if (key[2].key_single_flag) {key[2].key_single_flag = 0; // 清除标志位switch (view) {case 3: // 调整小时time.hours = (time.hours + 1) % 24;break;case 4: // 调整分钟time.minutes = (time.minutes + 1) % 60;break;case 5: // 调整秒time.seconds = (time.seconds + 1) % 60;break;}}// 处理B4的短按和长按事件
if (key[3].key_single_flag == 1) {key[3].key_single_flag = 0; // 清除短按标志位LCD_Clear(Black);LCD_SetBackColor(Black); // 根据需要设置背景色LCD_SetTextColor(White); // 根据需要设置文字色// 短按逻辑,用于开始、暂停和恢复倒计时if (view == 1 && countdownStatus == COUNTDOWN_STOPPED) {StartCountdown();//开始倒计时} else if (view == 1 && countdownStatus == COUNTDOWN_RUNNING) {PauseCountdown();} else if (view == 1 && countdownStatus == COUNTDOWN_PAUSED) {StartCountdown(); // 使用StartCountdown来恢复倒计时}
} else if (key[3].key_long_flag == 1) {key[3].key_long_flag = 0; // 清除长按标志位// 长按逻辑,用于取消倒计时并返回到初始状态if (view == 1) {StopCountdown();// 可能需要重置倒计时时间time.hours = times[timernum].hours;time.minutes = times[timernum].minutes;time.seconds = times[timernum].seconds ;}
}}void lcd_process(void)
{switch(view){case 1:{sprintf((char *)lcdtext,"  No %d",timernum+1);LCD_DisplayStringLine(Line1,lcdtext);sprintf((char *)lcdtext,"     %02d:%02d:%02d",time.hours,time.minutes,time.seconds);LCD_DisplayStringLine(Line3,lcdtext);sprintf((char *)lcdtext,"      %s",timerstatus);LCD_DisplayStringLine(Line5,lcdtext);}break;case 2: //设置界面{sprintf((char *)lcdtext,"  No %d",timernum+1);LCD_DisplayStringLine(Line1,lcdtext);sprintf((char *)lcdtext,"     %02d:%02d:%02d",time.hours,time.minutes,time.seconds);LCD_DisplayStringLine(Line3,lcdtext);sprintf((char *)lcdtext,"      %s",timerstatus);LCD_DisplayStringLine(Line5,lcdtext);}break;case 3: //设置小时{sprintf((char *)lcdtext,"  No %d",timernum+1);LCD_DisplayStringLine(Line1,lcdtext);sprintf((char *)lcdtext,"     %02d:%02d:%02d",time.hours,time.minutes,time.seconds);LCD_DisplayStringLine(Line3,lcdtext);sprintf((char *)lcdtext,"     --");LCD_SetTextColor(Green);LCD_DisplayStringLine(Line4,lcdtext);LCD_SetTextColor(White);sprintf((char *)lcdtext,"      %s",timerstatus);LCD_DisplayStringLine(Line5,lcdtext);}break;case 4://设置分钟{sprintf((char *)lcdtext,"  No %d",timernum+1);LCD_DisplayStringLine(Line1,lcdtext);sprintf((char *)lcdtext,"     %02d:%02d:%02d",time.hours,time.minutes,time.seconds);LCD_DisplayStringLine(Line3,lcdtext);sprintf((char *)lcdtext,"        --");LCD_SetTextColor(Green);LCD_DisplayStringLine(Line4,lcdtext);LCD_SetTextColor(White);sprintf((char *)lcdtext,"      %s",timerstatus);LCD_DisplayStringLine(Line5,lcdtext);}break;case 5://设置秒{sprintf((char *)lcdtext,"  No %d",timernum+1);LCD_DisplayStringLine(Line1,lcdtext);sprintf((char *)lcdtext,"     %02d:%02d:%02d",time.hours,time.minutes,time.seconds);LCD_DisplayStringLine(Line3,lcdtext);sprintf((char *)lcdtext,"           --");LCD_SetTextColor(Green);LCD_DisplayStringLine(Line4,lcdtext);LCD_SetTextColor(White); sprintf((char *)lcdtext,"       %s",timerstatus);LCD_DisplayStringLine(Line5,lcdtext);}break;}}
void pwmAndLed_process(void)
{static _Bool ledflag = false;if(countdownStatus == COUNTDOWN_RUNNING){HAL_TIM_PWM_Start(&htim16, TIM_CHANNEL_1);__HAL_TIM_SET_COMPARE(&htim16,TIM_CHANNEL_1,800);if(uwTick-ledtime<500)return;ledtime = uwTick;//更新时间ledflag = !ledflag;if(ledflag){LED_display(0x01);}else{LED_display(0x00);}}else{HAL_TIM_PWM_Stop(&htim16, TIM_CHANNEL_1);LED_display(0x00);}
}/* 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 *//* 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,tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) *//* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT *//************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

EeromAddr是一个用于存储时间的小时分钟还有秒的数据地址,这个地址是EEPROM中的地址,题目要求可以设置五个默认的定时时间,struct Time times[5];用于存储五个定时时间,uint8_t timernum = 0;相当于一个指针,指向当前定时的时间,范围在times的范围0-4之间,time是当前使用的定时器的时间,view是屏幕显示状态的索引。

StartCountdown调用后开始计时,PauseCountdown调用后暂停计时,StopCountdown调用后停止计时

ReadFromEeprom用于将EEPROM中的存储的时间读取到times数组中,每次读取后与下一次读取需要有时间间隔防止实训混乱

key_process中按键以用于切换五个不同的定时时间,仅仅在view=1即展示状态才可以切换,使用mod运算timernum = (timernum + 1) % 5;保证timernum在0-4时间,为了防止后续修改与当前数组的值不同,每次按下按键以切换不同定时值时都需要调用ReadFromEeprom函数将times数组中的时间更新为最新的值

按下按键2后,通过判断不同的view确定不同的动作,当前在view=1展示状态下后点击按键2进入view=2设置状态,再次按下进入设置小时的状态下,之后每次按键按下都在设置小时、分钟、秒之间切换

如果长按按键2,保存当前设置的值到EEPROM中,同样每次写入时需要间隔一定时间,调用ReadFromEeprom更新times数组,回到view=1展示状态

按键3按下根据不同view设置时分秒的值

最后一个按键按键4,根据当前定时器的状态,控制短按需要执行的函数,同样只有view=1按下当前按键才有用,如果当前在停止或者暂停状态,短按按键4进入开始状态,然后短按暂停,长按停止同时将当前time的值设置为初始值

lcd_process中利用switch-case状态机模式显示不同的lcd状态

pwmAndLed_process用于处理pwm和led的状态,当countdownStatus == COUNTDOWN_RUNNING运行状态时,开始输出pwm设置占空比为80%,同时利用滴答定时器的UWTick来计时实现led以0.5s的周期闪烁,

led.h

#ifndef __LED_H
#define __LED_H#include "stm32g4xx_hal.h"
#include "main.h"
void LED_display(uint8_t led);
#endif

led.c

#include "led.h"void LED_display(uint8_t led)
{HAL_GPIO_WritePin(GPIOC,GPIO_PIN_All,GPIO_PIN_SET);HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_SET);HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_RESET);HAL_GPIO_WritePin(GPIOC,led<<8,GPIO_PIN_RESET);HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_SET);HAL_GPIO_WritePin(GPIOD,GPIO_PIN_2,GPIO_PIN_RESET);
}

PD2是一个锁存器高电平打开引脚,设置的值才可以到led中

key.h

#ifndef __KEY_H
#define __KEY_H#include "stm32g4xx_hal.h"
#include "main.h"
#include "stdbool.h"struct Key{uint8_t key_status;bool key_gpio;bool key_single_flag;bool key_long_flag;uint8_t key_times;
};
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim);
#endif

比上次几个版本多了判断长时间按下和按下按键的时间

key.c

#include "key.h"
#define FAST_INCREMENT_PERIOD 10 // 快速增加的周期计数阈值
struct Key key[4]={0,0,0,0};
extern struct Time time;
extern uint8_t view;void IncreaseSettingValue(void) {// 根据当前设置的位置,递增小时、分钟或秒switch (view) {case 3:time.hours = (time.hours + 1) % 24;break;case 4:time.minutes = (time.minutes + 1) % 60;break;case 5:time.seconds = (time.seconds + 1) % 60;break;}}void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{if(htim->Instance==TIM2){key[0].key_gpio = HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0);key[1].key_gpio = HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_1);key[2].key_gpio = HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_2);key[3].key_gpio = HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0);for(int i = 0;i<4;i++){switch(key[i].key_status){case 0:{if(key[i].key_gpio==0){key[i].key_times = 0;//最新的一次按下key[i].key_status = 1;}}break;case 1:{if(key[i].key_gpio==0){key[i].key_status = 2;}else{key[i].key_status = 0;}}break;case 2:{if(key[i].key_gpio==1) //按键已经松开{key[i].key_status = 0;if(key[i].key_times<80){key[i].key_single_flag = 1;//短按}}else{ //按键没有松开,开始计时key[i].key_times++;if(key[i].key_times>80) //0.8s{key[i].key_long_flag = 1; //长按if (key[2].key_times % FAST_INCREMENT_PERIOD == 0) {IncreaseSettingValue(); }}}}break;}}}}

在case2中按键如果没有松开开始计时,该定时器中断是10ms进入一次,key_times++一次相当于过去了10ms,所以判断key[i].key_times>80可以判断是否为长按,在长按中判断是不是按键3按下并且设置一个FAST_INCREMENT_PERIOD周期实现每100ms调用IncreaseSettingValue增加一次

i2c_hal.h

#ifndef __I2C_HAL_H
#define __I2C_HAL_H#include "stm32g4xx_hal.h"void I2CStart(void);
void I2CStop(void);
unsigned char I2CWaitAck(void);
void I2CSendAck(void);
void I2CSendNotAck(void);
void I2CSendByte(unsigned char cSendByte);
unsigned char I2CReceiveByte(void);
void I2CInit(void);
void EEROM_Write(uint8_t addr,uint8_t data); 
uint8_t EEROM_Read(uint8_t addr);
#endif

i2c_hal.c

/*程序说明: CT117E-M4嵌入式竞赛板GPIO模拟I2C总线驱动程序软件环境: MDK-ARM HAL库硬件环境: CT117E-M4嵌入式竞赛板日    期: 2020-3-1
*/#include "i2c_hal.h"#define DELAY_TIME	20/*** @brief SDA线输入模式配置* @param None* @retval None*/
void SDA_Input_Mode()
{GPIO_InitTypeDef GPIO_InitStructure = {0};GPIO_InitStructure.Pin = GPIO_PIN_7;GPIO_InitStructure.Mode = GPIO_MODE_INPUT;GPIO_InitStructure.Pull = GPIO_PULLUP;GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_HIGH;HAL_GPIO_Init(GPIOB, &GPIO_InitStructure);
}/*** @brief SDA线输出模式配置* @param None* @retval None*/
void SDA_Output_Mode()
{GPIO_InitTypeDef GPIO_InitStructure = {0};GPIO_InitStructure.Pin = GPIO_PIN_7;GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_OD;GPIO_InitStructure.Pull = GPIO_NOPULL;GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_HIGH;HAL_GPIO_Init(GPIOB, &GPIO_InitStructure);
}/*** @brief SDA线输出一个位* @param val 输出的数据* @retval None*/
void SDA_Output( uint16_t val )
{if ( val ){GPIOB->BSRR |= GPIO_PIN_7;}else{GPIOB->BRR |= GPIO_PIN_7;}
}/*** @brief SCL线输出一个位* @param val 输出的数据* @retval None*/
void SCL_Output( uint16_t val )
{if ( val ){GPIOB->BSRR |= GPIO_PIN_6;}else{GPIOB->BRR |= GPIO_PIN_6;}
}/*** @brief SDA输入一位* @param None* @retval GPIO读入一位*/
uint8_t SDA_Input(void)
{if(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_7) == GPIO_PIN_SET){return 1;}else{return 0;}
}/*** @brief I2C的短暂延时* @param None* @retval None*/
static void delay1(unsigned int n)
{uint32_t i;for ( i = 0; i < n; ++i);
}/*** @brief I2C起始信号* @param None* @retval None*/
void I2CStart(void)
{SDA_Output(1);delay1(DELAY_TIME);SCL_Output(1);delay1(DELAY_TIME);SDA_Output(0);delay1(DELAY_TIME);SCL_Output(0);delay1(DELAY_TIME);
}/*** @brief I2C结束信号* @param None* @retval None*/
void I2CStop(void)
{SCL_Output(0);delay1(DELAY_TIME);SDA_Output(0);delay1(DELAY_TIME);SCL_Output(1);delay1(DELAY_TIME);SDA_Output(1);delay1(DELAY_TIME);}/*** @brief I2C等待确认信号* @param None* @retval None*/
unsigned char I2CWaitAck(void)
{unsigned short cErrTime = 5;SDA_Input_Mode();delay1(DELAY_TIME);SCL_Output(1);delay1(DELAY_TIME);while(SDA_Input()){cErrTime--;delay1(DELAY_TIME);if (0 == cErrTime){SDA_Output_Mode();I2CStop();return ERROR;}}SDA_Output_Mode();SCL_Output(0);delay1(DELAY_TIME);return SUCCESS;
}/*** @brief I2C发送确认信号* @param None* @retval None*/
void I2CSendAck(void)
{SDA_Output(0);delay1(DELAY_TIME);delay1(DELAY_TIME);SCL_Output(1);delay1(DELAY_TIME);SCL_Output(0);delay1(DELAY_TIME);}/*** @brief I2C发送非确认信号* @param None* @retval None*/
void I2CSendNotAck(void)
{SDA_Output(1);delay1(DELAY_TIME);delay1(DELAY_TIME);SCL_Output(1);delay1(DELAY_TIME);SCL_Output(0);delay1(DELAY_TIME);}/*** @brief I2C发送一个字节* @param cSendByte 需要发送的字节* @retval None*/
void I2CSendByte(unsigned char cSendByte)
{unsigned char  i = 8;while (i--){SCL_Output(0);delay1(DELAY_TIME);SDA_Output(cSendByte & 0x80);delay1(DELAY_TIME);cSendByte += cSendByte;delay1(DELAY_TIME);SCL_Output(1);delay1(DELAY_TIME);}SCL_Output(0);delay1(DELAY_TIME);
}/*** @brief I2C接收一个字节* @param None* @retval 接收到的字节*/
unsigned char I2CReceiveByte(void)
{unsigned char i = 8;unsigned char cR_Byte = 0;SDA_Input_Mode();while (i--){cR_Byte += cR_Byte;SCL_Output(0);delay1(DELAY_TIME);delay1(DELAY_TIME);SCL_Output(1);delay1(DELAY_TIME);cR_Byte |=  SDA_Input();}SCL_Output(0);delay1(DELAY_TIME);SDA_Output_Mode();return cR_Byte;
}//
void I2CInit(void)
{GPIO_InitTypeDef GPIO_InitStructure = {0};GPIO_InitStructure.Pin = GPIO_PIN_7 | GPIO_PIN_6;GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;GPIO_InitStructure.Pull = GPIO_PULLUP;GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_HIGH;HAL_GPIO_Init(GPIOB, &GPIO_InitStructure);
}void EEROM_Write(uint8_t addr,uint8_t data)
{I2CStart();I2CSendByte(0xA0);I2CWaitAck();I2CSendByte(addr);I2CWaitAck();I2CSendByte(data);I2CWaitAck();I2CStop();
}uint8_t EEROM_Read(uint8_t addr)
{uint8_t data = 0; // 定义一个变量来存储接收到的数据I2CStart();I2CSendByte(0xA0);I2CWaitAck();I2CSendByte(addr);I2CWaitAck();I2CStop();I2CStart();I2CSendByte(0xA1);I2CWaitAck();data = I2CReceiveByte();I2CWaitAck();I2CStop();return data; // 返回接收到的数据
}

stm32g4xx_it.c

/* USER CODE BEGIN Header */
/********************************************************************************* @file    stm32g4xx_it.c* @brief   Interrupt Service Routines.******************************************************************************* @attention** <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.* All rights reserved.</center></h2>** This software component is licensed by ST under BSD 3-Clause license,* the "License"; You may not use this file except in compliance with the* License. You may obtain a copy of the License at:*                        opensource.org/licenses/BSD-3-Clause********************************************************************************/
/* USER CODE END Header *//* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32g4xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes *//* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
extern struct Time time;
extern CountdownStatus countdownStatus;
/* USER CODE END TD *//* 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 -----------------------------------------------*/
/* USER CODE BEGIN PFP *//* USER CODE END PFP *//* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 *//* USER CODE END 0 *//* External variables --------------------------------------------------------*/
extern TIM_HandleTypeDef htim2;
/* USER CODE BEGIN EV *//* USER CODE END EV *//******************************************************************************/
/*           Cortex-M4 Processor Interruption and Exception Handlers          */
/******************************************************************************/
/*** @brief This function handles Non maskable interrupt.*/
void NMI_Handler(void)
{/* USER CODE BEGIN NonMaskableInt_IRQn 0 *//* USER CODE END NonMaskableInt_IRQn 0 *//* USER CODE BEGIN NonMaskableInt_IRQn 1 *//* USER CODE END NonMaskableInt_IRQn 1 */
}/*** @brief This function handles Hard fault interrupt.*/
void HardFault_Handler(void)
{/* USER CODE BEGIN HardFault_IRQn 0 *//* USER CODE END HardFault_IRQn 0 */while (1){/* USER CODE BEGIN W1_HardFault_IRQn 0 *//* USER CODE END W1_HardFault_IRQn 0 */}
}/*** @brief This function handles Memory management fault.*/
void MemManage_Handler(void)
{/* USER CODE BEGIN MemoryManagement_IRQn 0 *//* USER CODE END MemoryManagement_IRQn 0 */while (1){/* USER CODE BEGIN W1_MemoryManagement_IRQn 0 *//* USER CODE END W1_MemoryManagement_IRQn 0 */}
}/*** @brief This function handles Prefetch fault, memory access fault.*/
void BusFault_Handler(void)
{/* USER CODE BEGIN BusFault_IRQn 0 *//* USER CODE END BusFault_IRQn 0 */while (1){/* USER CODE BEGIN W1_BusFault_IRQn 0 *//* USER CODE END W1_BusFault_IRQn 0 */}
}/*** @brief This function handles Undefined instruction or illegal state.*/
void UsageFault_Handler(void)
{/* USER CODE BEGIN UsageFault_IRQn 0 *//* USER CODE END UsageFault_IRQn 0 */while (1){/* USER CODE BEGIN W1_UsageFault_IRQn 0 *//* USER CODE END W1_UsageFault_IRQn 0 */}
}/*** @brief This function handles System service call via SWI instruction.*/
void SVC_Handler(void)
{/* USER CODE BEGIN SVCall_IRQn 0 *//* USER CODE END SVCall_IRQn 0 *//* USER CODE BEGIN SVCall_IRQn 1 *//* USER CODE END SVCall_IRQn 1 */
}/*** @brief This function handles Debug monitor.*/
void DebugMon_Handler(void)
{/* USER CODE BEGIN DebugMonitor_IRQn 0 *//* USER CODE END DebugMonitor_IRQn 0 *//* USER CODE BEGIN DebugMonitor_IRQn 1 *//* USER CODE END DebugMonitor_IRQn 1 */
}/*** @brief This function handles Pendable request for system service.*/
void PendSV_Handler(void)
{/* USER CODE BEGIN PendSV_IRQn 0 *//* USER CODE END PendSV_IRQn 0 *//* USER CODE BEGIN PendSV_IRQn 1 *//* USER CODE END PendSV_IRQn 1 */
}/*** @brief This function handles System tick timer.*/
void SysTick_Handler(void)
{/* USER CODE BEGIN SysTick_IRQn 0 */static uint32_t ticks = 0;if (countdownStatus == COUNTDOWN_RUNNING && ++ticks >= 1000) {ticks = 0; // 重置计数器// 倒计时逻辑if (time.seconds > 0) {time.seconds--;} else if (time.minutes > 0) {time.minutes--;time.seconds = 59;} else if (time.hours > 0) {time.hours--;time.minutes = 59;time.seconds = 59;} else {// 倒计时结束countdownStatus = COUNTDOWN_STOPPED;}}/* USER CODE END SysTick_IRQn 0 */HAL_IncTick();/* USER CODE BEGIN SysTick_IRQn 1 *//* USER CODE END SysTick_IRQn 1 */
}/******************************************************************************/
/* STM32G4xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32g4xx.s).                    */
/******************************************************************************//*** @brief This function handles TIM2 global interrupt.*/
void TIM2_IRQHandler(void)
{/* USER CODE BEGIN TIM2_IRQn 0 *//* USER CODE END TIM2_IRQn 0 */HAL_TIM_IRQHandler(&htim2);/* USER CODE BEGIN TIM2_IRQn 1 *//* USER CODE END TIM2_IRQn 1 */
}/* USER CODE BEGIN 1 *//* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

SysTick_Handler是1ms进入一次使用SysTick_Handler定时ticks累积到1000时代表过去了1s,在这里倒计时

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/680758.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java-并发高频面试题-2

接着之前的Java-并发高频面试题 7. synchronized的实现原理是怎么样的&#xff1f; 首先我们要知道synchronized它是解决线程安全问题的一种方式&#xff0c;而具体是怎么解决的呢&#xff1f;主要是通过加锁的方式来解决 在底层实现上来看 是通过 monitorenter、monitorexit…

【Spring原理进阶】SpringMVC调用链+JSP模板应用讲解

&#x1f389;&#x1f389;欢迎光临&#x1f389;&#x1f389; &#x1f3c5;我是苏泽&#xff0c;一位对技术充满热情的探索者和分享者。&#x1f680;&#x1f680; &#x1f31f;特别推荐给大家我的最新专栏《Spring 狂野之旅&#xff1a;底层原理高级进阶》 &#x1f680…

【Python网络编程之Ping命令的实现】

&#x1f680; 作者 &#xff1a;“码上有前” &#x1f680; 文章简介 &#xff1a;Python开发技术 &#x1f680; 欢迎小伙伴们 点赞&#x1f44d;、收藏⭐、留言&#x1f4ac; Python网络编程之Ping命令的实现 代码见资源&#xff0c;效果图如下一、实验要求二、协议原理2…

所谓的意志力,也许根本就不存在

许多讲自我提升的书&#xff0c;往往会把成功的原因归结为两点&#xff1a;自律&#xff0c;以及专注。 他们会告诉你&#xff1a;为什么别人能够成功、而你不能&#xff1f;第一是你不够自律&#xff0c;无法每天雷打不动地坚持「好习惯」&#xff1b;第二&#xff0c;是你不够…

[Java][算法 滑动窗口]Day 02---LeetCode 热题 100---08~09

第一题 无重复字符串的最长子串 思路 其实就是在字符串S中 找到没有重复的最长子串的长度 这道题的难点就是在于如何判断最长并且无重复 首先 最长长度 可以使用变量max记录保存 再者 判断有无重复 最简单的方法就是 暴力遍历法 即对于每次找的子串都再次寻找遍历…

【Chrono Engine学习总结】5-sensor-5.1-sensor基础并创建一个lidar

由于Chrono的官方教程在一些细节方面解释的并不清楚&#xff0c;自己做了一些尝试&#xff0c;做学习总结。 1、Sensor模块 Sensor模块是附加模块&#xff0c;需要单独安装。参考&#xff1a;【Chrono Engine学习总结】1-安装配置与程序运行 Sensor Module Tutorial Sensor …

【国产MCU】-CH32V307-基本定时器(BCTM)

基本定时器(BCTM) 文章目录 基本定时器(BCTM)1、基本定时器(BCTM)介绍2、基本定时器驱动API介绍3、基本定时器使用实例CH32V307的基本定时器模块包含一个16 位可自动重装的定时器(TIM6和TIM7),用于计数和在更新新事件产生中断或DMA 请求。 本文将详细介绍如何使用CH32…

苹果Mac键盘如何将 F1 到 F12 取消按Fn

苹果电脑安装了Win10操作系统之后&#xff0c;F1到F12用不了怎么办的解决方法。本文将介绍一些解决方法&#xff0c;帮助您解决无法使用F1到F12功能键的问题。 使用 Mac系统的人都知道&#xff0c;Mac系统默认是没有开启 F1-F12 的使用的&#xff0c;平时我们使用的系统都可以使…

AcWing 802. 区间和 离散化

文章目录 题目链接题目描述解题思路代码实现总结 题目链接 链接: AcWing 802. 区间和 题目描述 解题思路 离散化是一种常用的技巧&#xff0c;它能够将原始的连续数值转换为一组离散的值&#xff0c;从而简化问题的处理。在这段代码中&#xff0c;离散化的过程主要分为三个步…

那些也许你不知道的操作符!

前言 操作符有很多种&#xff0c;目前我们已经了解了一部分 例如最简单的、-、*、/、&#xff0c;还有我们学到的&&&#xff0c;||&#xff0c;!等&#xff0c;但是操作符可不是就只有这么些的&#xff0c;让我们一起来看看吧 目录 1. 移位操作符 原码、反码、补码…

Stream Query Denoising for Vectorized HD Map Construction

参考代码&#xff1a;截止2024.02未开源 动机与出发点 这篇文章是在StreamMapNet的基础上做的&#xff0c;为了在局部地图感知任务上提升时序上的感知稳定性&#xff0c;参考DN-DETR中的去噪方案&#xff0c;为局部地图感知提出一种针对局部地图元素的加噪声方案以及去噪逻辑。…

【开源】JAVA+Vue.js实现海南旅游景点推荐系统

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 用户端2.2 管理员端 三、系统展示四、核心代码4.1 随机景点推荐4.2 景点评价4.3 协同推荐算法4.4 网站登录4.5 查询景点美食 五、免责说明 一、摘要 1.1 项目介绍 基于VueSpringBootMySQL的海南旅游推荐系统&#xff…

蓝牙BLE学习-安全

1.基本概念 蓝牙标准规定了5种基本的安全服务 身份验证:根据通信设备的蓝牙地址验证其身份。蓝牙不提供本地用户身份验证。保密性:确保只有授权的设备才能访问和查看传输的数据&#xff0c;防止窃听造成的信息泄露。授权(Authorization):在允许设备使用某项服务之前&#xff…

Verilog刷题笔记29

题目&#xff1a; Create a 100-bit binary ripple-carry adder by instantiating 100 full adders. The adder adds two 100-bit numbers and a carry-in to produce a 100-bit sum and carry out. To encourage you to actually instantiate full adders, also output the ca…

C++异常特性以及使用

异常 1.C传统的处理错误方式2.异常概念3.异常使用规则抛出和匹配规则 4.异常的重新抛出4.异常安全5.异常规范6.使用自定义的异常7.C标准异常体系7.异常优缺点 1.C传统的处理错误方式 终止程序&#xff1a;如assert&#xff0c;缺陷&#xff1a;用户难以接受。如发生内存错误&a…

[CUDA 学习笔记] Reduce 算子优化

Reduce 算子优化 注: 本文主要是对文章 【BBuf的CUDA笔记】三&#xff0c;reduce优化入门学习笔记 - 知乎 的学习整理 Reduce 又称之为归约, 即根据数组中的每个元素得到一个输出值, 常见的包括求和(sum)、取最大值(max)、取最小值(min)等. 前言 本文同样按照英伟达官方 PP…

C++ //练习 5.6 改写上一题的程序,使用条件运算符(参见4.7节,第134页)代替if else语句。

C Primer&#xff08;第5版&#xff09; 练习 5.6 练习 5.6 改写上一题的程序&#xff0c;使用条件运算符&#xff08;参见4.7节&#xff0c;第134页&#xff09;代替if else语句。 环境&#xff1a;Linux Ubuntu&#xff08;云服务器&#xff09; 工具&#xff1a;vim 代码…

EasyRecovery软件2024永久绿色免费版下载

EasyRecovery软件在数据恢复领域享有良好的声誉&#xff0c;并且被许多用户认为是一款好用且功能强大的软件。以下是对其功能和用户评价的简要概述&#xff1a; 恢复功能&#xff1a; EasyRecovery提供全面的数据恢复功能&#xff0c;可以恢复因删除、格式化、分区丢失、硬盘故…

Ubuntu20.04更新Cmake版本详解

最近在跑一个融合惯导定位的slam框架ins_eskf_kitti&#xff0c;在框架的安装过程中&#xff0c;需要对从GitHub上克隆下来的glog进行编译。其命令如下&#xff1a; glog&#xff1a; git clone https://github.com/google/glog.git cd glog mkdir build cd build cmake .. m…

3月第一批次❗教资认定流程简易版来啦

&#x1f4dd;材料准备 1、身份证 2、户口本/学生证/居住证/毕业证 3、考试合格证明(免试人员需要师范生职业能力证书) 4、普通话证书 5、学历证书或认证报告 6、近期一寸白底证件照 7、有效期内体检报告 8、个人承诺书(网上签署) 网上申报 1、上传个人承诺书 2、校验普通话证书…