STM32单片机使用GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15这八个引脚对拨码开关程序用HAL库写
时间: 2023-07-08 11:29:16 浏览: 120
好的,以下是使用HAL库编写的拨码开关程序:
#include "main.h"
#include "stm32f1xx_hal.h"
/* 定义GPIO引脚 */
#define SW1_Pin GPIO_PIN_0
#define SW2_Pin GPIO_PIN_1
#define SW3_Pin GPIO_PIN_5
#define SW4_Pin GPIO_PIN_6
#define SW5_Pin GPIO_PIN_7
#define SW6_Pin GPIO_PIN_13
#define SW7_Pin GPIO_PIN_14
#define SW8_Pin GPIO_PIN_15
/* 定义GPIO端口 */
#define SW1_GPIO_Port GPIOA
#define SW2_GPIO_Port GPIOA
#define SW3_GPIO_Port GPIOA
#define SW4_GPIO_Port GPIOA
#define SW5_GPIO_Port GPIOA
#define SW6_GPIO_Port GPIOB
#define SW7_GPIO_Port GPIOB
#define SW8_GPIO_Port GPIOB
/* 定义拨码开关读取函数 */
uint8_t Read_Dip_Switch(void)
{
uint8_t dip_switch_value = 0;
/* 读取GPIO引脚状态 */
if(HAL_GPIO_ReadPin(SW1_GPIO_Port, SW1_Pin) == GPIO_PIN_SET)
{
dip_switch_value |= 0x01;
}
if(HAL_GPIO_ReadPin(SW2_GPIO_Port, SW2_Pin) == GPIO_PIN_SET)
{
dip_switch_value |= 0x02;
}
if(HAL_GPIO_ReadPin(SW3_GPIO_Port, SW3_Pin) == GPIO_PIN_SET)
{
dip_switch_value |= 0x04;
}
if(HAL_GPIO_ReadPin(SW4_GPIO_Port, SW4_Pin) == GPIO_PIN_SET)
{
dip_switch_value |= 0x08;
}
if(HAL_GPIO_ReadPin(SW5_GPIO_Port, SW5_Pin) == GPIO_PIN_SET)
{
dip_switch_value |= 0x10;
}
if(HAL_GPIO_ReadPin(SW6_GPIO_Port, SW6_Pin) == GPIO_PIN_SET)
{
dip_switch_value |= 0x20;
}
if(HAL_GPIO_ReadPin(SW7_GPIO_Port, SW7_Pin) == GPIO_PIN_SET)
{
dip_switch_value |= 0x40;
}
if(HAL_GPIO_ReadPin(SW8_GPIO_Port, SW8_Pin) == GPIO_PIN_SET)
{
dip_switch_value |= 0x80;
}
return dip_switch_value; /* 返回读取的拨码开关值 */
}
int main(void)
{
HAL_Init(); /* 初始化HAL库 */
__HAL_RCC_GPIOA_CLK_ENABLE(); /* 使能GPIOA时钟 */
__HAL_RCC_GPIOB_CLK_ENABLE(); /* 使能GPIOB时钟 */
while(1)
{
uint8_t dip_switch_value = Read_Dip_Switch(); /* 读取拨码开关值 */
/* 在这里可以根据拨码开关的值执行相应的操作 */
}
}
在上述代码中,我们先定义了8个GPIO引脚和对应的GPIO端口,这里使用了STM32 HAL库中的宏定义。然后我们编写了一个名为Read_Dip_Switch
的函数,用于读取8个拨码开关的值,并将拨码开关值以一个字节的形式返回。
在main
函数中,我们通过循环不断读取拨码开关的值,并可以根据拨码开关的值执行相应的操作。需要注意的是,在使用GPIO之前,需要先使能对应GPIO端口的时钟。
相关推荐



















