«

»

Août 26

Robotics 101 : PWM (2)

Using a PWM

You now know how to configure a PWM, great ! Now let’s see how to use it.

Sample code :

Code overview :

The first part of the code configures the pwm; as we have seen in the last tutorial.

palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(2));

Each pad can be used in many other ways than a simple GPIO: these other ways are called ALTERNATE modes. Here we select the third ALTERNATE mode of PC6. You can find what are the alternate functions of every pin in the datasheet of the stm32f407 as follows:
alternate functions

pwmStart(&PWMD3, &pwmcfg);

This line starts the PWM, it links the the PWMConfig to a PWMDriver. A PWMDriver is an Abstraction that allows you to control a PWM (actually it is rather complex and is out of the reach of this course for now). All you need to know is that there are PWMDrivers for timers 2 to 5, you can only use one PWMDriver by Timer (using 4 different frequencies on a single timer won’t work) and that in order to control the output of the timer i you have to link your PWMConfig to the pointer to PWMDi.
The pwmStart function takes as parameters a pointer to a PWMDriver and a pointer to a PWMConfig (in order to know how to use the timer linked to the driver).

You may have to activate the Timer (by default they may not be powered in order to save energy), to do so open the file mcuconf.h in your project folder and write TRUE as follows :

#define STM32_PWM_USE_TIM3 TRUE /* Here the 3rd Timer is activated, didn't want to use it we would have written FALSE*/
(don’t worry we will cover how to properly mess with this file in a next course)

That’s it, your PWM is ready to use !
Note that by default the signal is high half of the period.

Now let’s select the width of the signal:

pwmEnableChannel(&PWMD3, 0, i); // the first channel PWM of the timer 3 is HIGH for i ticks

This tells the driver to set the output of the 1st channel of the 3rd Timer to HIGH for i ticks (at the period defined in the PWMConfig).
pwmEnableChannel takes three inputs: a pointer to the PWMDriver, the channel of the Timer (indexes start at 0, so 2 corresponds to the 3rd channel etc…) and the number of ticks to set the output HIGH.
Note that each channel can have a different width (but they must have the same period and timer frequency).

In this example you managed to control the brightness of the LED (if you plugged a LED on PC6 as in the Robotics 101 : Basic GPIOs course, as i mentioned in the first part of the PWM tutorial.

And you’re done, it’s that simple : you now know how to use a PWM with chibiOS.

In a next course we will see how to use it to drive a motor (as soon as i receive my H-Bridge order).
But next we will see how to use the serial driver in order to communicate with your computer (bear with me, it can also be used to control a pretty neat servo motor called the ax12 which is our favorite in the club)

Felix.