Getting Started With The Msp430 Launchpad: Student Guide and Lab Manual
Getting Started With The Msp430 Launchpad: Student Guide and Lab Manual
Getting Started With The Msp430 Launchpad: Student Guide and Lab Manual
MSP430 LaunchPad
Student Guide and Lab Manual
Revision 2.22a
July 2013
Technical Training
Organization
Important Notice
Important Notice
Texas Instruments and its subsidiaries (TI) reserve the right to make changes to their products or to
discontinue any product or service without notice, and advise customers to obtain the latest version of
relevant information to verify, before placing orders, that information being relied on is current and
complete. All products are sold subject to the terms and conditions of sale supplied at the time of order
acknowledgment, including those pertaining to warranty, patent infringement, and limitation of liability.
TI warrants performance of its semiconductor products to the specifications applicable at the time of sale in
accordance with TI’s standard warranty. Testing and other quality control techniques are utilized to the
extent TI deems necessary to support this warranty. Specific testing of all parameters of each device is not
necessarily performed, except those mandated by government requirements.
In order to minimize risks associated with the customer’s applications, adequate design and operating
safeguards must be provided by the customer to minimize inherent or procedural hazards.
TI assumes no liability for applications assistance or customer product design. TI does not warrant or
represent that any license, either express or implied, is granted under any patent right, copyright, mask
work right, or other intellectual property right of TI covering or relating to any combination, machine, or
process in which such semiconductor products or services might be or are used. TI’s publication of
information regarding any third party’s products or services does not constitute TI’s approval, warranty or
endorsement thereof.
Revision History
Oct 2010 – Revision 1.0
June 2011 – Revision 1.30 update to include new parts
August 2011 – Revision 1.31 fixed broken hyperlinks, errata
August 2011 – Revision 1.40 added module 8 CapTouch material
September 2011 –Revision 1.50 added Grace module 9 and FRAM lunch session
September 2011 –Revision 1.51 errata
October 2011 –Revision 1.52 added QR codes
October 2011 –Revision 1.53 errata
January 2012 –Revision 2.0 update to CCS 5.1 and version 1.5 hardware
February 2012 –Revision 2.01 minor errata
February 2013 –Revision 2.10 price change, update to CCS5.3, minor errata
May 2013 –Revision 2.20 updated CapTouch chapter; added Energia chapter
July 2013 –Revision 2.22 re-added Energia chapter
Mailing Address
Texas Instruments
Training Technical Organization
6550 Chase Oaks Blvd
Building 2
Plano, TX 75023
Workshop Agenda
► Introduction to Value Line
Code Composer Studio
Initialization and GPIO
Analog-to-Digital Converter
Interrupts and the Timer
Low-Power Optimization
Serial Communications
Grace
FRAM
Capacitive Touch
Using Energia (Arduino)
http://www.ti.com/msp430
For future reference, the main Wiki for this workshop is located here:
http://processors.wiki.ti.com/index.php/Getting_Started_with_the_MSP430_LaunchPad_Workshop
Getting Started with the MSP430 LaunchPad - Introduction to Value Line 1-1
Chapter Topics
Chapter Topics
Introduction to Value Line .......................................................................................................... 1-1
Chapter Topics .......................................................................................................................... 1-2
Introduction to Value Line ......................................................................................................... 1-3
TI Processor Portfolio............................................................................................................ 1-3
MSP430 Released Devices .................................................................................................. 1-3
MSP430G2xx Value Line Parts ............................................................................................ 1-4
MSP430 CPU ........................................................................................................................ 1-4
Memory Map ......................................................................................................................... 1-5
Value Line Peripherals .......................................................................................................... 1-6
LaunchPad Development Board ........................................................................................... 1-7
Lab 1: Download Software and Setup Hardware ...................................................................... 1-8
Objective ............................................................................................................................... 1-8
Verify That You Have Installed the Following: ...................................................................... 1-8
Download Checklist................................................................................................................... 1-9
MSP-EXP430G2 LaunchPad Experimenter Board ............................................................. 1-11
Hardware Setup .................................................................................................................. 1-11
Running the Application Demo Program............................................................................. 1-12
1-2 Getting Started with the MSP430 LaunchPad - Introduction to Value Line
Introduction to Value Line
Getting Started with the MSP430 LaunchPad - Introduction to Value Line 1-3
Introduction to Value Line
MSP430 CPU
1-4 Getting Started with the MSP430 LaunchPad - Introduction to Value Line
Introduction to Value Line
Memory Map
Memory Map
MSP430G2553 shown
Flash programmable via JTAG or 0FFFFh Interupt Vector Table
In-System (ISP) 0FFE0h
FFDFh Flash
ISP down to 2.2V. Single-byte or
Word 0C000h
Interruptible ISP/Erase
Main memory: 512 byte segments 010FFh Information
(0-n). Erasable individually or all 01000h Memory
Information memory: 64 byte
segments (A-D)
Section A contains device-specific 03FFh RAM
calibration data and is lockable 0200h
Programmable Flash Memory 01FFh 16-bit
Timing Generator Peripherals
0100h
0FFh 8-bit
Peripherals
010h
0Fh 8-bit Special
Function
Registers
0h
Getting Started with the MSP430 LaunchPad - Introduction to Value Line 1-5
Introduction to Value Line
1-6 Getting Started with the MSP430 LaunchPad - Introduction to Value Line
Introduction to Value Line
Getting Started with the MSP430 LaunchPad - Introduction to Value Line 1-7
Lab 1: Download Software and Setup Hardware
Then we will review the contents of the MSP430 LaunchPad kit and verify its operation with the
pre-loaded demo program. Basic features of the MSP430 LaunchPad running the
MSP430G2553 will be explored.
Specific details of Code Composer Studio will be covered in the next lab exercise. These
development tools will be used throughout the remaining lab exercises in this workshop.
1-8 Getting Started with the MSP430 LaunchPad - Introduction to Value Line
Download Checklist
Download Checklist
Integrated Development Environments (IDE)
Energia ( port of Arduino) http://energia.nu/download
Code Composer Studio v5.4 http://processors.wiki.ti.com/index.php/Download_CCS
You can download either the web installer or offline installer. The web installer is smaller, but the off-line
installer is more flexible. If you have a fast internet access, we suggest the off-line installer.
Clicking the link for either installer, you will be directed to log in (or create a free) my.TI account. Then,
once you agree to the export conditions you will either be e-mailed a link or be directed to a web page with
the link.
Warning – If you use the Web Installer, you must have internet access during installation.
Getting Started with the MSP430 LaunchPad - Introduction to Value Line 1-9
Download Checklist
Additional information:
• www.ti.com/launchpadwiki
• www.ti.com/launchpad
• www.ti.com/captouch
• Capacitive Touch Library
2. Look on the side of your LaunchPad kit and find the revision number.
At the time this workshop was written, version 1.5 is the current version. The steps in this
workshop are only tested for verrsion1.5, but most likely will work with v1.4..
Open the MSP430 LaunchPad kit box and inspect the contents. The kit includes:
− LaunchPad emulator socket board (MSP-EXP430G2)
− Mini USB-B cable
− MSP430G2553 (pre-installed and pre-loaded with demo program)
− An extra processor, the MSP430G2452
− 10-pin PCB connectors are soldered to the board; two female are also included
− 32.768 kHz micro crystal (not soldered to the board)
− Quick start guide and two LaunchPad stickers
Hardware Setup
The LaunchPad experimenter board includes a pre-programmed MSP430 device which is already
located in the target socket. When the LaunchPad is connected to your PC via USB, the demo
starts with an LED toggle sequence. The on-board emulator generates the supply voltage and all
of the signals necessary to start the demo.
3. Connect the MSP430 LaunchPad to your PC using the included USB cable.
The driver installation starts automatically. If prompted for software, allow Windows to install
the software automatically.
4. At this point, the on-board red and green LEDs should toggle back and forth.
This lets us know that the hardware is working and has been set up correctly.
You’re done.
Agenda
12
Getting Started with the MSP430 LaunchPad - Code Composer Studio 2-1
Module Topics
Module Topics
Code Composer Studio ..............................................................................................................................2-1
Module Topics..........................................................................................................................................2-2
Code Composer Studio ............................................................................................................................2-3
Lab 2: Code Composer Studio .................................................................................................................2-7
Objective..............................................................................................................................................2-7
Procedure .............................................................................................................................................2-8
Optional Lab Exercise – Crystal Oscillator...........................................................................................2-14
Objective............................................................................................................................................2-14
Procedure ...........................................................................................................................................2-14
2-2 Getting Started with the MSP430 LaunchPad - Code Composer Studio
Code Composer Studio
Getting Started with the MSP430 LaunchPad - Code Composer Studio 2-3
Code Composer Studio
Project Wizard…
16
2-4 Getting Started with the MSP430 LaunchPad - Code Composer Studio
Code Composer Studio
Getting Started with the MSP430 LaunchPad - Code Composer Studio 2-5
Code Composer Studio
2-6 Getting Started with the MSP430 LaunchPad - Code Composer Studio
Lab 2: Code Composer Studio
Getting Started with the MSP430 LaunchPad - Code Composer Studio 2-7
Lab 2: Code Composer Studio
Procedure
Note: CCS5.x should have already been installed during the Lab1 exercise.
This folder contains all CCS custom settings, which includes project settings and views
when CCS is closed, so that the same projects and settings will be available when CCS is
opened again. It also contains a list of your current projects. The workspace is saved
automatically when CCS is closed.
2-8 Getting Started with the MSP430 LaunchPad - Code Composer Studio
Lab 2: Code Composer Studio
2. The first time CCS opens, the “License Setup Wizard” should appear. In case you started
CCS before and made the wrong choices, you can open the wizard by clicking Help
Code Composer Studio Licensing Information then click the Upgrade
tab and the Launch License Setup… .
If you’re planning on working with the LaunchPad and value-line parts only, the
CODE SIZE LIMITED version of Code Composer with its 16kB code size limit will
fully support every chip in the family.
If you are attending another workshop in conjunction with this one, like the Stellaris
LaunchPad workshop, you can return here and change this to the FREE LICENSE
version. This license is free when connected to the Stellaris LaunchPad (and many other
boards), but not the MSP430 LaunchPad board. When not connected to those boards, you
will have 30 days to evaluate the tool, but you can extend that period by 90 days.
Select the CODE SIZE LIMITED radio button and click Finish.
You can change your CCS license at any time by following the steps above.
Getting Started with the MSP430 LaunchPad - Code Composer Studio 2-9
Lab 2: Code Composer Studio
3. You should now see the open TI Resource Explorer tab open in Code Composer.
The Resource Explorer provides easy access to code examples, support and Grace2™.
Grace2™ will be covered in a later module. Click the X in the tab to close the
Resource Explorer.
4. At this point you should see an empty CCS workbench. The term workbench refers to
the desktop development environment. Maximize CCS to fill your screen.
The workbench will open in the “CCS Edit” view. Notice the tab in the upper right-hand
corner. A perspective defines the initial layout views of the workbench windows,
toolbars, and menus which are appropriate for a specific type of task (i.e. code
development or debugging). This minimizes clutter to the user interface. The “CCS
Edit” perspective is used to create or build C/C++ projects. A “CCS Debug” perspective
will automatically be enabled when the debug session is started. This perspective is used
for debugging your projects. You can customize the perspectives and save as many as
you like.
Make the selections shown below (your dialog may look slightly different than this one).
If you are using the MSP430G2231, make the appropriate choices for that part. Make
sure to click Empty Project (with main.c) and then click Finish.
6. Code Composer will add the named project to your workspace and display it in the
Project Explorer pane. Based on your template selection, it will also add a file
called main.c and open it for editing. Click on Temperature_Sense_Demo in the
Project Explorer pane to make the project active. Click on the left of the project name
to expand the project.
Source Files
7. Next, we will add code to main.c. Rather than create a new program, we will use the
original source code that was preprogrammed into the MSP430 device (i.e. the program
used in Lab1).
Open the Temperature_Sense_Demo.txt file. Copy and paste its contents into
main.c, erasing the original contents of main.c, then close the
Temperature_Sense_Demo.txt file.
Near the top of the file, note the statement
#include “msp430g2553.h”
If you are using an earlier revision of the board, change this statement to:
#include “msp430g2231.h”
Be sure to save main.c by clicking the Save button in the upper left.
Click on the “Debug” button . When the Ultra-Low-Power Advisor (ULP Advisor)
appears, click the Proceed button. We’ll take a look at the MSP430’s ultra-low-power
abilities in a later lab.
When the download completes, CCS is in the Debug perspective. Notice the Debug tab
in the upper right-hand corner indicating that we are now in the “CCS Debug” view.
Click and drag the perspective tabs to the left until you can see all of both tabs. The
program ran through the C-environment initialization routine in the runtime support
library and stopped at main() in main.c.
Debug Environment
9. The basic buttons that control the debug environment are located in the top of the Debug
pane. If you ever accidentally close the pane, your Debug controls will vanish. They can
be brought back by clicking View Debug on the menu bar.
11. Click Suspend . The code should stop somewhere in the PreApplicationMode()
function.
12. Next single-step (Step Into) the code once and it will enter the timer ISR for
toggling the LEDs. Single-step a few more times (you can also press the F5 key) and
notice that the red and green LEDs alternate on and off.
13. Click Reset CPU and you should be back at the beginning of main().
Procedure
Solder Crystal Oscillator to LaunchPad
1. Very carefully solder the included clock crystal to the LaunchPad board. The crystal
leads provides the orientation. They are bent in such a way that only one position will
have the leads on the pads for soldering. Be careful not to bridge the pads. The small size
makes it extremely difficult to manage and move the crystal around efficiently so you
may want to use tweezers and tape to arranging it on the board. Be sure the leads make
contact with the pads. You might need a magnifying device to insure that it is lined up
correctly. You will need to solder the leads to the two small pads, and the end opposite
of the leads to the larger pad.
Click this link to see how one user soldered the crystal to their board:
http://justinstech.org/2010/07/msp430-launchpad-dev-kit-how-too/
Open the Verify_Crystal.txt file. Copy and paste its contents into main.c,
erasing all the previous contents of main.c. Then close the Verify_Crystal.txt
file – it is no longer needed.
5. Click the “Debug” button When the Ultra-Low-Power Advisor (ULP Advisor)
appears, click the Proceed button. The “CCS Debug” view should open, the program will
load automatically, and you should now be at the start of main().
6. Run the code. If the crystal is installed correctly the red LED will blink slowly. (It
should not blink quickly). If the red LED blinks quickly, you’ve probably either failed to
get a good connection between the crystal lead and the pad, or you’ve created a solder
bridge and shorted the leads. A good magnifying glass will help you find the problem.
You’re done.
Agenda
Reset State …
21
Getting Started with the MSP430 LaunchPad - Initialization and GPIO 3-1
Module Topics
Module Topics
Initialization and GPIO .............................................................................................................................3-1
Module Topics..........................................................................................................................................3-2
Initialization and GPIO ...........................................................................................................................3-3
Reset and Software Initialization .........................................................................................................3-3
Clock System .......................................................................................................................................3-4
G2xxx - No Crystal Required - DCO ..................................................................................................3-4
Run Time Calibration of the VLO .......................................................................................................3-5
System MCLK & Vcc .........................................................................................................................3-5
Watchdog Timer ..................................................................................................................................3-6
Lab 3: Initialization and GPIO ................................................................................................................3-7
Objective..............................................................................................................................................3-7
Procedure .............................................................................................................................................3-8
3-2 Getting Started with the MSP430 LaunchPad - Initialization and GPIO
Initialization and GPIO
Software Initialization
Clock System …
23
Getting Started with the MSP430 LaunchPad - Initialization and GPIO 3-3
Initialization and GPIO
Clock System
Clock System
Very Low Power/Low Frequency VLO
Oscillator (VLO)*
4 – 20kHz (typical 12kHz) Min. Puls ACLK
Filter Peripherals
500nA standby
0.5%/ C and 4%/Volt drift
Not in ’21x1 devices OSC_Fault MCLK
Crystal oscillator (LFXT1) CPU
Programmable capacitors
Failsafe OSC_Fault
16MHz SMCLK
Minimum pulse filter
DCO Peripherals
Digitally Controlled Oscillator
(DCO)
On PUC, MCLK and SMCLK are
0-to-16MHz sourced from DCOCLK at ~1.1 MHz.
+ 3% tolerance
ACLK is sourced from LFXT1CLK in
LF mode with an internal load
Factory calibration in Flash capacitance of 6pF. If LFXT1 fails,
ACLK defaults to VLO.
3-4 Getting Started with the MSP430 LaunchPad - Initialization and GPIO
Initialization and GPIO
TAR
fVLO = 8MHz/Counts
CCRx
Getting Started with the MSP430 LaunchPad - Initialization and GPIO 3-5
Initialization and GPIO
Watchdog Timer
SMCLK 1
ACLK 1
WDTSSEL A EN WDTHOLD
Lab …
29
3-6 Getting Started with the MSP430 LaunchPad - Initialization and GPIO
Lab 3: Initialization and GPIO
Getting Started with the MSP430 LaunchPad - Initialization and GPIO 3-7
Lab 3: Initialization and GPIO
Procedure
Create a New Project
1. Create a new project by clicking:
File New CCS Project
Make the selections shown below (your dialog may look slightly different than this one).
If you are using the MSP430G2231, make the appropriate choices for that part. Make
sure to select the Empty Project (with main.c)template, and then click
Finish.
3-8 Getting Started with the MSP430 LaunchPad - Initialization and GPIO
Lab 3: Initialization and GPIO
Source File
2. In the main.c editing window, replace the existing code with the following code. Again, if
you are using the MSP430G2231, use that include header file. The short #ifdef structure
corrects an inconsistency between the 2231 and 2553 header files. This inconsistency
should be corrected in future releases. Rather than typing all the following code, you can
feel free to cut and paste it from the workbook pdf file.
#include <msp430g2553.h>
#ifndef TIMER0_A1_VECTOR
#define TIMER0_A1_VECTOR TIMERA1_VECTOR
#define TIMER0_A0_VECTOR TIMERA0_VECTOR
#endif
void main(void)
{
// code goes here
The WDTCTL is the watchdog timer control register. This instruction sets the password
(WDTPW) and the bit to stop the timer (WDTHOLD). Look at the header file and User’s
Guide to understand how this works. (Please be sure to do this – this is why we asked
you to open the header file and document).
Getting Started with the MSP430 LaunchPad - Initialization and GPIO 3-9
Lab 3: Initialization and GPIO
5. Next, we need to configure the LED that’s connected to the GPIO line. The green LED
is located on Port 1 Bit 6 and we need to make this an output. The LED turns on when
the output is set to a “1”. We’ll clear it to turn the LED off. Leave a line for spacing and
type the next two lines of code.
P1DIR = 0x40;
P1OUT = 0;
(Again, check the header file and User’s Guide to make sure you understand the
concepts).
6. Now we’ll set up the clock system. Enter a new line, then type:
BCSCTL3 |= LFXT1S_2;
The BCSCTL3 is one of the Basic Clock System Control registers. In the User’s Guide,
section 5.3 tells us that the reset state of the register is 005h. Check the bit fields of this
register and notice that those settings are for a 32768 Hz crystal on LFXT1 with 6pF
capacitors and the oscillator fault condition set. This condition would be set anyway
since the crystal would not have time to start up before the clock system faulted it.
Crystal start-up times can be in the hundreds of milliseconds.
The operator in the statement logically OR’s LFXT1S_2 (which is 020h) into the
existing bits, resulting in 025h. This sets bits 4 & 5 to 10b, enabling the VLO clock.
Check this with the documents.
7. The clock system will force the MCLK to use the DCO as its source in the presence of a
clock fault (see the User’s Guide section 5.2.7). So we need to clear that fault flag. On
the next line type:
IFG1 &= ~OFIFG;
The IFG1 is Interrupt Flag register 1. A bit field in the register is the Oscillator Fault
Interrupt Flag - OFIFG (the first letter is an “O”, and not a zero). Logically ANDing
IFG1 with the NOT of OFIFG (which is 2) will clear bit 1. Check this in section 5 of
the User’s Guide and in the header file.
8. We need to wait about 50 µs for the clock fault system to react. Running on the 12kHz
VLO, stopping the DCO will buy us that time. On the next line type:
_bis_SR_register(SCG1 + SCG0);
SR is the Status Register. Find the bit definitions for the status register in the User’s
Guide (section 4). Find the definitions for SCG0 and SCG1 in the header file and notice
how they match the bit fields to turn off the system clock generator in the register. By the
way, the underscore before bis defines this is an assembly level call from C. _bis is a bit
set operation known as an intrinsic.
9. There is a divider in the MCLK clock tree. We will use divide-by-eight. Type this
statement on the next line and look up its meaning:
BCSCTL2 |= SELM_3 + DIVM_3;
The operator logically ORs the two values with the existing value in the register.
Examine these bits in the User’s Guide and header file.
10. At this point, your code should look like the code below. We have added the comments
to make it easier to read and understand. Click the Save button on the menu bar to save
the file.
#include "msp430g2553.h"
#ifndef TIMER0_A1_VECTOR
#define TIMER0_A1_VECTOR TIMERA1_VECTOR
#define TIMER0_A0_VECTOR TIMERA0_VECTOR
#endif
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; // watchdog timer setup
11. Just one more thing – the last piece of the puzzle is to toggle the green LED. Leave
another line for spacing and enter the following code:
while(1)
{
P1OUT = 0x40; // LED on
_delay_cycles(100);
P1OUT = 0; // LED off
_delay_cycles(5000);
}
The P1OUT instruction was already explained. The delay statements are built-in intrinsic
function for generating delays. The only parameter needed is the number of clock cycles
for the delay. Later in the workshop we will find out that this isn’t a very good way to
generate delays – so don’t get used to using it. The while(1) loop repeats the next four
lines forever.
12. Now, the complete code should look like the following. Be sure to save your work.
#include "msp430g2553.h"
#ifndef TIMER0_A1_VECTOR
#define TIMER0_A1_VECTOR TIMERA1_VECTOR
#define TIMER0_A0_VECTOR TIMERA0_VECTOR
#endif
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; // watchdog timer setup
while(1)
{
P1OUT = 0x40; // LED on
_delay_cycles(100);
P1OUT = 0; // LED off
_delay_cycles(5000);
}
}
Great job! You could have just cut and pasted the code from VLO.txt in the Files folder,
but what fun would that have been?
13. Click the “Debug” button . Click the Proceed button when the ULP Advisor
appears. The “CCS Debug” view should open, the program will load automatically, and
you should now be at the start of main().
14. Run the code. If everything is working correctly the green LED should be blinking about
once every three or four seconds. Running the CPU on the other clock sources will speed
this up considerably. This will be covered in the remainder of the lab exercise.
15. Click on the Terminate button to stop debugging and return to the “CCS Edit”
perspective. Save your work by clicking File Save As and select the parent
folder as Lab3. Name the file Lab3a.c. Click OK.
Expand the Lab3 project by clicking on to the left of the Lab3 project name.
Close the Lab3a.c editor tab and double click on main.c in the Project Explorer pane.
Unfortunately, Eclipse has added Lab3a.c to our project, which will cause us grief later
on (you can’t have two main() functions in the same program).
Note: If you have decided NOT to solder the crystal on to LaunchPad, then skip to the
“Running the CPU on the DCO without a Crystal” section. But, you should
reconsider; as this is important information to learn.
And we also want the red LED (P1.0) to start out ON, so
Change: P1OUT = 0;
To: P1OUT = 0x01;
17. We need to select the external crystal as the low-frequency clock input.
Change: BCSCTL3 |= LFXT1S_2;
To: BCSCTL3 |= LFXT1S_0 + XCAP_3;
Check the User’s Guide to make sure this is correct. The XCAP_3 parameter selects the
12pF load capacitors. A higher load capacitance is needed for lower frequency crystals.
18. In the previous code we cleared the OSCFault flag and went on with our business, since
the clock system would default to the VLO anyway. Now we want to make sure that the
flag stays cleared, meaning that the crystal is up and running. This will require a loop
with a test. Modify the code to
Change: IFG1 &= ~OFIFG;
To: while(IFG1 & OFIFG)
{
IFG1 &= ~OFIFG;
_delay_cycles(100000);
}
The statement while(IFG1 & OFIFG) tests the OFIFG in the IFG1 register. If that
fault flag is clear we will exit the loop. We need to wait 50 µs after clearing the flag until
we test it again. The _delay_cycles(100000); is much longer than that. We need it
to be that long so we can see the red LED light at the beginning of the code. Otherwise it
would flash so quickly that we wouldn’t be able to see it.
19. Finally, we need to add a line of code to turn off the red LED, indicating that the fault test
has been passed. Add the new line after the while loop:
P1OUT = 0;
20. Since we made a lot of changes to the code (and had a chance to make a few errors),
check to see that your code looks like:
#include "msp430g2553.h"
#ifndef TIMER0_A1_VECTOR
#define TIMER0_A1_VECTOR TIMERA1_VECTOR
#define TIMER0_A0_VECTOR TIMERA0_VECTOR
#endif
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; // watchdog timer setup
while(1)
{
P1OUT = 0x40; // LED on
_delay_cycles(100);
P1OUT = 0; // LED off
_delay_cycles(5000);
}
}
Again, you could have cut and pasted from XT.txt, but you’re here to learn.
21. Click the “Debug” button . Click the Proceed button in the ULP Advisor. The “CCS
Debug” perspective should open, the program will load automatically, and you should
now be at the start of main().
22. Look closely at the LEDs on the LaunchPad and Run the code. If everything is working
correctly, the red LED should flash very quickly (the time spent in the delay and waiting
for the crystal to start) and then the green LED should blink every second or so. That’s
about three times the rate it was blinking before due to the higher crystal frequency.
When done, halt the code by clicking the suspend button .
23. Click on the Terminate button to stop debugging and return to the “CCS Edit”
perspective. Save your work by clicking File Save As and select the parent
folder as Lab3. Name the file Lab3b.c and click OK. Make sure to exclude Lab3b.c
from the build. Close the Lab3b editor tab and double click on main.c in the Project
Explorer pane.
Notice the trap here. It is possible to erase the segment A of the information flash
memory. Blank flash memory reads as 0xFF. Plugging 0xFF into the calibration of the
DCO would be a real mistake. You might want to implement something similar in your
own fault handling code.
25. We need to comment out the line that stops the DCO. Comment out the following line:
// __bis_SR_register(SCG1 + SCG0);
26. Finally, we need to make sure that MCLK is sourced by the DCO.
Change: BCSCTL2 |= SELM_3 + DIVM_3;
To: BCSCTL2 |= SELM_0 + DIVM_3;
Double check the bit selection with the User’s Guide and header file.
#ifndef TIMER0_A1_VECTOR
#define TIMER0_A1_VECTOR TIMERA1_VECTOR
#define TIMER0_A0_VECTOR TIMERA0_VECTOR
#endif
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; // watchdog timer setup
while(1)
{
P1OUT = 0x40; // LED on
_delay_cycles(100);
P1OUT = 0; // LED off
_delay_cycles(5000);
}
}
28. Click the “Debug” button . Click the Proceed button in the ULP Advisor. The “CCS
Debug” perspective should open, the program will load automatically, and you should
now be at the start of main().
29. Look closely at the LEDs on the LaunchPad and Run the code. If everything is working
correctly, the red LED should be flash very quickly (the time spent in the delay and
waiting for the crystal to start) and the green LED should blink very quickly. The DCO
is running at 1MHz, which is about 33 times faster than the 32768 Hz crystal. So the
green LED should be blinking at about 30 times per second.
30. Click the Terminate button to stop debugging and return to the “CCS Edit”
perspective. Save your work by clicking File Save As and select the parent
folder as Lab3. Name the file Lab3c.c. Click OK. Make sure to exclude Lab3c.c from
the build. Close the Lab3c.c editor tab and double click on main.c in the Project Explorer
pane.
Optimized Code Running the CPU on the DCO and the Crystal
The previous code was not optimized, but very useful for educational value. Now we’ll look at
an optimized version. Delete the code from your main.c editor window (click anywhere in the
text, Ctrl-A, then delete). Copy and paste the code from OPT_XT.txt into main.c. Examine the
code and you should recognize how everything works. A function has been added that
consolidates the fault issue, removes the delays and tightens up the code. Build, load, and run as
before. The code should work just as before. If you would like to test the fault function, short the
XIN and XOUT pins with a jumper before clicking the Run button. That will guarantee a fault
from the crystal. You will have to power cycle the LaunchPad to reset the fault.
Click on the Terminate button to stop debugging and return to the “CCS Edit”
perspective. Save your work by clicking File Save As and select the parent folder as
Lab3. Name the file Lab3d.c. Click OK. Make sure to exclude Lab3d.c from the build. Close the
Lab3d.c editor tab.
Notice the trap here. It is possible to erase the segment A of the information flash
memory that holds the calibration constants. Blank flash memory reads as 0xFF.
Plugging 0xFF into the calibration of the DCO would be a real mistake. You might want
to implement something similar in your own fault handling code.
33. We need to comment out the line that stops the DCO. Comment out the following line:
// __bis_SR_register(SCG1 + SCG0);
34. Finally, we need to make sure that MCLK is sourced by the DCO.
Change: BCSCTL2 |= SELM_3 + DIVM_3;
To: BCSCTL2 |= SELM_0 + DIVM_3;
Double check the bit selection with the User’s Guide and header file. Save your work.
#ifndef TIMER0_A1_VECTOR
#define TIMER0_A1_VECTOR TIMERA1_VECTOR
#define TIMER0_A0_VECTOR TIMERA0_VECTOR
#endif
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; // watchdog timer setup
while(1)
{
P1OUT = 0x40; // LED on
_delay_cycles(100);
P1OUT = 0; // LED off
_delay_cycles(5000);
}
}
36. Click the “Debug” button . Click the Proceed button in the ULP Advisor. The
“CCS Debug” perspective should open, the program will load automatically, and you
should now be at the start of main().
37. Run the code. If everything is working correctly, the green LED should blink very
quickly. With the DCO running at 1MHz, which is about 30 times faster than the 32768
Hz crystal. So the green LED should be blinking at about 30 times per second. When
done halt the code.
38. Click on the Terminate button to stop debugging and return to the “CCS Edit”
perspective. Save your work by clicking File Save As and select the parent
folder as Lab3. Name the file Lab3e.c. Click OK. Make sure to exclude Lab3e.c from
the build. Close the Lab3e.c editor tab and double click on main.c in the Project Explorer
pane.
Click on the Terminate button to stop debugging and return to the “CCS Edit”
perspective. Save your work by clicking File Save As and select the parent folder as
Lab3. Name the file Lab3f.c. Click OK and then close the Lab3f.c editor pane. Make sure to
exclude Lab3f.c from the build.
Right-click on Lab3 in the Project Explorer pane and select Close Project.
You’re done.
Agenda
ADC10 …
31
Module Topics
Analog-to-Digital Converter ......................................................................................................................4-1
Module Topics..........................................................................................................................................4-2
Analog-to-Digital Converter ....................................................................................................................4-3
Fast Flexible ADC10 ...........................................................................................................................4-3
Sample Timing ....................................................................................................................................4-4
Autoscan + DTC Performance Boost ..................................................................................................4-4
Lab 4: Analog-to-Digital Converter ........................................................................................................4-5
Objective..............................................................................................................................................4-5
Procedure .............................................................................................................................................4-6
Analog-to-Digital Converter
Fast Flexible ADC10
Sequence
ADC10SC
Repeat-single TA1
TA0
Repeat-sequence TA2
Auto power-down
Sample Timing …
32
Sample Timing
Procedure
Create a New Project
1. Create a new project by clicking:
File New CCS Project
Make the selections shown below (your dialog may look slightly different than this one).
If you are using the MSP430G2231, make the appropriate choices for that part. Make
sure to click Empty Project (with main.c), and then click Finish.
Source File
Most coding efforts make extensive use of the “cut and paste” technique, or commonly known as
“code re-use”. The MSP430 family is probably more prone to the use of this technique than most
other processors. There is an extensive library of code example for all of the devices in both
assembly and C. So, it is extremely likely that a piece of code exists somewhere which does
something similar to what we need to do. Additionally, it helps that many of the peripherals in
the MSP430 devices have been deliberately mapped into the same register locations. In this lab
exercise we are going to re-use the code from the previous lab exercise along with some code
from the code libraries and demo examples.
1. We need to open the files containing the code that we will be using in this lab exercise.
Open the following two files using File Open File…
• C:\MSP430_LaunchPad\Labs\Lab3\Files\OPT_VLO.txt
• C:\MSP430_LaunchPad\Labs\Lab2\Files\Temperature_Sense_Demo.txt
2. Copy all of the code in OPT_VLO.txt and paste it into main.c, erasing all the
existing code in main.c. This will set up the clocks:
• ACLK = VLO
• MCLK = DCO/8 (1MHz/8)
3. Next, make sure the SMCLK is also set up:
Change: BCSCTL2 |= SELM_0 + DIVM_3;
To: BCSCTL2 |= SELM_0 + DIVM_3 + DIVS_3;
The SMCLK default from reset is sourced by the DCO and DIVS_3 sets the SMCLK
divider to 8. The clock set up is:
• ACLK = VLO
• MCLK = DCO/8 (1MHz/8)
• SMCLK = DCO/8 (1MHz/8)
4. If you are using the MSP430G2231, make sure to make the appropriate change to the
header file include at the top of the code.
5. As a test – build, load, and run the code. If everything is working correctly the green
LED should blink very quickly. When done, halt the code and click the Terminate
button to return to the “CCS Edit” perspective.
7. We are going to examine these code lines one at the time to make sure they are doing
what we need them to do. You will need to open the User’s Guide and header file for
reference again. (It might be easier to keep the header file open in the editor for
reference).
First, change ADC10DIV_3 to ADC10DIV_0.
ADC10CTL1 = INCH_10 + ADC10DIV_0;
ADC10CTL1 is one of the ADC10 control registers. INCH_10 selects the internal
temperature sensor input channel and ADC10DIV_0 selects divide-by-1 as the ADC10
clock. Selection of the ADC clock is made in this register, and can be the internal
ADC10OSC (5MHz), ACLK, MCLK or SMCLK. The ADC10OSC is the default
oscillator after PUC. So we will use these settings.
ADC10CTL0 = SREF_1 + ADC10SHT_3 + REFON + ADC10ON + ADC10IE;
ADC10CTL0 is the other main ADC10 control register:
• SREF_1: selects the range from V ss to V REF+ (ideal for the temperature sensor)
• ADC10SHT_3: maximum sample-and-hold time (ideal for the temperature sensor)
• REFON: turns the reference generator on (must wait for it to settle after this line)
• ADC10ON: turns on the ADC10 peripheral
• ADC10IE: turns on the ADC10 interrupt – we do not want interrupts for this lab
exercise, so change the line to:
ADC10CTL0 = SREF_1 + ADC10SHT_3 + REFON + ADC10ON;
The next line allows time for the reference to settle. A delay loop is not the best way to
do this, but for the purposes of this lab exercise, it’s fine.
_delay_cycles(1000);
Referring to the User’s Guide, the settling time for the internal reference is < 30µs. As
you may recall, the MCLK is running at DCO/8. That is 1MHz/8 or 125 kHz. A value of
1000 cycles is 8ms, which is much too long. A value of 5 cycles would be 40µs. Change
the delay time to that value:
_delay_cycles(5);
enables the conversion and starts the process from software. According to the user’s
guide, we should allow thirteen ADC10CLK cycles before we read the conversion result.
Thirteen cycles of the 5MHz ADC10CLK is 2.6µs. Even a single cycle of the DCO/8
would be longer than that. We will leave the LED on and use the same delay so that we
can see it with our eyes. Leave the next two lines alone:
P1OUT = 0x40;
_delay_cycles(100);
8. When the conversion is complete, the encoder and reference need to be turned off. The
ENC bit must be off in order to change the REF bit, so this is a two step process. Add the
following two lines right after the first __delay_cycles(100); :
9. Now the result of the conversion can be read from ADC10MEM. Next, add the following
line to read this value to a temporary location:
tempRaw = ADC10MEM;
Remember to declare the tempRaw variable right after the #endif line at the beginning
of the code:
volatile long tempRaw;
The volatile modifier forces the compiler to generate code that actually reads the
ADC10MEM register and place it in tempRaw. Since we’re not doing anything with
tempRaw right now, the compiler optimizer could decide to eliminate that line of code.
The volatile modifier prevents this from happening.
10. The last two lines of the while(1) loop turn off the green LED and delays for the next
reading of the temperature sensor. This time could be almost any value, but we will use
about 1 second in between readings. MCLK is DCO/8 is 125 kHz. Therefore, the delay
needs to be 125,000 cycles:
P1OUT = 0;
_delay_cycles(125000);
11. At this point, your code should look like the code below. We have added the comments
to make it easier to read and understand. Click the Save button on the menu bar to save
the file.
#include <msp430g2553.h>
#ifndef TIMER0_A1_VECTOR
#define TIMER0_A1_VECTOR TIMERA1_VECTOR
#define TIMER0_A0_VECTOR TIMERA0_VECTOR
#endif
void FaultRoutine(void);
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer
P1DIR = 0x41; // P1.0&6 outputs
P1OUT = 0; // LEDs off
while(1)
{
ADC10CTL1 = INCH_10 + ADC10DIV_0; // Temp Sensor ADC10CLK
ADC10CTL0 = SREF_1 + ADC10SHT_3 + REFON + ADC10ON;
_delay_cycles(5); // Wait for ADC Ref to settle
ADC10CTL0 |= ENC + ADC10SC; // Sampling & conversion start
void FaultRoutine(void)
{
P1OUT = 0x01; // red LED on
while(1); // TRAP
}
13. Click the “Debug” button . When the ULP Advisor appears, click Proceed. The
“CCS Debug” perspective should open, the program will load automatically, and you
should now be at the start of main().
14. Run the code. If everything is working correctly the green LED should be blinking about
once per second. Click Suspend to stop the code.
17. Make sure the Expressions window is still visible and run the code. It will quickly
stop at the breakpoint and the tempRaw value will be updated. Do this a few times,
observing the value. (It might be easier to press F8 rather than click the Run button).
The reading should be pretty stable, although the lowest bit may toggle. A typical
reading is about 734 (that’s decimal), although your reading may be a little different.
You can right-click on the variable in the watch window and change the format to
hexadecimal, if that would be more interesting to you. Each time the value changes it will
be highlighted in yellow.
18. Just to the left of the P1OUT = 0; instruction you should see a symbol indicating a
breakpoint has been set. It might be a little hard to see with the Program Counter arrow in
the way. Right-click on the symbol and select Breakpoint Properties...
We can change the behavior of the breakpoint so that it will stop the code execution,
update our watch expression and resume execution automatically. Change the Action
parameter to Update View as shown below and click OK.
19. Run the code. Warm your finger up, like you did in the Lab2 exercise, and put it on the
device. You should see the measured temperature climb, confirming that the ADC
conversion process is working. Every time the variable value changes, CCS will highlight
it in yellow.
21. Next, close the project by right-clicking on Lab4 in the Project Explorer pane and
select Close Project.
You’re done.
Agenda
Timer Architecture …
36
Getting Started with the MSP430 LaunchPad - Interrupts and the Timer 5-1
Module Topics
Module Topics
Interrupts and the Timer ...........................................................................................................................5-1
Module Topics..........................................................................................................................................5-2
Interrupts and the Timer ..........................................................................................................................5-3
Timer_A2/A3 Features ........................................................................................................................5-3
Interrupts and the Stack .......................................................................................................................5-3
Vector Table ........................................................................................................................................5-4
ISR Coding ..........................................................................................................................................5-4
Lab 5: Timer and Interrupts.....................................................................................................................5-5
Objective..............................................................................................................................................5-5
Procedure .............................................................................................................................................5-6
5-2 Getting Started with the MSP430 LaunchPad - Interrupts and the Timer
Interrupts and the Timer
Getting Started with the MSP430 LaunchPad - Interrupts and the Timer 5-3
Interrupts and the Timer
Vector Table
ISR Coding
ISR Coding
#pragma vector=WDT_VECTOR
__interrupt void WDT_ISR(void)
{
IE1 &= ~WDTIE; // disable interrupt
IFG1 &= ~WDTIFG; // clear interrupt flag
WDTCTL = WDTPW + WDTHOLD; // put WDT back in hold state
BUTTON_IE |= BUTTON; // Debouncing complete
}
#pragma vector - the following function is an ISR for the listed vector
_interrupt void - identifies ISR name
No special return required
Lab …
40
5-4 Getting Started with the MSP430 LaunchPad - Interrupts and the Timer
Lab 5: Timer and Interrupts
Getting Started with the MSP430 LaunchPad - Interrupts and the Timer 5-5
Lab 5: Timer and Interrupts
Procedure
Create a New Project
1. Create a new project by clicking:
File New CCS Project
Make the selections shown below (your dialog may look slightly different than this one).
If you are using the MSP430G2231, make the appropriate choices for that part. Make
sure to click Empty Project (with main.c), and then click Finish.
5-6 Getting Started with the MSP430 LaunchPad - Interrupts and the Timer
Lab 5: Timer and Interrupts
Source File
The solution file from the last lab exercise will be used as the starting point for this lab exercise.
We’ve cleaned up the file slightly to make it a little more readable by putting the initialization
code into individual functions.
• C:\MSP430_LaunchPad\Labs\Lab5\Files\Lab5_Start.txt
2. Copy all of the code in Lab5_Start.txt and paste it into main.c, erasing all the
existing code in main.c. This will be the starting point for this lab exercise.
And add a template for the function at the very bottom of the program:
void ConfigTimerA2(void)
{
Getting Started with the MSP430 LaunchPad - Interrupts and the Timer 5-7
Lab 5: Timer and Interrupts
7. Next, we need to populate the ConfigTimerA2() function with the code to configure
the timer. We could take this from the example code, but it’s pretty simple, so let’s do it
ourselves. Add the following code as the first line:
CCTL0 = CCIE;
We’d like to set up the timer to operate in continuous counting mode, sourced by the
ACLK (VLO), and generate an interrupt every second. Reference the User’s Guide and
header files and notice the following:
• TACTL is the Timer_A control register
• TASSEL_1 selects the ACLK
• MC_2 sets the operation for continuous mode
When the timer reaches the value in CCR0, an interrupt will be generated. Since the
ACLK (VLO) is running at 12 kHz, the value needs to be 12000 cycles.
8. We have enabled the CCR0 interrupt, but global interrupts need to be turned on in order
for the CPU to recognize it. Right before the while(1) loop in main(), add the following:
_BIS_SR(GIE);
These lines identify this as the TIMER ISR code and allow the compiler to insert the
address of the start of this code in the interrupt vector table at the correct location. Look
it up in the C Compiler User’s Guide. This User’s Guide was downloaded in lab 1.
10. Remove all the code from inside the while(1) loop in main() and paste it into the ISR
template. This will leave the while(1) loop empty for the moment.
11. Almost everything is in place for the first interrupt to occur. In order for the 2nd, 3rd,
4th,… to occur at one second intervals, two things have to happen:
a) The interrupt flag has to be cleared (that’s automatic)
b) CCR0 has to be set 12,000 cycles into the future
5-8 Getting Started with the MSP430 LaunchPad - Interrupts and the Timer
Lab 5: Timer and Interrupts
12. We need to have some code running to be interrupted. This isn’t strictly necessary, but
the blinking LEDs will let us know that some part of the code is actually running. Add
the following code to the while(1) loop:
P1OUT |= BIT0;
for (i = 100; i > 0; i--);
P1OUT &= ~BIT0;
for (i = 5000; i > 0; i--);
This routine does not use any intrinsics. So when we’re debugging the interrupts, they
will look fine in C rather than assembly. Don’t forget to declare i at the top of main.c:
volatile unsigned int i;
In ConfigLEDs(),
• Change: P1DIR = 0x41;
• To: P1DIR = BIT6 + BIT0;
14. At this point, your code should look like the code on the next two pages. We’ve added
the comments to make it easier to read and understand. Click the Save button on the
menu bar to save the file.
Getting Started with the MSP430 LaunchPad - Interrupts and the Timer 5-9
Lab 5: Timer and Interrupts
#include <msp430g2553.h>
#ifndef TIMER0_A1_VECTOR
#define TIMER0_A1_VECTOR TIMERA1_VECTOR
#define TIMER0_A0_VECTOR TIMERA0_VECTOR
#endif
void FaultRoutine(void);
void ConfigWDT(void);
void ConfigClocks(void);
void ConfigLEDs(void);
void ConfigADC10(void);
void ConfigTimerA2(void);
void main(void)
{
ConfigWDT();
ConfigClocks();
ConfigLEDs();
ConfigADC10();
ConfigTimerA2();
_BIS_SR(GIE);
while(1)
{
P1OUT |= BIT0;
for (i = 100; i > 0; i--);
P1OUT &= ~BIT0;
for (i = 5000; i > 0; i--);
}
}
void ConfigWDT(void)
{
WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer
}
void ConfigClocks(void)
{
if (CALBC1_1MHZ ==0xFF || CALDCO_1MHZ == 0xFF)
FaultRoutine(); // If calibration data is erased
// run FaultRoutine()
BCSCTL1 = CALBC1_1MHZ; // Set range
DCOCTL = CALDCO_1MHZ; // Set DCO step + modulation
BCSCTL3 |= LFXT1S_2; // LFXT1 = VLO
IFG1 &= ~OFIFG; // Clear OSCFault flag
BCSCTL2 |= SELM_0 + DIVM_3 + DIVS_3; // MCLK = DCO/8, SMCLK = DCO/8
}
5 - 10 Getting Started with the MSP430 LaunchPad - Interrupts and the Timer
Lab 5: Timer and Interrupts
void FaultRoutine(void)
{
P1OUT = BIT0; // P1.0 on (red LED)
while(1); // TRAP
}
void ConfigLEDs(void)
{
P1DIR = BIT6 + BIT0; // P1.6 and P1.0 outputs
P1OUT = 0; // LEDs off
}
void ConfigADC10(void)
{
ADC10CTL1 = INCH_10 + ADC10DIV_0; // Temp Sensor ADC10CLK
}
void ConfigTimerA2(void)
{
CCTL0 = CCIE;
CCR0 = 12000;
TACTL = TASSEL_1 + MC_2;
}
#pragma vector=TIMER0_A0_VECTOR
__interrupt void Timer_A (void)
{
ADC10CTL0 = SREF_1 + ADC10SHT_3 + REFON + ADC10ON;
_delay_cycles(5); // Wait for ADC Ref to settle
ADC10CTL0 |= ENC + ADC10SC; // Sampling and conversion start
P1OUT |= BIT6; // P1.6 on (green LED)
_delay_cycles(100);
ADC10CTL0 &= ~ENC; // Disable ADC conversion
ADC10CTL0 &= ~(REFON + ADC10ON); // Ref and ADC10 off
tempRaw = ADC10MEM; // Read conversion value
P1OUT &= ~BIT6; // green LED off
CCR0 +=12000; // add 12 seconds to the timer
}
Note: for reference, the code can found in Lab5_Finish.txt in the Files folder.
15. Click the “Debug” button . When the ULP Advisor appears, click Proceed. The
“CCS Debug” view should open, the program will load automatically, and you should
now be at the start of main().
16. Run the code and observe the LEDs. If everything is working correctly, the red LED
should be blinking about twice per second. This is the while(1) loop that the Timer is
interrupting. The green LED should be blinking about once per second. This is the rate
that we are sampling the temperature sensor. Click Suspend to stop the code.
Getting Started with the MSP430 LaunchPad - Interrupts and the Timer 5 - 11
Lab 5: Timer and Interrupts
19. Run the code. The debug window should quickly stop at the breakpoint and the
tempRaw value will be updated. Observe the watch window and test the temperature
sensor as in the previous lab exercise.
21. Close the project by right-clicking on Lab5 in the Project Explorer pane and
select Close Project.
You’re done.
5 - 12 Getting Started with the MSP430 LaunchPad - Interrupts and the Timer
Low-Power Optimization
Introduction
This module will explore low-power optimization. In the lab exercise we will show and
experiment with various ways of configuring the code for low-power optimization.
Agenda
Module Topics
Low-Power Optimization...........................................................................................................................6-1
Module Topics..........................................................................................................................................6-2
Low-Power Optimization .........................................................................................................................6-3
Low-Power Modes ..............................................................................................................................6-3
Low-Power Operation .........................................................................................................................6-3
System MCLK & Vcc .........................................................................................................................6-5
Pin Muxing ..........................................................................................................................................6-5
Unused Pin Termination ......................................................................................................................6-6
Ultra-Low-Power Advisor ...................................................................................................................6-6
Lab 6: Low-Power Modes ........................................................................................................................6-7
Objective..............................................................................................................................................6-7
Procedure .............................................................................................................................................6-8
Low-Power Optimization
Low-Power Modes
Low-Power Operation
Pin Muxing
Ultra-Low-Power Advisor
Ultra-Low-Power Advisor
Integrated into CCS build
flow
Checks your code against
a thorough checklist to
achieve the lowest power
possible
Provides detailed
notifications and remarks
Lab…
49
Procedure
Create a New Project
1. Create a new project by clicking:
File New CCS Project
Make the selections shown below (your dialog may look slightly different than this one).
If you are using the MSP430G2231, make the appropriate choices for that part. Make
sure to click Empty Project (with main.c), and then click Finish.
Source File
We’ll use the solution file from the last lab exercise as the starting point for this lab exercise.
• C:\MSP430_LaunchPad\Labs\Lab5\Files\Lab5_Finish.txt
2. Copy all of the code in Lab5_Finish.txt and paste it into main.c, erasing the
original contents of main.c. This will be the starting point for this lab exercise.
3. Close the Lab5_Finish.txt file. It’s no longer needed. If you are using the
MSP430G2231, make sure to make the appropriate change to the header file include at
the top of the main.c.
5. The current drawn by the red LED is going to throw off our current measurements, so
comment out the two P1OUT lines inside the while(1) loop.
6. As a test – build, load, and run the code. If everything is working correctly the green
LED should blink about once every three or four seconds. When done, halt the code and
click the Terminate button to return to the “CCS Edit” perspective.
10. Delete the contents of the ConfigPins() function and insert the following lines:
P1DIR = ~BIT3;
P1OUT = 0;
12. At this point, your code should look like the code below. We’ve added the comments to
make it easier to read and understand. Click the Save button on the menu bar to save the
file. The middle line of code will result in an “integer conversion resulted in truncation”
warning at compile time that you can ignore.
void ConfigPins(void)
{
P1DIR = ~BIT3; // P1.3 input, others output
P1OUT = 0; // clear output pins
P2SEL = ~(BIT6 + BIT7); // P2.6 and 7 GPIO
P2DIR |= BIT6 + BIT7; // P2.6 and 7 outputs
P2OUT = 0; // clear output pins
}
13. Now build, load and run the code. Make sure the green LED blinks once every three or
four seconds. Click the Terminate button to return to the “CCS Edit” perspective.
14. Next, remove all the jumpers on header J3 and connect your meter leads. Press the Reset
button on the LaunchPad board and measure the current between the blinks of the green
LED.
You should have a value around 106 µA.
Record your measurement here: _____________
No real savings here, but there is not much happening on this board to cause any issues.
Remove the meter leads and carefully replace the jumpers on header J3.
This code will turn on interrupts and put the device in LPM3 mode. Remember that this
mode will place restrictions on the resources available to us during the low power mode.
The CPU, MCLK, SMCLK and DCO are off. Only the ACLK (sourced by the VLO in
our code) is still running.
You may notice that the syntax has changed between this line and the one we deleted.
MSP430 code has evolved over the years and this line is the preferred format today; but
the syntax of the other is still accepted by the compiler.
16. At this point, the entire main() routine should look like the following:
void main(void)
{
ConfigWDT();
ConfigClocks();
ConfigPins();
ConfigADC10();
ConfigTimerA2();
while(1)
{
_bis_SR_register(LPM3_bits + GIE); // Enter LPM3 with interrupts
}
}
17. The Status Register (SR) bits that are set by the above code are:
• SCG0: turns off SMCLK
• SCG1: turns off DCO
• CPUOFF: turns off the CPU
When an ISR is taken, the SR is pushed onto the stack automatically. The same SR value
will be popped, sending the device right back into LPM3 without running the code in the
while(1) loop. This would happen even if we were to clear the SR bits during the ISR.
Right now, this behavior is not an issue since this is what the code in the while(1) does
anyway. If your program drops into LPM3 and only wakes up to perform interrupts, you
could just allow that behavior and save the power used jumping back to main(), just so
you could go back to sleep. However, you might want the code in the while(1) loop to
actually run and be interrupted, so we are showing you this method.
Add the following code to the end of your Timer ISR:
_bic_SR_register_on_exit(LPM3_bits);
19. Now build, load and run the code. Make sure the green LED blinks once every three
seconds. Halt the code and click the Terminate button to return to the “CCS Edit”
perspective. This code is saved as Lab6a.txt in the Files folder.
20. Next, remove all the jumpers on header J3 and connect your meter leads. Press the Reset
button on the LaunchPad board and measure the current between the blinks of the green
LED.
You should have a value around 0.6 µA.
Record your measurement here: _____________
This is a big difference! The CPU is spending the majority of the sampling period in
LPM3, drawing very little power.
Remove the meter leads and carefully replace the jumpers on header J3.
A graph of the current consumption would look something like the below. Our code still
isn’t generating quite this timing, but the DMM measurement would be the same.
21. The _delay_cycles(5); statement should provide about 40uS delay, although there
is likely some overhead in the NOP loop that makes it slightly longer. For two reasons
we’re going to leave this as a software delay;
1) the delay is so short that any timer setup code would take longer than the timer delay
2) the timer can only run on the ACLK (VLO) in LPM3.
At that speed the timer has an 83uS resolution … a single tick is longer than the delay we
need. But we can optimize a little. Change the statement as shown below to reduce the
specified delay to 32uS:
Change: _delay_cycles(5);
To: _delay_cycles(4);
22. The final thing to tackle is the conversion time delay in the Timer_A0 ISR. The ADC
can be programmed to provide an interrupt when the conversion is complete. That will
provide a clear indication that the conversion is complete. The power savings will be
minimal because the conversion time is so short, but this is fairly straightforward to do,
so why not do it?
Add the following ADC10 ISR template to the bottom of main.c:
// ADC10 interrupt service routine
#pragma vector=ADC10_VECTOR
__interrupt void ADC10 (void)
{
23. Copy all of the lines in the Timer ISR below delay_cycles(100); and paste them into
the ADC10 ISR.
24. In the Timer ISR delete the code from the P1OUT |= BIT6; line through the
P1OUT &= ~BIT6; line.
25. At the top of the ADC10 ISR, add ADC10CTL0 &= ~ADC10IFG; to clear the interrupt
flag.
26. In the ADC10 ISR delete the P1OUT &= ~BIT6; and CCR0 += 36000; lines.
27. Lastly, we need to enable the ADC10 interrupt. In the Timer ISR, add + ADC10IE to the
ADC10CTL0 register line.
The Time and ADC10 ISRs should look like this:
#pragma vector=TIMER0_A0_VECTOR
__interrupt void Timer_A (void)
{
ADC10CTL0 = SREF_1 + ADC10SHT_3 + REFON + ADC10ON + ADC10IE ;
_delay_cycles(4); // Wait for ADC Ref to settle
ADC10CTL0 |= ENC + ADC10SC; // Sampling and conversion start
CCR0 +=36000; // add 12 seconds to the timer
_bic_SR_register_on_exit(LPM3_bits);
}
28. Build and load the project. Eliminate any breakpoints and run the code. We eliminated
the flashing of the green LED since it flashes too quickly to be seen. Set a breakpoint on
the _bic_SR line in the ADC10 ISR and verify that the value in tempRaw is updating as
shown earlier. Click the Terminate button to halt the code and return to the “CCS
Edit” perspective. If you are having a difficult time with the code modifications, this
code can be found in Lab6b.txt in the Files folder.
29. Remove the jumpers on header J3 and attach the DMM leads as before. Press the Reset
button on the LaunchPad board and measure the current between the blinks of the green
LED.
You should have a value around 0.6 µA.
Record your measurement here: _____________
That may not seem like much of a savings, but every little bit counts when it comes to
battery life. To quote a well-known TI engineer: “Every joule wasted from the battery is
a joule you will never get back”.
Replace all the jumpers on header J3.
ULP Advisor
We’ve been ignoring the ULP Advisor for long enough. Let’s review the results
30. Resize the Problems pane so that you can see the contents. Click on the left of
Warnings and Infos.
Add the code on the following page to the end of your code in main.c . The
asm(" JMP $"); instruction traps code execution at that point by jumping to itself. A
while(1) loop would have done the same thing, but the ULP Advisor will flag that as a
software loop.
NOTE: Depending on your system and Adobe Acrobat you may have an issue with the
quote signs in the following code. Sometimes they paste into CCS as “curved” quotes
signs rather than the straight” ones. In that case you will need to find/replace the
offending characters in your code.
33. The last item in the Infos section says that we’re using a software delay loop. This refers
to the while(1) loop in the FaultRoutine() . If you want to replace that with the
assembly instruction used in the last step, go ahead. Otherwise we’ll just live with it.
34. The first item in the Infos section says that Port 3 is uninitialized. Actually, the 20-pin
device only has two ports as I/O, larger devices have a third. We can prevent this ULP
Advisor issue by initializing the third port. Add the last two lines shown below to the
ConfigPins() function.
void ConfigPins(void)
{
P1DIR = ~BIT3;
P1OUT = 0;
P2SEL = ~(BIT6 + BIT7);
P2DIR |= BIT6 + BIT7;
P2OUT = 0;
P3DIR = 0xFF; // Set P3 GPIO to outputs
P3OUT = 0; // Clear P3 outputs
35. Rebuild your code and look at the Problems pane. You should only see the single
truncation warning and info about the software delay. It’s doubtful that any power was
saved during this ULP Advisor exercise, but it is certainly worthwhile to pay attention to
the ULP Advisor output.
Summary
Our code is now as close to optimized as it gets, but again, there are many, many ways to get to
this point. Often, the need for hardware used by other code will prevent you from achieving the
very lowest power possible. This is the kind of cost/capability trade-off that engineers need to
make all the time. For example, you may need a different peripheral – such as an extra timer –
which costs a few cents more, but provides the capability that allows your design to run at its
lowest possible power, thereby providing a battery run-time of years rather than months.
36. Remove the jumpers on header J3 and attach the DMM leads as before. Press the Reset
button on the LaunchPad board and measure the current between the blinks of the green
LED.
You should have a value around 0.6 µA.
Record your measurement here: _____________
Congratulations on completing this lab! Remove and turn off your meter and replace all
of the jumpers on header J3. We are finished measuring current.
37. Close the project by right-clicking on Lab6 in the Project Explorer pane and
select Close Project.
You’re done.
Agenda
USI …
51
Module Topics
Serial Communications ..............................................................................................................................7-1
Module Topics..........................................................................................................................................7-2
Serial Communications ............................................................................................................................7-3
USCI ....................................................................................................................................................7-3
Protocols ..............................................................................................................................................7-3
Software UART Implementation .........................................................................................................7-4
USB COM Port Communication .........................................................................................................7-4
Lab 7: Serial Communications ............................................................................................................7-5
Objective..............................................................................................................................................7-5
Procedure .............................................................................................................................................7-6
Serial Communications
USCI
Universal Serial Communication Interface
USCI
USCI_A0 supports:
SPI (3 or 4 wire)
UART A
IrDA
USCI_B0 supports: B
SPI (3 or 4 wire)
I2C
Protocols …
52
Protocols
Vdd
R R
I2C SDA
SCL
• Inter-Integrated Circuit Interface
• Single Master/Multiple Slaves
µC DAC ADC µC
Master Slave Slave Slave
UART
• Universal Asynchronous Tx Rx
Receiver/Transmitter R/T Rx Tx R/T
• Full duplex
Objective
The objective of this lab is to learn serial communications with the MSP430 device. In this lab
exercise we will implement a software UART and communicate with the PC using the USB port.
It would be possible to do this on the MSP430G2553 since it has a USCI peripheral with a UART
ports. But often developers want to minimize cost to the greatest degree possible. Implementing a
UART in software could save several crucial pennies from the bill of materials.
Procedure
Create a New Project
1. Create a new project by clicking:
File New CCS Project
Make the selections shown below (your dialog may look slightly different than this one).
If you are using the MSP430G2231, make the appropriate choices for that part. Make
sure to click Empty Project (with main.c), and then click Finish.
Source File
In this lab exercise we will be building a program that transmits “HI”, “LO” or “IN” using the
software UART code. This data will be communicated through the USB COM port and then to
the PC for display on a terminal program. The UART code utilizes TIMER_A2, so we will need
to remove the dependence on that resource from our starting code. Then we will add some “trip
point” code that will light the red or green LED indicating whether the temperature is above or
below some set temperature. Then we will add the UART code and send messages to the PC.
The code file from the last lab exercise will be used as the starting point for this lab exercise.
• C:\MSP430_LaunchPad\Labs\Lab6\Files\Lab6a.txt
2. Copy all of the code from Lab6a.txt and paste it into main.c, erasing the previous
contents of main.c. This will be the starting point for this lab exercise. You should
notice that this is not the low-power optimized code that we created in the latter part of
the Lab6 exercise and we will be ignoring the warnings from the ULP Advisor. The
software UART implementation requires Timer_A2, so using the fully optimized code
from Lab6 will not be possible. But we can make a few adjustments and still maintain
fairly low-power.
Close the Lab6a.txt file. If you are using the MSP430G2231, make sure to make the
appropriate change to the header file include at the top of the main.c.
3. As a test – build, load, and run the code. Ignore the ULP Advisor warnings. Remove
tempRaw from the Expression pane. If everything is working correctly, the green LED
will blink once every three or four seconds, but the blink duration will be very, very
short. The code should work exactly the same as it did in the previous lab exercise.
When you’re done, halt the code and click the Terminate button to return to the
“CCS Edit” perspective.
The selection of intervals for the WDT+ is somewhat limited, but WDT_ADLY_250 will
give us a little less than a 1 second delay running on the VLO.
WDT_ADLY_250 sets the following bits:
• WDTPW: WDT password
• WDTTMSEL: Selects interval timer mode
• WDTCNTCL: Clears count value
• WDTSSEL: WDT clock source select
5. The code in the Timer_A0 ISR now needs to run when the WDT+ interrupts trigger:
• Change this:
// Timer_A2 interrupt service routine
#pragma vector=TIMER0_A0_VECTOR
__interrupt void Timer_A (void)
{
• To this:
// WDT interrupt service routine
#pragma vector=WDT_VECTOR
__interrupt void WDT(void)
{
6. There is no need to handle CCRO in the WDT ISR. Delete the CCR0 += 36000; line.
7. There is no need to set up Timer_A2 now. Delete all the code inside the
ConfigTimerA2() function.
8. Build, load, and run the code. Make sure that the code is operating like before, except
that now the green LED will blink about once per second. When you’re done, click the
Terminate button to return to the “CCS Edit” perspective. If needed, this code
can be found in Lab7a.txt in the Files folder.
11. We need to create a function that handles the UART transmit side. Adding a lot of code
tends to be fairly error-prone. So add the following function by copying and pasting it
from here or from Transmit.txt in the Files folder to the end of main.c:
// Function Transmits Character from TXByte
void Transmit()
{
BitCnt = 0xA; // Load Bit counter, 8data + ST/SP
while (CCR0 != TAR) // Prevent async capture
CCR0 = TAR; // Current state of TA counter
CCR0 += Bitime; // Some time till first bit
TXByte |= 0x100; // Add mark stop bit to TXByte
TXByte = TXByte << 1; // Add space start bit
CCTL0 = CCIS0 + OUTMOD0 + CCIE; // TXD = mark = idle
while ( CCTL0 & CCIE ); // Wait for TX completion
}
12. Transmission of the serial data occurs with the help of Timer_A2 (Timer A2 creates the
timing that will give us a 2400 baud data rate). Cut/paste the code below or copy the
contents of Timer_A2 ISR.txt and paste it to the end of main.c:
// Timer A0 interrupt service routine
#pragma vector=TIMER0_A0_VECTOR
__interrupt void Timer_A (void)
{
CCR0 += Bitime; // Add Offset to CCR0
if (CCTL0 & CCIS0) // TX on CCI0B?
{
if ( BitCnt == 0)
{
CCTL0 &= ~ CCIE ; // All bits TXed, disable interrupt
}
else
{
CCTL0 |= OUTMOD2; // TX Space
if (TXByte & 0x01)
CCTL0 &= ~ OUTMOD2; // TX Mark
TXByte = TXByte >> 1;
BitCnt --;
}
}
}
13. Now we need to configure Timer_A2. Enter the following lines to the
ConfigTimerA2() function in main.c so that it looks like this:
void ConfigTimerA2(void)
{
CCTL0 = OUT; // TXD Idle as Mark
TACTL = TASSEL_2 + MC_2 + ID_3; // SMCLK/8, continuos mode
}
14. To make this code work, add the following definitions at the top of main.c:
#define TXD BIT1 // TXD on P1.1
#define RXD BIT2 // RXD on P1.2
#define Bitime 13*4 // 0x0D
15. Since we have added a lot of code, let’s do a test build. In the Project Explorer
pane, right-click on main.c and select Build Selected File(s). Check for
syntax errors in the Console and Problems panes (other than the ULP Advisor issues).
The tempSet variable will hold the first temperature reading made by ADC10. The
code will then compare future readings against it to determine if the new measured
temperature is hotter or cooler than that set value. Note that we are starting the variable
out at zero. That way, we can use its non-zero value after it’s been set to make sure we
only set it once. We’ll need the “i” in the code below.
17. Add the following control code to the while(1) loop right after line containing
_bis_SR_register(LPM3_bits + GIE);
This code sets three states for the measured temperature; LO, HI and IN that are indicated by the
state of the green and red LEDs. It also sends the correct ASCII sequence to the Transmit()
function.
19. Finally, we need to asure that the MCLK and SMCLK are both running on the DCO. In
the ConfigClocks() function, make sure that the BCSCTL2 clock control register is
configured as shown below:
BCSCTL2 = 0;
Click the symbol next to Ports and find the port named MSP430 Application UART.
Write down the COM port number here_________. (The one on our PC was COM14).
Close the Device Manager.
24. In the terminal display, you will likely see IN displayed over and over again. This means
that the measured temperature is within a couple of degrees of the temperature that was
measured when the code started.
Warm the MSP430 with your finger. After a moment the red LED should light and the
Terminal should display HI. Now the MSP430 is a couple of degrees warmer than the
initial temperature. While your finger is still on the MSP430, click the Reset CPU
button and then the Resume button. The code will then record the initial
temperature while the chip is warm. Remove your finger from the MSP430.
You should see IN displayed in the Terminal window. But when the MSP430 cools
down, the green LED will light and the Terminal will display LO. .
25. This would also be a good time to note the size of the code we have generated. Click the
Console tab to view the pane at the bottom of your screen.
MSP430: Loading complete. Code Size - Text: 976 bytes Data: 6 bytes.
Based on what we have done so far, you could create a program more than sixteen times
the size of this code and still fit comfortably inside the MSP430G2553 memory.
You’re done.
Agenda
What is Grace?
57
Module Topics
Grace ...........................................................................................................................................................8-1
Module Topics..........................................................................................................................................8-2
Grace .......................................................................................................................................................8-3
Lab 8: Grace ............................................................................................................................................8-8
Grace
Lab 8: Grace
Objective
The objective of this lab is to create a simple project using Grace. This project will be similar to
an earlier project in that it will use the Timer to blink the LED. Using Grace to create the
peripheral initialization code will simplify the process.
Procedure
Create a Grace Project
1. Grace is part of your Code Composer Studio installation, although it is possible to run it
in a stand-alone fashion. Starting with CCS version 5.3 it is called Grace2.
Make the selections shown below (your dialog may look slightly different than this one).
If you are using the MSP430G2231, make the appropriate choices for that part. Make
sure to click Empty Grace (MSP430) Project, and then click Finish.
Welcome to Grace™
2. The Grace Welcome screen will appear within the editor pane of CCS. If you ever
manage to make this screen disappear, simply re-open *.cfg (main.cfg is the
filename here). When a Grace project is opened, the tool creates this configuration file to
store the changes you make. Click the Device Overview link at the top of the pane.
Grace presents you with a graphic representing the peripherals on the MSP430 device.
This isn’t just a pretty picture … from here we’ll be able to configure the peripherals.
Blue boxes denote peripherals that can be configured. Note that three of the blue boxes
have a check mark in the lower left hand corner. These check marks denote a peripheral
that already has a configuration. The ones already marked must be configured in any
project in order for the MSP430 to run properly.
If you are using the MSP430G2231, your Grace window will look slightly different.
DVCC
3. Let’s start at the top. Earlier in this workshop we measured the DVCC on the board at
about 3.6VDC. Change the pull down at the top to reflect that.
BCS+
4. Next, click on the blue Oscillators Basic Clock System + box.
Note the navigation hyperlinks at the top for the different views. These links may
disappear if the window is large enough and you slide to the bottom of it. If they do, slide
back to the top. Also note the navigation buttons on the top right of the Overview screen
and the tabs at the bottom left. Take a look at the different views, but finish by clicking
the Basic User link.
The default selections have the calibrated frequency at 1 MHz for the High Speed Clock
Source and 12 kHz for the low. Note the simplified view of the MCLK, SMCLK and
ACLK. If you need more detailed access, you can switch over to the Power User view. In
any case, leave the selections at their defaults and click the Grace tab in the lower left.
WDT+
5. Let’s configure the Watchdog Timer next. Click on the blue WatchDog WDT+ box in
the Overview graphic. Note the selection at the top of the next window that enables the
WDT+. Click the Basic User link. Stop Watchdog timer is the default selection … let’s
leave it that way. Click the Grace tab in the lower left. Notice that the peripherals we’ve
touched are adding tabs.
GPIO
6. GPIO is next. For this lab, we want to enable the GPIO port/pin that is connected to the
red LED (port 1, pin 0). Click on the upper right blue box marked GPIO. In the next
screen, click the links marked Pinout 32-QFN, Pinout 20-TSSOP/20-PDIP and Pinout
28-TSSOP to view the packages with the pinouts clearly marked. If you are using the
MSP430G2231, your package selections will be different. No databook is required. We
could make our changes here, but let’s use another view.
Resize the Grace window if you need to do so. Click the P1/P2 link. The Direction
Registers all default to inputs, so check the port 1, pin 0 Direction register to set it to an
output. No other changes are required. Click the Grace tab in the lower left.
Timer0_A3
7. We’re going to use the timer to give us a one second delay between blinks of the red
LED. To configure the timer, click on the blue box marked Timer0_A3 (This will be
Timer0_A2 if you are using the MSP430G2231). In the next screen, click the check box
marked Enable Timer_A3 in my configuration at the top of the screen. When you do
that, the view links will appear. Click on the Basic User link.
In our application code, we’re going to put the CPU into low-power mode LPM3. The
timer will wake up the CPU after a one second delay and then the CPU will run the ISR
that turns on the LED. Our main() code will then wait long enough for us to see the
LED, turn it off and go back to sleep.
Select Timer0_A3 CCR0 and then click on the Open Interrupt Vector File link.
Note the /* USER CODE START and /* USER CODE END comments in the
TIMER0_A0_VECTOR template. These comments indicate to Grace that the code
between them should not be overwritten during the code generation process.
The first line of code in the ISR will turn on the LED. When the ISR returns to the main
code, we want the CPU to be awake. The second line of code will do that (like we used in
Lab 6). Replace the middle comment in the template as shown below.
/*
* ======== Timer0_A3 Interrupt Service Routine ========
*/
#pragma vector=TIMER0_A0_VECTOR
__interrupt void TIMER0_A0_ISR_HOOK(void)
{
/* USER CODE START (section: TIMER0_A0_ISR_HOOK) */
P1OUT = BIT0; // Turn on LED on P1.0
_bic_SR_register_on_exit(LPM3_bits); // Return awake
/* USER CODE END (section: TIMER0_A0_ISR_HOOK) */
}
Click the Save button on the menu bar, and then click the main.cfg tab in the upper
left corner. Click the Grace tab in the lower left corner. Note that the configured
peripherals all have a check mark in them. The Outline pane on the right of your screen
also lists all the configured peripherals.
Application Code
9. Grace automatically creates a main.c template for us with the appropriate Grace calls.
Expand the Lab8 project and double click on main.c in the Project Explorer pane to
open the file for editing. It should look like the screen capture below:
The standard msp430.h definition file is included first, followed by the Grace.h Grace
definitions. This includes all the Chip Support Library functions.
Inside main() is Grace_init() that runs all of the Grace initialization that we just
configured. The main() function, of course, does not return anything … the return (0) is a
C coding formality to assist with third-party compiler compatibility.
11. The first thing we want the main code to do is to place the device into LPM3. When the
timer expires, the time ISR code will turn on the red LED. Our main() code will wait a
short time, then turn the red LED off. Replace the // … Fill-in user code here comment
with the while() loop code shown below:
/*
* ======== Standard MSP430 includes ========
*/
#include <msp430.h>
/*
* ======== Grace related includes ========
*/
#include <ti/mcu/msp430/Grace.h>
/*
* ======== main ========
*/
int main(void)
{
Grace_init(); // Activate Grace-generated config
while (1)
{
_bis_SR_register(LPM3_bits); // Enter LPM3
_delay_cycles(10000); // 10ms delay
P1OUT &= ~BIT0; // Turn off LED on P1.0
}
return (0);
}
12. Make sure that your LaunchPad board is plugged into your computer’s USB port. Build
and Load the program by clicking the Debug button. If you are prompted to save
any resources, do so now.
13. After the program has downloaded, click the Run button. If everything is correct, the red
LED should flash once every second. Feel free to go back and vary the timing if you like.
You could also go back and re-run the rest of the labs in the workshop using Grace.
If you’re so inclined, open the Lab8/src/grace folder in the Project Explorer pane
and look at the fully commented C code generated for each of the initialization files.
These could be cut/pasted into a non-Grace project if you choose.
This was a very simple example. In a more complex one, the power of Grace would be
even greater and your project development will be much further along than it would have
been if written entirely by hand. Terminate the debugger, close the Lab8 project and exit
Code Composer.
You’re done.
Agenda
68
Module Topics
FRAM Overview ........................................................................................................................................9-1
Module Topics..........................................................................................................................................9-2
FRAM – Next Generation Memory ..........................................................................................................9-3
FRAM Controller ................................................................................................................................9-5
FRAM and the Cache ..........................................................................................................................9-6
MPU ....................................................................................................................................................9-7
Write Speed .........................................................................................................................................9-8
Low Power...........................................................................................................................................9-9
Increased Flexibility and Endurance..................................................................................................9-10
Reflow and Reliability .......................................................................................................................9-11
FRAM Controller
4
3.5
3
RAM / 100% Cache Hit
Active Power (uA)
2.5
2 75% Cache Hit
75
77
MPU
Write Speed
Low Power
85
The latest MSP430 devices provide direct capacitive touch I/O pins, which lowers the cost and
power when implementing capacitive touch/sensing, while making them easier than ever to use in
a system.
Adding to the ease-of-use is the CAPT software library for buttons, sliders and wheels – in fact,
any type of capacitive sensing electrode. TI also provides GUI tools for Tuning your system,
estimating the Power requirements, and configuring your device.
Enough of the marketing, we begin this chapter with the What / Why / How of Capacitive Sensing.
Armed with a little background on the subject, we’ll discuss the basic steps to implementing Cap
Touch software. Finally, we provide a number of hands-on exercises to experiment and learn how
to use the device, library, and tools.
Chapter Outline
Outline
What is Capacitive Touch
Why Use TI’s MSP430
How Does Cap Touch Work?
Capacitive Sensing Details
Implementing Cap Touch
Additional Topics
Lab Exercise
http://www.ti.com/touch
Workshop Agenda
This learning module is part of a 1-day MSP430 Hands-On Workshop. There will be times in the
lab exercises where we refer to other chapters for extended learning about something being
implemented. For example, we use Hardware Interrupts and Interrupt Service Routines (ISR) in
the lab exercise for this chapter, but we leave the gory details of how they work to the chapter on
Interrupts.
This said, the chapter still works well as a stand-alone topic, if all you care about learning is the
information on Capacitive Touch & Sensing.
Workshop Agenda
1. Introduction to Value Line
2. Code Composer Studio
3. Initialization and GPIO
4. Analog-to-Digital Converter
5. Interrupts and Timers
6. Low-Power Optimization
7. Serial Communications
8. Grace
9. FRAM
► 10. Capacitive Touch
11. Using Energia (Arduino)
http://www.ti.com/touch
No Electrical Engineering degree is required, though, a basic knowledge of the physics behind
Cap Touch can help when implementing it – even when ‘just doing’ the software. To this end, we
spend a few pages providing a light background on the technology.
We also wanted to list the hardware and software requirements for this chapter. Links to these
items are provided at the beginning of the Lab10 exercise, as well as the workshop’s installation
guide.
Objectives
The user should be able to…
Describe how capacitive touch sensing interfaces work
Chapter Topics
Capacitive Touch ...................................................................................................................... 10-1
Workshop Agenda................................................................................................................... 10-2
Prerequisites, Tools and Objectives ....................................................................................... 10-3
What is Capacitive Touch ....................................................................................................... 10-5
Why Use TI’s MSP430 ............................................................................................................ 10-8
How Does Cap Touch Work? ............................................................................................... 10-10
A Short Physics Lesson .................................................................................................... 10-10
Applied Physics ................................................................................................................. 10-14
Capacitive Sensing Details ................................................................................................... 10-16
Capacitive Sensing I/O...................................................................................................... 10-16
Gate Time.......................................................................................................................... 10-17
Power Requirements (and Scan Rate) ............................................................................. 10-18
Measurement Methods (RO vs fRO) ................................................................................ 10-20
Sensor Threshold .............................................................................................................. 10-21
Implementing Cap Touch ...................................................................................................... 10-23
1. Planning – What Do You Need to Detect?.................................................................... 10-24
2. Write Code .................................................................................................................... 10-28
3. Tuning Sensors (Threshold, Gate time) ........................................................................ 10-33
Summary: TI's Cap Touch Library (TI_CAPT) .................................................................. 10-34
Additional Topics ................................................................................................................... 10-35
Hardware Sensor Design (For Reference Only) ............................................................... 10-35
For More Info... .................................................................................................................. 10-36
Lab Exercise ......................................................................................................................... 10-38
And, that is where we start. Replacing mechanical switches with Capacitive Touch/Sensing (we’ll
abbreviate this with CapTouch) buttons is one of the largest use cases for CapTouch. As the
following slide indicates, there are quite a few advantages to using this technology – not the least
of which is lower cost.
Replace mechanical
scroll wheel / buttons
with Capacitive touch
Advantages
Higher Reliability
No moving parts
Longer life
Better ESD & environ-
mental protection
Innovation
Flexible layout/design
- not restricted to buttons
Design slimmer products
Controls hidden until lit
Easy to clean
Lower Cost - Create directly on PCB (printed circuit board)
If you really miss that good ‘ol click of a mechanical switch, there’s an app for that, so to speak.
The technology, called Haptics, can provide a responsive feedback like we’ve grown to
appreciate from mechanical implementations. TI has a number of products that can help you to
implement Haptics solutions (even a new MSP430 device that does CapTouch along with
Haptics). To learn more about these solutions, visit the www.ti.com/touch webpage and click the
Haptics tab.
As a final note, the above slide shows one of the more famous CapTouch mechanical
replacements – and it may be the place where most of us really learned about Scroll Wheels. Of
course, we’re alluding to the iPod scroll wheel. My first generation iPod had a true mechanical
scroll wheel. Sure, it worked beautifully. But can you imagine implementing it on today’s small,
thin devices? CapTouch has enabled us to miniaturize a number of uniquely helpful (and fun)
products … while making them cheaper in the process.
Buttons, Sliders, and Wheels (nicknamed BSW) are the most obvious use of CapTouch.
But a whole new generation of CapTouch enabled products are finding innovative new ways to
use the technology. Proximity detection in one of the leading ways this is being done.
In fact, TI’s CapTouch BoosterPack – which we use throughout the upcoming lab exercise, ships
with a demo that stays asleep … until you wave your hand over the board.
It’s hard to summarize all the places where you can use CapTouch, but here’s a few of them. For
example, medical – and other sanitary-minded applications – are making heavy use of proximity
detection. Have you used one of those proximity detecting hand-sanitizer dispensers, yet?
Handset
Proximity Sensor
Hopefully, in the future we’ll be writing about your innovative new way to utilize the technology.
MSP430s feature unique peripherals for lower power, higher precision or lower
cost Capacitive Sensing implementations
MSP430s with Capacitive Touch I/Os provides glue less sensor interface
In fact, any MSP430 device with a comparator supports capacitive touch sensing
More devices with Touch Sense I/O are on the way…
The MSP430 is widely known as the most power-efficient microcontroller. But we don’t stop there;
by adding CapTouch sensing GPIO pins to our controllers, we take them to another level.
1/Scan Rate
Great devices notwithstanding, if you can’t figure out how to use them, what good are they?
That’s why TI provides a great number of demos, libraries, tools and application notes.
Voltage R
Potential energy
Battery is a good example as it current flow
stores electric potential energy V
Current flows from battery (+)
thru resistance
Schematic is common way to Drawing of
express circuits Schematic Diagram
Our circuit with a battery and a light-bulb is a good example of a simple electrical circuit. The
graphic also contains the schematic diagram for this simple circuit. We use schematic diagrams
since their notation is much easier to draw than light-bulbs and batteries.
Capacitance
Capacitor is a passive component that stores
Current only flows if … energy in the form of an electrostatic field
Voltage in capacitor is less C ― Field is created by two plates, separated by
than voltage across battery non-conductive material (called dielectric)
Current flows when voltage is applied to ‘empty’
capacitor; this ‘charges’ it
When charged, a capacitor acts like an open
circuit (no current flows thru it)
Once charged…
Capacitor can hold its
C Take voltage source away, capacitor holds
charge like a rechargeable battery
charge like a battery Some MSP430 development kits use a big
capacitor (‘Super Cap’) as a power source
Hopefully this concept of storing and releasing energy isn’t too difficult. It’s actually the crux of
what makes our CapTouch systems work.
The key to making a good capacitor is to provide the greatest amount of surface area between
the two very-close ‘plates’; and, using a good dielectric (non-conductive substance) between
them. The better the dieletric, the better the capacitor – plain and simple.
We rate dielectrics by giving the dielectric substance a value. We call this the substance’s
dielectric constant. (For example, air is “1” – good for capacitance; water is “80” – not so good.)
By the way, Super Caps are super cool. With today’s advances in producing capacitors, we can
get powerful capacitors (that store quite a bit of energy) into a relatively small space. And for
many applications they are a lot more convenient than using batteries, such as in development
boards. (Keep an eye out for this in an upcoming new TI MSP430 Launchpad.)
Bottom line, the time depends upon the quality of the capacitor; or better put, how much energy
the capacitor can hold. So, the amount of time varies depending upon the rating of the capacitor.
We document the time it takes, though, by defining a value that represents how long it takes to
charge the capacitor up to 63% of its capacity; this value is called the capacitor’s Time Constant
– which is abbreviated using the Greek letter τ (tau).
But, what’s really significant is that the Time Constant is … well, constant. So much so, that many
designers use it to establish a time base; for example, as when creating a table clock.
What if we were to continually charge, and then discharge an RC circuit. This is easily done in a
microcontroller:
• We turn on a GPIO pin, which starts filling a capacitor.
• We could use an analog comparator (we have them on our MSP430) to tell us when the capacitor
is (close to) full.
• The comparator triggers an interrupt where we turn off the GPIO pin and let the capacitor discharge
• When the capacitor is (almost) empty, the comparator interrupts the CPU again … and on and on
This constant oscillation of charging/discharging is called a Relaxation Oscillator (RO for short).
All we really need to do is count the number of up/down cycles and we can tell time.
By the way, our latest MSP430 devices don’t need to use anything as prosaic as a comparator
and interrupt to implement a RO, as we’ll see in a couple pages. We are now building many of
our GPIO pins to generate a very power-efficient oscillator (RO) on command; no extra pins,
comparators, interrupts or power are required.
Lower
Capacitance
Higher
Capacitance
Hopefully you will agree that this isn’t really that difficult to figure out. A bigger value for C means
that it takes longer to charge the capacitor. Longer to charge, longer to discharge, means that
one complete oscillation just takes longer. Hence, the oscillator slows down.
If we knew how to count oscillations, and could change the value of C, then couldn’t we really
make something cool … that’s where we’re going next.
Applied Physics
OK, so we actually gave away the whole idea for this in the last section.
Applying our physics lesson to CapTouch, we can effectively build an RC circuit right into a
printed circuit board (PCB). As seen below, we can build our “button” out of metal traces (or in
this case, we could all them pads) in the circuit board; these traces almost touch, but don’t quite.
Can see the schematic symbols drawn over the top of the diagram below?
Where the traces are “almost touching” these metal pads effectively create a capacitor.
text
Cap Touch elements are often created directly in the PCB (printed circuit board)
They have an inherent capacitance & resistance – which creates a specific
oscillation frequency when charged/discharged
When a conductive element (e.g Finger) is present, it affects the capacitance of
the system ( “ free space coupling ” )
How is C affected? C is directly proportional to the dielectric value
Dielectric is the 3D space between the conductors – not only on the PCB, but the air
around it
While air has a value ~1, a finger has a much greater dielectric constant (>1)
But here’s the cool thing, electrical circuits are not 2D, they are 3D. (Well, at least this is ‘cool’ if
you’re not at university taking a Fields & Waves course.)
What this means is that the dielectric isn’t just the stuff between the two metal traces on the
board, it’s actually everything in the 3D space around the metal traces. Most likely, the ‘dielectric’
in 3D space is just air – which, as you may remember is a good dielectric, with dielectric constant
of 1.
So, how might we change the value of C in our button’s circuit? How about introducing another,
lower quality, dielectric near our circuit, this would replace some of the air (which acts as a good
dielectric). In fact, human tissue has a lot of water in it, so that might work well in changing the
total dielectric value in the circuit – hence, it should change the value of C.
And there you go, if we change C, we change the frequency of oscillation. In in the next section
we cover how the oscillations can be counted, which means we’ll finally have a way to detect
when a finger ‘presses” a CapTouch “button”.
• Finally, let’s (loosely) define a few terms. Throughout this document, and most others on the
subject, a few terms are used interchangeably. We just want to speak to that here.
It boils down to this, what do we call the metal traces that make up our “button”?
Following are some of the terms you will see used:
− Electrode: this is actually a pretty decent term. Wikipedia defines this as:
“An electrode is an electrical conductor used to make contact with a nonmetallic part of a circuit”
So this is term describes quite well what we’re doing with CapTouch.
− Touchpad: is another widely used term. Wiki loosely defines touchpad as:
“A tactile sensor”
Most of us probably understand this term because it’s a ‘pad’ on the PCB that we ‘touch’.
− Sensor: Again from Wiki:
“A sensor (also called detector) is a converter that measures a physical quantity and converts it into
a signal which can be read by an observer”
Again, this works pretty well. This is just what we’re trying to do. With regards to the TI
CapTouch library, though, we really use this term as an abstract object. We define
Sensor to mean: Button, Slider, Wheel, and Proximity. For example, a Slider could
actually be made up of many electrodes that we end up swiping across.
− Element: If we have a sensor that could be made up of many electrodes – what does the
TI library call the individual electrodes? We call them Elements.
Later in the chapter, you’ll see that the TI Library allows us to define the Elements (i.e.
electrodes) for our applications. Additionally, we define Sensors that are made up from 1 or more
Elements.
The Library also provides ‘abstracted’ functions which provide straightforward answers to whether
a Button sensor is being touched … or maybe, where a finger is positioned around the Elements
that make up a Wheel sensor.
Using this feature, these devices can gluelessly implement CapTouch sensing.
On the MSP430 Value Line (‘G series) devices this feature is called PinOsc (short for Pin
Oscillator). The new Wolverine (‘FR58/59xx) devices have a similar feature, although it’s simply
called “Cap Sense I/O”.
Gate Time
Gate Time is an important value in our measurement of capacitance. But before we delve into it,
let’s talk about how we measure capacitance.
As we discussed earlier, the oscillations on a pin are directly proportional to the amount of
capacitance. So this means we can get a relative measurement of capacitance by counting the
number of oscillations in a fixed amount of time. This can be accomplished by using two timers,
as we demonstrate below:
Effectively, we use the oscillations as the “clock” for the “Timer/Counter”; in this way, it’s really
acting as a counter, counting the number of times the waveform oscillates up/down.
The other “Timer” in our diagram – we used the Watchdog (WDT) as an example – defines the
amount of time in which we count RO oscillations. If we keep the measurement window time
consistent, we can detect changes in capacitance by the varying number of oscillation counts.
So, back to the term Gate Time. Well, that’s just the name
we give to the length of the measurement window.
Also, since the Timers are only used during the actual
measurement window, they could be reused for other
tasks at other times. Longer Gate Times means the timers
are less available to other parts of your program.
In a few pages, when we discuss how to implement CapTouch, you’ll see the term Gate Time
used quite a bit.
There are many factors, but it basically comes down to time – how long do we have to expend
energy scanning electrodes. The top three factors include:
1. How many Elements need to be scanned?
2. How long will the scan take? Basically, this is the idea of Gate Time, which we just discussed.
3. How often do you need scan your Elements?
Thinking about this last one, you may have seen a simple example that shows a Sensor being
continuously scanned as part of the while loop at the end of main(). Conceptually, this is fine;
but in a real-world system, this is wasteful. Scanning too frequently does not provide any benefit
to the end-user; it just uses more power than is necessary.
This leads us to another important characteristic of CapTouch implementation, called Scan Rate.
This is the rate – that is, how often – our Sensor’s should be scanned. The more often we scan,
the more “responsive” the system will appear. But too often and we just waste power.
We have seen effective implementations, when power is absolutely critical, with Scan Rates as
low as 2Hz (twice a second). While it’s nice to know we can go that low, it’s more common to see
rates similar to that shown in the graphic below (20Hz).
This graphic is actually a screen capture from the Capacitive Touch Power Designer tool. It does
an effective job at letting you specify all the system variables that will affect your power
dissipation – it then calculates an estimated power budget for your CapTouch implementation. It
even shows, in bar graph fashion, the power “states” of the processor. (We’ll see a larger drawing
of these states on the next page.)
Number of elements, Gate Times (notice, you can list different Gate Times for different types of
Sensors), Scan Time, as well as the MSP430 device, voltage, and what clock frequency you
want to run system at.
Speaking of the ‘bar graph’ diagram from the Power Design tool, the next diagram is from one of
the MSP430 marketing presentations; it does a good job of showing the power “states” of the
MSP430 when running a CapTouch measurement.
100ms (10Hz) 2 uA
Basically, when measuring 1 electrode, the CPU will go thru four CPU “power” states:
4. CPU Active – the CPU is required to setup the Timers (Gate Time and Oscillation counter).
5. CPU in Low Power Mode (LPMx) – unless you have something else for the CPU to do, it can
be put into a Low Power Mode. The power usage here is threefold. Both timers will consume
some power as they perform their tasks. Also, the pin oscillator – while very power efficient –
does consume a small amount of power.
6. CPU Active – the Gate Time’r wakes up the CPU when the measurement is complete. The
CPU then disables the timers and pin oscillators, thus freeing them up for other uses. The
CPU may also have to do some calculations, depending upon what library function you used
to perform the scan.
7. CPU in LMP3 – once again, unless you have other work for the CPU to perform, it can go
into Low Power Mode. In common use, your processor will spend more time asleep than
awake. (Sounds kind of like a cat’s life, doesn’t it.)
The power numbers shown above are great, with average current, in one use-case, down below
1µA. Some of the upcoming MSP430 devices will drive these power numbers even lower!
We know RO means Relaxation Oscillator. The other, fRO, just means Fast RO. The following
graphic outlines the differences between these two methods.
Do you want to use a fixed gate time and count how many cycles occur? This method is called
RO – which is what we’ve discussed up until this point in the chapter. This is more widely used
than fRO.
With fRO, you measure the length of Gate Time while counting a fixed number of oscillations.
This excerpt (from Capacitive Touch Sensing, MSP430™ Button Gate Time Optimization and
Tuning Guide (SLAA574.PDF)) provides some good reasons you might pick one over the other.
Sensor Threshold
When is a “touch” really a touch?
Tuning your system, to determine the answer to this question, is done empirically. Press the
button and look at the resulting waveforms. Before we talk about how to see these waveforms,
though, let’s discuss what waveform we are actually talking about.
By waveform, we are just talking about a plot of the count values from the timer. (Because, as we
said before, the timer count values are directly proportional to the capacitance.) Another way to
say this is that for every Gate Time measurement, we will get one timer count value that we can
plot, as in the following graphic.
Threshold
It appears that the above waveform consists of around 500 count times. That means we scanned
this element 500 times.
With the release of the new TouchPro Tool (in May 2013), things have gotten a lot easier. You
can send data to this tool (running on your PC) over the serial port directly from your application.
This means we can now view our ‘count’ value waveforms in near real-time. This makes
experimentation much easier. You can try different types of contact (or proximity) and watch how
they affect the waveforms in real-time. While the tool may be pretty simple to use, it’s very
powerful in use.
This example
is sending
count data for
4 elements.
Only three
were chosen
for display
The data is
sent back to
the PC via
serial port
Using this tool, you can visualize your sensor count values in real-time
Take the appropriate count threshold values from this display and plug
them into your sensor definition data structures.
Winston, we couldn’t agree more. With the proper planning, CapTouch becomes much easier to
implement.
To aid you in the Planning phase, we created a Planning Worksheet. Filling out this worksheet
should step you through all the items you need to implement a CapTouch design. Over the next
couple pages we will introduce you to most of the items on the worksheet. Later you will get
hands-on experience with it in the lab exercises.
From a Coding perspective, using the TI CAPT library makes implementation pretty easy. The
key is getting all the necessary data structures, timers and clocking implemented correctly. For a
microcontroller programmer, these should be familiar issues to tackle.
In effect, we already introduced you to the Tuning phase of the design. We’ll use the TouchPro
GUI to assist us with Tuning our designs for just the right “feel”. The tool can also help you with
tuning your gate and scan times; again, by providing real-time feedback.
If you like charting out your development using block diagrams, you might appreciate this, more
detailed, planning sequence.
Here’s how we might implement a program for the CapTouch BoosterPack. One key item is
remembering that Wheels (and Sliders) are made up of multiple elements. (Note: If you are
unsure as to how many elements are in a Sensor – like the wheel – you should examine the
board’s schematic diagram.)
Which device to select? Picking a device with CapTouch I/O’s provides an obvious advantage.
Beyond that, the choice really has more to do with whatever other tasks your system needs to
solve. From a CapTouch perspective, the Value Line series (with PinOsc) provides great value.
Your choice may also depend greatly upon what other device features –
or clock frequencies - are needed in your complete application
Is cost a consideration? The MSP430 Value Line devices (‘G2xxx)
provide Cap Sensing I/O’s … while being very competitively priced
HAL (hardware abstraction layer) is a common term used by libraries when their software directly
touches hardware. This is exactly the case for the CapTouch library. They have defined over 20
different HAL implementations – this makes it easy to select the hardware that you want to use
when implementing CapTouch.
Below, see how the HAL names are defined – each part of the name maps to different hardware
functionality. The Library Users Guide provides HAL recommendations for most devices.
The final part of the Planning process is to choose the frequencies and rates for your CapTouch
implementation. Below, we show a screen capture from the TI CapTouch Power Designer tool, as
it effectively encapsulates the details we need to specify.
Note: During the ‘Tuning’ step, you may end up tweaking these time values.
We can enter the device we just selected. Then add your voltage and preferred clock frequency.
Next, enter the numbers of buttons, sliders, wheels and proximity sensors from the top of your
Planning Worksheet. Finally, we need to choose the Gate and Scan timings. Notice that they
allow you to specify different Gate Times for each type of sensor. This is appropriate, as it takes
quite a bit more time to effectively read a Proximity sensor versus a Button.
What timing values should you choose? The default values, suggested by the Power Design
Tool, are a good starting point. Based on the needs of your end application – extreme power
sensitivity, lots of electromagnetic noise in your system’s environment, thick overlay material, etc.
– you may want to alter these values.
If you’re experienced you may already know you need to alter your Gate or Scan times. For the
rest of us, we may just want to choose the defaults and – based on feedback during the Tuning
phase of our development flow – alter our timings later, if necessary.
2. Write Code
The planning is done, how do we translate these choices into the code that will drive our designs?
Using the TI CapTouch Library involves adding 3 things to your project, as well as adding a bit of
code to your main program.
2. Writing Code
To begin, let’s examine what code you must either include or
write to implement Capacitive Touch Sensing with the TI library
First thing is to add the Library files. It’s usually easiest to just add the entire folder (which
contains 4 source files) directly to your project. We show you how to do this in the lab exercise.
1
No changes are usually required to any of these files. 0F
Next, add the two files: structure.c / structure.h to your project. The TI library provides
many different code examples, one for each of the HAL definitions. We recommend that you copy
the ‘structure’ files from the appropriate example. (It just means less editing later on.) You will use
these files to describe the Elements and Sensors you have chosen for your application –
basically, this comes down to allocating data struct’s for each “Element” and “Sensor”.
Finally, you will need to add at least three items to your mainline code:
• Call into the Library to establish the background capacitance of your system.
• Setup your own timer, configured to provide the Scan Rate you’ve chosen.
• Finally, whenever your Scan Rate Timer interrupts your program, you call a Library function
to scan each of your sensors.
We quickly look at each of these here – but the lab gives you a chance to code it yourself.
1
The only reason to alter one of these files is when you plan to re-use one of the timers utilized
by your CapTouch HAL selection. In this case, both ‘uses’ must share the interrupt service routine
(ISR) which is defined in the Library source code (in the file, CTS_Layer.c).
structure.h
This file creates #definitions for many of the items you will use in your code. Oddly enough, this
file also contains #defines for Library code. This being the case, you could say this file is divided
into two halves – the top part you will need to edit to match your application choices, the bottom
part must be left unaltered.
Looking at the graphic below, we can see the four changes you need to make to this file.
structure.h
User Configuration
Only modify the top part of this file
1. Public Global Variables
Variable extern’s for each of your
sensors and elements
2. Ram Allocation
a) RAM for Flash
Library allocates static RAM, rather
than use dynamic (malloc/free)
b) Total # of elements
So the library knows how much
memory to allocate
3. Structure Array Definition
How many sensors are you defining?
4. Uncomment #def’s as needed
These are based on choice’s you’ve
made, such as your HAL selection
Leave the rest of the file alone!
Except for adding extern definitions for each of your Element and Sensor structure variables,
everything else deals with modifying #defines for your application. Some of these involve entering
a value (from your Planning Worksheet) for a #define. Others only require you to un-comment the
#defines that are required for your implementation choices.
For example, if you plan to use Slider sensors, you need to un-comment out two #defines
towards the bottom of the user-configuration section of this file.
structure.c
The structure.c file also breaks into two halves. In this case, though, you will need to edit
both halves.
The first part of this file involves defining each Element (i.e. electrode) in your system. You need
to allocate – and complete – an Element data structure for each of the Elements you specified on
your Planning Worksheet.
We have already discussed most of the concepts that ended up being fields of the Element data
structure. At this point, we will leave it to the following graphic – as well as the upcoming lab
exercises – for you to learn more about these data structures.
structure.c (Elements)
You need to create file structure.c
#include “structure.h“
This entire file (unlike structure.h) is
// Define struct for each element in your system custom to your application
const struct Element middle = { Allocate a structure for each touchpad
Specify GPIO pin (port & bit), Element and Sensor
.threshold = 121 To make it easier, try copying the
.maxResponse = 121+655, structure.c file from library’s example for
the same HAL you’ve chosen:
};
const struct Element down = { e.g. RO_PINOSC_TA0_WDTp example
Specify GPIO pin (port & bit), (easier, since you can copy/modify
.threshold = 113 struct’s rather than create from scratch)
.maxResponse = 113+655, Element structures contain:
}; Which GPIO pin is the Element
… connected to?
… The count value for threshold
- Start with 0
- Update this field after Tuning phase
Set maxResponse
(only needed for wheels/sliders)
.maxResponse
The second part of the structure.c file involves creating data structures for each of the
Sensor’s in your system (which should all be on your Planning Worksheet).
You might notice below that this is where we actually specify in our code which HAL we have
selected. It’s also where we define the Gate Times in our code.
structure.c (Sensors)
Continuing structure.c
…
The 2nd part of file allocates a structure
for each Sensor
// Define struct for each sensor in your system
// Sensors are made up of elements Sensors are made up of 1 or more
const struct Sensor wheel = { Elements (defined at the top of the file)
.halDefinition = RO_PINOSC_TA0_WDTp, Sensor structures contain:
.numElements = 4,
.points = 64, Which HAL you’ve chosen
.sensorThreshold = 75,
.baseOffset = 0, How many elements in the sensor
- A button has 1
// Pointer to elements - Wheels/sliders have more than 1
.arrayPtr[0] = &up,
.arrayPtr[1] = &right, # of points: How many virtual points do
.arrayPtr[2] = &down, you want the library to track
.arrayPtr[3] = &left, (for wheels/sliders only)
// Timer Information (SMCLK / 8192)
.measGateSource = GATE_WDT_SMCLK, sensorThreshold: cumulative
.accumulationCycles= WDTp_GATE_8192 response required by the sensor (all
}; elements) to declare a valid touch
const struct Sensor myButton = { baseOffset : think of this as a running
.halDefinition = RO_PINOSC_TA0_WDTp, count of all elements (starting with 0)
.numElements = 1,
.baseOffset = 4, arrayPtr[]: address of each Element
.arrayPtr[0] = &middle, used for this sensor (in order)
// Timer Information Timer info: Gate Time clock rate
You may have also noticed that Sensor data structures reference the structures for each of their
Elements. In fact they do this in three ways:
• How many Elements are there for this Sensor?
• The Sensor structure has an array that contains pointers to each of the associated
Elements. It’s important to note, that the Elements should be specified in this array in the
order that a user would “swipe” over their associated electrodes. Doing so means that the
Library Wheel function – TI_CAPT_Wheel() – will be able to provide you with positional
information (i.e. where
along the wheel the user’s
finger is positioned).
main.c
As we mentioned earlier, there aren’t many things we need to add to our mainline code to enable
CapTouch. One of these items is hidden in the function below, called ConfigTimer1(). The code in
this function is not CapTouch specific; rather, this is the timer we use to generate our Scan Rate
time-base. Whenever this timer interrupts the CPU, we go run the TI_CAPT_Button() function in
the Timer1 interrupt service routine.
#include “CTS_Layer.h“
#include “structure.h” main.c
// Main Function
void main(void)
{
WDT_halt(); // Turn off watchdog timer
ConfigClocks(); Initialize hardware
ConfigPins(); // Initialize pins for ULP Set Timer1 to interrupt CPU
ConfigTimer1(); // Set Timer for Scan rate at Scan Rate (we chose 20Hz)
// Establish capacitance baseline
TI_CAPT_Init_Baseline( &myButton ); Read baseline (i.e. background)
TI_CAPT_Update_Baseline( &MyButton, 5 ); capacitance for your sensor
// Background loop starts here
while (1) { Enables interrupts (GIE) and
__bis_SR_register( LPM1_bits + GIE ); put the CPU to sleep (LMP1)
} CPU wakes on Timer1 interrupt
#pragma vector=TIMER0_A2_VECTOR
__interrupt void TimerA2_ISR (void)
{ Read your ‘myButton’ sensor
if ( TI_CAPT_Button ( &myButton ) )
Returns “1” if pressed, “0” if not
{
ToggleLed ();
}
}
The preceding graphic shows how we can use the Library functions to manage and access the
Sensors in our system. First, for each Sensor, we needed to establish an initial capacitance
baseline value.
If you said, “The Element’s data structure”, then you got it correct.
In practice, we set the Threshold to “0” when we first write our code. We then run the code,
connecting it to the TouchPro GUI tool and measure the count values for various degrees of
touch. We then select an appropriate Threshold value for each Element, then go back and add
that value to our code (in the structure.c file).
What if there is so much noise that you cannot pick an effective Threshold value?
You might remember that we can increase a Sensor’s sensitivity by increasing the Gate Time.
Here’s a case where you might want to do that. Luckily, we won’t see this in our upcoming lab
exercise – there will be some noise, but it won’t be significant enough to cause a problem.
Note: There is a short discussion on increasing Gate Times and sensitivity in the Hardware
Sensor Design part of this chapter (page 10-35).
We need to “instrument” our code (i.e. add a little bit of code) to connect our program to the tool.
For each Sensor, we add two function calls to our code.
• The first call, TI_CAPT_Custom() returns an array of normalized timer “count” values.
This array consists of one ‘count’ value for each Element in the Sensor.
• We then use the UART to send these values to the host computer running the TouchPro
GUI. The GUI recognizes and plots the data in real-time.
Tracking Control
Buttons
Cap Touch Layer
Custom
Init/Update
Wheel
Slider
Baseline
Baseline
Raw
Button
Dominant Element
Calculate Delta Capacitance / Baseline Tracking
Filter HAL Selection
RO_COMPAp_TA0_WDTp
RO_PINOSC_TA0_WDTp
RO_COMPB_TA0_WDTA
RO_COMPB_TA0_WDTA
fRO_PINOSC_TA0_SW
RO_PINOSC_TA0
HAL
RC_PAIR_TAO
…
User Defined H/W Configuration
H/W
Here is a block diagram summary of TI’s CapTouch Library. We can see the HAL definitions we
discussed earlier sitting adjacent to the MSP430 device hardware.
The next layer provides some internal (to the Library) functions to filter and extract the important
data for us.
The final layer provides user-callable functions. Some of these are more abstracted than others.
For example, as we saw before, the Button function returns a binary value of whether it’s being
touched or not. At the other end of the spectrum, the Custom and Raw functions provide little to
no abstraction. We use Custom for Tuning our system; Raw is rarely used in straightforward
CapTouch applications, but could be very useful in unique circumstances.
Custom
Init/Update
Wheel
Slider
Baseline
Baseline
Raw
Button
Dominant Element
Slider/Wheel
Calculate Delta
Was Capacitance
it / Baseline Tracking
Button touched?
Custom/Raw
Filter HAL Selection
Little to no
Binary - was Where at
RO_COMPAp_TA0_WDTp
abstraction
RO_PINOSC_TA0_WDTp
RO_COMPB_TA0_WDTA
RO_COMPB_TA0_WDTA
Custom is good
for tuning
RO_PINOSC_TA0
interpret the
Simplified usage
data as yourself
Interprets the data to tell if the
sensor was touched; and where
User Defined H/W Configuration
PinOsc GPIO WDT Timer_A/B Comparator
Additional Topics
Hardware Sensor Design (For Reference Only)
We state “For Reference Only” since hardware design is really outside the scope of this
workshop. Our main purpose here is to bring awareness to a few h/w considerations … but more
importantly, to refer you to the excellent designers guide:
TI provides quite a few options when implementing Capacitive Touch and Haptics solutions. You
find the MSP430 class solutions under the “Capacitive Touch” tab at www.ti.com/touch.
Here’s a picture of this page, but since it’s so small, we’ve repeated references to all the
applications notes, user guides, and documents on the next page of this book.
Capacitive Touch
Designer Guides
Software Library
Reference Designs
To learn more…
Training
Getting Started with the MSP430 LaunchPad Workshop
Tools
MSP430 Touch Pro Tool
MSP430 Capacitive Touch Power Designer GUI
Design Guides
Capacitive Touch Sensing, MSP430™ Button Gate Time Optimization and Tuning Guide
Capacitive Touch Sensing, MSP430™ Slider/Wheel Tuning Guide
Capacitive Touch Sensing, Sensor Design Guide
Capacitive Touch Sensing, SYS/BIOS
Getting Started with the MSP430 LaunchPad Workshop
MSP430 Low Cost PinOsc Capacitive Touch Overview
MSP430x5xx and MSP430x6xx Family User's Guide (Rev. M)
Software Library
MSP430 Capacitive Touch Sense Software Library
Reference Designs
1-uA Capacitive Grip Detection Based on MSP430 Microcontrollers Appnote
MSP430 Low Cost PinOsc Capacitive Touch Keypad
10cm Proximity detection Appnote
Wireless Remote Controller With Capacitive Touch Pad Using MSP430F51x2
Go … Read … Learn more about implementing Capacitive Touch/Sensing with the MSP430!
Requirements
Capacitive Touch BoosterPack (430BOOST-CAPTOUCH1) available here for US$10.
During Workshop Installation, you should have downloaded and installed the following:
− BoosterPack User’s Guide - http://www.ti.com/lit/pdf/slau337b
− CapTouch BoosterPack Demo/Code/GUI - http://www.ti.com/litv/zip/slac490
− Capacitive Touch Library - http://www.ti.com/litv/zip/slac489
− CT Lib Programmer’s Guide - http://www.ti.com/litv/pdf/slaa490b
− Getting Started with Capacitive Touch - http://www.ti.com/lit/slaa491c
− MSP430 Capacitive Touch Power Designer GUI -http://www.ti.com/tool/msptouchpowerdesignergui
− MSP430 Touch Pro Tool - http://www.ti.com/tool/msptouchprogui
The Capacitive Touch BoosterPack includes an MSP430G2452 that is pre-programmed with a
capacitive touch demo. To eliminate the potential to break the pins of your devices while extracting
them, if you have version 1.5 of the LaunchPad board, we will simply reprogram the ‘G2553 already on
your board. In other words, we recommend that you DO NOT INSTALL the MSP430 device that comes
with the CapTouch BoosterPack.
This lab exercise was written for the MSP430 Value-Line LaunchPad kit - version 1.5. This version has
been shipping for 1½ years, as of this writing.
If you are using the older version 1.4 of the Value-Line Launchpad, we recommend: downloading the
older version of this workshop (v2.10) as it contains directions and lab files for using the ‘G2452 device
that comes with the Cap Touch BoosterPack.
Lab Topics
Lab 10: Capacitive Touch ..................................................................................................... 10-38
Objective ................................................................................................................... 10-38
Requirements ............................................................................................................ 10-38
Lab 10a – Capacitive Touch Boosterpack Demo.............................................................. 10-40
Install Hardware and Run the Boosterpack Demo Program ..................................... 10-40
Lab10b – Touch Pro GUI Tool ‘Wheel’ Demo................................................................... 10-41
Lab10c – Create a Capacitive Sense Project From a Blank Page ................................... 10-45
Planning ........................................................................................................................ 10-45
Complete the Cap Touch Planning Worksheet ......................................................... 10-45
Project and File Management ....................................................................................... 10-48
Create (and Explore) New Project ............................................................................ 10-48
Add Cap Touch Sensing Library to Your Project ...................................................... 10-53
Add Starter Files from Library’s Examples ................................................................ 10-53
Writing/Editing Code ..................................................................................................... 10-56
structure.c.................................................................................................................. 10-56
structure.h ................................................................................................................. 10-58
main.c ........................................................................................................................ 10-60
Build, Load and Run .................................................................................................. 10-63
Tuning the Button .......................................................................................................... 10-64
Threshold .................................................................................................................. 10-65
Ideas for Further Exploration..................................................................................... 10-65
(Optional) Lab10d Using Grace to Configure Clocks & Timer .......................................... 10-66
What Do We Want? ...................................................................................................... 10-66
Create Project and Use Grace ...................................................................................... 10-66
Accessing the Code From Grace .................................................................................. 10-72
2. Plug the BoosterPack PCB onto the top of the LaunchPad’s Molex BoosterPack
connectors.
Make sure the Texas Instruments logo is nearest the buttons on the LaunchPad board.
Then plug the LaunchPad board into your computer’s USB port.
3. Open Code Composer in your usual workspace and import the Cap Touch demo.
Make sure that the single discovered project is selected: that you are NOT copying the files;
then click Finish.
4. Build the project and load it into the MSP430 on your Launchpad.
Click on the project in the Project Explorer pane to make it active, and then click the Debug
button on the menu bar to build and program the code into your ‘G2553 device.
6. Cycle the power on the LaunchPad board by removing and re-inserting the USB
connection.
7. Bring the demo out of sleep mode and try out the buttons and scroll wheel.
Pass your hand close over the Capacitive Touch surface – the demo is set to remain in low
power mode until it detects a proximity event. You should see the LEDs illuminate in
sequence.
Touch your fingertip to the rocket button in the center circle and note the LED under it and the
red LED on the LaunchPad PCB light. Touch again to turn them off. Also, try touching
between the inner and outer circle to momentarily illuminate LEDs on the outside ring.
<SLAC490>\Software\CapTouch_BoosterPack_UserExperience_GUI\CapTouch_BoosterPack_UserExperience_GUI.exe
Give the tool a few moments to link with your LaunchPad, and then touch any of the
Capacitive Touch buttons. Note that gestures are also recognized.
9. Exit the Demo’s GUI tool when you are done. Also, close the Lab10a project in CCS.
The Texas Instruments Touch Pro GUI provides an example application that only utilizes the
scroll wheel feature of the Boosterpack. Additionally, it contains the serial port code required to
send data to the Touch Pro GUI.
Hint: In Windows 7 or 8, just click on the Start Menu, then type in “Device Manger”.
2. Open Code Composer in your usual workspace and import the Cap Touch demo.
C:\TI\msp430\TouchPro_1_01_00_00\32bit\TouchProTool_project_files\
examples\TouchProTool_Demo_Bit_Banging\CCS
4. Run the MSP430 TouchPro GUI tool from the Windows Start menu:
Troubleshooting Suggestions
If your COM port doesn’t show up:
1. Halt the program, unplug the Launchpad, wait 10-15 seconds and then plug the board it back
into a different USB port … once Windows says it’s found the board, try launching the
TouchPro GUI and select your COM port.
2. Try doing the same thing as tip #1, but this time close CCS before (or after) you unplug the
Launchpad.
3. Try troubleshooting tip # 2 (closing CCS and unplugging the board) a couple more times.
Note, since the program should now be in flash, you should not have to re-open CCS in order
to use the TouchPro GUI tool.
4. Occasionally, we have had to reset our computer for the TouchPro tool to gain access to the
Launchpad’s COM port.
7. Disconnect the Launchpad from the display by clicking the USB connector icon.
Note: The GUI does not keep an indefinite amount of data. After about 500 samples it
starts discarding the oldest data.
11. You can also exit the GUI tool, as we won’t be using this for the next exercise.
a Blank Page
In this section, we’ll learn how to build a simple Capacitive Touch project. The goal of this this is
to use the middle button on the BoosterPack board to light the middle LED. When we push the
button, the LED should go on; when we release the button, the LED should go off.
Planning
As discussed in the presentation, in the Planning phase we’ll make many of our design
decisions. This should enable us to quickly create code during the Design phase of the lab.
As we said, our goal in this lab is to get the Middle Button working on the Capacitive Touch
Boosterpack. ‘Clicking’ this button should turn on the middle LED. (Note: The middle LED on the
Boosterpack is connected to the same pin as the RED LED on the ‘G2553 Value-Line
Launchpad.)
Here is a diagram of the Port/Pin connections to the BoosterPack Touchpad electrodes. From this
diagram (and the schematic, if you go examine it), we want to scan I/O Port 2, Bit 5.
Hint: Remember, Buttons and Proximity sensors only have 1 Element, but Wheels and
Sliders usually have more than 1.
For each Sensor/Element, Fill-in the Variable names & Port/Pins #’s
Hint: We recommend that you list the multiple Elements of Sliders and Wheels “in order”.
On your board, the elements of multi-element sensors are laid out in a specific order,
following the way a user would slide their finger across the elements in a continuous
motion. For example, if a slider had 4 elements, as the user swiped from K0 to K1,
the library would pick up less-and-less of K0, and more of K1.
For the library to calculate this correctly, we need to specify the Elements of our
Sensor “in order”. Listing them on the worksheet in the correct order will make it
easier when we create the Sensor data structure in the Design/Coding phase.
All this discussion … and we’re not even using a slider or wheel in this part of the lab.
This has you re-enter the #’s of Elements from the beginning of the worksheet, as well as
your selected device.
You will also pick the speed and voltage of the device. Finally, you need to enter the
necessary Gate Time(s) and Scan Rate. We suggest using the default values from the
MSP430 CapTouch Power Designer. (In fact, we will be using the Power Design Tool in
the next step of the lab.)
MSP430 Device
HAL
Capacitive Touch Library
Hardware Abstraction Layer
MSP430 Device
HAL
Capacitive Touch Library
Hardware Abstraction Layer
Running the Power Designer should give you a result similar to this:
Notice, the CPU should be in Low Power Mode most of the time.
Hint: If you make changes to any of the items specified in the Power Designer tool, you
may want to re-open the tool and apply the new choices. This will give you an
updated estimate of your power usage.
Note: You should get a Warning if you choose the template: Empty Project (with main.c)
This is because the Lab10c folder already has a main.c file in it. The warning
notifies you of the conflict; as well as telling you it could not create main.c. (In other
words, it leaves the original main.c untouched.)
• unusedInterrupts.c: The MSP430 compiler complains (i.e. warns you) if there are
interrupt vectors that have not been configured, yet.
− This file simply defines all the interrupt vectors and maps them to a
UNUSED_HWI_ISR() function.
− Notice that two vectors in this file are //commented out. This is because these
two interrupts are used (and defined) in this lab. Timer1 vector is defined in
main.c, while the Watchdog vector will be utilized by the CapTouch Library.
• main.c:
− The main() function sets up the clocks, GPIO, and Timer1; the function ends in a
while loop that enables GIE (global interrupt enable) and puts the CPU to sleep.
− The CPU stays asleep waiting for the Timer1 interrupt to wake it up.
− GPIO_init() and the Timer1 ISR functions are both defined in this file.
During the build, you should have noticed an error. Apparently, the compiler cannot find a
header file.
CCS makes it easy to add a folder from the workspace, just click on the Workspace button and
choose the appropriate folder.
8. Trying building your file again. Upon a successful build, go ahead and run the
program.
When running, you should see the Green LED (as well as LED6 on the Boosterpack) flashing
on/off about once per second. If this is the case, then we know that our clocks and 20Hz scan
rate timer are working properly.
Note the “From Directory” in the graphic above. If you installed your files per our directions, you
should have this folder. If you chose a different path for the CapTouch Library, your ‘From’
directory location will be different.
11. Add another (-I) search path to the new Library folder.
Once again, this is easy since we can just add it using the Workspace button.
Hint: Every time you add source files to a project, stop and think if you need to include a
directory to the compiler’s search path.
Note: If you build the program right after step 11, you will get an error. We will “fix” this on the
next page.
__________________________________________________________________________
13. Copy structure.h and structure.c from the CapTouch Library’s Code Examples
folder.
Rather than create these files from scratch, we’re going to copy then modify them – which is
what we recommend you do when you implement your own design.
We suggest choosing the files that match your HAL selection. The HAL we chose was
RO_PINOSC_TA0_WDTp; therefore, we recommend copying the ‘structure’ files from that
directory path. (Doing so will mean fewer modifications required later on.)
Right-click on your project → Add Files…
Navigate to your CAPT library Code Examples folder and copy the two files to your project:
http://processors.wiki.ti.com/index.php/GCC_Extensions_in_TI_Compilers
Hint: Please remember that if you try to building your program with the Release (i.e. optimized)
build configuration, you will end up running into the same path and gcc errors.
In other words, you must add these options to every build configuration that you plan to
use.
Writing/Editing Code
Get your Planning Worksheet ready. We’ll be using it as we write our code and fill-in the blanks.
structure.c
Per our earlier planning, we want our structure.c file to contain 1 Sensor (middle button)
which contains 1 Element. The structure.c file we copied gets us close to what we need; it
just requires a little editing.
17. Open structure.c and remove the code that isn’t required.
− Delete the superfluous comments at the beginning of the file (tedious to scroll thru)
− Eliminate all Element struct’s except the middle_element.
− Finally, we’ll keep the middle_button sensor, but you can get rid of the other two
//*** Sensor
const struct Sensor middle_button = {
.halDefinition = RO_PINOSC_TA0_WDTp,
.numElements = 1,
.baseOffset = 4,
// Pointer to elements
.arrayPtr[0] = &middle_element, // point to first element
// Timer Information
.measGateSource= GATE_WDT_SMCLK, //0->SMCLK, 1-> ACLK
//.accumulationCycles= WDTp_GATE_32768 //32768
.accumulationCycles= WDTp_GATE_8192 //8192
//.accumulationCycles= WDTp_GATE_512 //512
//.accumulationCycles= WDTp_GATE_64 //64
};
18. Update the following items – most of them are from the Planning Worksheet.
Many items are fine, just as they are:
− Port and bit definitions
− HAL selection
− Number of elements
− Gate clock source
But other items need to be updated…
Hint: Try changing the “middle_element” name using the CCS refactoring feature.
Highlight the variable, then: Right-click → Refactor → Rename
You should see the name change in both places where it exists.
structure.h
19. Open structure.h for editing.
23. Verify/update the remaining #define’s in the “User Configuration Section” of the file.
You should specifically check on two items in the remaining part of the User Configuration
Section (the top part of this file):
• Make sure the HAL you chose (on your Planning Worksheet) is uncommented. If you
imported this file from the correct code example, this should already be set correctly.
• Since we’re not using a slider or wheel in this exercise, you can comment out their
#definitions.
24. Save your changes. The top portion of your code should look like our code below:
Note, we removed some of the commented-out #defines to minimize space in this listing:
//******************************************************************************
// The following elements need to be configured by the user.
//******************************************************************************
#ifndef CTS_STRUCTURE
#define CTS_STRUCTURE
#include "msp430.h"
#include <stdint.h>
/* Public Globals */
extern const struct Element myButton_element; // myButton_element is defined in structure.c
extern const struct Sensor myButton; // myButton is defined in structure.c
// OSCILLATOR DEFINITIONS
//#define RO_COMPAp_TA0_WDTp 64
#define RO_PINOSC_TA0_WDTp 65
//******************************************************************************
// End of user configuration section.
//******************************************************************************
main.c
We’re now going to adapt the current program so that it lights the LED when the middle button is
touched. We already have a program that initializes our system and puts the CPU to sleep; then,
Timer1 wakes the system every 50ms and toggles the green LED.
Further, we have already defined our capacitive touch sensor (and element) in the structure.c/.h
files. What remains is adding a few items to main.c. These include:
• A couple header files and global variables
• Code to read the sensor’s baseline (background) capacitance
• An if statement that lights the LED when a button press is sensed
• UART function to send data to the TouchPro tool. This will aid with ‘tuning’ your button’s
responsiveness
#include Section
25. Open main.c and add the header files required to use the CapTouch library.
The CTS_Layer.h file includes prototypes for all the CapTouch library functions, so we will
need to include it. Also, we need to reference structure.h, since it provides visibility to the
Sensor variable we defined in structure.c.
#define Section
26. Add two items to the #define section of main.c.
We use the TUNE definition to determine whether or not to send data to the TouchPro GUI.
We’ve seen earlier that the TouchPro tool can handle multiple data channels; in our case, this
means sending count data from multiple Elements. How many channels will we send? It’s
common to set this equal to the total number of Elements in your system – which happens to
be defined in structure.h (as TOTAL_NUMBER_OF_ELEMENTS).
In our example, what will be the value for total number of elements? ___________________
Global Variables
27. No global variables are needed.
Though, later we will add a local variable to the Timer1 ISR.
main() function
28. Add the following function calls to main(), after the call to UART_init().
These two functions call into the Cap Touch library to calculate/update the baseline
capacitance for our Button sensor. The first call makes an initial measurement; the second
makes two more measurements to ensure accuracy.
That’s all the code required for the main() function. The rest of the code will be added to the
Timer1 ISR.
Timer1 ISR
Three items need to be added to the Timer1 ISR.
30. Use the CapTouch library to determine if the button is being pushed. If detected, light
the LED.
We’ve already seen the code to turn the LED on/off. In fact, it’s in almost every lab in the
workshop.
The TI_CAPT_Button() function call determines whether the button was pushed. By passing
a pointer to the sensor, the Button function will count the oscillations over the button’s Gate
Time. If this count exceeds the Threshold, it will return 1, otherwise it returns 0.
TI_CAPT_Custom() does not return a value, but rather updates the ‘counts’ array with timer
count values obtained during the Gate Time.
Note: This is why the sensor data structure has the .baseOffset field; in essence, this field
is an index into the ‘counts’ array. In other words, it lets the TI_CAPT_Custom()
function know which position(s) to store count data within the ‘counts’ array.
The UART_sendDataFrame() function formats and sends the ‘counts’ array to the TouchPro
GUI. Its arguments are the ‘counts’ array, as well as the length of that array.
Hint: If you had many different sensors that you were tuning, you could call the
TI_CAPT_Custom() function for each sensor; after all the counts are collected, call
the UART_sendDataFrame() function.
33. Click the Debug button to start the debugger and load the program to your MSP430.
Is the Green LED still flashing on/off about once per second? ________________________
Describe how the BoosterPack’s middle LED. Does it light up? _______________________
__________________________________________________________________________
In fact, can you see the effects of your finger pressing the middle CapTouch button? ______
_________________________________________________________________________
OK, so what can we learn from visualizing the data in this way?
− First, the button appears to be working, even if the LED is always turned on.
− The LED is always on since we have the Threshold set at “0”. As you can see, the
count value is always above 0; hence, the Button function always returns “1”.
− There is only one channel of data … which is what we expected, since we are only
using a single sensor, which has just one element.
− In our example, there appears to be some periodic noise (maybe the flashing LED?).
− Try different types of button presses to get a feel for how they show up in the GUI.
− Remember, if you want to re-view this data later, use the File menu to save it; then
you can re-load the count data later on.
Threshold
36. Pick a Threshold value.
You want to pick a threshold that is high enough above the noise so that it doesn’t trigger
erroneously, but low enough not to miss any actual touches.
Based on our results above, we’re going to pick 100. (If we wanted to allow lighter touches,
maybe 80 would be better. But, for now we’ll stick with 100.)
37. Now we can finalize the code and set the threshold.
Terminate the Debug session and return to editing.
In structure.c, change the value for Threshold, replacing 0 with your chosen value.
Does the LED light when you push the button? ____________________________________
Hint: You can use the mouse to select nodes on the graph to get see its exact count value.
This is especially helpful if your tool is displaying multiple channels of data.
Make sure you are looking at the Y value at the bottom of the graph. That’s the value
which displays the count data.
39. Terminate the active debug session using the Terminate button, then close the
Lab10c project.
In lab 10c, we cheated and used the Grace tool. It conveniently wrote the code required to
configure our clocks and our Scan Rate timer. Of course, this isn’t really cheating – in fact, this is
one of the reasons TI created Grace – to make MSP430 programming easier.
While Grace is covered in quite a bit more detail in Chapter 8, we wanted to walk thru the steps
we used to create ‘our’ code.
Click on the “Device Overview” button to get a graphical layout of your MSP430 device:
When using any of these modules, first of all, make sure the Enable is selected.
Then click on Basic User to view:
Once you’re in the Watchdog+ module, click on the Basic User view.
6. Configure the Watchdog Timer as an interval timer running with a 1.024 ms period.
From our Planning Worksheet, our goal was to get the WDT+ timer down to a 1ms time
period. So working back from there, we chose the 500 kHz SMCLK, along with the 512
Divider.
Hint: Funny, though, but we are not actually going to use this code – or even program the
WDT+ timer ourselves. Because we’re using the RO_PINOSC_T0_WDTp version of
the HAL, the library functions will handle programming the Gate Timer for us.
We used to scratch our heads and use calculators or spreadsheets to figure out how
to set the clocks and timers to the rates we needed. Nowadays, Grace makes this
much easier for the devices it supports.
When we began this exercise, we didn’t know which clock to use, or how to set its
dividers. In just a couple minutes, though, Grace helped us figure that out … and, it
even writes the code for us.
Once again, we could have – and in the past, often have – figured the timing out on our own,
but this is so much easier.
Timer1 was a convenient choice as it wasn’t already being used in the application.
Due to our HAL selection, the CapTouch library was going to be using WDT+ and
Timer0. They only use these peripherals while running one of the TI_CAPT_ function
calls – which means we could have still used one of them to do our Scan Rate timing.
Even though it could be done, it was much easier utilizing another, available Timer.
When the build finishes, notice that a new “src” folder was added to the project.
As you can see above, here are the two files we used in our previous lab exercise.
11. Grab these files and try them in your previous project, if you want to test them out.
You could even use Grace to regenerate these files using different clock rates and such. This
would be an easy way to experiment with the previous lab exercise.
Sliders 0 0
Wheels 0 0
Proximity 0 0
Total # Elements 1
MS430G2553 1 0 0
1 MHz
20
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 1
What is Arduino
Chapter Topics
Using Energia (Arduino) with the MSP430 ............................................................................. 11-1
What is Arduino ....................................................................................................................... 11-3
Energia .................................................................................................................................... 11-4
Programming Energia (and Arduino) ...................................................................................... 11-7
Programming with ‘Wiring’ .................................................................................................. 11-7
Wiring Language/Library Reference ................................................................................... 11-8
How Does ‘Wiring’ Compare? ............................................................................................. 11-9
Hardware pinout ................................................................................................................ 11-10
Energia IDE ........................................................................................................................... 11-12
Examples, Lots of Examples ............................................................................................. 11-13
Energia/Arduino References ................................................................................................. 11-14
11 - 2 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
What is Arduino
What is Arduino
Physical Computing … Hardware Hacking … a couple of the names given to Arduino.
Our home computers are great at communicating with other computers and (sometimes) with
us, but they have no idea what is going on in the world around them. Arduino, on the other
hand, is made to be hooked up to sensors which feed it physical information.1 These can be
as simple as pressing a button, or as complex as using ultrasound to detect distance, or
maybe having your garage door tweet every time it’s opened.
So the Arduino is essentially a simple computer with eyes and ears. Why is it so popular?
Because the hardware is cheap, it’s easy to program and there is a huge web community,
which means that beginners can find help and download myriad programs.1
What is Arduino?
Hardware
Open source C boards with pins and I/O
Tools
IDE: write, compile, upload
Physical Computing
Software that interacts with the real world
Open-source ecosystem
Code Tools, Software, Hardware (Creative Commons)
‘Wiring’ Language includes:
C/C++ software
Popular solution for…
Open-source programmers, hobbyists,
Arduino library of functions
rapid prototyping
The idea is to write a few lines of code, connect a few electronic components to the Wiring
hardware and observe how a light turns on when person approaches it, write a few more
lines, add another sensor, and see how this light changes when the illumination level in a
room decreases. This process is called sketching with hardware; explore lots of ideas very
quickly, select the more interesting ones, refine and produce prototypes in an iterative
process.2
1
http://www.wired.com/gadgetlab/2008/04/just-what-is-an/
2
http://en.wikipedia.org/wiki/Wiring_%28development_platform%29
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 3
Energia
Energia
/enerˈɡia/ ; e‧ner‧gi‧a
Energia (Russian: Энергия, Energiya, "Energy") was a Soviet rocket that was designed by NPO
Energia to serve as a heavy-lift expendable launch system as well as a booster for the Buran
spacecraft.3
Energia was a
Soviet Rocket
Energia is a fork of Arduino for
Texas Instruments MicroControllers
Software – Wiring programming language
Tools – Energia IDE
Hardware (supported MCU’s)
MSP430 LaunchPad
MSP430 FRAM “FraunchPad”
Stellaris Cortex-M4F Launchpad
Dev’l Project – energia.github.com/Energia/
Support – forum.43oh.com
Energia is a rapid electronics prototyping platform for the Texas Instruments msp430 LaunchPad.
Energia is based on Wiring and Arduino and uses the Processing IDE. It is a fork of the Arduino
ecosystem, but centered around the popular TI microntrollers: MSP430 and ARM Cortex-M4F.
3
http://en.wikipedia.org/wiki/Energia
11 - 4 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Energia
Energia Lineage
Fritzing
(2009)
Design By Numbers (or DBN programming language) was an influential experiment in teaching
programming initiated at the MIT Media Lab during the 1990s. Led by John Maeda and his
students they created software aimed at allowing designers, artists and other non-programmers
to easily start computer programming. The software itself could be run in a browser and published
alongside the software was a book and courseware.4
Processing (2001) - One of the stated aims of Processing is to act as a tool to get non-
programmers started with programming, through the instant gratification of visual feedback.5
This process is called sketching with hardware; explore lots of ideas very quickly, select the
more interesting ones, refine and produce prototypes in an iterative process.
Wiring (2003)6 - The Wiring IDE is a cross-platform application written in Java which is derived
from the IDE made for the Processing programming language. It is designed to introduce
programming and sketching with electronics to artists and designers. It includes a code editor …
capable of compiling and uploading programs to the board with a single click.
The Wiring IDE comes with a C /C++ library called "Wiring", which makes common
input/output operations much easier. Wiring programs are written in C/C++, although users
only need to define two functions to make a runnable program: setup() and loop().
When the user clicks the "Upload to Wiring hardware" button in the IDE, a copy of the code is
written to a temporary file with an extra include header at the top and a very simple main()
function at the bottom, to make it a valid C++ program.
4
http://en.wikipedia.org/wiki/Design_By_Numbers_%28programming_language%29
5
http://en.wikipedia.org/wiki/Processing_(programming_language)
6
http://en.wikipedia.org/wiki/Wiring_%28development_platform%29
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 5
Energia
Energia (2012) – As explained in the previous section of this chapter, Energia is a fork of Arduino
which utilizes the Texas Instruments microcontroller Launchpad development boards.
7
http://en.wikipedia.org/wiki/Arduino
8
http:// Fritzing.org
11 - 6 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Programming Energia (and Arduino)
Programming in Arduino is relatively easy. Essentially, it is C/C++ programming, but the Wiring
library simplifies many tasks. As an example, we use the Blink sketch (i.e. program) that is one of
examples that is included with Arduino (and Energia). In fact, this example is so ubiquitous that
most engineers think of it as “Hello World” of embedded programming.
How does the ‘Wiring’ library help to make things easier? Let’s examine the Blink code above:
About the only difference between Arduino and Energia programming is that you might see some
hardware specific commands in the sketch. For example, in one of the later lab exercises, you will
see how you can change the clock source for the TI MSP430 microcontroller. Changing clocks is
often done on the MSP430 so that you can balance processing speed against long battery life.
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 7
Programming Energia (and Arduino)
Arduino provides a language reference on their website. This defines the operators, controls, and
functions needed for programming in Arduino (and Energia).9 You will also find a similar HTML
reference available in the Energia installation zip file.
9
http://arduino.cc/en/Reference/HomePage
11 - 8 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Programming Energia (and Arduino)
This comparison helps to demonstrate the simplicity of programming with Energia. As stated
before, this can make for very effective rapid prototyping.
Later, during one of the lab exercises, we will examine some of the underpinings of Wiring.
Although the language makes programming easier, the same actual code is required for both
sides of this diagram. In the case of Wiring, this is encapsulated by the language/library. You will
see later on where this is done; armed with this knowledge, you can change the default values
defined by the folks who ported Arduino over to Energia for the TI microcontrollers.
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 9
Programming Energia (and Arduino)
Hardware pinout
Arduino programming refers to Arduino “pins” throughout the language and examples. In the
original implementation, these refer directly to the original hardware platform.
When adapting the Arduino library/language over to other processors, such as the TI
microcontrollers, these pins must be mapped to the available hardware. The following screen
capture from the Energia wiki shows the mapping for the MSP430 (v1.5 ‘G2553) Launchpad
development board. There are similar diagrams for the other supported TI boards; please find
these at wiki page: https://github.com/energia/Energia/wiki/Hardware.
The Grey values show the hardware elements that are being mapped, such as the LED’s or
PushButton. You can use these alternative names: RED_LED; GREEN_LED; PUSH2; and
TEMPSENSOR. Thus, to turn on the red LED, you could use:
pinMode(RED_LED, OUTPUT);
digitalWrite(RED_LED, HIGH);
Pins can also be address by there alternative names, such as P1_0. These correlate to the GPIO
port (P1) and pin (0) names (P1.0) as defined by the MSP430. (In fact, the Launchpads
conveniently show which I/O pins are mapped to the Boosterpack header connectors.) Using
these symbols, we can write to pins using the following:
pinMode(P1_0, OUTPUT);
digitalWrite(P1_0, HIGH);
11 - 10 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Programming Energia (and Arduino)
The remaining colored items show how various pins are used for digital, analog or
communications purposes. The color legend on the right side of the diagram demonstrates the
meaning of the various colors.
Green indicates that you can use the associated pins with the digitalRead() and
digitalWrite() functions.
Purple is similar to Green, though you can also use the analogWrite() function with these
pins.
Yellow , Orange
Orange , and Red specify these pins are used for serial communication: UART,
I2C, and SPI protocols, respectively.
Finally, Blue demonstrates which pins are connected to the MSP430’s ADC (analog to
digital converter).
Sidebar
How can some ‘pins’ be connected to various pieces of hardware? (For example, PUSH2 and A3
(analog input 3) are both mapped to pin 5.)
Well, most processors today have multiplexed pins; i.e. each pin can have multiple functionality.
While a given ‘pin’ can only be used for one function at a time, the chip designers give users
many options to choose from. In an ideal world, we could just put as many pins as we want on a
device; but unfortunately this costs too much, therefore multiplexing is a common
cost/functionality tradeoff.
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 11
Energia IDE
Energia IDE
The Energia IDE (integrated debugger and editor; integrated development environment) has been
written in Java. This is how they can provide versions of the tools for multiple host platforms
(Wndows, Mac, Linux).
Energia Debugger
Verify/Compile
Download
New
Open
Installation Save
Simply unzip Energia package
Everything is included: debugger, libraries,
board files, compilers
Download button…
Performs compile and downloads the
program to the target
Debugging – Use common open-src methods
Write values to serial port: Serial.println()
Toggle pins & watch with o-scope
Installation of the tools couldn’t be much simplier – unzip the package … that’s it. (Though, if you
have not already installed TI’s Code Composer Studio IDE, you may have to install drivers so that
the Energia debugger can talk to the TI Launchpad board.)
Editing code is straightforward. Syntax highlighting, as well as brace matching help to minimize
errors.
Compiling and downloading the program is as simple as clicking the Download button.
Debugging code is handled in the common, open-source fashion: printf() style. Although, rather
than using printf(), you can use the Serial print functions to keep track of what is going on with
your programs. Similarly, we often use LED’s to help indicate status of program execution. And, if
you have an oscilloscope or logic analyzer, you can also toggle other GPIO pins to evaluate the
runtime state of your program sketches. (We explore using LED’s and serial communications in
the upcoming lab exercises.)
11 - 12 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Energia IDE
Selecting example…
Opens sketch in
debugger window
Click download to
compile, download
and run
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 13
Energia/Arduino References
Energia/Arduino References
There are many more Arduino references that could possibly be listed here, but this should help
get you started.
Launchpad Boards
MSP430: http://www.ti.com/tool/msp-exp430g2 (wiki) (eStore)
ARM Cortex-M4F: Launchpad Wiki eStore
Arduino:
Site: http://www.arduino.cc/
Reference: http://arduino.cc/en/Reference/HomePage
Comic book: http://www.jodyculkin.com/.../arduino-comic-latest3.pdf
Energia
Home: http://energia.nu/
Download: http://energia.nu/download/
Wiki: https://github.com/energia/Energia/wiki
Supported Boards: https://github.com/energia/Energia/wiki/Hardware
(H/W pin mapping)
Getting Started: https://github.com/energia/Energia/wiki/Getting-Started
Support Forum: http://forum.43oh.com/forum/28-energia/
Launchpad Boards
MSP430: http://www.ti.com/tool/msp-exp430g2 (wiki) (eStore)
ARM Cortex-M4F: Launchpad Wiki eStore
Arduino
Site: http://www.arduino.cc/
Reference: http://arduino.cc/en/Reference/HomePage
Comic book: http://www.jodyculkin.com/.../arduino-comic-latest3.pdf
11 - 14 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
Lab 11
This set of lab exercises will give you the chance to start exploring Energia: the included
examples, the ‘Wiring’ language, as well as how Arduino has been adapted for the TI Launchpad
boards.
The lab exercises begin with the installation of Energia, then give you the opportunity to try out
the basic ‘Blink’ example included with the Energia package. Then we’ll follow this by trying a few
more examples – including trying some of our own.
Lab Exercises
Installing Energia
A. Blinking the LED
B. Pushing the Button
C. Serial Communication & Debugging
D. Interrupts
E. Blink Fast … Blink Slow … Blink Very Slow
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 15
Lab 11
Installing Energia
If you already installed Energia as part of the workshop prework, then you can skip this step and
continue to Lab 11a – Blink.
These installation instructions were adapted from the Energia Getting Started wiki page. See this
site for notes on Mac OSX and Linux installations.
https://github.com/energia/Energia/wiki/Getting-Started
Note: If you are attending a workshop, the following files should have been downloaded as part
of the workshop’s pre-work. If you need them and do not have network access, please
check with your instructor.
Installing Energia
2. Download Energia, if you haven’t done so already.
The most recent release of Energia can be downloaded from the download page.
Windows Users
Double click and extract the energia-0101EXXXX-windows.zip file to a desired location.
11 - 16 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 17
Lab 11
File Preferences
Which opens:
11 - 18 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
6. Select the board you are using – most likely the msp430g2553 (16MHz).
To select the board or rather the msp430 in your LaunchPad, select Board from the Tools
menu and choose the board that matched the msp430 in the LaunchPad.
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 19
Lab 11
As simple as this example is, it’s a great way to begin. In fact, if you have followed the flow of this
workshop, you may recognize the Blink example essentially replicates the lab exercise we
created in Chapter 3 of the workshop.
As we pointed out during the Energia chapter discussion, the Wiring language simplifies the code
quite a bit. We will explore how this is accomplished – i.e. where these differences/simplifications
come from in Lab11e – Changing the CPU Clocks (Blink Fast, Blink Slow, Blink Really Slow).
11 - 20 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
/*
Blink
Turns on an LED on for one second, then off for one second,
repeatedly. This example code is in the public domain.
*/
void setup () {
// initialize the digital pin as an output.
// Pin 14 has an LED connected on most Arduino boards:
pinMode (RED_LED, OUTPUT);
}
void loop () {
digitalWrite (RED_LED, HIGH); // turn on LED
delay (1000); // wait one second (1000ms)
digitalWrite (RED_LED, LOW); // turn off LED
delay (1000); // wait one second
}
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 21
Lab 11
To compile and upload the Sketch to the LaunchPad click the button.
Do you see the LED blinking? What color LED is blinking? __________________________
Hint: We recommend you check out the Hardware Pin Mapping to answer this last
question. There’s a copy of it in the presentation. Of course, the original is on the
Energia wiki.
11 - 22 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
Modifying Blink
4. Copy sketch to new file before modification.
We recommend saving the original Blink sketch to a new file before modifying the code.
Save it to:
C:\MSP430_LaunchPad\Energia\Blink_Green
C:\MSP430_LaunchPad\Energia\Blink_Green\Blink_Green.ino
Energia requires the sketch file (.ino) to their to be in a folder named for the project.
________________________________________________________________________
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 23
Lab 11
When you push the button the (GREEN or RED) LED goes (ON or OFF)? ______________
By the way, you probably know this already from earlier in the workshop, but which button are
we using? Remember, the “user” button is called PUSH2 (the board silkscreen says P1.3) as
shown here:
_________________________________________________________________________
_________________________________________________________________________
_________________________________________________________________________
11 - 24 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
_________________________________________________________________________
Finally, this is a very simple way to read and respond to a button. What would be a more
efficient way to handle responding to a pushbutton? (And why would this be important to
many of us MSP430 users?)
________________________________________________________________________
_________________________________________________________________________
(Note, we will look at this ‘more efficient’ method in a later part of the lab.)
Hint: The changes required are similar to what you would do in C, they are not unique to
Energia/Arduino.
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 25
Lab 11
In and of itself, this is a useful and common thing we do in embedded processing. It’s the most
common way to talk with other hardware. Beyond that, this is also the most common debugging
method in Arduino programming. Think of this as the “printf” for the embedded world of
microcontrollers.
void setup() {
Serial.begin(9600); // msp430g2231 must use 4800
pinMode(PUSH2, INPUT_PULLUP);
}
void loop() {
int sensorValue = digitalRead(PUSH2);
Serial.println(sensorValue);
}
As you can see, serial communication is very simple. Only one function call is needed to
setup the serial port: Serial.begin(). Then you can start writing to it, as we see here in the
loop() function.
Note: Why are we limited to 9600 baud (roughly, 9600 bits per second)?
The Launchpad onboard emulation’s USB to serial bridge is limited to 9600 baud. It is not
a hardware limitation of the MSP430 device. Please refer to the wiki for more info:
https://github.com/energia/Energia/wiki/Serial-Communication.
11 - 26 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
With the Serial Monitor open, and the sketch running, you should see something like this:
You should see either a “1” or “0” depending
upon whether the putton is up or down.
Also, notice that the value is updated
continuously, since the sketch reads the button
and writes it to port in the loop() function.
________________________________________________________________________
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 27
Lab 11
Did you see the Serial Monitor and LED changing when you push the button?
________________________________________________________________________
Serial Port; LED (And, what if you didn’t have an LED available on your board?):
_________________________________________________________________________
_________________________________________________________________________
________________________________________________________________________
How is this (and all our sketches, up to this point) inefficient? ________________________
________________________________________________________________________
11 - 28 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
Thusfar, we have actually worked with a couple different interrupts without having to know
anything about them. Our serial communications involved interrupts, although the Wiring
language insulates us from needing to know the details. Also, there is a timer involved in the
delay() function; thankfully, it is also managed automatically for us.
In this part of the lab exercise, you will setup two different interrupts. The first one will be triggered
by the pushbutton; the second, by one of the MSP430 timers.
Save it to:
C:\MSP430_LaunchPad\Energia\Interrupt_PushButton
3. Before we modify the file, run the sketch to make sure it works properly.
Adding an Interrupt
Adding an interrupt to our Energia sketch requires 3 things:
An interrupt source – what will trigger our interrupt. (We will use the pushbutton.)
An ISR (interrupt service routine) – what to do when the interrupt is triggered.
The interruptAttach() function – this function hooks a trigger to an ISR. In our case, we
will tell Energia to run our ISR when the button is pushed.
void myISR()
{
digitalWrite(GREEN_LED, HIGH);
}
In our function, all we are going to do is light the GREEN_LED. If you push the button and the
Green LED turns on, you will know that successfully reached the ISR.
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 29
Lab 11
Help Reference
1. _______________________________________________________________________
2. _______________________________________________________________________
3. _______________________________________________________________________
One you have figured out the parameters, add the function to your setup() function.
When you push the button, does the GREEN_LED light? ___________________________
When you push reset, the code should start over again. This should turn off the
GREEN_LED, which you can then turn on again by pushing PUSH2.
Note: Did the GREEN_LED fail to light up? If so, that means you are not getting an
interrupt.
First, check to make sure you have all three items – button is configured;
attachInterrupt() function called from setup(); ISR routine that lights the GREEN_LED
The most common error involves setting up the push button incorrectly. The button
needs to be configured with INPUT_PULLUP. In this way, the button is held high
which lets the system detect when the value falls as the button is pressed.
11 - 30 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
TIMER_A
9. Create a new sketch and call it Interrupt_TimerA
File New
File Save As…
C:\MSP430_LaunchPad\Energia\Interrupt_TimerA
#include <inttypes.h>
uint8_t timerCount = 0;
void setup()
{
pinMode(RED_LED, OUTPUT);
CCTL0 = CCIE;
TACTL = TASSEL_2 + MC_2;
}
void loop()
{
// Nothing to do.
}
__attribute__((interrupt(TIMER0_A0_VECTOR)))
void myTimer_A(void)
{
timerCount = (timerCount + 1) % 800;
if(timerCount ==0)
P1OUT ^= 1;
}
In this case, we are not using the attachInterrupt() function to setup the interrupt. If you
double-check the Arduino reference, it states the function is used for ‘external’ interrupts. In
our case, the MSP430’s Timer_A is an internal interrupt.
In essense, though, the same three steps are required:
a) The interrupt source must be setup. In our example, this means seting up the timers
CCTL0 (capture/compare control) and TACTL (TimerA control) registers.
b) An ISR function – which, in this case, is named “myTimer_A”.
c) A means to hook the interrupt source (trigger from TimerA) to our function. In this case,
we need to plug the Interrupt Vector Table ourselves. The GCC compiler uses the
__attribute__((interrupt(TIMER_A0_VECTOR))) line to plug the Timer_A0 vector.
Note: You might remember that we introduced Interrupts and Timers in Chapter 5. In that
lab, the syntax for the interrupt vector was slightly different that it is here. This is
because we were using the TI compiler in that lab. Energia uses the open-source
GCC compiler, which has a slightly different syntax.
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 31
Lab 11
3. Speed up the initial blink rate by changine the arguments for delay().
When we slow down the clock, it will be much easier to visualize the different clock rates if we
speed up the blink rate. Do this by changing the arguments to the delay() functions.
digitalWrite(RED_LED, HIGH);
delay(10); //changed from 1000
digitalWrite(RED_LED, LOW);
delay(50); //changed from 1000
_________________________________________________________________________
If Energia/Arduino is built around the C language, where is the main() function? Once we
answer this question, then we will see how the system clock is initialized.
11 - 32 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
When you click the Download button, the tools combine your setup() and loop() functions into
the main.cpp file included with Energia for your specific hardware.
Main should look like this:
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 33
Lab 11
C:\TI\energia-0101E0009\hardware\msp430\cores\msp430\wiring.c
The init() function implements the essential code required to get the MSP430 up and running.
If you have already completed Chapter 3 – Inititialization and GPIO, then you should
recognize most of these activities. At reset, you need to perform two essential activies:
Initialize the clocks (choose which clock source you want use)
Turn off the Watchdog timer (unless you want to use it, as a watchdog)
The Energia init() function takes this three steps further. They also:
Setup the Watchdog timer as a standard (i.e. interval) timer
Setup two GPIO pins
Enable interrupts globally
// wiring.c
void init()
{ wiring.c provides the core files for
disableWatchDog(); device specific architectures
initClocks();
init() is where the default
enableWatchDogIntervalMode();
initializations are handled
// Default to GPIO (P2.6, P2.7)
P2SEL &= ~(BIT6|BIT7); As discussed in Ch 3 (Init & GPIO)
__eint(); Watchdog timer (WDT+) is
} disabled
enableWatchDogIntervalMode()
Clocks are initialized (DCO 16MHz)
initClocks()
disableWatchDog() WDT+ set as interval timer
enableWatchDog()
delayMicroseconds()
delay()
watchdog_isr ()
initClocks() ...
11 - 34 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
In this lab exercise, we will do the latter method. This has advantages & disadvantages:
Advantages
Do not need to re-modify wiring.c after updating to new revision of Energia
Changes are explicitly shown in your own sketch
Each sketch sets its own clocking, if it needs to be changed
In our lab, it allows us to demonstrate that you can modify hardware registers – i.e.
processor specific hardware – from within your sketch
Disdvantages
Code portability – any time you add processor specific code, this is something that will
need to be modified whenever you want to port your Arduino/Energia code to another
target platform
A little less efficient in that clocking gets set twice
You have to change each sketch (if you always want a different clock source/rate)
8. Write the code to run the MSP430 using the DCO at 1MHz.
Add the following code to your setup() function. (We have provided comments for the code,
but for a better explanation of this code, please refer back to Lab 3.)
if (CALBC1_1MHZ ==0xFF || CALDCO_1MHZ == 0xFF)
FaultRoutine(); // If calibration data is erased
// run FaultRoutine()
BCSCTL1 = CALBC1_1MHZ; // Set range
DCOCTL = CALDCO_1MHZ; // Set DCO step + modulation
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 35
Lab 11
C:\MSP430_LaunchPad\Energia\Blink_VLO
As our final experiment, let’s change the clock source to the VLO – very low frequency oscillator.
This internal clock source runs about 12KHz, which is very slow compared to using the DCO.
Why would we want to use the VLO (do you remember this from Chapter 3)?
_________________________________________________________________________
13. Replace “clock setting code” in setup() with the following code to use the VLO.
Sorry, but once again, we’re going to defer the explanation of this code snippet back to Lab 3.
BCSCTL3 |= LFXT1S_2; // clock system setup
IFG1 &= ~OFIFG;
__bis_status_register(SCG1 + SCG0);
BCSCTL2 |= SELM_3 + DIVM_3;
You can delete the Fault Routine, if you would like. We will not use it for the VLO. No
calibration data is provided for the VLO. There is a white paper available that describes how
to calibrate the VLO from the DCO, though, most users prefer to use an external crystal
(called LFXT1) when a low-power, accurate clock is needed.
You would have to wait a long time to see it blink. Think of it this way, we saw it blinking when
the clock was running at 1MHz. We then changed the clock to 12KHz. That is a very large
difference. You might see it ‘blink’ if you wait long enough.
15. Can you really have an efficient delay()? Yes, you can.
What we haven’t discussed, up to this point, is that delay() is actually quite efficient. It uses a
timer, rather than a traditional delay loop. Using the timer, it can put the processor to sleep
while it wait for the specified time. Very clever!
If you want to see how this is implemented, examine how it was done in wiring.c. You will
notice that they change the watchdog timer (WDT) into a standard interval timer, then use
that timer to implement delay().
11 - 36 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
We took this code to setup the watchdog timer from wiring.c. The only thing we changed
was to set the WDTSSEL bit, which causes the timer to be sourced from VLO.
18. Finally, you should be able to run – and view – the LED blinking slowly.
If it’s still too slow for your taste, try changing the delay() functions to 1 and 5, respectively, as
opposed to 10 and 50.
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 37
Lab 11
Sidebar – initClocks()
Here is a snippet of the initClocks() function found in wiring.c. I say snippet, since I cut out the
other CPU speeds that are also available (8 & 12 MHz).
The beginning of this function starts out by setting the calibration constants (that are provided in
Flash memory) to their associated clock configuration registers.
If you work your way through the second and third parts of the code, you can see the BCS (Basic
Clock System) control registers being set to configure the clock sources and speeds. Once again,
there are more details on this in Chapter 3 and its lab exercise.
11 - 38 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
C:\TI\energia-0101E0009\hardware\msp430\boards.txt
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 39
Lab Debrief
Lab Debrief
Q&A: Lab11A (1)
Lab A
Red
3. Do you see the LED blinking? What color LED is blinking? _____________________
Pin 2
What pin is this LED connected to? _______________________________________
(Code says Pin14, it was RED that blinked)
_______________________________________
(Be aware, in the current release of Energia, this could be a trick question.)
11 - 40 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab Debrief
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 41
Lab Debrief
9. Considerations for debugging… How you can use both of these items for debugging?
(Serial Port and LED)
Use the serial port to send back info, just as you might use printf() in your C code.
_____________________________________________________________________
An LED works well to indicate you reached a specific place in code. For example,
later on we’ll use this to indicate our program has jumped to an ISR (interrupt routine)
_____________________________________________________________________
Similarly, many folks hook up an oscilloscope or logic analyzer to a pin, similar to
using an LED. (Since our boards have more pins than LEDs.)
_____________________________________________________________________
11 - 42 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab Debrief
Notes:
Use reset button to start program again and clear GREEN_LED
Most common error, not configuring PUSH2 with INPUT_PULLUP.
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430 11 - 43
Lab Debrief
11 - 44 Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430