Lesson 8: Part 1: PWM - LED Brightness Control

Introduction

PWM - namely Pulse-width modulation, enable us to output digital signal that toggle between high(3.3V) and low(0V) state in desire frequency. A example of signal will be as below:
Example of PWM waveform


3 terms that is use in PWM are below:
  1. Period : the time require to complete a cycle of high state and low state.
  2. Frequency: Inverse of period.  The frequency of the PWM waveform.
  3. Duty cycle: A measurement of the ratio of high state as compare to a period of PWM. A 50% of duty cycle meaning half of the period is at high state with another half of period at low state. Example above have a 33% duty cycle.
By applying capacitor at PWM pin, we can 'smoothen' the PWM and use it as DAC. For example using it to control the brightness of the LED. Increase LED brightness by increase duty cycle and vice versa.

Another important usage of PWM is in servo motor control. 

Example Code

In STM32F030, the PWM is generate using one of the MCU timer.

In the coming example, we will be using Timer14 and enable the PWM waveform output at pin PB1. And by connecting the PB1 into on-board LED-LD3, we can observe the PWM effect without any equipment.

As on board LED is at pin PC9, we need to first pull up the PC9 pin, and then physically connect the pin from PC9 to PB1 as shown below:
Short Between PC9 (LED-LD3) and PB1 (PWM output)


You can retrieve the sample code at github here.


In pwm.c source, there is additional define namely: PWM_PB1_BLINK. This define is use to demonstrate a PWM waveform with different frequency, thus enabling the LED blink at different rate.

When enable PWM_PB1_BLINK, LD3 will be blinking at rate of 0.5seconds, due to PWM generated have period of 0.5seconds.

When disable PWM_PB1_BLINK, the brightness of the LD3 will be reduce slightly. This is because the PWM is running at 50% duty cycle, thus reducing the overall brightness. But no blinking is observe because the PWM waveform is running at 10millisconds (refer below for the capture waveform on scope), which is too fast for our eyes to perceive. One exercise is you can try is change the value of PWM_DUTY_CYCLE. When PWM_DUTY_CYCLE is reduce, the brightness will be reduce.
Disable define PWM_PB1_BLINK Generate PWM Of 10mS Period

SFR Configurations

Key configurations of SFR is describes as below:
  1. Enable Timer 14 block
  2. Setting of PWM duty cycle
  3. Settings of PWM period or frequency
  4. Configurations of Timer 14
  5. Configurations of GPIO-PB1
  6. Configurations of GPIO-PC9

No comments:

Post a Comment