Change the brightness level of a STM32 GPIO LED

136 Views Asked by At

I am using a STM32 NUCLEO-L432KC Microcontroller.

Here is what I want to program:

My LED shall have three LED brightness levels: 100, 50 and 10%

Once the Microcontroller is powered up, the light shall shine with 100%. One click of a button and the brightness level decreases.

Additionally, I can turn on and turn off the LED while holding the button 3 seconds whenever I want.

My problem is, however, that I do not know how to dim my LED / brightness level.

Note: I only know how to use GPIO commands. I have heard of timers, but I want to first learn to change the brightness level using only GPIO / Basic c commands.

Here is what I have so far:

/* USER CODE BEGIN PV */
int button = 0;
/* USER CODE END PV */

while(1) {

// Read the status of the GPIO button pin
button = HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_3);

// If the button is pressed
          if(!button)
          {
              HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_8); // Toggles the state of the GPIO LED pin
              HAL_Delay(500);
          }
}
2

There are 2 best solutions below

6
Guillius On

What you need is some form of PWM (pulse width modulation). Typically, that is done at the low-level using timers. Sometimes, there are library functions you can use that provide a more high-level interface to a PWM output.

0
matiko122 On

Normally this kind of operation is achivied by usage of PWM signal which will be switching LED so quickly that it will appears dimmer. Signal like that can be generated by timer peripherals on-board your MCU (here is an example article about it: https://controllerstech.com/pwm-in-stm32/ . It's not specifically for this MCU but if you will use the graphical configurator it should be fairly similar. Also it contains some theory about it so it so that you can understand what it is). Alternatively you can, with the knowledge of what is the clock on that MCU, create a very crude PWM signal on that GPIO output by using delays.