Tag Archives: Timer

Microcontroller Timer

Switch Debouncing Tutorial

Switch Debouncing Tutorial Pt/2

 

In this switch debouncing tutorial part 2 C code debounce algorithms will be looked at further, and their effectiveness.  All the software solutions shown will be demonstrated on the MSP430G Launchpad.  However the basic principle of operation shown in the examples, can be applied to all microcontrollers, particularly the last example which is based on some code found at Jack Ganssle tutorial, this can be easily implemented on any system using the C language.

MSP430 Single Switch Debounce WatchDog

The first debounce algorithm example is based on some Arduino code, which uses the millis() function.  In this case the millis second count is generated by the watchdog timer on the MSP430.  The launchpad switch connected to GPIO P1.3 is used in this test code.

The while loop on line 1 is inside the main function, line 5 AND’s port 1 with BIT3 as this is the only GPIO pin of interested.  Lines 6 to 9 will set the variable reading to a 1 if the value on pin P1.3 is a 1 i.e. not pressed, and 0 if the switch is pressed.  Lines 11 and 12 check to see if the switch has changed from it’s previous stored state, if this is true then the time when the switch was pressed is saved to the variable lastDebounceTime.  Lines 14 and 15 determine if the switches state hasn’t changed for a time equal to the variable debounceDelay, this then means that it is the current stable state of the push switch.  The stable state is assigned to the variable switchState, then lines 17 to 20 determine the if the LED connected to GPIO P1.0 is on or off.   The debounceDelay was set to 10, and the algorithm performed very well allowing fast presses of the single switch, without any issues.

The watchdog timer was used in this example as it was simple to set-up and generate an interrupt every 0.5mS.  Lines 36 to 33 show the interrupt handler, some basic statements inside the interrupt generate a 1mS count, which continuously increments.  The function Mils_Count() in lines 35 to 39, is used to obtain the current count value.  The watchdog timer is not meant to be used in this way, but it is so often disabled in many examples, yet is a resource that can be exploited.  If you were producing a production embedded system this would probably not be the case, but this adds a little extra functionality to some of the low end MSP430G devices.  The watchdog set-up shown will be used in some of the other debounce examples in this tutorial, and can easily be substituted with a standard timer.

MSP430 Single Switch Debounce WatchDog Example Code

The link below contains the zip file with the full example C code, there is a small advert page first via Adfly, which can be skipped and just takes a few seconds, but helps me to pay towards the hosting of the website.

MSP430 Single Switch Debounce WatchDog

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.

MSP430 Interrupt Button Control

The second example configures the GPIO pins to trigger interrupts when a change in state is detected, which is caused by a switch being pressed.  Only the interrupt handler is shown in the code snippet below, but the entire C code can be downloaded further down the page.

There are two GPIO pins set-up to generate interrupts P1.3 and P1.7.  When a switch is pressed on either of these pins, the interrupt handler is called.  The switch case statements are used here, the port 1 interrupt flag register (P1IFG) being used as the switch.  Once the correct pin interrupt has been identified, the interrupt edge select is toggled (lines 8 and 14).  Then the corresponding LED is toggled, as shown in lines 9 and 15.  Lines 10 and 16 use a delay function which basically waits for 40mS (1MHz clock).  This produced a reasonable outcome at slow to medium rates, pressing the switch at a faster rate produced indeterminate results.  The delay function is not the best method to carry out a delay as it wastes CPU time.  This technique is also not as robust a the first algorithm, especially if the switch is pressed quickly, but it does allow a whole port of switches to be used.

MSP430 Interrupt Button Control Example Code

The link below contains the zip file with the full example C code, there is a small advert page first via Adfly, which can be skipped and just takes a few seconds, but helps me to pay towards the hosting of the website.

MSP430 Interrupt Button Control

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.

  

MSP430 Multiple Switch Debounce WatchDog

The third example has two examples of switch debounce algorithms, these are split into two individual functions which can be run from the main function, simply by commenting one of them out at a a time.  The functions incorporate aspects of the previous two examples, allowing multiple switches to be debounced.  The code snippet below shows both of the functions Press_Time() and Debounce_Buttons() residing inside a while loop, which is inside the main function.

The Press_Time() function will be looked at first.

Starting with line 3, the if statement is used to ensure that the switches connected to BIT3 or BIT7 have been pressed, if not the statement is considered false.  Line 5 assigns the variable state with the AND’ed value of port 1 (P1IN) with hex value 0x88 or binary 10001000.  Line 7 assigns the current Mils_Count() value to the variable Reaction_Count.  The switch case statements are used here with the variable state being used as the switch.  If the switch on P1.7 is pressed then the case statement on line 14 will be selected.  A while loop is then entered, which waits until the current Mils_Count() minus the variable Reaction_Count is greater than the variable Button_Reaction_Delay.  This allows a tunable delay to be entered with ease, for testing a delay of 100-150mS was found to produce satisfactory results.  This method produced better results than the interrupt method, but will suffer with increased switching speed.

The second function Debounce_Buttons() is basically a copy of the first example.  The variables are just doubled up and surrounded by a if statement so the code is only executed when a switch is pressed.

This works well as per the first example but with two switches, however the code is very inefficient, due to the large number if statements that are executed each time a switch is pressed.

MSP430 Multiple Switch Debounce WatchDog Example Code

The link below contains the zip file with the full example C code, there is a small advert page first via Adfly, which can be skipped and just takes a few seconds, but helps me to pay towards the hosting of the website.

MSP430 Multiple Switch Debounce WatchDog

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.

MSP430 Ganssle Switch Debounce Multiple Switches

This fourth and final example is based on sample code provided by Jack Ganssle, he has an excellent tutorial located here.  The code is based on his third example, there is also a good description of the code operation with his article.  The code snippet below shows the main body of the algorithm, I have made some modifications adding a compound bitwise AND operator, as well as adding some of his considerations regarding OR’ing the final debounced port value.

Line 6 shows a function call for rawPortData(), this function simply returns the current state of port 1 and can be seen below in the next code snippet.

The debounceSwitch() function returns the debouncedORd value, and is called in the following way.

The checkButtons() function uses switch case statements to interpret which switch or GPIO pin has changed, the nice part about this code is the debouncedORd value makes the code very intuitive.

This last example is easy to port to other microcontrollers, just by changing the code in functions checkButtons() and rawPortDate().  Needless to say this code works very well and produces excellent results with the PCB tac switches used, under fast or slow switching.

MSP430 Ganssle Switch Debounce Multiple Switches Example Code

The link below contains the zip file with the full example C code, there is a small advert page first via Adfly, which can be skipped and just takes a few seconds, but helps me to pay towards the hosting of the website.

MSP430 Ganssle Switch Debounce Multiple Switches

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.

Switch Debouncing Tutorial

Switch Debouncing Tutorial Pt/1

 

In this switch debouncing tutorial part 1 the cause and effect of switch bounce will be explained and demonstrated, then a cost effective hardware debouncing solution will be discussed, with oscilloscope captures to demonstrate the results.  The last section of part 1 will show a simple program based on the MSP430 , this can be used to see the effects of a particular switch connected to the GPIO.  Switch deboucing tutorial part 2 of this tutorial will look at further C code debounce algorithms and their effectiveness.

All the software solutions shown will be demonstrated on the MSP430G Launchpad.  However the basic principle of operation shown in the examples, can be applied to all microcontrollers, particularly the last example which is based on some code found on Jack Ganssle tutorial, this can be easily implemented on any system using the C language.

Switch Contact Bounce

Switch contact bounce is a common issue for all mechanical switches, this includes mechanical relays.  The contact bounce occurs when the metal contacts of the switch are forced together, the property of the metals used causes the contacts to bounce apart.  How often the contacts bounce apart before finally latching shut depends on the contact type and the property of the switch.  The bouncing effect can causes multiple high frequency pulses, as opposed to a clean transition at the output.  If we take an example of a microcontroller with a switch connected to one of it’s GPIO pins, the microcontroller is able to read these high frequency pulses, misinterpreting them as legitimate presses, resulting in an undesired action.

The image below shows a basic circuit used to test switch contact bounce.

Switch Debouncing Tutorial switch circuit without debounce

With the circuit constructed on some breadboard, an oscilloscope was connected to the GPIO pin header and set to trigger when the switch was pressed, the resultant capture can be seen below.

Switch Debouncing Tutorial switch without debounce circuit poor quality switchThe oscilloscope captures shows the steady state of just over 3.3V, as the switch is pressed and released, multiple pulses are visible during this time.  The switch used for this capture was an old switch I found in a bag of spares I had, it was a small momentary touch which had a sprung button.  Many of these extra pulses would be picked up by a microcontroller, causing unexpected behaviour with your program if no debouncing was used.

The next oscilloscope capture was taken using a small PCB mounted tac switch, this was set-up in the same way as the previous test.

Switch Debouncing Tutorial switch without debounce circuit good quality

It can clearly been seen that this inexpensive PCB switch has a far superior switching action, but there is still bouncing going on, as the expanded image below shows in greater detail.

Switch Debouncing Tutorial switch without debounce circuit good quality zoomed

Hardware Solution

There are many hardware solutions to solve switch contact bounce, ranging in price from a dedicated microcontroller programmed purely to act as a debouncer, or a dedicated key encoder (MM74C923) with built in debounce, to a low end solution using just a resistor and capacitor.  This tutorial will only cover the latter option, as when combined with a suitable software algorithm, provides a cost effective solution for most small microcontroller applications.

A simple resistor capacitor switch deboucing circuit can be seen below.

Switch Debouncing Tutorial switch circuit with debounce

 

The resistor capacitor combination forms an RC circuit, which has a time constant determined by τ = R*C, therefore 47kΩ*100nF = 4.7mS.  The capacitor is considered charged after approximately 5*τ, therefore roughly 25mS.  So when the switch S2 is pressed effectively closing the switch, the voltage across the capacitor is discharged through the switch to ground.  As there is very little resistance this happens quickly, but as will be shown not instantly.  When the switch is released and becomes open, the capacitor is charged via R2 and should take approximately 25mS to charge back up to the supply voltage.  Any spikes caused by bouncing contacts are absorbed by the RC circuit, however care must be taken when selecting the values to ensure the switching action is fast enough for the project.  If the resistor or capacitor is too large the time lag may cause the system responsiveness to suffer, too small and a switch with a long bounce characteristic will still have an issue.  Capturing the switch bounce with an oscilloscope is the best way to view the problem and then take the appropriate action.  The oscilloscope capture below shows the circuit in action using the cheap PCB tac switch.

Switch Debouncing Tutorial switch with debounce

This clearly shows a huge improvement in the switching noise, the falling edge shows a clean edge, while the leading edge is curved due to C1 charging through R2.  The next image shows the falling edge of the capture on a smaller time base.

Switch Debouncing Tutorial switch with debounce falling edge

The falling edge can still be seen to show the capacitor discharge curve, this takes approximately 1uS, therefore the resistance to ground is approximately 2Ω.  The next image shows the rising edge of the capture on a smaller time base, the image clearly shows the capacitor curve levelling off around 25mS.

Switch Debouncing Tutorial switch with debounce rising edge

This circuit will work sufficiently in most situations, but it is best practice to discharge the capacitor in a more controlled fashion, especially if there are higher currents and voltages involved.  A second resistor can be used in conjunction with R2, thus ensuring C1 has a higher resistance path to ground, when the switch S2 is closed.  The image below shows a circuit using this additional resistor (R1).

Switch Debouncing Tutorial switch circuit with debounce 2nd resistor

The combination of R1 and R2 has very little impact on the original time constant, but allows a controlled discharge of the capacitor to ground.  The value of R1 would typically be less than 6.8kΩ, being dependant on the requirements of the system.  This will ultimately improve the life of the switch, as it avoids high instantaneous currents.

Before finishing part 1 of this tutorial, a basic code example is shown below which allows some of the contact bounces from a switch to be recorded on a MSP430 Launchpad.

The code snippet above is used with an external switch, connected to GPIO pin P1.0, which is configured to function with Timer0_A.  Timer0_A is set-up in capture mode and configured to trigger an interrupt on every falling edge pulse.  Every time the interrupt is triggered the variable count is incremented, therefore by running this code it is possible to determine roughly how noisy a switch is.  To see the updated count value, the code can be run then the switch pressed, the code can then be paused to check the value of Count, or a breakpoint can be set and the variable Count watched.

Test Code

The link below contains the zip file with the full example C code, there is a small advert page first via Adfly, which can be skipped and just takes a few seconds, but helps me to pay towards the hosting of the website.

MSP430 Debounce Switch Test

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.

In Part 2 debounce algorithms will shown with C examples, they will all be written to run on the MSP430 but the principle of operation can be carried over to other microcontrollers.  The last code example in particular can easily be implemented on other microcontrollers.

MSP430 Timer Tutorial Launchpad article

MSP430 Timer PWM Tutorial

 

In this MSP430 timer PWM tutorial the basic workings of the on board timer peripheral will be explained, along with some C code examples which can be downloadable at the end of the tutorial.  Additionally the video below demonstrates the examples ‘A picture paints a thousand words, a video displays a thousand pictures’.

The MSP430G2253 will be used as it has two timers opposed to the MSP430G2231 which only has one timer, this will allow for different examples to be shown.  All the code in the MSP430 timer tutorial is written in Code Composer Studio (CCS) v5.5.  As the tutorial will be using the MSP430G2253 as the test microcontroller, downloading the datasheet for this maybe of use and can be found here.

Before reading further if you are having trouble understanding how the registers work, and how the C code updates the individual register settings?  It would be worth reading my MSP430 Programming Tutorial, Part 1 covers the basics and Part 2 gives clear examples.  You can find them here Part 1 and Part 2.

The MSP430G2253 has two 16 bit timers, Timer0 and Timer1 both are Timer_A variants with three capture/compare registers.  The MSP430 family guide lists two types of 16 bit timer, Timer_A and Timer_B.  For the most part they are very similar except Timer_A has up to three capture/compare registers, were as Timer_B has up to seven.  The MSP430G2253 also has a watchdog timer which can be used detect system malfunctions, but will not be covered in this tutorial. The feature list for Timer_A is shown below:

  • Asynchronous 16 bit timer/counter with four operating modes
  • Selectable configurable clock source
  • Up to three configurable counter/compare registers
  • Configurable as outputs for PWM
  • Asynchronous input and output latching
  • Interrupt vector register for fast decoding of all Timer_A interrupts

Asynchronous 16 Bit Timer

The 16 bit timer increments or decrements a value from the Timer_A register (TAR), every rising edge of the clock pulse.  The TAR value can be read or written with software, and an interrupt can be enabled to generate when it overflows.  If the timer is run asynchronous to the CPU clock, any reading from the TAR should occur while the timer is not running, as the result is likely to be unpredictable.

The four modes of operation for the timer are:

Stop – The timer is stopped

Up – The timer counts from zero to the value of TACCR0

Continuous – The timer counts from zero to 0FFFFh

Up/Down – The timer repeatedly counts from zero up to the value of TACCRO (+1) and then back down to zero.

Configurable Clock Source

The clock source for the timer can be from ACLK, SMCLK or from an external source via TACLK or INCLK (Device specific).  The clock source selected can be then divided by 1, 2, 4 or 8.

Counter Compare Registers

The capture/compare blocks inside Timer_A are all identical.  Any of the TACCRx blocks may be used to capture timer data or generate intervals.  When in capture mode the Capture Compare inputs CCIxA and CCIxB, can be connected to external pins or internal signals. They can be configured to capture on a rising, falling or both edges.  The compare mode is used to generate PWM output signals, or interrupts at specific time intervals.  Each capture/compare block has an output unit, which is used to to generate output signals like PWM.

Interrupt Vector Register

The Timer_A module has two interrupt vectors linked to it: TACCR0 interrupt vector TACCR0 Capture Compare Interrupt Flag (CCIFG) and Timer_A Interrupt Vector Register (TAIV) for all CCIFG flags and Timer_A Interrupt Flag (TAIFG).  The TACCR0 CCIFG has the highest priority of all the interrupts for Timer_A.  The TAIV is used to prioritise and combine the TACCR1 CCIFG, TACCR2 CCIFG and TAIFG flags.

Timer_A Registers

The Timer_A module is configured with software by setting the bits inside the various registers, which alter the timers parameters.  The image below list the various registers associated with the Timer_A module.

MSP430 Timer Tutorial Guide Timer_A Registers

Timer_A Control

This register determines where the clock is sourced from and how the clock is divided either by 1, 2, 4 or 8.  The timers control mode is also set here, whether it’s stopped, counts up, continuous or up/down.  The TAR , clock divider and count direction can also be reset with the TACLR bit being set.  Lastly the Timer_A interrupt enable/disable and interrupt pending flag are also found here.  A typical command for this register looks like this TA0CTL = TASSEL_2 + MC_1; or TA1CTL = TASSEL_2 + MC_1;

Timer_A Counter

The Timer_A registers or TAR holds the count of Timer_A.  A command using this register could look something like this depending on your application TAR = 4500-1;

Timer_A Capture/Compare 0

The Timer_A capture/compare register 0 or TACCR0, is used in two cases.  In compare mode this holds the value for comparison with the timer value in the TAR.  When in capture mode, the value in the TAR is copied into the TACCR0 when a capture is performed.  An example of the register code would be as follows TA0CCR0 = 200-1;. 

Timer_A Capture/Compare Control 0

The Timer_A capture/compare control register 0 or TACCTL0, is a 16 bit register used to determine how the TACCR0 is set-up.  The register controls whether the timer module is set to capture or compare.  The trigger edge for the capture mode can be set, as well as where the source originates from, either internal or external.  Asynchronous or synchronous operation can determined, as well as synchronised capture or compare input.  There are various output modes, which are used to determine the operation of PWM signals for example.  Also this register allows interrupts to enabled for the timer module.  An example of the register code would be as follows TA0CCTL0 = OUTMOD_7 + CCIE;.

Timer_A Capture/Compare 1

The Timer_A capture/compare register 1 or TACCR1.  Has the same operation as TACCR0.  An example of the register code would be as follows TA0CCR1 = 200-1;. 

Timer_A Capture/Compare Control 1

The Timer_A capture/compare control register 1 or TACCTL1, is a 16 bit register used to determine how the TACCR1 is set-up.  Has the same operation as TACCTL0.  An example of the register code would be as follows TA0CCTL1 = OUTMOD_7;.

Timer_A Capture/Compare 2

The Timer_A capture/compare register 2 or TACCR2.  Has the same operation as TACCR0.  An example of the register code would be as follows TA0CCR2 = 200-1;. 

Timer_A Capture/Compare Control 2

The Timer_A capture/compare control register 2 or TACCTL2, is a 16 bit register used to determine how the TACCR2 is set-up.  Has the same operation as TACCTL0.  An example of the register code would be as follows TA0CCTL2 = CCIE;. 

Timer_A Interrupt Vector

The Timer_A interrupt vector register or TAIV, is used to prioritise and combine the remaining interrupt flags.  When reading the TAIV it will give the value of the current interrupt, as well as clearing that interrupts flag.

 

Timer Example 1

This first example demonstrates the use of one timer, which is used to flash the MSP430G2253 Launchpad LED’s on and off.  The code snippet below only shows the timer set-up and the interrupt handler, as these are the most relevant parts.

The code is fairly short and quite simple to walk through, in line 5 we first load the TA0CCR0 with the value 3000.  Line 6 turns the interrupt on for the TA0CCR0 when it overflows.  Line 7 sets the clock source to ACLK (12kHz) and the counter to count-up mode.  So the interrupt is generated every 250mS approximately.  Line 9 sets the MSP430 to low power mode and enables interrupts.  Lines 12 to 22 are the interrupt handler for Timer0_A, this interrupt automatically clears when called.  Inside the interrupt handler, the variable Control is used to ensure the green LED flashes once for every time the red LED flashes four times.  The closing brace marks the end of the main function.

Example 1 Code

The link below contains the zip file with the full example C code, there is a small advert page first via Adfly, which can be skipped and just takes a few seconds, but helps me to pay towards the hosting of the website.

MSP430 Timer Tutorial Timer Example 1

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.

Timer Example 2

The second example demonstrates the use of two timers, which are used to output PWM signals on GPIO pins P1.2 and P2.1.  The timer set-up code and also the GPIO set-up code is shown below.  The clock was set to 8MHz for this example.

Before walking through the code, the image below is extracted from the MSP430G2253 datasheet, this shows GPIO pin P1.2 and it’s functions.  The line which is highlighted demonstrates P1.2 can be used as an input and output for Timer0_A.

MSP430 Timer Tutorial GPIO Pin Functions

Walking through the code starting with line 5, this sets GPIO pin P1.2 as an output.  Line 6 selects the function for GPIO pin P1.2, and in this case it is used for PWM.  Lines 7 and 8 perform the same operation, except they are for GPIO pin P2.1.  line 11 the TA0CCR0 is loaded with 200, this sets the PWM frequency to 40kHz approximately.  Line 12 sets the output mode to reset/set.  Line 13 sets the count value of TA0CCR1, which determines the PWM duty cycle, in this case 50%. Line 14 sets the clock used by the TA0CTL to SMCLK and the counter to count-up mode.  Lines 17 to 20 set-up Timer1_A in the same way as Timer0_A, except the frequency is set to 8kHz approximately.

The image below shows a capture from the oscilloscope for this code, GPIO pin P1.2 is shown on channel 1 and P2.1 is shown by channel 2.

MSP430 Timer Tutorial Dual PWM example

Example 2 Code

The link below contains the zip file with the full example C code, there is a small advert page first via Adfly, which can be skipped and just takes a few seconds, but helps me to pay towards the hosting of the website.

MSP430 Timer Tutorial Timer Example 2

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.

Timer Example 3

The third example demonstrates the use of two timers, using PWM generated by Timer0_A and a timed interrupt on Timer1_A to alter the duty cycle.  The PWM output is configured to output on GPIO pin P1.6.  As with the previous code examples, only the timer set-up code is shown. The clock was set to 1MHz for this example.

Lines 5 to 8 in this example are almost identical to lines 5 to 8 in the example 2 code.  The main difference is the PWM frequency is set to 1kHz (clock set to 1MHz) and the duty cycle is initially set to 0.1%.  Lines 11 to 13 set-up Timer1_A, this has a count of 4000 so generates an interrupt every 4mS.  Line 15 sets the MSP430 to low power mode and enables interrupts.

Lines 18 to 25 are the interrupt handler for Timer1_A, as with the first example this interrupt automatically clears when called.  Inside the interrupt the value stored in TA0CCR1 is added to the variable IncDec_PWM which is multiplied by 2 every time the interrupt handler is called.  IncDec_PWM is a global variable and assigned the value 1.  This equates to the value in TA0CCR1 being incremented or decremented by 2, therefore the duty cycle changes by 2 or (0.2%) every time the interrupt handler is called.  This equates to a transition time of approximately two seconds from high to low and low to high.  The final if statement inside the interrupt handler reverses the direction of the duty cycle, causing the LED to decrease in brightness until a value greater than 998 is reached, and increase in value when a value less than 2 is reached.

Example 3 Code

The link below contains the zip file with the full example C code, there is a small advert page first via Adfly, which can be skipped and just takes a few seconds, but helps me to pay towards the hosting of the website.

MSP430 Timer Tutorial Timer Example 3

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.

There is also one more additional example for the timer, which demonstrates the capture mode.  This is actually part of a another tutorial based around switch debouncing, the timer is used to capture the undesired pulses generated by a noisy switch.  You can find the additional code by browsing to the end of my Switch Debouncing Tutorial Pt/1.

C2000 Solar MPPT tutorial

C2000 Solar MPPT tutorial Pt/3

 

In this third part of the C2000 Solar MPPT Tutorial, the software will be looked at in greater detail.  This will entail a look at the Perturb & Observe algorithm, ADC code and timing code to ensure everything operates in a controlled manner.

The software is based around a Perturb and Observe (P&O) algorithm, the P&O algorithm falls under the category of a hill climbing algorithm.  Hill climbing algorithms are named so due to the algorithm taking steps over sampled data to reach a desired value, in the case of the P&O this takes steps towards the MPP by increasing or decreasing the duty cycle.  There are other hill climbing algorithms such as dP/dV Feedback Control and Incremental Conductance, I intend to revisit these and write code at a later date, but for now will focus on the P&O.  Some further information on MPPT algorithms can also be found here.

Perturb & Observe Algorithm

The P&O algorithm is a relatively simple algorithm, as such it has a few drawbacks:

  • The algorithm can be confused and track in the wrong direction, this can occur under fast changing irradiance conditions, the severity of this confusion depends on the P&O setup i.e. step size and update frequency.
  • The algorithm oscillates around the set point showing characteristics of an on/off controller.  More on this can be found on a previous tutorial I wrote regarding PID control, which can be found here.

The flowchart below shows the P&O algorithm used for this project

C2000 Solar MPPT Tutorial Perturb and Observe Algorithm Flow Chart

As can be seen from the flowchart the algorithm is fairly easy to follow, turning this into C code is also relatively easy, the final C code P&O algorithm can be seen below inside the function Adj_PWM().

So lets now run through the code briefly starting with line 3, this basically assigns the value in the counter compare A register to variable PWM_Temp.  PWM_Temp could simply be assigned to a temporary global variable, but I chose to get it straight from the register in this case.  Lines 5 to 24 form the main body of the algorithm, looking back at the flowchart the first two steps “Sample” and “Calculate” are carried out elsewhere in the ADC section of the code.  Lines 5 to 14 are illustrated by the right hand branch of the flowchart and lines 15 to 24 are illustrated by the left hand branch of the flowchart.

You have some simple if and else statements that determine which direction the algorithm takes, which is dependant on the sampled ADC data.  The result of these steps will either increase or decrease the PWM duty cycle, this increase or decrease determines the step size and in this case that value is 2.

The next block of code from lines 26 to 31 are used to prevent the duty cycle from reaching too large, and too small a value.  This was used during tuning, but also serves to provide some boundaries for the PWM, for example the duty cycle for the half bridge MOSFET drivers cannot exceed 99%, or the boost function will not operate correctly.

Lines 32 and 33 are used to update the duty cycle to the counter compare A registers for PWM1 and PWM2, both are the same duty cycle but PWM2 is 180o out of phase with PWM1.  Line 35 then assign the latest calculated solar panel voltage IP_Volt to the variable Old_IP_Volt and line 36 assign the latest calculated solar panel power New_PW_In to the variable Old_PW_In, both these variables are then used when the Adj_PWM() function is called again.

In order to help visualise the two PWM signals, the below image shows an oscilloscope trace with PWM1 in yellow and PWM2 in blue, both are set to 50% duty cycle and PWM2 is out of phase by 180o with PWM1.

C2000 Solar MPPT Tutorial 50% Duty 180 Phase

ADC Code

The next piece of code to be looked at is the ADC, I am not going to show the set-up code for the ADC or the PWM that triggers the ADC SOC, but will just show the code relating to the sampling and calculation.  However I intend to write a tutorial on each peripheral inside the C2000 with code examples, when time allows.  The ADC sampling is triggered by the PWM on every first event, therefore the sampling rate is 15ksps.  The final ADC sampling code can be seen below inside the function Data_Update()

So starting with lines 3 to 6 these are the local variables used for the function, the two floats are used to store the ADC values and the two integers are used to determine how many samples in the for loop.  The float in line 4 is a float array with four arrays, now the same result could be achieved with four separate floats.  I have left it as a float array for now, but if four floats were used the code should be optimised, by using 64 samples the following division of 128 (lines 23 to 26) could be substituted with a right bit wise shift of 7.

Lines 8 to 21 consist of the for loop, this uses the integer i as a counter and numberOfsamples as the count value.  Inside the for loop shown on line 10 this statement will wait until the next PWM trigger is received, which then initiates the ADC SOC channel number 0, once ADC channel 0 is finished it initiates channel 1 and so on and so forth.  The samples are saved in each of the channel numbers registers, then using the += addition assignment operator are added to the sum_of_ADC_samples_Array[n].  So an accumulated value is built up of the total samples every time the for loop is executed.  In addition there are 8 ADC channels being sampled, channel 0 to 7, but only 4 samples are accumulated so ADC channel 0 and 4 are added to sum_of_ADC_samples_Array[0] and channel 1 and 5 are added to sum_of_ADC_samples_Array[1] and so on and so forth.  When the ADC channel sampling sequence has finished, the trigger flag for the SOC sequence is cleared (line 20) and the loop waits for the next trigger event from the PWM.  Once i reaches 64 the loop is exited, each of the of the sum_of_ADC_samples_Array[n] now have 128 accumulated sample values in.

Lines 23 to 26 divide the sum_of_ADC_samples_Array[n] by 128 and assign the value to ADC_An floats.  Lines 28 to 31 convert the new floats to real world voltages read on the GPIO. Lines 33 to 36 then use constant values calculated from the electronic component values in the circuitry, to convert the floats to actual voltages and currents sampled in the circuit.  Lines 38 to 40 simply convert the input voltage and current to an input power and the output voltage and current to an output power.

 

Timing Code

The timing code is quite critical as it determines the update frequency of the MPPT, it must also ensure the code does not overrun and cause unpredictable behaviour.  The internal timer module was used, Timer 0 was set-up to trigger an interrupt every 100mS or 10Hz. The interrupt code is shown below.

When the interrupt is called an integer called SysTick is set to one, then the interrupt flag is cleared allowing the interrupt request to be executed and exited quickly.

Inside the main function there is a continuous while loop, the following code is run inside this loop.

Every time the interrupt sets the integer called SysTick to one, it allows the functions Data_Update() and Adj_PWM() to be executed, once these functions have completed SysTick is set to zero.  There are some additional lines of code on line 5 and line 10, these are used for testing and allowing the code execution time to be displayed on an oscilloscope.  The code on line 5 switches GPIO pin 19 high, then the code on line 10 switches GPIO pin 19 back to low, so a square wave pulse is produced and the pulse width gives an indication of the code execution time of the functions Data_Update() and Adj_PWM(). The following images show captures from an oscilloscope.

C2000 solar MPPT PWM and MPPT update frequency

This first image shows the 15kHz PWM being displayed on channel 1, the individual wave pulses are not visible as the time base is set to display channel 2.  The blue trace shown on channel 2 can be seen to have a frequency of 10Hz, with a pulse width of 4.4mS, so the functions Data_Update() and Adj_PWM() take 4.4mS to execute.  Putting this into context there should be 128 ADC samples captured, taken from 64 triggers of the PWM signal, therefore 64*66.67uS (one 15kHz cycle) = 4.27mS.  A single ADC sample and conversion takes around 650nS, if we multiply that by the 8 samples, a conversion is being completed every 8*650nS = 5.2uS (it will be faster than this due to ADC pipelining effects).  It can be clearly seen that there is plenty of room for more oversampling if required, as the 5.2uS sample and conversion time easily fits inside the 66.67uS window of the PWM trigger.  There is also a small amount of code overhead being added artificially by toggling GPIO pin 19, which is not significant but something to be aware of.

C2000 solar MPPT PWM and MPPT update frequency zoomed

The second image has a smaller time base setting (100uS) effectively zooming in, which allows the individual pulses from the 15kHz PWM to be visible.  So going back to the step size of 2 shown in the Adj_PWM() function, this can be put into context when the maximum duty cycle value as a variable, for 100% duty cycle equals 1000.  Therefore with a PWM update frequency of 10Hz and a maximum step size of 2, this equates to a maximum duty cycle change of 2% per second.

I captured some video which shows 3 variables being graphed in Code Composer Studio, these variables are PV Power, PV Volts and the Duty Cycle.  The video also demonstrates the MPPT in action under simulated fast changing cloud conditions, as well as some natural cloud.

There will be one final part to this series of tutorials this will cover some of the set-up and testing, and will also include a link to the full C code for the project.

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.

Stellaris timer example frequency counter

Stellaris Timer Example

In this Stellaris timer example two timers are used to code a basic frequency counter.

The code process is quite simple to implement, and as mentioned previously with other stellaris examples I would recommend using the StellarisWare Peripheral Driver Library PDF as a reference, which can be found here.

The first timer is configured to count the leading edge of the incoming square wave, the second timer is used to count for a fixed time and then generate an interrupt. Then a simple calculation is performed using the second fixed timer value, and the accumulated leading edges counted. The positive going edge count is then stored, and also reset every time the second timers interrupt is generated.  The image below outlines the basic operation of the example that will be shown.

Stellaris Timer Example Code frequency counter LM3S6965

 

As can be seen from the image timer 2 was chosen to generate an interrupt every 100mS, this was deemed as an adequate time to refresh the count, and can easily be increased or decreased pending on the application.  The stellaris LM3S clock frequency is running at 8MHz. Each clock pulse period can be calculated by taking the reciprocal of 8MHz (1/8MHz) which is 125nS, then dividing 100mS by 125nS we reach a value of 800,000.  The 800,000 is not used directly in this code, as the clock is simply divided by a constant, but this illustrates how the value was reached.

A signal generator was used to feed a square wave into the stellaris, this was then varied and the results of the stellaris code displayed on the on-board OLED.  A video of the frequency counter in action can be seen below.

So now lets dive into the code.  As mentioned before the system clock was running at 8MHz, using the on-board crystal, the code snippet below is used to configure the clock and also some OLED initialisation.

Then both of the timer peripherals need to be enabled.

In the code example Timer0 is used to generate an interrupt every 100mS, and Timer1 is used to measure the leading edge pulses from the signal generator.  Therefore a GPIO input needs to be setup and assigned to function with Timer1, the next section of code performs this.

An interrupt needs to be enabled and set-up for Timer0A.

Then the 2 timers need to be configured.  The first 2 lines of code set-up Timer0 as a full width periodic timer, and Timer1 as a half-width edge count capture.  Then Timer0 (TimerA) is loaded with the 100mS count period, and Timer1 is loaded with a value of 10000.  Timer1 is loaded with a value as it counts down for every positive going edge.  This timer example could effectively count upto 2MHz (a quarter of the 8MHz clock frequency), it was tested successfully with higher frequencies, to do so the value preloaded into Timer1 needs to be increased.  The final line in this snippet, sets Timer1 (TimerA) to trigger on positive going edges.

Finally the timers need to be enabled.

Now that the timers are configured and enabled the code for the interrupt handler for Timer0 can be configured.  This basically clears the interrupt, stores the value counted by Timer1 and then resets Timer1.

This is not necessarily the best way to do this, but it performed the task required of the test at the time.  As has been mentioned the code displays the frequency value on the OLED, to do this an itoa function is used to change an integer into a char and then print to the display, all this takes quite a few processor cycles, and in this way has been removed from delaying the interrupt handler.

The final code block shows the function used to calculate the timer frequency.  It could be improved upon using a modulus to display the frequency in kHz, and printing a decimal point in the appropriate place, this would allow displaying a greater range of frequencies with more ease.

The following image shows a screen capture from the YouTube video, which demonstrates the program works within a reasonable accuracy.

Stellaris Timer Example Code frequency counter LM3S6965

Example Code

The link below contains the zip file with the complete C code, there is a small advert page first via Adfly, which can be skipped and just takes a few seconds, but helps me to pay towards the hosting of the website.

Frequency Counter

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.