UCOSIII外部中断控制按键代码
时间: 2023-11-19 15:22:30 浏览: 110
物联网项目实战开发之基于STM32的按键检测代码程序(外部中断方式)
5星 · 资源好评率100%
下面是一个简单的UCOSIII外部中断控制按键的代码示例:
```c
#include "stm32f4xx.h"
#include "ucos_ii.h"
#define KEY_GPIO_PORT GPIOA
#define KEY_GPIO_PIN GPIO_Pin_0
#define KEY_EXTI_LINE EXTI_Line0
#define KEY_EXTI_PORT EXTI_PortSourceGPIOA
#define KEY_EXTI_PIN EXTI_PinSource0
#define KEY_EXTI_IRQ EXTI0_IRQn
static OS_EVENT* key_sem;
void Key_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
GPIO_InitStructure.GPIO_Pin = KEY_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(KEY_GPIO_PORT, &GPIO_InitStructure);
SYSCFG_EXTILineConfig(KEY_EXTI_PORT, KEY_EXTI_PIN);
EXTI_InitStructure.EXTI_Line = KEY_EXTI_LINE;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = KEY_EXTI_IRQ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0f;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0f;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void Key_ISR(void)
{
OS_ERR err;
EXTI_ClearITPendingBit(KEY_EXTI_LINE);
OSSemPost(key_sem, OS_OPT_POST_ALL, &err);
}
void Key_Task(void* pdata)
{
OS_ERR err;
while (1) {
OSSemPend(key_sem, 0, OS_OPT_PEND_BLOCKING, NULL, &err);
// 处理按键按下事件
printf("Key pressed!\r\n");
}
}
int main(void)
{
OS_ERR err;
OSInit();
Key_Init();
key_sem = OSSemCreate(0, &err);
OSTaskCreate(Key_Task, NULL, OSTaskStkChk, 10, 0, NULL, &err);
OSStart();
return 0;
}
void HardFault_Handler(void)
{
while (1);
}
```
上述代码中,`Key_Init()`函数用于初始化按键所对应的GPIO口、中断线和中断服务函数。在中断服务函数`Key_ISR()`中,使用`OSSemPost()`函数发送信号量,以通知任务处理按键按下事件。而在任务函数`Key_Task()`中,则使用`OSSemPend()`函数等待信号量,并在信号量被触发时处理按键按下事件。
阅读全文