Search Microcontrollers

Showing posts with label PWM. Show all posts
Showing posts with label PWM. Show all posts

Sunday, March 2, 2014

Stellaris Launchpad - PWM Library

I played a bit with PWM, which I actually need to drive a laser diode (2.4W 808nm) at the moment (will dig into this probably more in future posts).
Once you get the basics PWM is not difficult with the LM4F, however I found way easier for my application to create a minimalist library to deal with PWM signals, each time I look at it I keep repeating to myself that it could be better... but the way it is now already fits my needs (and maybe yours, but feel free to improve it and let me know :) ).

One thing I wanted was to have a simple interface that would allow me to play with multiple PWM generators at the same time, 8 seemed a fair amount, so I pre-allocated an array of 8, but it is fairly easy to expand the array.
Meh, some range checking would help maybe, but the Stellaris does not run on MS Windows, so it does pretty much what you tell it to do, just be careful not to add more than 8 pwm or at least remember to expand the array and you should be fine.

That said, each pwm generator is actually coming from a timer, we can use 16 bit or 32 bit timers and I figured that a 16 bit timer would do (did not try yet, but I think I found how to use it in 32 bit mode).
Still I did not implement pre-scaling which could be beneficial if you have to run with very low frequencies (<2Hz).

Here's  the library (don' t expect anything fancy, it's  just easy to use and actually works)


#include <inc/hw_memmap.h>
#include <inc/hw_types.h>
#include <driverlib/gpio.h>
#include <driverlib/sysctl.h>
#include <driverlib/uart.h>
#include <inc/hw_timer.h>
#include <driverlib/timer.h>
#include <driverlib/pin_map.h>

int pwm_count = 0;
int pwmtimers[8][4];

/**
 * each timer can send the signal out to 2 different gpios
 * 0 means to set it to the lowest of the two 1 to the highest
 *
 * TIMER    PIN(gpio=0) PIN(1)
 * T0A         PB6 PF0
 * T0B PB7 PF1
 * T1A PB4     PF2
 * T1B          PB5     PF3
 * T2A          PB0     PF4
 * T2B          PB1     PB1
 * T3A          PB2     PB2
 * T3B          PB3     PB3
 *
 *
 *
 */
int addPWM(int pwm_timer,int subtimer, int gpio) {
pwmtimers[pwm_count][0] = pwm_timer;
pwmtimers[pwm_count][1] = subtimer;
if (gpio == 0) {
if ((int)subtimer == (int)TIMER_A) {
switch (pwm_timer) {
case TIMER0_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_6;
pwmtimers[pwm_count][3] = GPIO_PB6_T0CCP0;
break;
case TIMER1_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_4;
pwmtimers[pwm_count][3] = GPIO_PB4_T1CCP0;
break;
case TIMER2_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_0;
pwmtimers[pwm_count][3] = GPIO_PB0_T2CCP0;
break;
case TIMER3_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_2;
pwmtimers[pwm_count][3] = GPIO_PB2_T3CCP0;
break;
}
} else {
switch (pwm_timer) {
case TIMER0_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_7;
pwmtimers[pwm_count][3] = GPIO_PB7_T0CCP1;
break;
case TIMER1_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_5;
pwmtimers[pwm_count][3] = GPIO_PB5_T1CCP1;
break;
case TIMER2_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_1;
pwmtimers[pwm_count][3] = GPIO_PB1_T2CCP1;
break;
case TIMER3_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_3;
pwmtimers[pwm_count][3] = GPIO_PB3_T3CCP1;
break;
}
}
} else if (subtimer == TIMER_A) {
switch (pwm_timer) {
case TIMER0_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_0 | 0x100; // port F
pwmtimers[pwm_count][3] = GPIO_PF0_T0CCP0;
break;
case TIMER1_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_2 | 0x100;
pwmtimers[pwm_count][3] = GPIO_PF2_T1CCP0;
break;
case TIMER2_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_4 | 0x100;
pwmtimers[pwm_count][3] = GPIO_PF4_T2CCP0;
break;
case TIMER3_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_2;
pwmtimers[pwm_count][3] = GPIO_PB2_T3CCP0;
break;
}
} else { // timer B
switch (pwm_timer) {
case TIMER0_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_1 | 0x100;
pwmtimers[pwm_count][3] = GPIO_PF1_T0CCP1;
break;
case TIMER1_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_3 | 0x100;
pwmtimers[pwm_count][3] = GPIO_PF3_T1CCP1;
break;
case TIMER2_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_1;
pwmtimers[pwm_count][3] = GPIO_PB1_T2CCP1;
break;
case TIMER3_BASE:
pwmtimers[pwm_count][2] = GPIO_PIN_3;
pwmtimers[pwm_count][3] = GPIO_PB3_T3CCP1;
break;
}
}
return pwm_count++;
}

/**
 *
 */
void pwmStop(int pidx) {
TimerDisable(pwmtimers[pidx][0], pwmtimers[pidx][1]);       
 //enables timerx_y
}

/**
 *
 */
void pwmStart(int pidx) {
TimerEnable(pwmtimers[pidx][0], pwmtimers[pidx][1]);        
//enables timerx_y
}

/**
 * Frequency in HZ and Duty cycle in %
 * example : pwm_setFreqDC(0,25000,0.3)  sets 25KHz with 30% duty cycle
 */
void pwmSetFreqDC(int idx, int freq,double dutyCycle) {
int period = (SysCtlClockGet() / freq);
int pidx = idx;
TimerLoadSet(pwmtimers[pidx][0], 
                     pwmtimers[pidx][1], period - 1); // sets pwm period
TimerMatchSet(pwmtimers[pidx][0], 
                     pwmtimers[pidx][1], period *dutyCycle); // sets duty cycle
}



/**
 *
 */
void pwmConfigure(int idx) {
int timerp = 0;
// ENABLE gpio port
int gpioPort;
volatile int pidx = idx;

if ((pwmtimers[pidx][2] & 0x100) > 0) { // pidx changes value here ????

SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
gpioPort = GPIO_PORTF_BASE;
} else {

SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
gpioPort = GPIO_PORTB_BASE;
}

// configure gpio pin
GPIOPinTypeGPIOOutput(gpioPort, pwmtimers[pidx][2] & 0xff);
GPIOPadConfigSet(gpioPort, // identifies the GPIO PORT
pwmtimers[pidx][2] & 0xff,  // identifies the pin within the GPIO Port
GPIO_STRENGTH_8MA_SC, // sets the strength to 8mA with Slew Rate control
GPIO_PIN_TYPE_STD);   // sets the pad control type to push-pull

// clear output pin
GPIOPinWrite(gpioPort, pwmtimers[pidx][2] & 0xff, 0);

// setup timer
switch (pwmtimers[pidx][0]) {
case TIMER0_BASE:
timerp = SYSCTL_PERIPH_TIMER0;
break;
case TIMER1_BASE:
timerp = SYSCTL_PERIPH_TIMER1;
break;
case TIMER2_BASE:
timerp = SYSCTL_PERIPH_TIMER2;
break;
case TIMER3_BASE:
timerp = SYSCTL_PERIPH_TIMER3;
break;
}
SysCtlPeripheralEnable(timerp);  // enables timer x

GPIOPinConfigure(pwmtimers[pidx][3]);  // port x pin y set to TIMERz_k output
    GPIOPinTypeTimer(gpioPort, pwmtimers[pidx][2] & 0xff); // port x pin y set to timer type output, does not bind

// configure Timer
if (pwmtimers[pidx][1] == TIMER_A)
TimerConfigure(pwmtimers[pidx][0],
(TIMER_CFG_SPLIT_PAIR | TIMER_CFG_A_PWM));
else
TimerConfigure(pwmtimers[pidx][0],
(TIMER_CFG_SPLIT_PAIR | TIMER_CFG_B_PWM));
// 16 bit timer TIMERx_y set to PWM mode
TimerControlLevel(pwmtimers[pidx][0], pwmtimers[pidx][1], 1); 
        // invert the signal for TIMERx_y
}

---------------------

The addPWM(timer, subtimer, gpio)  function allows you to select which timer you want to use.
To see which timers are available, you should use the lm4f datahseet or the summary table I placed at the beginning of the code, it should be quite easy to read.
For each timer/subtimer there are up to two output options in regard to the gpio pin to be used.
I sorted them alphabetically, so if for a timerxy you have options being PB2 and PF4 then PB2 would be 0 and PF4 1 in the gpio parameter of the function.
If the timer has one single configurable output, then both 0 and 1 would produce the same result.

This function just fills in the pwmtimers array, does not do anything with the hardware.
Say you call addPWM 3 times, the first one would be index 0 in the array, the second one index 1 and so on.
There is no functionality to remove an element from that array (did not see the point).

Once all the basic parameters are set (by addPWM) it is time to configure the needed hardware.
Relevant timer peripheral must be enabled, associated gpio port should be enabled too, the selected pin should be configured as output, set in timer mode and eventually pad-configured with high current push-pull with slew rate control.
The timer should be configured in split mode / pwm, also the pwm signal should be inverted (see previous article for a detailed explanation of these steps).
It is not difficult, but honestly i' d rather not code this process each time I need to use a pwm, so the pwmConfigure(idx) function takes care of ALL of it by fetching the needed values from the pwmtimers array.
Not really elegant maybe, but quite effective. 

The idea here is that once you specified what a pwm signal should be, the next operation should just refer to the array index, like configure idx 0, set frequency and duty cycle for idx 0 , start idx 0 etc.

So, next in line comes the pwmSetFreqDC( idx,  freq, dutyCycle) which allows us to set the frequency (you need to pass the number of hertz, like 25000  if you want 25KHz, no range checking is done, it' s  up to you to pass a possible value) and the duty cycle as a fraction (i.e. 0.3 if you want 30%).

The you can start your signal with pwmStart(idx)

Let's see an example that drives the R,G and B components of the onboard LED.

---------------------

 /*
 * Stellaris LAUNCHPAD LM4F120H5QR
 * --->  PART_LM4F120H5QR  <---
 */

#include <inc/hw_memmap.h>
#include <inc/hw_types.h>
#include <driverlib/gpio.h>
#include <driverlib/sysctl.h>
#include <driverlib/uart.h>
#include <inc/hw_timer.h>
#include <driverlib/timer.h>
#include <driverlib/pin_map.h>
#include <utils/uartstdio.c>


void setClock()
{
 SysCtlClockSet(  SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL 
             | SYSCTL_XTAL_16MHZ  | SYSCTL_OSC_MAIN);
}


int main(void) {
 setClock();

 // Add PWM timers to the library array

 addPWM(TIMER0_BASE,TIMER_B,1); //0
 addPWM(TIMER1_BASE,TIMER_A,1); //1
 addPWM(TIMER1_BASE,TIMER_B,1); //2

 // Configure Them
 pwmConfigure(0);
 pwmConfigure(1);
 pwmConfigure(2);

 // Set Frequency and duty cycle
 pwmSetFreqDC(0,25000,0.9);
 pwmSetFreqDC(1,25000,0.7);
 pwmSetFreqDC(2,25000,0.3);

 // Start the signal
 pwmStart(0);
 pwmStart(1);
 pwmStart(2);

 while (1) {
    // do nothing, forever... looks like my dream life :)
  }
}

--------------

When I was debugging it, I really stumbled against a stupid detail which I am going to tell you now, so you may avoid to think you are stupid and you should not deal with these things (because I did, at some point).

As you can see I am using all 3 components of the led, to debug my library I tried to use one , then two.
I tried to configure but not start them... but each time all 3 components were active.
I thought that the timers were starting as soon as they were configured, possibly with the frequency and DC I used before.
Why, if I did not start the green signal, the green component is there?
Turns out the answer is way easier than you' d think.
No, there is no green pwm signal, but the green light is on and the reason (my DSO confirmed it, I would have discovered this before if I was not too lazy to pull it out and probe the pins) is that the output is a steady HIGH.
Why?
I configured the pwm signals to be inverted, so when the timers are off, you should expect a steady high output, if this bothers you, then change it to not inverted in the TimerControlLevel call ( set to 0 the last parameter) and calculate the complementary value for the dutycycle in  pwmSetFreqDC simply using (1-dutyCycle).
I tried and it worked (my DSO confirmed it, I love that instrument!).

I hope this simple library can be useful for you, if you are using  another model of the lm4f, you might need to add some code to the addPWM function in order to consider the timers available in your device, the rest should probably be ok.

If you have improvements, I'd be glad to see them.
My next step will be to add UART or I2C control to drive the signals, again nothing fancy, but this is what I need :)

Happy coding!

Tuesday, February 18, 2014

Stellaris Launchpad - PWM

One thing being a bit confusing is that the Cortex M4F used in the Launchpad (LM4F120H5QR) DOES NOT have a PWM module.

[Note : the pwm module is present in the Tiva C version of the launchpad]

Does it mean you cannot generate HW controlled PWM signals?
Nope, you can and you can have quite some good control over them, still having the MCU regulating them in the background without the need of forcing GPIO pins up & down.

Some more advanced functionality is available only in those parts containing the dedicated PWM peripherals, but what really matters is that, when using the launchpad, we are actually using timers to generate PWM signals.

This is key, as an example when we set the function mode of the GPIO pin it is going to be

GPIOPinTypeTimer(GPIO_PORTF_BASE, GPIO_PIN_2) 

and not

GPIOPinTypePWM(GPIO_PORTF_BASE, GPIO_PIN_2)


The M4F has several 32 bit timers, that can be split into 2 x16 bit timers each.
According to the documentation PWM functionality should be available both in 32 bit and in 2x16 bit mode, however, I never managed to have it working in 32 bit mode.

Does it matter?
It actually does because the number of bits of the timer limits the number of cpu cycles that define the PWM period.
16 bit = 65.536 and if the cpu Frequency is set to 50MHz , the minimum frequency you could achieve with 16 bits is just  a bit less than 1KHz

P = 65536 * 1 / 50.000.000 = 0.00131072 s
F = 1 / 0.00131072 = 762.939453125 Hz

(Note : I verified these values with my oscilloscope by setting the period counter to 0xffff)

There is actually a solution since timers can be pre-scaled (a 16 bit timer can be pre-scaled with an 8 bit value -> the minimum frequency goes down to 763  / 256 = 2.98Hz)

However the precision with which you can set the duty cycle is still at 16 bit, but still it should be enough for most applications.

In general a 32 bit timer can be split into TIMER_A and TIMER_B each of them being 16 bits.
If you are using the full 32 bits for the same timer, then it will be only TIMER_A.

In my first experiment I used the blue component of the on-board LED to test the PWM signal, this is connected to PORT_F , PIN2.
If you check the M4F datasheet , in table 11-2 you can discover that PF2 (Port F , Pin 2) can be connected to T1CCP0 whcih actually means Timer 1 Capture Compare Pin 0

(@TI - Lmf4f120h5qr datasheet)

The previous table (11-1) shows that such pin is related to TIMER1 - TIMER_A

 
(@TI - Lmf4f120h5qr datasheet)

What all this means is that since we want to use GPIO_PF2, then we need to use TIMER1_TIMER_A

Now that we know all this, we can start to enable our GPIO port :
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);  
// enables LED GPIO Port

Set all 3 color components as outputs (we need this to turn the led completely off before starting)
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE,
GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3); 
// sets r,g,b as output

and turn the LED off

GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3, 0); 
// turns off the led

Since we are dealing with a LED, I configured the Pad control to output 8mA (you can set it at 2,4 and 8mA).
I am not sure this is really needed since setting the pin as timer output (which we will do later) might do that for us automatically... still, it doesn't  hurt.

GPIOPadConfigSet(GPIO_PORTF_BASE , // identifies the GPIO PORT
 GPIO_PIN_2, // identifies the pin within the GPIO Port
 GPIO_STRENGTH_8MA_SC, // sets the strength to 8mA with Slew Rate control
 GPIO_PIN_TYPE_STD);// sets the pad control type to push-pull

Time to enable our timer (note : enabling it does not mean we are also starting it).

SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER1);// enables timer 1 

Now we need to configure PF2 in its mux mode 7 which represents TIMER1_A output

GPIOPinConfigure(GPIO_PF2_T1CCP0);  
// port F pin 2 set to TIMER1_A output
Remember T1CCP0 we found before in the table?

Then we configure the output mode of the pin to be adequate for timer output (this is the part I am guessing overrides the Pad control configuration we did before)

GPIOPinTypeTimer(GPIO_PORTF_BASE, GPIO_PIN_2); 
// port F pin 2 set to timer type output, does not bind  it to any timer, the driverlib guide states :

This function cannot be used to turn any pin into a timer pin; it only configures a timer pin for proper operation. Devices with flexible pin muxing also require a GPIOPinConfigure() function call.

As stated before, I did not manage to have it working at 32 bits, the only configuration I was able to succesfully implement was with SPLIT_PAIR

TimerConfigure(TIMER1_BASE,        
   (TIMER_CFG_SPLIT_PAIR|TIMER_CFG_A_PWM)); 
// 16 bit timer TIMER1_A set to PWM mode

Ok, time to set the PWM parameters : Frequency (Period) and dutyCycle.

ulPeriod = SysCtlClockGet() / 10000; // 10KHz
dutyCycle = (unsigned long) (ulPeriod - 1) * 0.3 // 30% DC

Here, the interesting thing to notice is that the dutyCycle variable is in fact a value that the timer will compare with its counter, when it reaches it, it turns ON the signal and when it reaches the end of the period it resets the signal to zero.
What this means is that if you calculated your duty cycle variable as a percentage, say 30% of the total period, the signal will be 0 (OFF) from 0 to that value and 1 from that value up to the end of the period.
In fact setting the variable to 30% means you will have a 70% duty cycle, setting it at 80% means you will have a 20% DC.
You can work out the math easily to calculate the complementary value or you could simply invert the signal generated by the timer with this function call :

TimerControlLevel(TIMER1_BASE, TIMER_A, 1);  
// inverts the signal for TIMER1_A

And finally, we set period, duty cycle and fire up the timer

TimerLoadSet(TIMER1_BASE, TIMER_A, ulPeriod - 1); 
// sets pwm period
TimerMatchSet(TIMER1_BASE, TIMER_A, dutyCycle); 
// sets duty cycle
TimerEnable(TIMER1_BASE, TIMER_A);  
//starts timer1_a
while (1)
{
 // nothing to do here, pwm is active
}


You can see the full code here :
--------------------------------------------------------------/*
 * Stellaris LAUNCHPAD LM4F120H5QR
 * --->  PART_LM4F120H5QR  <---
 */
#define PART_LM4F120H5QR

#include <inc/hw_memmap.h>
#include <inc/hw_types.h>
#include <driverlib/gpio.h>
#include <driverlib/sysctl.h>
#include <driverlib/uart.h>
#include <inc/hw_timer.h>
#include <driverlib/timer.h>
#include <driverlib/pin_map.h>
#include <utils/uartstdio.c>

int main(void) {
unsigned long ulPeriod, dutyCycle;

SysCtlClockSet(
SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ
| SYSCTL_OSC_MAIN);
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);  // enables LED GPIO Port
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE,
GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3); // sets r,g,b as output

GPIOPadConfigSet(GPIO_PORTF_BASE , // identifies the GPIO PORT
GPIO_PIN_2,           // identifies the pin within the GPIO Port
GPIO_STRENGTH_8MA_SC, // sets the strength to 8mA with Slew Rate control
GPIO_PIN_TYPE_STD);   // sets the pad control type to push-pull

GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3, 0); // turns off the led

SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER1);  // enables timer 1 which can be connected to Port F / Pin 2
GPIOPinConfigure(GPIO_PF2_T1CCP0);             // port F pin 2 set to TIMER1_A output
GPIOPinTypeTimer(GPIO_PORTF_BASE, GPIO_PIN_2); // port F pin 2 set to timer type output, does not bind
/* it to any timer, the driverlib guide states :
This function cannot be used to turn any pin into a timer pin; it only configures a timer pin for
proper operation. Devices with flexible pin muxing also require a GPIOPinConfigure() function
call.*/

ulPeriod = (SysCtlClockGet() / 25000); // set to 25KHz
dutyCycle = (unsigned long) (ulPeriod - 1) * 0.5;
TimerControlLevel(TIMER1_BASE, TIMER_A, 1);  // invert the signal for TIMER1_A
//
TimerConfigure(TIMER1_BASE, (TIMER_CFG_SPLIT_PAIR|TIMER_CFG_A_PWM)); // 16 bit timer TIMER1_A set to PWM mode
TimerLoadSet(TIMER1_BASE, TIMER_A, ulPeriod - 1); // sets pwm period
TimerMatchSet(TIMER1_BASE, TIMER_A, dutyCycle); // sets duty cycle
TimerEnable(TIMER1_BASE, TIMER_A);              //enables timer1_a
while (1) {

}
}

--------------------------------------------------------------

 PF2 is also exported to the J4 connector of the Launchpad, so we can probe the signal with an oscilloscope.


This is how the signal looks like on my DSO when setting  F = 25KHz and DutyCycle = 50%


I did not cover the pre-scaling part, maybe I will add that in the future.

Monday, September 10, 2012

Driving a Mosfet with PWM

I played a bit with mosfets and finally managed to set up my first test circuit to drive them with the MSP430G2.

While in theory it's all quite simple, the correct selection of components to be used is extremely important.
The basic Idea is that the MCU generates a pwm signal which controls the gate of the mosfet.

Practically a few things must be considered, in fact you might get away with it easily if you do not need a lot of current to go through your power mosfet.

If you have no idea on how mosfets work, you can check my post here.

It all comes down to the internal resistance  between Drain and Source, you need it very high when the device is OFF and very low when the device is ON.
That's because if you are planning to have several Amps going through your transistor when it is on, you want a very low internal resistance or you will dissipate a considerable amount of heat (which is power you are wasting in whatever you are doing -except if you are doing a heating system-).

P = RI^2 from Ohm's law, so say you have 20 Amps and your R is 1 Ohm, you are dissipating 1*20*20 = 400W of power.

Mosfets tend to have a gate threshold (Vgs) at around 2 to 4V, however, while they "open" at that low voltage, their internal Rds resistance is still pretty high.
Every device has its own Rds curve in relation to the Vgs, but normally you want to drive the gate at about 12V or more.

You can find on the market some "logic level" mosfets that can be driven directly with a TTL signal, however they are normally not suitable to drive high currents and high voltages.

I chose a N channel mosfet for my experiment, particularly the IRF3710.
This device can deliver 46Amps at 100V with a reasonably low RdsON value (about 28mOhm) with Vgs over 7V.
Definitely it is not possible to drive it with a 3.3V signal.

A bit of math let's us find P = 46*46*0.028 =  60W which is still a lot, but I will probably be working in the range of 10Amps with way better results.

The problem with these devices is that to be able to let such big currents to pass through the channel, they need to create quite a big channel.
To open the N channel in the P doped semiconductor substrate, we will need a lot of charges, meaning the gate will act as a reasonably big capacitor.

We definitely need to charge that capacitor as quick as possible as a partial charge would result in a lower gate voltage which in turn would generate a higher Rds.
This means that not only we need to provide a sufficiently high voltage on the gate, but also we need to provide enough amount of current.

That's where gate drivers come in help.

They basically act as a "primary stage" mosfet to raise voltage and current to drive more efficiently the power device gate.

I was suggested to look into the Microchip TC4420 and similar devices.
This one particularly contains two logic level mosfets configured as a totem pole, that can output 18V and up to 6A.

These little buddies make your life way easier.

I first tested their output signal by feeding them the pwm signal of the MSP430G2 on one side and a 12V supply on the other.
(if you want to know how to output a pwm signal from the msp430g2, you can check here )

Despite the fact that I arranged the test on a solderless breadboard, I managed to obtain some decent frequencies.


As you can see in the picture I definitely have some (non desired) ringing, but that's probably reasonable if you consider all those  jumper wires going around in the breadboard.
Normally with these circuits you need to keep very short traces on a nicely designed PCB, that would definitely help in reducing parasitic effects (inductance/capacitance etc).
Plus I did not add any filtering cap for now, which would also help.
The waveform in the picture is at 1.32MHz, not too bad after all on a breadboard.

The next step was to add the power mosfet, so I did setup a test circuit like this one :


The two channels of the Oscilloscope are used to plot the output of the gate driver and the output of the power mosfet.
A Load resistor is added to simulate some load on the line... and at my first attempt I was able to get the "magic smoke" out :)
The load was too high, not a problem for the mosfet because it can handle 46Amp and the PSU can only provide 20, it was not a problem for the PSU either... but the tiny jumper wire did not appreciate much the glorious 20A pulses.
Now they smell funny and they are bit "crusty", but they still work (with a higher R Load impedance).

Channel 1 of the scope measures Vds (voltage between Drain and Source) which goes to (almost) zero when the gate is fully open.
Technically it's the voltage across the internal Rds resistor, so if it goes nicely down to zero it means we successfully drive the gate.
I will need to repeat this test with a higher load on the line (but not on the breadboard, melted plastic does not smell really nice).


Channel 1 is red and the volt scale is 2V per division.
You can see the zero level being marked by the little (1) red marker on the left side.
Channel 2 is yellow, showing the gate driver output, the two signals are inverted since when the gate signal (yellow) is high, it closes the circuit, so the Vds (red) drops to zero.
That's what I get at 80Khz.
I increased the frequency at about 320KHz and the result is visible in the picture below.


Both channels are now at 2V per division, aligned to their zero V.
You can see the rising edge of the Vds (red) being a bit "slow", that's definitely something that needs to be improved, which I assume can be achieved by discharging quicker the mosfet's gate.
Indeed proper cabling/pcb design is also needed, in fact the TC4420 can output up to 6A, no way that's going to happen using those tiny jumper wires.
I don't think it's something I can work on on a solderless breadboard like that, I probably need a better layout and definitely shorter connections.
Next step will be to add some caps, an inductive load on the output and  a freewheeling diode, that's where the real "magic smoke" could happen :)

Update : adding a 10Ohm gate resistor on the mosfet the signal becomes like this :


Normally a fast diode should be placed in parallel with the resistor, to improve the shutdown of the gate (or at least this is what I understood reading this interesting document)

Friday, August 10, 2012

MSP430G2 - Timers and PWM

We previously used a timer (TIMER A) to execute a procedure at regular intervals.
This is definitely a useful way of using the timers, but there is much more we can do with them.

Another interesting application is the generation of PWM (Pulse Width Modulation) signals.
I am not planning to explain here what PWM is, and I will assume you are familiar with the basic concepts (Frequency and Duty Cycle), if not you should be able to find everything here :
http://en.wikipedia.org/wiki/Pulse-width_modulation.

These signals have  a number of different practical applications, they can be used to control precisely the speed of electric motors, to drive power transistors in switching power supplies, they can be used to dim a led light etc.

A PWM signal is characterized by two parameters : Frequency and Duty Cycle.
The MSP430G2 time handles both of them.

The first thing we have to define is the period T (which also defines the frequency F=1/T).

Let's image to run the Timer A  at his full speed (16MHz) having the MCLK sourced from DCO with divider = 1 and SMCLK, also selected as clock source for Timer A, with the minimum division : 1
Let's also assume that Timer A is configured to run in "up mode", basically it will count from 0 to the values set in TACCR0.
Each count will take 1 / 16.000.000 seconds (1 cpu clock), so, if we make the timer to count 8 times, the period will be :

T =   1 / 16.000.000 * 8 = 1 / 2.000.000 s
and obviously the frequency F = 1 / T = 2MHz

TACCR0 has to be set to 7 for this (the count starts from 0)

Defining the Duty Cycle means we are defining the period for which the signal should be on (Ton) in each cycle.

Since the MSP430 has several capture/compare devices per each timer, we can use a second one (CC1) to define Ton.
The duty cycle is defined as Ton/T, but we also know that the periods are directly proportional to the number of timer counts, so, assuming we want to obtain a 25% Duty cycle

 0.25 = Ton / T

We know T = 8 -> Ton = 8 * 0.25 = 2


TACCR0 = 7;  // PWM Period (CC0)
TACCR1 = 1;  // PWM Ton   (CC1)          


In this picture, on the Y axis we have the Timer A counter value, on the X Axis each block is is a counter clock (in our case 1 / 16.000.000 s).
Since the timer is configured in "up mode", it will start from 0 and increment by one until it reaches TACCR0 (7) then it will drop again to 0.
Another action will be triggered when TACCR1 is reached.
How the CC0 and CC1 triggers can be combined is defined by choosing the "output mode" of the time as visible in fig 12-12 (from TI's MSP430 User guide).
The waveform we want to obtain is the red/green one, which matches with Mode 7.



This is chosen setting the right value in the TACCTL1 register

TACCTL1 = OUTMOD_7;

Obviously we could just set up an interrupt, check the TAR counter and drive accordingly an output pin, but that would work only for low frequencies as the cpu cycles needed to compare the values and drive the pin would affect our waveform, plus we would be using the CPU almost exclusively for this purpose.

Luckily the timer is autonomous for this and can automatically drive an output pin, using the criteria defined by the mode selected (reset/set in our case).
This means we do not need an interrupt nor we need to do anything special with the CPU which could be "sleeping" or performing other tasks.

Checking the device specific Datasheet (msp430g2553 in my case) we find that pin P1.2 supports the function TA0.1 (timer A output) with mode 1 (PSEL = 1 , PSEL2 = 0, DIR = output -1-).


The bit related to pin 1.2 is the 3rd in the registers :

7654x3210 
0000x0100
and 0100b = 0x4 in hex  (also 2^pinNbr)


P1DIR |= 0x04;     // P1.2  set as output
P1SEL |= 0x04;     // P1.2  TA0.1 option

So globally the test program is :

#include <msp430g2553.h>

void clockConfig()
{
 // configure the CPU clock (MCLK)
 // to run from DCO @ 16MHz and SMCLK = DCO
 BCSCTL1 = CALBC1_16MHZ; // Set DCO
 DCOCTL = CALDCO_16MHZ;
 BCSCTL2= DIVS_0 + DIVM_0; // divider=1 for SMCLK and 1 for MCLK
}

void main(void)
{
WDTCTL = WDTPW + WDTHOLD;   // Stop WDT
clockConfig();

P1DIR |= 0x04;     // P1.2  output
P1SEL |= 0x04;     // P1.2  set to TA0.1 
TACCR0 = 7;        // PWM Period
TACCTL1 = OUTMOD_7;    // CCR1 reset/set
TACCR1 = 1;  // CCR1 PWM Ton -> duty cycle
TACTL = TASSEL_2 + MC_1;    // SMCLK, up mode
_BIS_SR(CPUOFF);      // Enter LPM0
} 

If we hook an oscilloscope probe to P1.2 we can see this :



In the lower left rectangle you can verify that the signal frequency is correctly 2MHz.
In the next two pictures you can see the effect of changing the Duty Cycle value (via TACCR1) to 50% and to 75%.

Since the maximum clock frequency of the clock is 16MHz and we need at least an "up" value and a "down" value, it means that the maximum pwm frequency we can obtain is 16/2= 8MHz, as visible below. 


The signal appears heavily rounded mainly due to the way I connected the probe (non shielded cable, about 30cm long, definitely not the best setup to monitor a 8MHz signal).
This high frequency is not really usable for PWM purposes, unless you are happy with 3 duty cycle levels (0%,50%,100%).

This is because your Ton time is defined by a finite number of cycles, if you are working with a T defined by a large number in TACCR0 (thus increasing your period T and lowering your PWM frequency) you can probably have  a fine control over the duty clycle.

So it's a bit of trade off between maximum frequency and detailed control of the duty cycle, where to set the bar really depends on your application.
In many cases you will probably be happy with frequencies of few KHz and about 1% of Duty Cycle increments.

Let's make a numeric example :

Required F = 10KHz -> T = 1 / 10.000 s
Duty Cycle increments = 1% -> dT = 1 / 10.000 * 1 / 100 = 1 / 1.000.000 s

The easiest way to achieve this would be to set SMCLK to run at 1MHz, TACCR0 = 99 (100 cycles/period = 1MHz/100 = 10KHz) and TACCR1 between 0 and 99.

I deliberately chose the lowest possible value for SMCLK, any value equal or bigger than that would 4 do, i.e. SMCLK = 4MHz

-> TTACR0 = 4 * 100 -1 = 399;
-> TACCR1 between 0 to 399 with a minimum increment of 1/4% = 0.25%