GPIO Module

Note

The GPIO Module contains wrappers for reading and writing pin states.
Doxygen:

Features

Defining a pin

Before being able to read or write a pin, first a pin handle needs to be defined. These pin handles can be used with all other functions in this module now

// Define a handle for GPIO Pin PA1
GPIO_Handle_t myPin = { GPIOA, 1 };

Often pins are low-active as well. This can be specified easily with the last parameter of the pin handle. This will cause values to automatically be inverted before writing and after reading.

// Define a handle for the low active GPIO Pin PB2
GPIO_Handle_t myLowActivePin = { GPIOB, 2, true };

Initializing a pin

Some pins have been preconfigured through the STM32CubeIDE but not all.

The following example initializes a pin to be a high speed, open drain output with a pull-up resistor.

GPIO_Init(myPin);

GPIO_SetSpeed(myPin, GPIO_SPEED_HIGH);
GPIO_SetPullResistor(myPin, GPIO_PULLUP);
GPIO_SetMode(myPin, GPIO_MODE_OUTPUT_OD);
result_t GPIO_Init()

Initializes the GPIO Hardware.

Returns

Status result

void GPIO_SetSpeed(GPIO_Handle_t handle, GPIO_Speed_t speed)

Sets the output speed of a GPIO pin.

Warning

Higher values mean higher current flowing. This can lead to reflections or hardware damage

Parameters
  • handle – GPIO Handle

  • speed – GPIO Speed

void GPIO_SetPullResistor(GPIO_Handle_t handle, GPIO_PullResistor_t pull_resistor)

Enables or disables a pull-resistor for a GPIO pin.

Parameters
  • handle – GPIO Handle

  • pull_resistor – Pull Resistor to use

void GPIO_SetMode(GPIO_Handle_t handle, GPIO_Mode_t mode)

Sets the mode of the GPIO pin.

Parameters
  • handle – GPIO Handle

  • mode – Mode of the GPIO pin (open drain, push-pull, etc)

Write a value to a pin

To set the value of a pin, first make sure it’s configured as an output using GPIO_SetMode(). Then it can be directly written to using the following code:

GPIO_SetValue(myPin, true); // Set pin to HIGH

// Other code

GPIO_SetValue(myPin, false); // Set pin to LOW

The pin can also be toggled using the following code:

GPIO_ToggleValue(myPin); // Sets pin to HIGH if it was LOW or to LOW if it was HIGH
void GPIO_SetValue(GPIO_Handle_t handle, bool state)

Sets the value of a GPIO pin.

Parameters
  • handle – GPIO Handle

  • New – state of GPIO pin

void GPIO_ToggleValue(GPIO_Handle_t handle)

Toggles the state of a GPIO pin.

Parameters

handle – GPIO Handle

Read a value from a pin

To get the value of a pin, first make sure it’s configured as an input using GPIO_SetMode(). Then it can be directly read from using the following code:

bool state = GPIO_GetValue(myPin);

if (state) {
    // Pin is HIGH
} else {
    // Pin is LOW
}
bool GPIO_GetValue(GPIO_Handle_t handle)

Gets the value of a GPIO pin.

Parameters

handle – GPIO Handle

Returns

State of GPIO pin