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

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

相关文章

Ubuntu Desktop - Terminal 输出全部选中 + 复制

Ubuntu Desktop - Terminal 输出全部选中 复制 1. Terminal2. Terminal 最大化3. Edit -> Select All4. Copy & PasteReferences 1. Terminal 2. Terminal 最大化 3. Edit -> Select All 4. Copy & Paste Edit -> Copy or Shift Ctrl C Edit -> Paste…

PV、UV、IP

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言1. PV1.1 PV 计算1.2 PV 的影响因素 2. UV2.1 UV 计算2.2UV 的影响因素 3. IP3.1 IP和UV①UV大于IP②UV小于IP 三者的关系PV 和 UV 前言 PV、UV、IP是我们在运…

印度5G不是比中国先进,而是印度用户敢用,中国用户不敢用!

分析机构OpenSignal给出的数据指出中国手机用户的平均速率比印度用户还要低&#xff0c;这说明中国5G落后于印度&#xff0c;其实这是片面的说法&#xff0c;中国运营商的5G网络能力肯定强于印度运营商&#xff0c;但是中国用户不敢用&#xff0c;而印度用户敢用&#xff0c;这…

mysql经典4张表问题

1.数据库表结构关联图 2.问题&#xff1a; 1、查询"01"课程比"02"课程成绩高的学生的信息及课程分数3.查询平均成绩大于等于60分的同学的学生编号和学生姓名和平均成绩4、查询名字中含有"风"字的学生信息5、查询课程名称为"数学"&…

java的excel列行合并模版

1.效果 2.模版 <tableborder"1"cellpadding"0"cellspacing"0"class"tablebor"id"TABLE"><tr align"center" class"bg217"><td style"background-color: #008000; color: #ffffff;p…

【初中生讲机器学习】6. 分类算法中常用的模型评价指标有哪些?here!

创建时间&#xff1a;2024-02-07 最后编辑时间&#xff1a;2024-02-09 作者&#xff1a;Geeker_LStar 你好呀~这里是 Geeker_LStar 的人工智能学习专栏&#xff0c;很高兴遇见你~ 我是 Geeker_LStar&#xff0c;一名初三学生&#xff0c;热爱计算机和数学&#xff0c;我们一起加…

Web 扫描神器:Gobuster 保姆级教程(附链接)

一、介绍 Gobuster 是一款用于目录和文件枚举的开源工具。它主要用于在Web应用程序或网站上查找隐藏的目录和文件&#xff0c;从而进行信息收集或渗透测试。以下是 Gobuster 的一些主要特点和功能&#xff1a; 快速且高效&#xff1a; Gobuster 被设计为快速、高效的工具&…

第九个知识点:内部对象

Date对象: <script>var date new Date();date.getFullYear();//年date.getMonth();//月date.getDate();//日date.getDay();//星期几date.getHours();//时date.getMinutes();//分date.getSeconds();//秒date.getTime();//获取时间戳&#xff0c;时间戳时全球统一&#x…

【人工智能】神奇的Embedding:文本变向量,大语言模型智慧密码解析(10)

什么是嵌入&#xff1f; OpenAI 的文本嵌入衡量文本字符串的相关性。嵌入通常用于&#xff1a; Search 搜索&#xff08;结果按与查询字符串的相关性排序&#xff09;Clustering 聚类&#xff08;文本字符串按相似性分组&#xff09;Recommendations 推荐&#xff08;推荐具有…

牛客周赛 Round 32 F.小红的矩阵修改【三进制状态压缩dp】

原题链接&#xff1a;https://ac.nowcoder.com/acm/contest/75174/F 时间限制&#xff1a;C/C 1秒&#xff0c;其他语言2秒 空间限制&#xff1a;C/C 262144K&#xff0c;其他语言524288K 64bit IO Format: %lld 题目描述 小红拿到了一个字符矩阵&#xff0c;矩阵中仅包含&q…

spring boot学习第十一篇:发邮件

1、pom.xml文件内容如下&#xff08;是我所有学习内容需要的&#xff0c;不再单独分出来&#xff0c;包不会冲突&#xff09;&#xff1a; <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"…

《CSS 简易速速上手小册》第3章:CSS 响应式设计(2024 最新版)

文章目录 3.1 媒体查询基础&#xff1a;网页的智能眼镜3.1.1 基础知识3.1.2 重点案例&#xff1a;适应三种设备的响应式布局3.1.3 拓展案例 1&#xff1a;改变字体大小3.1.4 拓展案例 2&#xff1a;暗模式适配 3.2 响应式图片和视频&#xff1a;让内容自由呼吸3.2.1 基础知识3.…

LeetCode周赛——384

1.修改矩阵&#xff08;模拟&#xff09; class Solution { public:vector<vector<int>> modifiedMatrix(vector<vector<int>>& matrix) {int n matrix.size();int m matrix[0].size();vector<int> ans(m);for(int i 0; i < m; i)for(…

操作系统——内存管理(附带Leetcode算法题LRU)

目录 1.内存管理主要用来干什么&#xff1f; 2.什么是内存碎片&#xff1f; 3.虚拟内存 3.1传统存储管理方式的缺点&#xff1f; 3.2局部性原理 3.3什么是虚拟内存&#xff1f;有什么用&#xff1f; 3.3.1段式分配 3.3.2页式分配 3.3.2.1换页机制 3.3.2.2页面置换算法…

计算机网络——08应用层原理

应用层原理 创建一个新的网络 编程 在不同的端系统上运行通过网络基础设施提供的服务&#xff0c;应用进程批次通信如Web Web服务器软件与浏览器软件通信 网络核心中没有应用层软件 网络核心没有应用层功能网络应用只能在端系统上存在 快速网络应用开发和部署 网络应用…

【MySQL】数据库和表的操作

数据库和表的操作 一、数据库的操作1. 创建数据库2. 字符集和校验规则&#xff08;1&#xff09;查看系统默认字符集以及校验规则&#xff08;2&#xff09;查看数据库支持的字符集&#xff08;3&#xff09;查看数据库支持的字符集校验规则&#xff08;4&#xff09;校验规则对…

Powershell Install 一键部署Openssl+certificate证书创建

前言 Openssl 是一个方便的实用程序,用于创建自签名证书。您可以在所有操作系统(如 Windows、MAC 和 Linux 版本)上使用 OpenSSL。 Windows openssl 下载 前提条件 开启wmi,配置网卡,参考 自签名证书 创建我们自己的根 CA 证书和 CA 私钥(我们自己充当 CA)创建服务器…

【蓝桥杯嵌入式】新建工程 | 点亮LED | LCD配置

目录 源代码 硬件资源 产品图片 硬件布局 资源配置表 跳线 下载方式 新建工程 点亮LED code 函数调用 LED初始化 Delay点灯 流水灯 积累流水灯 整合效果 LCD移植 lcd.c lcd.h fonts.h LCD初始化 main.c预览 闲话 源代码 网址&#xff1a;后续会上传…

FL Studio版本升级-FL Studio怎么升级-FL Studio升级方案

已经是新年2024年了&#xff0c;但是但是依然有很多朋友还在用FL Studio12又或者FL Studio20&#xff0c;今天这篇文章教大家如何升级FL Studio21 FL Studio 21是Image Line公司开发的音乐编曲软件&#xff0c;除了软件以外&#xff0c;我们还提供了FL Studio的升级服务&#…

设计模式2-对象池模式

对象池模式&#xff0c;Object Pool Pattern&#xff0c;当你的应用程序需要频繁创建和销毁某种资源&#xff08;比如数据库连接、线程、socket连接等&#xff09;时&#xff0c;Object Pool 设计模式就变得很有用。它通过预先创建一组对象并将它们保存在池中&#xff0c;以便在…