Skip to main content
Ala
Senior
January 17, 2022
Question

Control LED light

  • January 17, 2022
  • 5 replies
  • 2648 views

hey there

I have a project where I need to control light of a LED and dim it. usually we use TIMER PWM GENERATION. for example in CubeMX I set a pin to TIMx CHy and by choosing "PWM Generating CHy" I can easily control LED light using PWM signal.

but in my case this LED pin has no TIM Channel connected to it. what should I do to dim the LED?

This topic has been closed for replies.

5 replies

Ahmet Yasin CİVAN
Associate III
January 17, 2022

You can use GPIO with delay loops.

Ala
AlaAuthor
Senior
January 17, 2022

sure! but this occupies CPU and also is not efficient.

is there a way to generate an internal PWM signal and control LED with it?

Nikita91
Lead II
January 17, 2022

Set a timer as timebase at 1000Hz, and in the ISR toggle the LED GPIO.

This will generate your "PWM"

You should be able to manage about 16 light levels

Ala
AlaAuthor
Senior
January 17, 2022

this one sounds great! but it affects the entire process, as ISR happens fast, though I might end up doing such...

Nikita91
Lead II
January 17, 2022

You can set the timer to 500Hz, and the ISR is quite short.

Javier1
Principal
January 17, 2022

So you need to implement a softpwm.

There is three ways:(that i can think of now)

  • software bitbang (toglegpio;delay;togglegpio),Process intensive, not scalable, huge jitters.
  • interrupt based bitbang (as @Nikita91​ )said , less process intensive, jitter depends of the interrupt priority.
  • DMA based GPIO bitbang, lesser processor intensive, very scalable, a bit more complex and memory hungry.

If your system can spare those interrution times i would choose the second option.

I had to implement a bunch of pins at the same time and my system couldnt spare lots of processing time so i had to do the third option

https://www.hackster.io/javier-munoz-saez/all-pins-as-pwm-at-the-same-time-baremetal-stm32-1df86f

hit me up in https://www.linkedin.com/in/javiermuñoz/
Javier1
Principal
January 17, 2022

You could also use the DAC if that function is available in your pin (overkill)

hit me up in https://www.linkedin.com/in/javiermuñoz/
gbm
Lead III
January 17, 2022

You may use 2 channel DMA to GPIO BSRR triggered by timer update and compare; set on update, reset on compare. The only quirk is to prevent outputting active level at timer update when duty is equal to 0.

My STM32 stuff on github - compact USB device stack and more: https://github.com/gbm-ii/gbmUSBdevice