STM32 bit bang PWM
Jump to navigation
Jump to search
On many of the cheaper STM32 Development Boards there is a LED attached to PC13. This is perfectly ok if you want to switch it on or off, but PC13 is not attached to any of the timer channels, so it will not be possible to control the brightness using PWM.
Fortunately, while not ideal, it is possible to bitbang the PWM in a manner which doesn't require too much computation. Contrary to PWM using a Timer channel, it does require some computation in the MCU.
Bit-banding
#define BITBAND_BIT_ADDR(src_byte_addr, bit) (((((uint32_t)(src_byte_addr) & 0x000fffff) << 5) | ((uint32_t)(src_byte_addr) & 0xfff00000) | 0x02000000) + (((uint32_t)(bit)) << 2))
Code
Timer Settings
Firstly configure some timer (we use TIM10 here):
We also need to enable the global timer 10 interrupt:
Implementation
We use bitbanding to address the bit used for GPIO:
// The led_bb_bit points to the bitband address for controlling the PC13 uint8_t *led_bb_bit = (uint8_t*) BITBAND_BIT_ADDR(&LED_GPIO_Port->ODR, 13);
Result
Miscellaneous Links
- ]https://github.com/STM32World/firmware/tree/master/mcustm32f405_bitbang_pwm Stm32World STM32F405 Example]
- Blackpill STM32F411 Example