STM32 IO 读取

1.硬件原理图

2.代码

cpp 复制代码
#include "stm32f10x.h"

/* ---------- SW5 8 位拨码开关 ----------
 * 硬件:一端接 GND,另一端经 RN1(10k) 上拉到 3.3V
 * 逻辑:闭合(ON)=0,断开(OFF)=1
 * 位序:bit0 = SW5-1 ... bit7 = SW5-8
 */

typedef struct {
    GPIO_TypeDef *port;
    uint16_t      pin;
} sw_pin_t;

static const sw_pin_t SW5_PIN[8] = {
    { GPIOB, GPIO_Pin_7  },   /* SW5-1 */
    { GPIOB, GPIO_Pin_6  },   /* SW5-2 */
    { GPIOA, GPIO_Pin_12 },   /* SW5-3 */
    { GPIOC, GPIO_Pin_13 },   /* SW5-4 */
    { GPIOA, GPIO_Pin_4  },   /* SW5-5 */
    { GPIOA, GPIO_Pin_5  },   /* SW5-6 */
    { GPIOA, GPIO_Pin_6  },   /* SW5-7 */
    { GPIOA, GPIO_Pin_7  },   /* SW5-8 */
};

void SW5_Init(void)
{
    GPIO_InitTypeDef gpio;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA |
                           RCC_APB2Periph_GPIOB |
                           RCC_APB2Periph_GPIOC, ENABLE);

    gpio.GPIO_Speed = GPIO_Speed_50MHz;
    gpio.GPIO_Mode  = GPIO_Mode_IPU;

    gpio.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 |
                    GPIO_Pin_7 | GPIO_Pin_12;
    GPIO_Init(GPIOA, &gpio);

    gpio.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
    GPIO_Init(GPIOB, &gpio);

    gpio.GPIO_Pin = GPIO_Pin_13;
    GPIO_Init(GPIOC, &gpio);
}

/* 读取一次,返回原始电平(OFF=1,ON=0) */
uint8_t SW5_ReadRaw(void)
{
    uint8_t v = 0, i;

    for (i = 0; i < 8; i++) {
        if (GPIO_ReadInputDataBit(SW5_PIN[i].port, SW5_PIN[i].pin))
            v |= (uint8_t)(1u << i);
    }
    return v;
}

/* 读取开关编号(ON=1,符合人的直觉),可直接当地址/ID 用 */
uint8_t SW5_ReadCode(void)
{
    return (uint8_t)(~SW5_ReadRaw());
}
相关推荐
luoshanxuli201022 分钟前
STM32 智能微光高效采集移动电源
stm32·单片机·嵌入式硬件
鼎芯电子集成电路1 小时前
鼎芯SN74LVC1G17DCKR:单路施密特缓冲器信号调理设计参考
单片机·嵌入式硬件·国产替代·国产芯片·鼎芯·sn74lvc1g17dckr
红龙创客2 小时前
轻AI越影视觉开发板GUI教程:从开箱上手到修改显示界面
嵌入式硬件·嵌入式·海思
听情歌落俗2 小时前
嵌入式学习2-STM32HAL库
单片机·嵌入式硬件
Brilliantwxx2 小时前
【STM32 外设篇】 LCD 显示(1):从显示屏分类到 ILI9341 与 GRAM
stm32·单片机·嵌入式硬件
jianqiang.xue3 小时前
GCC 15 还是 ST-ARM-Clang:STM32 的 VS Code 工具链怎么定
c语言·arm开发·stm32·嵌入式硬件·嵌入式·ai编程·代码审查
LabVIEW开发4 小时前
INA219 读毫安级电流,LabVIEW 里没有现成库:自己封一个 SubVI
单片机·嵌入式硬件·labview
新晨单片机设计4 小时前
S012B-基于STM32单片机紫外线检测系统
stm32·单片机·嵌入式硬件·紫外线检测
送外卖的工程师14 小时前
STM32智能窗帘窗户控制系统
stm32·单片机·嵌入式硬件