CW32F030K8U7用库来实现按键长按3秒lcd灯亮的全部代码包括初始化
时间: 2024-03-13 11:44:09 浏览: 54
液晶显示器单片机初始化程序
4星 · 用户满意度95%
好的,以下是使用ST标准库实现按键长按3秒LCD灯亮的代码,包括初始化:
```c
#include "stm32f0xx.h"
#include "stm32f0xx_gpio.h"
#include "stm32f0xx_rcc.h"
#include "stm32f0xx_tim.h"
#include "stm32f0xx_exti.h"
#include "stm32f0xx_syscfg.h"
#define LED_PIN GPIO_Pin_0
#define LED_PORT GPIOA
#define KEY_PIN GPIO_Pin_0
#define KEY_PORT GPIOB
void init_gpio(void)
{
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
// LED
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
// KEY
GPIO_InitStructure.GPIO_Pin = KEY_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(KEY_PORT, &GPIO_InitStructure);
// Connect EXTI Line0 to PB0
SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOB, EXTI_PinSource0);
// Configure EXTI Line0
EXTI_InitTypeDef EXTI_InitStructure;
EXTI_InitStructure.EXTI_Line = EXTI_Line0;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
// Enable and set EXTI Line0 Interrupt
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void init_timer(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Prescaler = 47999; // 1ms
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = 3000; // 3 sec
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM3, DISABLE);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPriority = 0x01;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
int main(void)
{
init_gpio();
init_timer();
while(1)
{
}
}
void EXTI0_1_IRQHandler(void)
{
if(EXTI_GetITStatus(EXTI_Line0) != RESET)
{
TIM_Cmd(TIM3, ENABLE);
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
void TIM3_IRQHandler(void)
{
if(TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
{
GPIO_SetBits(LED_PORT, LED_PIN);
TIM_Cmd(TIM3, DISABLE);
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
}
}
```
上述代码实现了以下功能:
1. 初始化LED和按键GPIO口。
2. 初始化定时器TIM3,使其定时3秒后触发中断。
3. 在按键中断服务函数中,启动定时器。
4. 在定时器中断服务函数中,点亮LED并停止定时器。
需要注意的是,定时器的计数时钟频率为48MHz,因此需要将预分频器设置为47999,这样计数器每计数一次就相当于1ms。同时,定时器的溢出时间需要设置为3000,这样计数器计数到3000时就会触发中断,即3秒后。
阅读全文