蓝桥杯嵌入式第9届真题(完成) STM32G431
题目
分析和代码
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>© 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>© 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; // 清除标志位
// 将当前时间写入EEPROM
EEROM_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>© 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,在这里倒计时