如果觉得不错就点个赞吧~
目录
一 元件相关
需要准备元件:32板,杜邦线,跳线,几个LED灯,几个电阻,ST-Link,面包板,四角独立按键
二 面包板上的连线
32和Link,的连接我写在了另一篇中,需要的同学可以自己去看[stm32] Start Tour-LED灯闪烁
以下是四角独立按键的连线图,注意看独立按键底下有两条平行铁片
三 具体代码
代码我分模块进行编写:
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_0|GPIO_Pin_1;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_SetBits(GPIOA,GPIO_Pin_0|GPIO_Pin_1);//初始LED不亮
}
void LED_Off()//关闭LED
{
GPIO_SetBits(GPIOA,GPIO_Pin_0|GPIO_Pin_1);//输出低电平
}
void LED_On()//打开LED
{
GPIO_ResetBits(GPIOA,GPIO_Pin_0|GPIO_Pin_1);//输出高电平
}
void LED_Turn(void)//LED取反
{
if(GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_0|GPIO_Pin_1)==0)//GPIO_ReadOutputDataBit函数,可实现要求LED取反
{ //该函数在_gpio.h中第355行
GPIO_SetBits(GPIOA,GPIO_Pin_0|GPIO_Pin_1);
}
else
{
GPIO_ResetBits(GPIOA,GPIO_Pin_0|GPIO_Pin_1);
}
}
Key.c
#include "stm32f10x.h" // Device header
#include "Delay.h"
void Key_Init(void)//按键初始化,跟LED初始化一样的结构
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//打开时钟,我这里定义跟LED一样是GPIOA
GPIO_InitTypeDef GPIO_InitStructure;//结构体定义,GPIO_InitStructure为随便起的名字
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;//上拉输入
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_2;//PA2
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
}
//读取按键值
unsigned char Key_GetNum(void)
{
unsigned char KeyNum=0;
//按键是否按下判断
if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_2)==0)//GPIO_ReadInputDataBit函数
{ //该函数在_gpio.h中第353行
Delay_ms(20);
while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_2)==0);
Delay_ms(20);
KeyNum=1;
}
return KeyNum;
}
main.c
#include "stm32f10x.h"
#include "Delay.h"
#include "LED.h"
#include "Key.h"
unsigned char KeyNum;
int main(void)
{
LED_Init();
Key_Init();
while(1)
{
KeyNum=Key_GetNum();
if(KeyNum==1)//按键按下
{
LED_Turn();
}
}
}
四 实现效果
按一下亮,按一下暗,一开始灯不亮