当前位置:首页 > 单片机 > 单片机
[导读]说明:GPIOA,GPIO_Pin_0对应key1;GPIOA,GPIO_Pin_1对应key2;GPIOA,GPIO_Pin_2对应LED1;GPIOA,GPIO_Pin_3对应LED2#include"stm32f10x.h"#include"stm32f10x_rcc.h"#include"stm32f10x_gpio.h"#include"system_stm3

说明:GPIOA,GPIO_Pin_0对应key1;GPIOA,GPIO_Pin_1对应key2;GPIOA,GPIO_Pin_2对应LED1;GPIOA,GPIO_Pin_3对应LED2

#include"stm32f10x.h"

#include"stm32f10x_rcc.h"

#include"stm32f10x_gpio.h"

#include"system_stm32f10x.h"

/*控制小灯:0灭1亮*/

#defineON1

#defineOFF0

#defineKEY_ON0

#defineKEY_OFF1

voidRCC_Configuration(void);

voidGPIO_Configuration(void);

voidSetLed(uint8_tset);

voiddelay_ms(u16time);

uint8_tKeyScan(GPIO_TypeDef*GPIOx,uint16_tGPIO_Pin_x);

intmain()

{

SystemInit();

RCC_Configuration();

GPIO_Configuration();

SetLed(ON);

while(1)

{

if(KeyScan(GPIOA,GPIO_Pin_0)==KEY_ON)

{

/*LED1反转读取GPIOA0端口位的值并用1减去之后再写入此位即LED1的控制位*/

GPIO_WriteBit(GPIOA,GPIO_Pin_2,(BitAction)(1-GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_2)));

}

if(KeyScan(GPIOA,GPIO_Pin_1)==KEY_ON)

{

/*LED2反转读取GPIOA0端口位的值并用1减去之后再写入此位即LED2的控制位*/

GPIO_WriteBit(GPIOA,GPIO_Pin_3,(BitAction)(1-GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_3)));

}

}

}

voidRCC_Configuration(void)

{

RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);

}

voidGPIO_Configuration(void)

{

GPIO_InitTypeDefGPIO_InitStructure;

GPIO_InitStructure.GPIO_Pin=GPIO_Pin_2|GPIO_Pin_3;

GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;

GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;

GPIO_Init(GPIOA,&GPIO_InitStructure);

GPIO_InitStructure.GPIO_Pin=GPIO_Pin_0|GPIO_Pin_1;

GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;/*配置按键的引脚为上拉*/

//GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;/*输入模式不需要配置端口的输出速率GPIO_Speed*/

GPIO_Init(GPIOA,&GPIO_InitStructure);

}

voidSetLed(uint8_tset)

{

if(set==ON){

GPIO_SetBits(GPIOA,GPIO_Pin_2);//LED1

GPIO_SetBits(GPIOA,GPIO_Pin_3);//LED2

}

if(set==OFF){

GPIO_ResetBits(GPIOA,GPIO_Pin_2);

GPIO_ResetBits(GPIOA,GPIO_Pin_3);

}

}

/**

*@brief:按键按下检测

*@param:端口:GPIOx端口位:GPIO_Pin_x

*@retval:按键的状态:按下弹起

*/

uint8_tKeyScan(GPIO_TypeDef*GPIOx,uint16_tGPIO_Pin_x)

{

/*检测是否有按键按下*/

if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin_x)==KEY_ON)

{

/*延时消抖延时大约5ms*/

delay_ms(5);

if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin_x)==KEY_ON)

{

while(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin_x)==KEY_ON);/*等待按键释放*/

returnKEY_ON;

}

else

{

returnKEY_OFF;

}

}

returnKEY_OFF;

}

voiddelay_ms(u16time)

{

u16i=0;

while(time--)

{

i=12000;

while(i--);

}

}


本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭