蓝桥杯嵌入式第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.hqwc.cn/news/466238.html

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

相关文章

分析“e^iπ+1=0”的错谬及其违反数学规则

如果评选从远古到现代对人类智商羞辱最严重的事件&#xff0c;欧拉公式“e^iπ-1”若说第二、就没有哪个能称第一。 看下面罗列的关系&#xff0c;数学伦理在大数学家欧拉眼里形同虚设&#xff1a; ①“e^iπ-1”没有代码&#xff0c;不能表示数量变化关系&#xff0c;它来自e^…

2024年Midjourney 付费订阅流程 | Midjourney 各版本介绍,使用虚拟信用卡支付买Midjourney流程指南

1.Midjourney介绍 Midjourney 是一款备受欢迎的人工智能生成图像工具&#xff0c;它可以通过输入文字描述&#xff0c;自动生成精美的图像。与许多其他图像生成工具不同&#xff0c;Midjourney 不需要安装任何软件&#xff0c;也不受个人电脑性能的限制&#xff0c;因为它运行…

《21天精通IPv4 to IPv6》第17天:IPv6的全球部署现状——IPv6全球部署现状怎么样?

博主猫头虎的技术世界 &#x1f31f; 欢迎来到猫头虎的博客 — 探索技术的无限可能&#xff01; 专栏链接&#xff1a; &#x1f517; 精选专栏&#xff1a; 《面试题大全》 — 面试准备的宝典&#xff01;《IDEA开发秘籍》 — 提升你的IDEA技能&#xff01;《100天精通鸿蒙》 …

C++进阶(十五)C++的类型转换

&#x1f4d8;北尘_&#xff1a;个人主页 &#x1f30e;个人专栏:《Linux操作系统》《经典算法试题 》《C》 《数据结构与算法》 ☀️走在路上&#xff0c;不忘来时的初心 文章目录 一、C语言中的类型转换二、为什么C需要四种类型转换三、C强制类型转换1、static_cast2、reint…

Excel——重复项处理

一、高亮重复项 选择需要高亮重复项的列/单元格 选择【数据】——【重复项】—— 【高亮重复项】 如果高亮重复项的数据较长&#xff0c;例如&#xff1a;身份证号、银行卡&#xff0c;可以勾选下列选项&#xff0c;能够精准检查重复项。 结果如下所示 如果想要清除高亮的重复…

k8s-项目部署案例

一、容器交付流程 在k8s平台部署项目流程 在K8s部署Java网站项目 DockerFile 如果是http访问&#xff0c;需要在镜像仓库配置可信任IP 三、使用工作负载控制器部署镜像 建议至少配置两个标签 一个是声明项目类型的 一个是项目名称的 继续配置属性 资源配额 健康检查 五、使…

CVE-2022-25487 漏洞复现

漏洞描述&#xff1a;Atom CMS 2.0版本存在远程代码执行漏洞&#xff0c;该漏洞源于/admin/uploads.php 未能正确过滤构造代码段的特殊元素。攻击者可利用该漏洞导致任意代码执行。 其实这就是一个文件上传漏洞罢了。。。。 打开之后&#xff0c;/home路由是个空白 信息搜集&…

模型 AARRR(获取、激活、留存、收益、推荐)

系列文章 主要是 分享 思维模型&#xff0c;涉及各个领域&#xff0c;重在提升认知。用户增长五环。 1 模型 AARRR(获取、激活、留存、收益、推荐)的应用 1.1 抖音的AARRR模型应用 抖音是一款非常成功的应用程序&#xff0c;它在用户获取、用户激活、用户留存、收入获取和用户…

为什么大模型需要向量数据库?

AIGC 时代万物都可以向量化&#xff0c;向量化是 LLM 大模型以及 Agent 应用的基础。 比如&#xff1a;爆火的 Google 大模型 Gemini 1.0 原生支持的多模态&#xff0c;在预训练的时候就是把文本、图片、音频、视频等多模态先进行 token 化&#xff0c;然后构建一维的“语言”…

python+flask+django医院预约挂号系统6nrhh

医院预约挂号系统主要有管理员、用户和医生三个功能模块。以下将对这三个功能的作用进行详细的剖析。 技术栈 后端&#xff1a;python 前端&#xff1a;vue.jselementui 框架&#xff1a;django/flask Python版本&#xff1a;python3.7 数据库&#xff1a;mysql5.7 数据库工具…

新年福利:《YOLO目标检测》送书活动

博主简介 AI小怪兽&#xff0c;YOLO骨灰级玩家&#xff0c;1&#xff09;YOLOv5、v7、v8优化创新&#xff0c;轻松涨点和模型轻量化&#xff1b;2&#xff09;目标检测、语义分割、OCR、分类等技术孵化&#xff0c;赋能智能制造&#xff0c;工业项目落地经验丰富&#xff1b; …

力扣_字符串6—最小覆盖字串

题目 给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串&#xff0c;则返回空字符串 “” 。 示例 &#xff1a; 输入&#xff1a;s “ADOBECODEBANC”, t “ABC” 输出&#xff1a;“BANC” 解释&#xff1a;…