STM32中gpio_readoutputdatabit和gpio_readinputdatabit函数的区别解析
很多人都只是知道gpio_readoutputdatabit和gpio_readinputdatabit都是读取IO的高低电平。下面是大部分对两者的解释,输入电平和输出电平到底怎么区分。
GPIO_ReadInputDataBit函数用于读取指定GPIO管脚上的输入电平,返回值为指定管脚的电平状态(1或0)。
GPIO_ReadInputData函数用于读取整个GPIO端口的输入电平,返回值为整个端口上每个引脚的状态。
GPIO_ReadOutputDataBit函数用于读取指定GPIO管脚上的输出电平,返回值为指定管脚的电平状态(1或0)。
GPIO_ReadOutputData函数用于读取整个GPIO端口的输出电平,返回值为整个端口上每个引脚的状态。
举一个例子,光敏传感器的高低电平变化使LED灯熄灭或者点亮。首先在光敏传感器模块中设置为上拉输入,使光敏传感器的电平为1,在主函数模块中会读取光敏传感器的端口电平。如果光敏传感器读取的为1,使得LED1熄灭(白话说就是光敏传感器没有变化的情况下)。对于光敏传感器读取的使用是GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_13),ReadInputDataBit在while循环中不断读取的是光敏传感器的电平,也就是不断读取外设装置的电平状态。
ReadOutputDataBit,是在读取单片机在端口为所连接的小灯时,单片机给小灯的电平。比如蜂鸣器模块中,使用的是ReadOutputDataBit,如果读取到单片机给蜂鸣器低电平使其工作,那么就会使蜂鸣器关闭。
总的来说,ReadInputDataBit就是不断读取外设装置的状态,而ReadOutputDataBit在读取单片机给某个外设的状态。
光敏传感器模块程序。
#include "stm32f10x.h" // Device header
void lightsensor_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPD;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_13;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
}
uint8_t lightsensor_Get(void)
{
return GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_13);
}
LED点亮/熄灭模块。
#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_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA,&使用的是地址传递
GPIO_SetBits(GPIOA,GPIO_Pin_1);
}
void LED1_ON(void)
{
GPIO_ResetBits(GPIOA,GPIO_Pin_1);
}
void LED1_OFF(void)
{
GPIO_SetBits(GPIOA,GPIO_Pin_1);
}
}
主函数模块。
#include "stm32f10x.h" // Device header
#include"lightsensor.h"
#include"led.h"
int main(void)
{
led_Init();
lightsensor_Init();
while(1)
{
if(lightsensor_Get()==1)//读取的光敏传感器电平为1
{
LED1_OFF();
}
else//当光敏传感器受到改变,电平转为0
{
LED1_ON();
}
}
}
蜂鸣器模块
#include "stm32f10x.h" // Device header
void buzzer_Init(void)//创建函数
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_12;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);//初始化GPIOA,&使用的是地址传递
GPIO_SetBits(GPIOB,GPIO_Pin_12);
}
void buzzer_ON(void)
{
GPIO_ResetBits(GPIOB,GPIO_Pin_12);
}
void buzzer_OFF(void)
{
GPIO_SetBits(GPIOB,GPIO_Pin_12);
}
void buzzer_Turn(void)
{
if(GPIO_ReadOutputDataBit(GPIOB,GPIO_Pin_12)==0)
{
GPIO_SetBits(GPIOB,GPIO_Pin_12);
}
else
{
GPIO_ResetBits(GPIOB,GPIO_Pin_12);
}
}
作者:月亮上吃干脆面