LED.c
#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 LED1_Turn(void)
{
//如果低电平就变高电平,高电平就变低电平
if(GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_1)==0)
{
GPIO_SetBits(GPIOA, GPIO_Pin_1);
}
else
{
GPIO_ResetBits(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 LED2_Turn(void)
{
//如果低电平就变高电平,高电平就变低电平
if(GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_2)==0)
{
GPIO_SetBits(GPIOA, GPIO_Pin_2);
}
else
{
GPIO_ResetBits(GPIOA, GPIO_Pin_2);
}
}
Key.c
#include "stm32f10x.h" // Device header
#include "Delay.h"
//初始化按键
void KeyInit(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(void)
{
uint8_t KeyNum = 0;
//如果按键按下
if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)==0)
{
//按键刚按下会有个抖动,所有需要Delay一段时间
Delay_ms(20);
//如果按键一直按下,就会卡在这里直到松手
while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)==0);
Delay_ms(20);
KeyNum= 1;
}
if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11)==0)
{
//按键刚按下会有个抖动,所有需要Delay一段时间
Delay_ms(20);
//如果按键一直按下,就会卡在这里直到松手
while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)==0);
Delay_ms(20);
KeyNum= 2;
}
return KeyNum;
}
main.c
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "LED.h"
#include "Key.h"
//定义一个全局变量用来存一下键码的返回值
uint8_t KeyNum;
int main()
{
//初始化灯和按键
LED_Init();
KeyInit();
while(1)
{
KeyNum = Key_GetNum();
if(KeyNum == 1)
{
//LED1_ON();
LED1_Turn();
}
if(KeyNum == 2)
{
//LED1_OFF();
LED2_Turn();
}
}
}