Read four adjacent pins as a single port
The HAL library does not have a function to read an entire port, therefore we need to read one at a time and then accommodate each pin read in its respective bit using a variable
#include "bsp.h"
int main( void )
{
GPIO_InitTypeDef GPIO_InitStruct; /*gpios initial structure*/
uint32_t Port;
HAL_Init(); /*Init HAL library*/
__HAL_RCC_GPIOB_CLK_ENABLE(); /*Enable clock on port B*/
GPIO_InitStruct.Pin = 0x0F; /*pins B0 - B3 to set as input*/
GPIO_InitStruct.Mode = GPIO_MODE_INPUT; /*input mode*/
GPIO_InitStruct.Pull = GPIO_NOPULL; /*no pull-up niether pull-down*/
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; /*pin speed*/
/*use the previous parameters to set configuration on pin B0 and B3*/
HAL_GPIO_Init( GPIOB, &GPIO_InitStruct );
while(1)
{
/*Read the pin B0*/
Port = HAL_GPIO_ReadPin( GPIOB, GPIO_PIN_0 );
/*Read the pin B1 shift to the left by 1 and or with the previous value in Port variable*/
Port |= ( HAL_GPIO_ReadPin( GPIOB, GPIO_PIN_1 ) << 1u );
/*Read the pin B1 shift to the left by 2 and or with the previous value in Port variable*/
Port |= ( HAL_GPIO_ReadPin( GPIOB, GPIO_PIN_2 ) << 2u );
/*Read the pin B1 shift to the left by 3 and or with the previous value in Port variable*/
Port |= ( HAL_GPIO_ReadPin( GPIOB, GPIO_PIN_3 ) << 3u );
/*reads the four pins as a single port of fourt bits*/
if( Port == SOME_VALUE )
{
/*the pin B0 to B3 as a port is equal to SOME_VALUE, do something*/
}
/*this is just a simple delay to avoid polling the pin to often*/
HAL_Delay( 50 );
}
}