初学stm32没几天,做任务要用到非阻塞延时,上网查定时中断什么的看不懂不会用,想到较粗糙的for循环计时(但是误差比想像中小很多,大概十几毫秒)。能够实现LED闪烁模式的随时切换
主程序部分:
#include "stm32f10x.h" // Device header
#include "Delay.h" //delay延时函数头文件
#include "LED.h" //控制LED的函数的头文件
#include "Key.h" //控制按键输入函数的头文件
int main (void)
{
LED_Init(); //初始化LED
Key_Init(); //初始化按键
uint16_t i = 0;
while(1)
{
if (Key_GetNum_1() == 1) //读取按键电平
{
transf1:
LED_re();
while(1){
LED1_ON();
for(i=0;i<=500;i++)
{
Delay_ms(1); //把delay延时拆分得很小这样就约等于非阻塞,但是实质上还是用了阻塞函数延时
if(Key_GetNum_11() == 1){goto transf2;}
}
LED1_OFF();
for(i=0;i<=500;i++)
{
Delay_ms(1);
if(Key_GetNum_11() == 1){goto transf2;}
}
LED2_ON();
for(i=0;i<=500;i++)
{
Delay_ms(1);
if(Key_GetNum_11() == 1){goto transf2;}
}
LED2_OFF();
for(i=0;i<=500;i++)
{
Delay_ms(1);
if(Key_GetNum_11() == 1){goto transf2;}
}
}
}
if (Key_GetNum_11() == 1)
{
transf2:
LED_re();
while(1){
LED1_ON();
for(i=0;i<=1000;i++)
{
Delay_ms(1);
if(Key_GetNum_1() == 1){goto transf1;}
}
LED1_OFF();
for(i=0;i<=1000;i++)
{
Delay_ms(1);
if(Key_GetNum_1() == 1){goto transf1;}
}
LED2_ON();
for(i=0;i<=1000;i++)
{
Delay_ms(1);
if(Key_GetNum_1() == 1){goto transf1;}
}
LED2_OFF();
for(i=0;i<=1000;i++)
{
Delay_ms(1);
if(Key_GetNum_1() == 1){goto transf1;}
}
}
}
}
}
LED部分:
#include "stm32f10x.h" // Device header
void LED_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_SetBits(GPIOA,GPIO_Pin_1 |GPIO_Pin_2);
}
void LED1_ON(void)
{
GPIO_ResetBits(GPIOA,GPIO_Pin_1);
}
void LED1_OFF(void)
{
GPIO_SetBits(GPIOA,GPIO_Pin_1);
}
void LED2_ON(void)
{
GPIO_ResetBits(GPIOA,GPIO_Pin_2);
}
void LED2_OFF(void)
{
GPIO_SetBits(GPIOA,GPIO_Pin_2);
}
void LED_re(void)
{
LED1_OFF();
LED2_OFF();
}
Key部分:
#include "stm32f10x.h" // Device header
#include "Delay.h"
void Key_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
}
uint8_t Key_GetNum_1(void)
{
uint8_t KeyNum = 0;
if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1) == 0)
{
Delay_ms(20); //消抖
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1) == 0);//一直按着就阻塞在这里,松手后灯才执行ON或OFF,没有这个的话按键一按灯就ON或OFF
Delay_ms(20); //消抖
KeyNum = 1;
}
return KeyNum;
}
uint8_t Key_GetNum_11(void)
{
uint8_t KeyNum = 0;
if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_11) == 0)
{
Delay_ms(20); //消抖
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_11) == 0);//一直按着就阻塞在这里,松手后灯才执行ON或OFF,没有这个的话按键一按灯就ON或OFF
Delay_ms(20); //消抖
KeyNum = 1;
}
return KeyNum;
}
师从江协科技