3-4STM32C8T6按键控制LED开与关

实物接线如下:


为了代码的简洁性,这里需要对LED与KEY进行封装如下:

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()
{
   GPIO_ResetBits(GPIOA,GPIO_Pin_1);
}
void LED1_OFF()
{
  GPIO_SetBits(GPIOA,GPIO_Pin_1);
}
void LED1_Turn()
{
  if(GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_1)==0)
   GPIO_SetBits(GPIOA,GPIO_Pin_1);   
  else
   GPIO_ResetBits(GPIOA,GPIO_Pin_1);
}
void LED2_ON()
{
GPIO_ResetBits(GPIOA,GPIO_Pin_2);
}

void LED2_OFF()
{
  GPIO_SetBits(GPIOA,GPIO_Pin_2);
}
void LED2_Turn()
{
  if(GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_2)==0)
   GPIO_SetBits(GPIOA,GPIO_Pin_2);   
  else
   GPIO_ResetBits(GPIOA,GPIO_Pin_2);
}
c 复制代码
#ifndef __LED_H
#define __LED_H
void LED_Init(void);
void LED1_ON(void);
void LED1_OFF(void);
void LED2_ON(void);
void LED2_OFF(void);
void LED1_Turn(void);
void LED2_Turn(void);

#endif
c 复制代码
#include "stm32f10x.h"                  // Device header
#include "delay.h"
void Key_Init()
{
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
  GPIO_InitTypeDef GPIO_Structure;
  GPIO_Structure.GPIO_Mode=GPIO_Mode_IPU;
  GPIO_Structure.GPIO_Pin=GPIO_Pin_1 | GPIO_Pin_11;
  GPIO_Structure.GPIO_Speed=GPIO_Speed_50MHz; 
  GPIO_Init(GPIOB,&GPIO_Structure);    
}
uint8_t Key_GetNum()
{
  
  uint8_t  KeyNum=0;
   if( GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1)==0)
   {
        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_ms(20);
        while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_11)==0);
        Delay_ms(20);
       KeyNum=2;
   }
    
    return KeyNum;

}
c 复制代码
#ifndef __KEY_H
#define __KEY_H
void Key_Init(void);
uint8_t Key_GetNum(void);

#endif
c 复制代码
#include "stm32f10x.h"                  // Device header
#include "delay.h"
#include "LED.h"
#include "Key.h"
uint8_t KeyNum;
int main(void)
{
  LED_Init(); 
  Key_Init();
  while(1)
  {
      KeyNum=Key_GetNum();
      if(KeyNum==1)
      {
       LED1_Turn();
      }
         if(KeyNum==2)
      {
       LED2_Turn();
      }
  }
}
相关推荐
weixin_11223310 小时前
基于STM32闭环步进电机控制系统设计说明
stm32·单片机·嵌入式硬件
机器视觉知识推荐、就业指导11 小时前
STC89C52系列单片机简介
单片机·嵌入式硬件·51单片机
qq_259297247312 小时前
STM32
嵌入式硬件
qq_21513832713 小时前
【51单片机-B020】【protues仿真】基于51单片机智能晾衣架仿真
单片机·嵌入式硬件
小猪写代码13 小时前
STM32 GPIO的八种工作模式
stm32·单片机·嵌入式硬件·gpio
1+2单片机电子设计14 小时前
STM32 单片机的停车场管理系统设计与实现
stm32·单片机·嵌入式硬件·51单片机
如愿小李14 小时前
STM32之土壤湿度传感器模块
stm32·单片机·嵌入式硬件
weixin_5803820615 小时前
UART Hal库与寄存器比较
stm32·单片机·嵌入式硬件
景彡先生17 小时前
STM32以太网开发详解:基于LwIP协议栈实现TCP/UDP通信(附网络摄像头案例)
网络·stm32·tcp/ip