Category Archives: Electronics


MSP430 Voice Control Over Bluetooth


In this tutorial I will demonstrate a MSP430 voice control over Bluetooth, using a HC06 Bluetooth module.  I will be using an Android App I programmed which can be downloaded and installed, the C code for the MSP430 is also downloadable at the end of the tutorial.

**Update 18/01/2015 the Android App has been updated and now includes 23 generic commands

So before we look at everything in further detail, the video below gives a demonstration of what the simple App and basic hardware set/up can do.  Note it was filmed with an older phone, so excuse the quality and dodgy camera angles.

HC06 Bluetooth Module

This is my first foray into bluetooth, I will be looking at Bluetooth 4 (aka BLE) soon, but for now lets take a look at the HC06 bluetooth module.

MSP430 Voice Control Over Bluetooth HC06 module

The image above shows the HC06, the module is shown already soldered to a blue PCB and a connecting wire.  I purchased the whole assembly for under £3.50 including postage and packaging from Ebay.  You can also buy the module on it’s own for even cheaper, but you then need to mount it on a suitable PCB, as well as taking into account a few configuration considerations.  If you want to keep things simple then I recommend buying the same assembly as used in this tutorial.    An alternatively option if you looking for a neater Boosterpack design, is to source some parts from the 43oh website store, they sell the modules and Boosterpack PCB.  So lets look at a few specifications for the module, I have just listed the ones that are pertinent, bear in mind any module you buy may differ slightly.

  • Bluetooth protocal: Bluetooth Specification v2.0+EDR
  • Frequency: 2.4GHz ISM band
  • Emission power: ≤4dBm, Class 2 (~10 meter range)
  • Speed: Asynchronous: 2.1Mbps(Max) / 160 kbps, Synchronous: 1Mbps/1Mbps
  • Power supply: +3.3VDC 50mA (3.6V ~ 6V on-board regulator input)

The HC06 kits has six external connections, only four have header pins connected these are VCC, GND, TXD and RXD (Wakeup and State are not connected).  The TXD and RXD form the transmit and receive for a serial connection, these will be connected to the Universal Asynchronous Receiver/Transmitter (UART) on the MSP430G2553.

Hardware Set-Up

For this tutorial I kept it very simple, the demonstration uses the Launchpads on-board LED’s. The VCC and GND pins from the bluetooth module are connected to the launchpads VCC and GND pins.  TXD from the module is connected to P1.1 on the launchpad, this is the UART receive, and RXD from the module is connected to P1.2 on the launchpad, this is the UART transmit.  The image below should clarify the connections, as it shows the colour coded wire clearly.

MSP430 Voice Control Over Bluetooth HC06 module connected to Launchpad

Thats all there is to it for the hardware set-up, there was no need to add any further electronics as the potential control applications will become evident.


I was originally just playing around with the UART, and had intended to write a tutorial on this but remembered I had brought the HC06 module, so decided to dig it out.  Before I connected the module I had already tested the UART using a free terminal program called Putty running on Windows.  The MSP430 UART example programs are enough to learn the basics and get you started, the code I used is based on one of the examples.  After having great success with the initial UART tests, I then connected the bluetooth module.  To test the module I needed a similar program to Putty but running on Android, you will find dozens of terminal programs for Android just by searching the Play Store.

After some initial tests this worked fine and I had an LED switching on and off via bluetooth, all for about one hour of playing around.  It was at this point I thought wouldn’t it be cool to have voice control, my Nexus 5 supports ‘Ok Google’ for voice activation and that gave me the idea. Now I have to stress my App doe’s not support ‘Ok Google’  this is the first iteration, in fact you have to hit a button first and then speak the command.  I will write more about the Android App, but first lets go through the MSP430G2553 code.

MSP430G2553 Code

I am only going to run through the code quickly, as it can be downloaded below so will just walk through the main parts.

The first block of code deals with the watchdog and clock set/up, this also ensures the clock is calibrated, the accuracy is required for the UART operation although there is still a small margin of error due to the internal oscillator tolerance.

The GPIO’s are set-up next in lines 2 and 3, P1.1 and P1.2 are used for the UART.  In order to configure these both the GPIO function select registers need to be set to 1, this configures the pins to function with the secondary peripheral module.  If you are not familir with some of the GPIO or registry configuration commands, I would recommend you take a look at my two part MSP430 Programming Tutorial Part/1 and Part/2.  Lines 4 and 5 are used to configure P1.0 and P1.6, these are connected to the on-board LED’s, and are purely used here as a simple demonstration.

The next block of code is used to configure the Universal Serial Communication Interface (USCI), this supports multiple serial communication modes.  The MSP430G2553 has two USCI modules, USCI_A and USCI_B, USCI_A is used here in UART mode.

Starting with line 2 this configures USCI_A0 control register 1 and sets the clock source as the SMCLK.  Line 3 configures the USCI_A0 baud rate control register 0, using a value of 104.  The SMCLK is running at 1MHz, therefore 1MHz divided by 104 = 9615.4, which is almost 9600 baud. Line 4 configures the USCI_A0 baud rate control register 1, this is used for clock prescaler settings more information can be found in the family guide with relation to this.  Line 5 configures the USCI_A0 modulation control register, this parameter determines the modulation pattern, in short terms this allows extra adjustment depending on the divided clock frequency and desired baud rate.  Therefore providing a mechanism to achieve the most accurate result, with as little deviation from the desired baud rate.  Line 6 configures the USCI_A0 control register 1, this time it performs a software reset which initialises the USCI state machine.  Line 7 enables the interrupt on the USCI_A0 receive buffer.  Line 8 enables low power mode 0 which turns the CPU off and interrupts.

So now that the USCI_A is configured the processor will switch off until data is received, then when the receive buffer has a new byte of information an interrupt will be called.

The code snippet above is inside the interrupt handler for the USCI_A receive buffer.  Line 1 assigns the data inside the buffer to the variable Rx_Data, line 2 is used to wake up the CPU.

The variable Rx_Data is then used in a switch case statement to determine what has been sent over bluetooth.  The App on the phone can be programmed to send a string, but this first iterations simply converts a string into a single ASCII value, which is then sent over bluetooth. In the case of the code running on the MSP430, it is using the switch case to determine the ASCII value represented by a hexadecimal number.  The ASCII value sent and shown in line 3 is 0x41 which is a capital A, and line 4 is 0x42 which is a capital B.  So when you say the word ‘On’ the phone App translates this and sends a capital A to the HC06 bluetooth module, when you say the word ‘Off’ a capital B is sent.  There are other commands and I can and will add more, the full list currently supported is further down the tutorial.

The rest of the code shown is purely for demonstration, basically line 4 and 11 are used to disable a timer interrupt.  The timer interrupt requires disabling as the flash demo is not used if the on or off commands have been given.  Line 5 and 12 are used to change the function of pin P1.6 to a GPIO function.  Line 6 is used to turn the on-board launchpad LED’s on, and line 13 is used to turn the on-board launchpad LED’s off.

Android Voice App

I am not an Android App developer so this was put together quite quickly, literally six or so hours.  I have been testing it with the launchpad and it performs well, there were a few early teething problems but now it seems pretty solid in operation.  The App can currently only be downloaded here, I was going to upload to the Play Store but Google wanted 25$ for the privilege.  So I decided not to upload at this stage, as it may not be of any use to anyone other than me…time will tell!


I am not running through how to code the App here, just showing some screen shots of the operation with some notes, as the video should really cover this.  I have only tested this on my Google Nexus 5, so unsure if the layout will change on other phones.  If I have left any areas unclear or you have issues, leave a comment at the end of the article and I will answer as soon as I can.

Before running the App you need to enable your Bluetooth, wasn’t sure how to do this and it does not prompt you to enable it yet.

MSP430 Voice Control Over Bluetooth HC06 module Android App Not ConnectedOk the first screen capture shows the Apps main and only window, you will notice the big red text that says ‘Not Connected’ .  To connect a bluetooth device tap the blue box with the text ‘Choose BT Device’

MSP430 Voice Control Over Bluetooth HC06 module Android App Bluetooth SelectionYou will then be taken to a screen with a list of bluetooth devices, as you can see I have the HC06 device listed.  To select the device just tap on the listed device.  The HC06 module has a small LED on the board, this flashes when not connected, becoming solid once the device is connected.  If its your first time connecting you will need to pair the devices, the most common password used for the HC06 seems to be ‘1234’.

MSP430 Voice Control Over Bluetooth HC06 module Android App ConnectedAfter a few seconds the screen will return to the main window, and you should notice the red text has now changed green and reads ‘Connected’.  You will notice directly below this text is more black text which says ‘Captured Speech = ?’, this indicates no speech has been captured. By pressing the orange button which says ‘Press Then Give Voice Command’, you will enter the speech capture mode.

MSP430 Voice Control Over Bluetooth HC06 module Android App Capture ModeThe capture mode is just Google’s Speech to Text, this as the name suggests will convert your speech to text.

MSP430 Voice Control Over Bluetooth HC06 module Android App Unaccepted Code WordThe next screen shot demonstrates the captured speech being displayed, this is not a recognised command word shown, it could be in future though.  I have left all words displayed as if Google’s application has misidentified your speech, it’s better to know where the error lies. I guess I could have the recognised word change green for a valid command and red for an invalid one, so will maybe implement that at a future date.  You can disconnect the bluetooth device any time by pressing the red button labelled ‘Disconnect BT’.

A few of the commands supported are as follows:

  • on‘ command then generates a capital A and sends over bluetooth or hex 0x41
  • off‘ command then generates a capital B and sends over bluetooth or hex 0x42
  • flash‘ command then generates a capital C and sends over bluetooth or hex 0x43
  • 1‘ command then generates the number 1 and sends over bluetooth or hex 0x31
  • 2‘ command then generates the number 2 and sends over bluetooth or hex 0x32
  • 3‘ command then generates the number and sends over bluetooth or hex 0x33
  • 4‘ command then generates the number 4 and sends over bluetooth or hex 0x34
  • 5‘ command then generates the number 5 and sends over bluetooth or hex 0x35

I will probably add forward, backward, left, right and a few other obvious command words.

MSP430G2553 C 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 Voice Control Over Bluetooth MSP430G2553 C Code

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.

Android App BT_Voice_MCU.apk

**Update 18/01/2015 the Android App has been updated and now includes some additional commands, for a full list see this Excel file, the link below has also been updated.

The link below contains the zip file with the full Android App.apk file, 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.  I guess I need to put some sort of disclaimer here as this is a phone App, and untested on any other phone except my Nexus 5, but it appears 100% stable and has not caused any issues.  If you download and use this App, I am not responsible for any issues you may encounter so you do so at your own risk.


*Original* – MSP430 Voice Control Over Bluetooth BT_Voice_MCU Android App

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 Launchpad used as a programmer


In this MSP430 Launchpad used as a programmer tutorial, the MSP430 Launchpad board will be used to program a MSP430G2230 microcontroller.  The MSP430G2230 is an 8 pin microcontroller and comes in a Small Outline Integrated Circuit package (SOIC), so offers the developer the chance to reduce the overall footprint of the project on a budget.  As the MSP430G2230 comes in a SOIC package, for prototyping it’s often easier to increase the package size, which allows more conventional and off the shelf components to be used during the development stage.  Texas Instruments sells a Dual In-Line Package or DIP adaptor PCB, the image below shows the board and it can also be found here.

MSP430 Launchpad used as a Programmer for MSP430G2230 DIP Adaptor evaluation PCB

It is also possible to buy these from other vendors or even make them yourself, the next few images shows the MSP430G2230 soldered on to the Texas Instruments SOIC to DIP evaluation PCB.  Also shown is a PCB I manufactured for an ADS118IDGST 16bit ADC, which is a Micro Small Outline Package (MSOP-10), this was covered in an earlier Stellaris tutorial which can be found here.

MSP430 Launchpad used as a Programmer for MSP430G2230 DIP Adaptor and own MSOP-10 adaptor topMSP430 Launchpad used as a Programmer for MSP430G2230 DIP Adaptor and own MSOP-10 adaptor side

So once the MSP430G2230 is more accessible in a DIP package, it can be easily used on some vero-board or even a breadboard set-up.

The nest step is setting up the MSP430G Launchpad board so it can be used to program the MSP430G2230, this is a very simple process and involves the removal of the existing microcontroller.  There are only four pins used for programming and I used some breadboard which allowed easy wire connections.  The next image shows the four GPIO pins used and the corresponding pins on the Launchpad board.

MSP430 Launchpad used as a Programmer for MSP430G2230 pinout connections


As the image shows the DIP converted MSP430G2230 pins don’t directly align with the Launchpad, hence the need for the bread board.  So once the MSP430G2230 is wired up to the Launchpad board, a programme can be flashed from Code Composer Studio (CCS).  I wrote a small program to flash an LED which I connected to pin two on the MSP430G2230 or GPIO P1.2, this allowed me to verify the set-up so further development could progress.  The video below demonstrates the whole set-up in operation, the code has already been downloaded at this stage.

MSP430G2230 Simple Blinky 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.

MSP430G2230 Test Code


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 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.

EagleCad Tutorial Grid Size Unit Setting


The EagleCad Tutorial Grid Size Unit Setting will cover how to edit the EagleCad eagle.scr script file.  If you use EagleCad and find you want to use Mils or mm, or simple want to change the default grid settings, then this tutorial will show you how.  There is also some basic information on this on the EagleCad FAQ’s page located here.

This tutorial will concern itself with the eagle.scr script file, this deals with settings for the layouts, schematics and libraries.  There are two other script files called eagle.epf and a user specific eagler.usreagle.epf saves all the settings during work and eagle.usr contains user specific and global settings not associated with layouts, schematics and libraries, but things like window settings for example.

Before we go any further I use the mm setting mainly as I deal with metric measurements the majority of the time, I have access to a LPKP milling machine and all the drill bits are metric.  It is worth bearing in mind if you intend to send your Gerber files to a PCB fabrication house, ensure you are working within their requirements and tolerances.

The image below shows a screen capture of my EagleCad version 7 installation, the location for the script file can be seen as C:\EAGLE-7.0.0\scr\eagle.scr.  The location is the same for version 6 and I believe other versions as well, just the root EagleCad folder maybe different.

EagleCad Tutorial Grid Size Unit Setting eagle.scr file location

The next image shows the Eaglcad eagle.scr file opened in Notepad++, with the grid settings for the SCH (schematic) highlighted on line 16 (click to enlarge).  Also note the BRD (board) grid setting on line 10, this uses lines instead of dots.

EagleCad Tutorial Grid Size Unit Setting eagle.scr file open in NotePad++

So what does GRID MM 2.54 DOTS ON ALT MM 0.3175 actually mean, well you have probably guessed most of it already, but I will run through the meaning:

  • GRID – Specifies the grid command and the current unit which is MM
  • 2.54 – Sets the grid size to 2.54mm
  • DOTS – Sets the grid to be displayed as dots, LINES is an alternative option
  • ON – Sets the grid on as soon as you enter the schematic mode
  • ALT – Defines the alternate grid
  • MM – Sets the alternate units in this case to mm
  • 0.3175 – Sets the alternate grid size to 0.3175mm


The next image shows the result of this setting after the eagle.scr file were saved and EagleCad restarted and the schematics mode entered.

EagleCad Tutorial Grid Size Unit Setting eagle.scr gride size edited and saved

EagleCad also has a handy help file that gives you all these settings, as well as a few additional ones not mentioned.  Simply enter the help mode and search for grid, a screen capture of the help article is posted below.

EagleCad Tutorial Grid Size Unit Setting help file grid

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.

C2000 Solar MPPT Tutorial Pt/4


In this fourth and final part of the C2000 Solar MPPT Tutorial, the system set-up and testing will be looked at.  This will involve the overall hardware set-up for testing, ADC calibration, reduction of noise on the ADC sampling, efficiency test and some improvements for future iterations.  The final C2000 solar MPPT tutorial C code is also downloadable at the bottom of the page.

System Testing

Once the hardware was calculated and designed, the PCB was laid out and then printed using the freeware version of EagleCad.  The PCB was then printed on a LPKF milling machine, the finished component side of the PCB can be seen in the image below.

C2000 Solar MPPT Tutorial PCBThe board was given a thorough visual check, it was noted some of the drill holes on the component side were marginally out of alignment.  This is due to a slight misaligned of the milling machine alignment pins, the bottom of the PCB is milled first and then flipped so the component side can be milled.  When the board is flipped the minor misaligned becomes apparent, it is not enough to cause an issue, but I manually make all my own footprints allowing for the small idiosyncrasies and tolerances of the milling machine.

The components used for the design were mainly sourced from the education institution stock, with only the INA138 being ordered in.  This reduced any unwanted lead times and also keeps costs down.  There are down sides to this which were found with the IRFI640G MOSFETs.  The mistake was made of soldering these directly onto the PCB without checking the MOSFETs first, they were sourced from a large bag of perhaps 500 or more IRFI640G, all previously reclaimed from other boards.  Once the board was constructed it was noted the power supply was going straight into over current protection, this was narrowed down to two faulty MOSFETs that were short circuit, between Drain and Source.  A quick on the fly test I used to check the MOSFETs can be seen in the image below.

C2000 Solar MPPT Tutorial MOSFET Testing

System Calibration

Once the board was working, the next step was to test the buck circuits under controlled conditions,  The test involved the C2000 being set-up to supply a fixed PWM output of 50% duty cycle on PWM1, with PWM2 180o out of phase.  A dummy load in the shape of a 100W potentiometer set to 50Ω was connected to the output terminal, with a 20V supply applied to the solar panel input pins.  A multimeter was used to then measure the output DC voltage, which was observed to be 10V, this confirmed the buck circuit was operating correctly, the 20V was adjusted down to approximately 15V and the voltage was observed to half on the output.

After this initial test the ADC values being sampled needed to be calibrated, this would involve measuring the input voltage and current as well as the output voltage and current.  To achieve this to a good accuracy the same test conditions were used and two Hewlett Packard 34401A multimeter’s.  Some constant values were calculated from the signal conditioning circuitry (see the second part of this tutorial here) used to sample the ADC values, these were calculated as follows.

C2000 solar MPPT Tutorial ADC Constant Equations

These values would then need to be adjusted to meet the tolerances of the circuit.  A laptop was also set-up running Code Composer Studio (CCS) and the calculated ADC variables were viewed, and then the constant calculations values altered until the accuracy was satisfactory. The actual ADC constant values used can be seen in the below code snippet

Various test were carried out at this point to see how the ADC calibration and sampling was working, experimenting with sample and hold times, over sampling.  A useful tool is the graphing feature in CCS this allows trends to be observed in variables.  The original set-up used a timer to trigger the ADC sampling, however this generated more noise due to the MOSFET switching, so the PWM was used to trigger the ADC SOC.


The next image shows a screen capture from CCS, with the debug mode in operation.  The MPPT circuit was supplied with 17.5V from a regulated power supply, the load potentiometer was set to 40Ω, a PWM frequency of 25kHz (not 15kHz) with a 50% duty cycle was used in an open loop configuration.

C2000 Solar MPPT Tutorial 25kHz_25SH

What this graphed data shows is a 2 minute sample window (click the image to expand), the top graph is the input current with a variation of 2.4mA, and the bottom graph input volts with a variation of 10mV.  At the top right of the graph the ADC input variable values can also be seen, the two highlighted in yellow just indicates the value has just changed.

Efficiency Test

This basic efficiency calculation test was made by graphing the the input and output power under different power conditions.  The power efficiency fluctuated between 85~93%, with the greatest efficiency being achieved towards mid-range power.  The graphed data can be seen below with the input power at the top and the output power at the bottom.

C2000 solar MPPT Tutorial Power Efficiency Graph


This was a prototype design and the first attempt at a solar MPPT, as such there are some improvements that can be made for future iterations.

On the software side, the clock speed for the C2000 could be reduced as there is plenty of idle time, the processor could also be placed into a low power mode between timer interrupts, this would bring an overall reduction in power dissipation.  Additionally a battery charging statement machine could be easily added, with a further form of regulation to switch between full charge and float charge.  If the circuit did not require an interleaved design, the code structure and algorithm could be easily ported across to a lower power and less expensive microcontroller like an MSP430G series.

On the hardware, the MOSFETs are key components that could be changed making the system more efficient.  Greater use of surface mount devices would reduce the circuit trace lengths and noise.  An improved ground plan design would also help reduce noise.  The trace lengths for each circuit phase ideally need to be identical, this will help to balance the phases.  It is possible to sample the current in each phase, then use software to adjust the duty cycle to correct any imbalances, however this increases the overall systems complexity particularly the software.

C2000 Solar MPPT Tutorial C Code Download

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.

C2000 Solar MPPT Tutorial Full C Code

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.

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.

C2000 Solar MPPT tutorial Pt/2


In this second part of the C2000 Solar MPPT Tutorial, the hardware and circuit design will be looked at in greater depth.  The schematic for the system is posted again below for reference, which can be enlarged by simply clicking on it.

C2000 Solar MPPT Tutorial PWM and MPPT update frequency zoomed hardware schematic

Buck Converter Design

The first step was to design the buck circuit, this is determined by the output parameters of the system and it’s load.  For the first prototype based around the panel purchased for testing, it was decided to aim for a 12V output, therefore a maximum current of 750mA (assuming 10% losses).

When calculating a buck circuit the frequency of operation, inductor size and output capacitor size are important, as they determine the current and voltage ripple size.  It is desirable to have as smaller current and voltage ripple as possible.  A large current ripple can cause additional losses in a system, as there maybe times when the peak current is greater than the load requirements.  A large voltage ripple is obviously not desirable, good quality regulated power supplies have very low voltage ripples.

A general rule is the higher the frequency the smaller the inductor and output capacitor size, and a smaller inductor and capacitor size generally lowers the system cost.  However higher PWM frequencies decrease the system efficiency due to switching losses in the mosfets, so a trade off has to be reached which meets the design constraints of the end system.

For this system a PWM frequency of 15kHz was chosen, based on this, the solar panel and other design parameters for the buck circuit calculations can be performed.  First we can determine the system duty cycle at MPP, note the duty cycle will change to track the MPP with differing irradiance.  A figure of 90% was used for the buck converter efficiency,a typically buck converter efficiency is 90% or greater.

C2000 Solar MPPT Tutorial duty cycle equation

Next an ideal current ripple can be determined, it is important to note that the below formulae used only determines a single phase current ripple.

C2000 Solar MPPT Tutorial current ripple equation

ΔIL is the inductor ripple current, and in this case a 30% figure was used for the multiplier. Now that the current ripple is know the inductor size can be calculated with the following equation.

C2000 Solar MPPT Tutorial inductor size equation

Using two 1.34mH inductors on each phase will ensure the inductor ripple current is effectively halved, knowing this an inductor ripple current of 90mA can be used to calculate the minimum output capacitor size.

C2000 Solar MPPT Tutorial output capacitor size equation

Δvout is the desired ripple voltage.  The constant 8 is determined by the simplification of an equation, which can be found in various sources, one such source is an Application Note by On-Semiconductor AND9135/D.

There are two other factors for the inductor and capacitor that are important to consider: the inductor peak current and the capacitors Equivalent Series Resistance (ESR).  The inductor for this project will be hand wound using a toroidal core, which will be covered shortly.  The capacitors ESR can affect the reliability of the capacitor.  A capacitor will dissipate power as heat depending on it’s ESR, so a low ESR is desirable as excessive heating will shorten the life of a capacitor and be less efficient.  For this early prototype, cheap off the shelf capacitors were used as their reliability over time was not a concern at this stage.

The inductors were constructed using a T68-26A toroidal core, this core has a nominal inductance or Al value of 58nH.  The following equation was used to determine how many turns of wire the core would need.

C2000 Solar MPPT Tutorial inductor turns ratio equation

A 0.3mm outside diameter enamelled cable was chosen, this has a maximum current rating of 1.4A.  Then a very useful website found here was used, this allows you to calculate the total length of cable required based on the toroidal core dimensions and cable diameter. Using a vice the cores were both wound and then measured using a LCR meter and measured at 1.3mH, an image below shows the hand winding process used.

C2000 solar MPPT toroidal inductor core winding


For the prototype system Vishay IRFI640G MOSFETs were used, these are not the most efficient having a high RDSON value (180mΩ), but they were stocked at the time of writing.

The power losses from the High Side and Low Side MOSFETs are a combination of conduction and AC switching losses.  The conduction losses are a result of I²R losses inside the MOSFET when it is fully on, and the switching losses are the result of the MOSFET transitions from its on and off states.  Some example calculations will now be shown using data from the IRFI640G datasheet and various sources, on a synchronous MOSFET buck circuit efficiency.

C2000 Solar MPPT Tutorial switching losses legend

The first equation is for the High Side MOSFET and is based on the Vmp of the solar panel at maximum output current running through each interleaved phase.

C2000 Solar MPPT Tutorial High Side losses equation

The next equation is for the Low Side MOSFET using the same current figure.

C2000 Solar MPPT Tutorial Low Side losses equationThe results from these two equations can be combined to work out the overall efficiency, the losses will also be multiplied by a factor of 2 as this is for a two phase interleaved circuit.

C2000 Solar MPPT Tutorial 15kHz Power losses equation

Now if we increase the PWM frequency to 150kHz, the circuit losses will also be shown to increase.

C2000 Solar MPPT Tutorial 150kHz Power losses equation

The switching losses in this next example will be shown to increase with increasing current, the next example uses a 15kHz switching frequency but with 2A, increasing the overall power to 24W.

C2000 Solar MPPT Tutorial 15kHz at 2A Power losses equation

A MOSFET with a lower RDS(ON) will have lower conduction losses, but it will typically have a higher QG (Gate Charge) resulting in higher switching losses.  Therefore a careful balance between these characteristics should be found to maximise the circuits efficiency.  Taking into account the nominal parameters of the system, such as input voltage, output current, switching frequency and duty cycle, will allow the best efficiency to be achieved.  This will often involve using MOSFETs with different characteristics for the High and Low Side drivers.


MOSFET Driver Circuit

The Half-Bridge (H-Bridge) driver is an IC designed specifically for driving MOSFETs. The IC takes the incoming PWM signal, and then drives two outputs for a High and a Low Side MOSFET.  This type of H-bridge is often used to to drive motors, but has other applications such as the following example.  The IC used is a IRS2003 half bridge driver made by International Rectifier, the image below shows an example circuit from the datasheet.

C2000 Solar MPPT Tutorial IRS2003 example circuit

The IRS2003 allows 2 PWM signals to be connected to HIN and LINNot this gives the user the opportunity to fine tune the dead-band switching of the MOSFETs.  The capacitor wired between VB and VS along with the diode form a charge pump, this allows the drive voltage to the MOSFETs to be almost doubled.  HIN and LINNot in this case are wired together and supplied with the same PWM signal, the IRS2003 has internal timing to ensure the High Side MOSFET, and the Low Side MOSFET are never on at the same time.  The capacitor between VB and VS needs to be sized to ensure it can drive enough current to the gate of the chosen MOSFET, over coming the gate capacitance.

ADC Feedback Circuits

There are four ADC ports used on this project, two sampling voltage and two sampling current.  The hardware employed to sample the voltage signals will be covered first, followed by the current sampling circuit.  But first a brief introduction to the TMS320F28027 ADC.

The ADC measures voltage from 0V to 3.3V, with a 12bit resolution.  It is important to not exceed the input voltage of the microcontrollers GPIO pins, the TMS320F28027 has a maximum input voltage of 3.63V.  Using this information the step resolution for the ADC can be calculated.

C2000 Solar MPPT Tutorial ADC resolution equation

The input on the ADC also has a small internal capacitance and resistance, this is used for Sample and Hold acquisition depending on the characteristics of the circuit being sampled. The internal ADC circuit taken from the TMS320x2802x datasheet is shown below.

C2000 Solar MPPT Tutorial internal ADC S-H

To ensure the readings being sampled are as accurate as possible, the source resistance or RS shown in the above image ideally needs to be as small as possible.  This will be achieved by placing an opamp configured as a unity gain buffer in all the ADC sample circuits.  The unity gain buffer will ensure a high input impedance, therefore reducing loading effects on the sampled circuitry to a minimum, as well as offering a very low output impedance to the C2000 internal ADC circuit.  Rail to rail opamps were used and supplied with 3.3V, this ensured the voltage passed to the ADC would not exceed this, thus ensuring the system has ADC protection built in.

The voltage sampling circuits consist of a simple potential divider, the maximum voltage the solar panel can produce is 21.6V when open circuit.

C2000 Solar MPPT Tutorial voltage potential divider equation

The same resistor and opamp configuration is used for the input and output voltage measurement.  A more complex opamp circuit could have been used with offset, to fully exploit the range of the ADC, however this would provide more than enough accuracy for the prototype.

The current sampling circuit involved a slightly more complex approach.  The circuit would revolve around a Texas Instruments INA138 High Side Measurement current shunt monitor. The INA138 is basically a differential amplifier housed inside a small package, with a wide operating voltage.  The INA138 would be supplied with 12V, this then allows for a greater range to be measured around the 0V-3.3V range and was also the second supply voltage available for this circuit.  A typical configuration taken from the datasheet is shown in the image below.

C2000 Solar MPPT Tutorial INA138 typical circuit

There are differences in input and output current so two formulas would be needed to ensure the range was correct.  The shunt resistors comprised of two 1Ω (1%) resistors in parallel, so the combined value becomes 0.5Ω.  The parallel resistors were measured and the actual value was approximately 0.47Ω.  A quick calculation to check these could withstand the power loads was made.

C2000 Solar MPPT Tutorial shunt resistor power equation

This was not the best long term solution, but within tolerance for the 1% resistors in parallel.

The shunt resistor is connected directly across the internal differential amplifiers inputs. The calculations for the INA138 are fairly simple, the gain resistor soldered externally determines the overall gain of the device.  The datasheet for the INA138 states that the device has a gain of 1 with a 5kΩ resistor, gain of 2 with a 10kΩ, gain of 5 with a 25kΩ and so on and so forth. The input and output current gain resistors were calculated as follows.

C2000 Solar MPPT Tutorial INA138 gain resistors equation

These values would ensure the output from both the current feedback circuits falls in-line with the ADC input.

Schematic Design and Layout

Certain aspects of the design were simulated in OrCad 16.6 first, to back-up the theory with simulation.  Then the design was taking over to EagleCad to enable faster prototyping.  Component symbols and foot prints where designed for all the non standard parts, ensuring these were all compatible with the LPKF milling machine used.  Once the schematic design was complete and the Electrical Rule Check (ERC) and Design Rule Check (DRC) were satisfactory, a schematic design was made for a two layer board.  The layout kept the PWM and digital switching side and analogue circuitry away from each other to avoid unnecessary noise.  The below image shows the final PCB prototype layout.

C2000 Solar MPPT Tutorial PCB layout

The next part of this tutorial will go more in-depth into the C2000 software and Perturb and Observe algorithm, also including a downloadable version of the C code.

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.