cancel
Showing results for 
Search instead for 
Did you mean: 

how to blink 2 LEDs with a Timer?

Samuel1
Associate III

Hello everybody,

I wanted to turn 2 LEDs with Timer on / off. The period is 4s and the first LED should be on for 2s and off for 2s. and then the 2nd LED should do the same but not at the same time. But unfortunately I can not do that with a timer and only the the first LED PB14 flashes. I do not know how I can go from if and else if condition to the lower part of the function, although I stopped the timer. I call the function in Main loop.

can someone help please?

thanks

this is the funktion:

void led1(){

uint8_t x=1;

HAL_TIM_Base_Start(&htim3);

uint16_t Wert= __HAL_TIM_GetCounter(&htim3);

if(x==1){

if(Wert< 10968){

HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14,GPIO_PIN_RESET);

}

else if (Wert<=21972){

HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14,GPIO_PIN_SET);

HAL_TIM_Base_Stop(&htim3);

Wert=0;

}

}

if(x%2==0){

uint16_t Wert1=0;

HAL_TIM_Base_Start(&htim3);

Wert1= __HAL_TIM_GetCounter(&htim3);

if (Wert1< 10968){

HAL_GPIO_WritePin(GPIOB,GPIO_PIN_7,GPIO_PIN_RESET);

}

else if (Wert1>= 500&& Wert1<=21972){

HAL_GPIO_WritePin(GPIOB,GPIO_PIN_7,GPIO_PIN_SET);

}

HAL_TIM_Base_Stop(&htim3);

Wert1=0;

}

x++;

}

3 REPLIES 3

You're logic here is super confusing.

What STM32 part?

What is the maximal setting for the counter? What rate is it clocking?

The counter's not going to get anywhere if you keep stopping and starting it.

Consider using interrupts. Consider if you could count off milliseconds in the SysTick_Handler.

void SysTick_Handler(void)
{
  static int i = 0;
 
  if (i == 0)
    HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14,GPIO_PIN_SET);
  else if (i == 2000)
    HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14,GPIO_PIN_RESET);
  else if (i == 1000)
    HAL_GPIO_WritePin(GPIOB,GPIO_PIN_7,GPIO_PIN_SET);
  else if (i == 3000)
    HAL_GPIO_WritePin(GPIOB,GPIO_PIN_7,GPIO_PIN_RESET);
 
  i = (i + 1) % 4000; // looping every 4 seconds
 
  // ...
  //  Usual code
 
  HAL_IncTick();
}

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
S.Ma
Principal

If you want LEDs to blink in seconds period you don't need a timer. you could just use Systick (1msec timer) and create your LED periods from the systick 1msec interrupt using SW period counters.

the period is 21972.taktfre 180 Mhz. prescaler = 32,768th With this logic I wanted to actually to build a signal with variable width. That's why I'm brewing a timer. PWM woudnt help here.