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());
}