Pull-up and pull-down resistors help set a clear default voltage level on a microcontroller pin to avoid random signals.
Pull-up and pull-down resistor configuration in Embedded C
GPIO_InitTypeDef GPIO_InitStruct = {0};
// For pull-up resistor
GPIO_InitStruct.Pin = GPIO_PIN_X;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIO_PORT_X, &GPIO_InitStruct);
// For pull-down resistor
GPIO_InitStruct.Pull = GPIO_PULLDOWN;
HAL_GPIO_Init(GPIO_PORT_X, &GPIO_InitStruct);GPIO_PULLUP sets the pin to HIGH by default through the resistor.
GPIO_PULLDOWN sets the pin to LOW by default through the resistor.
// Configure pin PA0 with pull-up resistor GPIO_InitTypeDef GPIO_InitStruct = {0}; GPIO_InitStruct.Pin = GPIO_PIN_0; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
// Configure pin PB1 with pull-down resistor
GPIO_InitStruct.Pin = GPIO_PIN_1;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLDOWN;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);This program sets up pin PA0 with a pull-up resistor and reads its state. Without pressing a button or connecting the pin to ground, it will read HIGH (1).
#include "stm32f1xx_hal.h" int main(void) { HAL_Init(); __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitTypeDef GPIO_InitStruct = {0}; // Configure PA0 as input with pull-up resistor GPIO_InitStruct.Pin = GPIO_PIN_0; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); // Read the pin state int pin_state = HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0); // Normally prints 1 because of pull-up resistor if (pin_state == GPIO_PIN_SET) { // Simulate output // printf("Pin PA0 reads HIGH\n"); } else { // printf("Pin PA0 reads LOW\n"); } while(1) {} }
Pull-up and pull-down resistors prevent pins from floating, which means they avoid random noise signals.
Many microcontrollers have built-in pull-up and pull-down resistors you can enable in software.
Always check your hardware datasheet to know if internal resistors are available or if you need external ones.
Pull-up resistors make a pin read HIGH by default.
Pull-down resistors make a pin read LOW by default.
They help keep input pins stable and avoid random signals.