MSP430 LaunchPad Workshop v2.22
MSP430 LaunchPad Workshop v2.22
MSP430 LaunchPad Workshop v2.22
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 TIs 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. Customers are responsible for their applications using TI components. In order to minimize risks associated with the customers 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. TIs publication of information regarding any third partys products or services does not constitute TIs 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
ii
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
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
C2000
32-bit Real-time
Tiva
32-bit All-around MCU
Hercules
32-bit Safety
ARM Cortex-M3 Cortex-R4
Sitara
32-bit Linux Android
ARM Cortex-A8 Cortex-A9
DSP
16/32-bit All-around DSP
DSP C5000 C6000
Multicore
32-bit Massive Performance
C66 + C66 A15 + C66 A8 + C64 ARM9 + C674 Fix or Float Up to 12 cores
4 A15 + 8 C66x DSP MMACs:
352,000
Motor Control 32-bit Float Lock step $5 Linux CPU C5000 Low Vector Dual-core R4 Power DSP Digital Power Nested IntCtrl (NVIC) ECC Memory 3D Graphics 32-bit fix/float Precision PRU-ICSS industrial subsys C6000 DSP Timers/PWM Ethernet (MAC+PHY) SIL3 Certified TI RTOS (SYS/BIOS) 512K Flash 300 MHz $1.85 to $20.00 TI RTOS (SYS/BIOS) 512K Flash 80 MHz $1.00 to $8.00 N/A 256K to 3M Flash 220 MHz $5.00 to $30.00 Linux, Android, C5x: DSP/BIOS SYS/BIOS C6x: SYS/BIOS L1: 32K x 2 L2: 256K 1.35 GHz $5.00 to $25.00 L1: 32K x 2 L2: 256K 800 MHz $2.00 to $25.00
1-3
MSP430 CPU
1-4
Memory Map
Memory Map
Flash programmable via JTAG or In-System (ISP) ISP down to 2.2V. Single-byte or Word Interruptible ISP/Erase Main memory: 512 byte segments (0-n). Erasable individually or all Information memory: 64 byte segments (A-D)
MSP430G2553 shown 0FFFFh Interupt Vector Table 0FFE0h Flash FFDFh 0C000h 010FFh 01000h
Information Memory
1-5
Independently programmable Any combination of input, output, and interrupt (edge selectable) is possible Read/write access to port-control registers is supported by all instructions Each I/O has an individually programmable pull-up/pull-down resistor Some parts/pins are touch-sense enabled (PinOsc) 2/3 capture/compare registers Extensive interrupt capabilities Also available as an interval timer Provides correct reset signal during power up and down Power consumption included in baseline current draw
16-bit Timer_A2 or A3
Brownout Reset
Serial Communication
USI with I2C and SPI support USCI with I2C, SPI and UART support Inverting and non-inverting inputs Selectable RC output filter Output to Timer_A2 capture input Interrupt capability 8 external channels (device dependent) Voltage and Internal temperature sensors Programmable reference Direct transfer controller send results to conversion memory without CPU intervention Interrupt capable Some parts have a slope converter
Comparator_A+
1-6
1-7
1-8
Download Checklist
Download Checklist
Integrated Development Environments (IDE)
Energia ( port of Arduino) Code Composer Studio v5.4
http://energia.nu/download 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.
These files are all found at the workshops wiki page: http://www.ti.com/launchpad-workshop
Install ?
Temperature demo source and GUI LaunchPad Users Guide C Compiler Users Guide MSP430x2xx Users Guide
1-9
Download Checklist
MSP430 Touch Pro Tool MSP430 CapTouch Power Designer CapTouch BoosterPack Software Capacitive Touch Library Getting Started with Capacitive Touch CapTouch BoosterPack Users Guide CapTouch Power Designer User Guide CapTouch Lib Programmers Guide
Additional information:
www.ti.com/launchpadwiki www.ti.com/launchpad www.ti.com/captouch
Capacitive Touch Library
1 - 10
Download Checklist
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.
1 - 11
Download Checklist
Youre done.
1 - 12
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 Optional: Capacitive Touch
12
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
2-3
Project Project
Link
Source files
Code and Data
Source files Source Header filesfiles Link Header Files Header Library filesFiles Library files Library files Build and tool settings Build and tool settings Link Build and tool settings
Header files
Declarations/Defines
Library files
Code and Data
A workspace contains your settings and preferences, as well as links to your projects. Deleting projects from the workspace deletes the links, not the files
A project contains your build and tool settings, as well as links to your input files. Deleting files from the workspace deletes the links, not the files Project Wizard
16
2-4
2-5
2-6
2-7
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
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 youre 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.
2-9
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.
2 - 10
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.
2 - 11
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). Click File Open File and navigate to C:\MSP430_LaunchPad\Labs\Lab2\Files. 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.
8. CCS can automatically save modified source files, build the program, open the debug perspective view, connect and download it to the target (flash device), and then run the program to the beginning of the main function. Click on the Debug button . When the Ultra-Low-Power Advisor (ULP Advisor) appears, click the Proceed button. Well take a look at the MSP430s 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.
2 - 12
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.
Hover over each button to see its function. 10. At this point your code should be at the beginning of main(). Look for a small blue arrow left of the opening brace of main() in the middle window. The blue arrow indicates where the Program Counter (PC) is pointing to. Click the Resume button Notice the red and green LEDs are toggling, as they did before. 11. Click Suspend function. to run the code.
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().
2 - 13
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/
2 - 14
3. Click File Open File and navigate to C:\MSP430_LaunchPad\Labs\Lab2\Files. 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. 4. If you are using the MSP430G2231, find the #include <msp430g2553.h> statement near the top of the code and replace it with #include <msp430g2231.h> Save your changes to main.c. 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().
2 - 15
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, youve probably either failed to get a good connection between the crystal lead and the pad, or youve created a solder bridge and shorted the leads. A good magnifying glass will help you find the problem.
8. Next, close the project by right-clicking on Verify_Crystal in the Project Explorer pane and select Close Project.
Youre done.
2 - 16
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 Optional: Capacitive Touch
Reset State
21
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
Software Initialization
After a system reset the software must:
Initialize the stack pointer (SP), usually to the top of RAM Reconfigure clocks (if desired) Initialize the watchdog timer to the requirements of the application, usually OFF for debugging Configure peripheral modules
Clock System
23
3-3
Clock System
Clock System
Very Low Power/Low Frequency Oscillator (VLO)* 4 20kHz (typical 12kHz) 500nA standby 0.5%/ C and 4%/Volt drift Not in 21x1 devices Crystal oscillator (LFXT1) Programmable capacitors Failsafe OSC_Fault Minimum pulse filter Digitally Controlled Oscillator (DCO) 0-to-16MHz + 3% tolerance Factory calibration in Flash
OSC_Fault
MCLK CPU
16MHz DCO
SMCLK Peripherals
On PUC, MCLK and SMCLK are sourced from DCOCLK at ~1.1 MHz. ACLK is sourced from LFXT1CLK in LF mode with an internal load capacitance of 6pF. If LFXT1 fails, ACLK defaults to VLO.
DCO
24
3-4
Calibrate the VLO during runtime Clock Timer_A runs on calibrated 1MHz DCO Capture with rising edge of ACLK/8 from VLO fVLO = 8MHz/Counts Code library on the web (SLAA340)
MCLK & Vcc
26
3-5
Watchdog Timer
If ACLK / SMCLK fail, clock source = MCLK (WDT+ fail safe feature) If MCLK is sourced from a crystal, and the crystal fails, MCLK = DCO (XTAL fail safe feature)
16-bit Counter
28
Active clock source cannot be disabled (WDT mode) May affect LPMx behavior & current consumption WDT(+) always powers up active
Lab
29
3-6
3-7
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
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 #define TIMER0_A0_VECTOR #endif void main(void) { // code goes here }
TIMERA1_VECTOR TIMERA0_VECTOR
MSP430G2xx Users Guide this document (slau144h) was downloaded in Lab1. This is the Users Guide for the MPS430 Value Line family. Open the .pdf file for viewing.
4.
For debugging purposes, it would be handy to stop the watchdog timer. This way we need not worry about it. In main.c right at //code goes here type: (Be sure not to forget the semicolon at the end). 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 Users 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).
3-9
5. Next, we need to configure the LED thats 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. Well 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 Users Guide to make sure you understand the concepts). 6. Now well 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 Users 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 ORs 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 Users 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 Users 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 Users 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 Users Guide and header file.
3 - 10
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" TIMERA1_VECTOR TIMERA0_VECTOR #ifndef TIMER0_A1_VECTOR #define TIMER0_A1_VECTOR #define TIMER0_A0_VECTOR #endif void main(void) { WDTCTL = WDTPW + WDTHOLD; P1DIR = 0x40; P1OUT = 0; BCSCTL3 |= LFXT1S_2; IFG1 &= ~OFIFG; _bis_SR_register(SCG1 + SCG0); } BCSCTL2 |= SELM_3 + DIVM_3;
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; _delay_cycles(100); P1OUT = 0; _delay_cycles(5000); } // LED on // LED off
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 isnt a very good way to generate delays so dont get used to using it. The while(1) loop repeats the next four lines forever.
3 - 11
12. Now, the complete code should look like the following. Be sure to save your work.
#include "msp430g2553.h" TIMERA1_VECTOR TIMERA0_VECTOR #ifndef TIMER0_A1_VECTOR #define TIMER0_A1_VECTOR #define TIMER0_A0_VECTOR #endif void main(void) { WDTCTL = WDTPW + WDTHOLD; P1DIR = 0x40; P1OUT = 0; BCSCTL3 |= LFXT1S_2; IFG1 &= ~OFIFG; _bis_SR_register(SCG1 + SCG0); BCSCTL2 |= SELM_3 + DIVM_3; while(1) { P1OUT = 0x40; _delay_cycles(100); P1OUT = 0; _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 cant have two main() functions in the same program). Right-click on Lab3a.c in the Project Explorer pane and select Resource Configurations, then Exclude from build Check both boxes and click OK.
3 - 12
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.
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 wouldnt 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;
3 - 13
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" TIMERA1_VECTOR TIMERA0_VECTOR #ifndef TIMER0_A1_VECTOR #define TIMER0_A1_VECTOR #define TIMER0_A0_VECTOR #endif
void main(void) { WDTCTL = WDTPW + WDTHOLD; P1DIR = 0x41; P1OUT = 0x01; BCSCTL3 |= LFXT1S_0 + XCAP_3; while(IFG1 & OFIFG) { IFG1 &= ~OFIFG; _delay_cycles(100000); } P1OUT = 0; _bis_SR_register(SCG1 + SCG0); BCSCTL2 |= SELM_3 + DIVM_3; while(1) { P1OUT = 0x40; _delay_cycles(100); P1OUT = 0; _delay_cycles(5000); }
// watchdog timer setup // I/O setup // clock system setup // wait for OSCFault to clear
Again, you could have cut and pasted from XT.txt, but youre 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. Thats 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 .
3 - 14
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. BCSCTL2 |= SELM_3 + DIVM_3; Change: BCSCTL2 |= SELM_0 + DIVM_3; To: Double check the bit selection with the Users Guide and header file.
3 - 15
if (CALBC1_1MHZ ==0xFF || CALDCO_1MHZ == 0xFF) { while(1); // If cal constants erased, } // trap CPU!! BCSCTL1 = CALBC1_1MHZ; DCOCTL = CALDCO_1MHZ; P1DIR = 0x41; P1OUT = 0x01; BCSCTL3 |= LFXT1S_0 + XCAP_3; while(IFG1 & OFIFG) { IFG1 &= ~OFIFG; _delay_cycles(100000); } P1OUT = 0; // _bis_SR_register(SCG1 + SCG0); BCSCTL2 |= SELM_0 + DIVM_3; while(1) { P1OUT = 0x40; _delay_cycles(100); P1OUT = 0; _delay_cycles(5000); } // Set range // Set DCO step + modulation // I/O setup // clock system setup // wait for OSCFault to clear
The code can be found in DCO_XT.txt, if needed. Save your changes. 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().
3 - 16
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 well 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.
3 - 17
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. BCSCTL2 |= SELM_3 + DIVM_3; Change: BCSCTL2 |= SELM_0 + DIVM_3; To: Double check the bit selection with the Users Guide and header file. Save your work.
3 - 18
if (CALBC1_1MHZ ==0xFF || CALDCO_1MHZ == 0xFF) { while(1); // If cal constants erased, } // trap CPU!! BCSCTL1 = CALBC1_1MHZ; DCOCTL = CALDCO_1MHZ; P1DIR = 0x40; P1OUT = 0; BCSCTL3 |= LFXT1S_2; IFG1 &= ~OFIFG; // _bis_SR_register(SCG1 + SCG0); BCSCTL2 |= SELM_0 + DIVM_3; while(1) { P1OUT = 0x40; _delay_cycles(100); P1OUT = 0; _delay_cycles(5000); } // Set range // Set DCO step + modulation // I/O setup // clock system setup
The code can be found in DCO_VLO.txt, if needed. Save your changes. 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.
3 - 19
Youre done.
3 - 20
Analog-to-Digital Converter
Introduction
This module will cover the basic details of the MSP430 Value Line analog-to-digital converter. In the lab exercise you will write the necessary code to configure and run the converter.
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 Optional: Capacitive Touch
ADC10
31
4-1
Module Topics
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
4-2
Analog-to-Digital Converter
Analog-to-Digital Converter
Fast Flexible ADC10
1.5V or 2.5V
Internal or External reference Timer-A triggers Interrupt capable Data Transfer Controller (DTC) Auto power-down
S/H
Batt Temp Direct Data Transfer Transfer Controller Controller RAM, Flash, Peripherals
Sample Timing
32
4-3
Analog-to-Digital Converter
Sample Timing
4-4
4-5
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.
4-6
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:
3. Next, make sure the SMCLK is also set up: Change: To:
The SMCLK default from reset is sourced by the DCO and DIVS_3 sets the SMCLK divider to 8. The clock set up is:
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.
4-7
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 Users 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:
4-8
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, its fine.
_delay_cycles(1000); Note that the compiler will accept a single or double underscore.
Referring to the Users Guide, the settling time for the internal reference is < 30s. 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 40s. Change the delay time to that value:
_delay_cycles(5);
enables the conversion and starts the process from software. According to the users guide, we should allow thirteen ADC10CLK cycles before we read the conversion result. Thirteen cycles of the 5MHz ADC10CLK is 2.6s. 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); :
ADC10CTL0 &= ~ENC; ADC10CTL0 &= ~(REFON + ADC10ON);
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 were 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); Getting Started with the MSP430 LaunchPad - Analog-to-Digital Converter 4-9
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 #define TIMER0_A0_VECTOR #endif volatile long tempRaw; void FaultRoutine(void); void main(void) { WDTCTL = WDTPW + WDTHOLD; P1DIR = 0x41; P1OUT = 0; TIMERA1_VECTOR TIMERA0_VECTOR
if (CALBC1_1MHZ ==0xFF || CALDCO_1MHZ == 0xFF) FaultRoutine(); // If cal 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 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 P1OUT = 0x40; _delay_cycles(100); ADC10CTL0 &= ~ENC; ADC10CTL0 &= ~(REFON + ADC10ON); tempRaw = ADC10MEM; P1OUT = 0; _delay_cycles(125000); // green LED off // green LED on
Note: for reference, this code can found in Lab4.txt. 12. Close the OPT_VLO.txt and Temperature_Sense_Demo.txt reference files. They are no longer needed.
4 - 10
4 - 11
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.
Youre done.
4 - 12
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 Optional: Capacitive Touch
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
Getting Started with the MSP430 LaunchPad - Interrupts and the Timer
5-3
Vector Table
Interrupt Source
Power-up External Reset Watchdog Timer+ Flash key violation PC out-of-range NMI Oscillator Fault Flash memory access violation Timer1_A3 Timer1_A3 Comparator_A+ Watchdog Timer+ Timer0_A3 Timer0_A3 USCI_A0/USCI_B0 receive USCI_B0 I2C status USCI_A0/USCI_B0 transmit USCI_B0 I2C receive/transmit ADC10 I/O Port P2 (up to 8) I/O Port P1 (up to 8)
System Interrupt
Reset Non-maskable Non-maskable Non-maskable maskable maskable maskable maskable maskable maskable maskable maskable maskable maskable maskable
Word Address
0FFFEh
Priority
31 (highest) 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 - 0
0FFFCh 0FFFAh 0FFF8h 0FFF6h 0FFF4h 0FFF2h 0FFF0h 0FFEEh 0FFECh 0FFEAh 0FFE8h 0FFE6h 0FFE4h 0FFE2h 0FFE0h
ISR Coding
39
ISR Coding
ISR Coding
#pragma vector=WDT_VECTOR { __interrupt void WDT_ISR(void) IE1 &= ~WDTIE; // disable interrupt
#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
Getting Started with the MSP430 LaunchPad - Interrupts and the Timer
5-5
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
Source File
The solution file from the last lab exercise will be used as the starting point for this lab exercise. Weve cleaned up the file slightly to make it a little more readable by putting the initialization code into individual functions. 1. Open the Lab5_Start.txt file using File Open File
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. 3. Close the Lab5_Start.txt file. It is no longer needed. 4. As a test build, load, and run the code. If everything is working correctly the green LED should be blinking about once per second and it should function exactly the same as the previous lab exercise. When done, halt the code and click the Terminate button to return to the CCS Edit perspective.
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
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 its pretty simple, so lets do it ourselves. Add the following code as the first line:
CCTL0 = CCIE;
This enables the counter/compare register 0 interrupt in the CCTL0 capture/compare control register. Unlike the previous lab exercise, this one will be using interrupts. Next, add the following two lines:
CCR0 = 12000; TACTL = TASSEL_1 + MC_2;
Wed 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 Users 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 Users Guide. This Users 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 (thats automatic) b) CCR0 has to be set 12,000 cycles into the future So add the following as the last line in the ISR:
CCR0 +=12000;
5-8
Getting Started with the MSP430 LaunchPad - Interrupts and the Timer
12. We need to have some code running to be interrupted. This isnt 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 |= for (i = P1OUT &= for (i = BIT0; 100; i > 0; i--); ~BIT0; 5000; i > 0; i--);
This routine does not use any intrinsics. So when were debugging the interrupts, they will look fine in C rather than assembly. Dont forget to declare i at the top of main.c:
volatile unsigned int i;
14. At this point, your code should look like the code on the next two pages. Weve 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 #define TIMER0_A0_VECTOR #endif volatile long tempRaw; volatile unsigned int i; void void void void void void FaultRoutine(void); ConfigWDT(void); ConfigClocks(void); ConfigLEDs(void); ConfigADC10(void); ConfigTimerA2(void); TIMERA1_VECTOR TIMERA0_VECTOR
void main(void) { ConfigWDT(); ConfigClocks(); ConfigLEDs(); ConfigADC10(); ConfigTimerA2(); _BIS_SR(GIE); while(1) { P1OUT |= for (i = P1OUT &= for (i = }
void ConfigClocks(void) { if (CALBC1_1MHZ ==0xFF || CALDCO_1MHZ == FaultRoutine(); // // BCSCTL1 = CALBC1_1MHZ; // DCOCTL = CALDCO_1MHZ; // BCSCTL3 |= LFXT1S_2; // IFG1 &= ~OFIFG; // BCSCTL2 |= SELM_0 + DIVM_3 + DIVS_3; // }
0xFF) If calibration data is erased run FaultRoutine() Set range Set DCO step + modulation LFXT1 = VLO Clear OSCFault flag 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; while(1); } void ConfigLEDs(void) { P1DIR = BIT6 + BIT0; P1OUT = 0; } void ConfigADC10(void) { ADC10CTL1 = INCH_10 + ADC10DIV_0; } 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.
Getting Started with the MSP430 LaunchPad - Interrupts and the Timer
5 - 11
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.
Youre 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
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 Optional: Capacitive Touch
42
6-1
Module Topics
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
6-2
Low-Power Optimization
Low-Power Optimization
Low-Power Modes
Low-Power Operation
6-3
Low-Power Optimization
6-4
Low-Power Optimization
Pin Muxing
6-5
Low-Power Optimization
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
6-6
6-7
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.
6-8
Source File
Well use the solution file from the last lab exercise as the starting point for this lab exercise. 1. Open the Lab5_Finish.txt file using File Open File
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. Its 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.
In ConfigTimerA2() : Change: CCR0 = 12000; CCR0 = 36000; To: In the Timer ISR : CCR0 += 12000; Change: CCR0 += 36000; To:
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.
6-9
6 - 10
(Sending a zero to an input pin is meaningless). 11. There are two pins on Port2 that are shared with the crystal XIN and XOUT. This lab will not be using the crystal, so we need to set these pins to be GPIO. The device datasheet indicates that P2SEL bits 6 and 7 should be cleared to select GPIO. Add the following code to the ConfigPins() function:
P2SEL = ~(BIT6 + BIT7); P2DIR |= BIT6 + BIT7; P2OUT = 0;
12. At this point, your code should look like the code below. Weve 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; P1OUT = 0; P2SEL = ~(BIT6 + BIT7); P2DIR |= BIT6 + BIT7; P2OUT = 0; } // // // // // P1.3 input, others output clear output pins P2.6 and 7 GPIO P2.6 and 7 outputs 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.
6 - 11
6 - 12
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.
void main(void) { ConfigWDT(); ConfigClocks(); ConfigPins(); ConfigADC10(); ConfigTimerA2();
16. At this point, the entire main() routine should look like the following:
6 - 13
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);
This line of code clears the bits in the popped SR. More recent versions of the MSP430 clock system, like the one on this device, incorporate a fault system and allow for fail-safe operation. Earlier versions of the MSP430 clock system did not have such a feature. It was possible to drop into a lowpower mode that turned off the very clock that you were depending on to wake you up. Even in the latest versions, unexpected behavior can occur if you, the designer, are not aware of the state of the clock system at all points in your code. This is why we spent so much time on the clock system in the Lab3 exercise.
// Timer_A0 interrupt service routine #pragma vector=TIMER0_A0_VECTOR __interrupt void Timer_A (void) { ADC10CTL0 = SREF_1 + ADC10SHT_3 + REFON _delay_cycles(5); // ADC10CTL0 |= ENC + ADC10SC; // P1OUT |= BIT6; // _delay_cycles(100); ADC10CTL0 &= ~ENC; // ADC10CTL0 &= ~(REFON + ADC10ON); // tempRaw = ADC10MEM; // P1OUT &= ~BIT6; // CCR0 += 36000; // _bic_SR_register_on_exit(LPM3_bits); // }
+ ADC10ON; Wait for ADC Ref to settle Sampling and conversion start P1.6 on (green LED) Disable ADC conversion Ref and ADC10 off Read conversion value green LED off Add one second to CCR0 Clr LPM3 bits from SR on exit
6 - 14
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 isnt generating quite this timing, but the DMM measurement would be the same.
6 - 15
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?
// ADC10 interrupt service routine #pragma vector=ADC10_VECTOR __interrupt void ADC10 (void) { }
6 - 16
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 _delay_cycles(4); // ADC10CTL0 |= ENC + ADC10SC; // CCR0 +=36000; // _bic_SR_register_on_exit(LPM3_bits); } // ADC10 interrupt service routine #pragma vector=ADC10_VECTOR __interrupt void ADC10 (void) { ADC10CTL0 &= ~ADC10IFG; ADC10CTL0 &= ~ENC; ADC10CTL0 &= ~(REFON + ADC10ON); tempRaw = ADC10MEM; _bic_SR_register_on_exit(LPM3_bits); }
+ ADC10ON + ADC10IE ; Wait for ADC Ref to settle Sampling and conversion start add 12 seconds to the timer
// // // //
clear interrupt flag Disable ADC conversion Ref and ADC10 off Read conversion value
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.
6 - 17
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: _____________ A graph of the current consumption would look something like this:
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.
6 - 18
ULP Advisor
Weve been ignoring the ULP Advisor for long enough. Lets review the results 30. Resize the Problems pane so that you can see the contents. Click on the Warnings and Infos. Our Problems pane looked like this: left of
31. The first warning is due to the following statement in main() : P2SEL = ~(BIT6 + BIT7); P2SEL is 8 bits while the defines for BIT6 and BIT7 are 16. That results in a truncation as noted. There are several things we could do to recast, etc. to make the warning go away, but since its pretty readable as-is, well just live with this warning. Either way there is no impact to the device current. 32. The next ten warnings result from un-programmed interrupt vectors. If one of these interrupts accidentally triggered, it could result in our device running in a very unexpected way. Well leave the ISR unpopulated with code, but you might want to implement a reset or other fault handling system. That will likely cause a very small stack memory leak, but if youre experiencing unexpected interrupts from un-programmed sources, you have larger problems. 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.
6 - 19
6 - 20
33. The last item in the Infos section says that were 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 well 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; P3OUT = 0; }
35. Rebuild your code and look at the Problems pane. You should only see the single truncation warning and info about the software delay. Its doubtful that any power was saved during this ULP Advisor exercise, but it is certainly worthwhile to pay attention to the ULP Advisor output.
6 - 21
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.
Youre done.
6 - 22
Serial Communications
Introduction
This module will cover the details of serial communications. In the lab exercise we will implement a software UART and communicate with the PC through the USB port.
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 Optional: Capacitive Touch
USI
51
7-1
Module Topics
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
7-2
Serial Communications
Serial Communications
USCI Universal Serial Communication Interface
USCI_A0 supports:
USCI
A B
USCI_B0 supports:
Protocols
52
Protocols
SPI Master
SPI Slave
I2C
SDA SCL
ADC Slave
Rx Tx
C Slave
UART
R/T
R/T
53
7-3
Serial Communications
A simple UART implementation, using the Capture & Compare features of the Timer to emulate the UART communication Half-duplex and relatively low baud rate (9600 baud recommended limit), but 2400 baud in our code (1 MHz DCO and no crystal) Bit-time (how many clock ticks one baud is) is calculated based on the timer clock & the baud rate One CCR register is set up to TX in Timer Compare mode, toggling based on whether the corresponding bit is 0 or 1 The other CCR register is set up to RX in Timer Capture mode, similar principle The functions are set up to TX or RX a single byte (8-bit) appended by the start bit & stop bit
54
7-4
Serial Communications
7-5
Serial Communications
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.
7-6
Serial Communications
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. 1. Open the Lab6a.txt file using File Open File
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 youre done, halt the code and click the Terminate CCS Edit perspective. button to return to the
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:
WDT password Selects interval timer mode Clears count value WDT clock source select
7-7
Serial Communications
5. The code in the Timer_A0 ISR now needs to run when the WDT+ interrupts trigger:
// Timer_A2 interrupt service routine #pragma vector=TIMER0_A0_VECTOR __interrupt void Timer_A (void) { // WDT interrupt service routine #pragma vector=WDT_VECTOR __interrupt void WDT(void) {
Change this:
To this:
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 youre 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.
7-8
Serial Communications
// 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 }
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:
// 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; if (TXByte & 0x01) CCTL0 &= ~ OUTMOD2; TXByte = TXByte >> 1; BitCnt --; }
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:
// TX Space // TX Mark
7-9
Serial Communications
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:
// TXD Idle as Mark // SMCLK/8, continuos mode
14. To make this code work, add the following definitions at the top of main.c:
// TXD on P1.1 // RXD on P1.2 // 0x0D
15. Since we have added a lot of code, lets 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).
7 - 10
Serial Communications
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 its been set to make sure we only set it once. Well 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); if (tempSet == 0) { tempSet = tempRaw; } if (tempSet > tempRaw + 5) { P1OUT = BIT6; P1OUT &= ~BIT0; for (i=0;i<5;i++) { TXByte = TxLO[i]; Transmit(); } } if (tempSet < tempRaw - 5) { P1OUT = BIT0; P1OUT &= ~BIT6; for (i=0;i<5;i++) { TXByte = TxHI[i]; Transmit(); } } if (tempSet <= tempRaw + 2 & { P1OUT &= ~(BIT0 + BIT6); for (i=0;i<5;i++) { TXByte = TxIN[i]; Transmit(); } }
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.
7 - 11
Serial Communications
0x4C, 0x4F, 0x0A, 0x08, 0x08 0x48, 0x49, 0x0A, 0x08, 0x08 0x49, 0x4E, 0x0A, 0x08, 0x08
The terminal program on the PC will interpret the ASCII code and display the desired characters. The extra Line Feeds and Back Spaces are used to format the display on the Terminal screen. Add the following arrays to the top of main.c:
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;
7 - 12
Serial Communications
7 - 13
Serial Communications
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.
Youre done.
7 - 14
Grace
Introduction
This module will cover the Grace graphical user interface. Grace generates source code that can be used in your application and it eliminates manual configuration of peripherals. The lab will create a simple project using Grace and we will write an application program that utilizes the generated code.
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 Optional: Capacitive Touch
What is Grace?
57
8-1
Module Topics
Module Topics
Grace ...........................................................................................................................................................8-1 Module Topics..........................................................................................................................................8-2 Grace .......................................................................................................................................................8-3 Lab 8: Grace ............................................................................................................................................8-8
8-2
Grace
Grace
8-3
Grace
8-4
Grace
8-5
Grace
8-6
Grace
8-7
Lab 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.
8-8
Lab 8: Grace
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. 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 Grace (MSP430) Project, and then click Finish.
8-9
Lab 8: Grace
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 isnt just a pretty picture from here well 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.
8 - 10
Lab 8: Grace
DVCC
3. Lets 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.
8 - 11
Lab 8: Grace
WDT+
5. Lets 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 lets leave it that way. Click the Grace tab in the lower left. Notice that the peripherals weve 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 lets 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.
8 - 12
Lab 8: Grace
Timer0_A3
7. Were 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, were 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. We need the following settings for the timer:
Timer Selection: Interval Mode / TAO Output OFF Desired Timer period: 1000ms Enable the Capture/Compare Interrupt
Grace creates an interrupt handler template for you at this step. Then click the View All Interrupt Handlers link and youll see:
8 - 13
Lab 8: Grace
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.
8 - 14
Lab 8: Grace
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.
8 - 15
Lab 8: Grace
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();
} }
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 computers USB port. Build and Load the program by clicking the Debug any resources, do so now. button. If you are prompted to save
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 youre 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.
Youre done.
8 - 16
FRAM Overview
Introduction
This module will give you a quick overview of an exciting new memory technology from Texas Instruments. Although FRAM is not currently available in the Value-Line parts, it is shipping in other MSP430 devices
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 Optional: Capacitive Touch
68
9-1
Module Topics
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
9-2
Address 21st century macro trends Wireless, Low Power, Security Drive new applications in our highly networked world (Energy Harvesting) Improve time to market & lower total cost of ownership (Universal memory)
Lower power consumption Faster Access speeds Higher Write Endurance Higher inherent security Lower total solution cost Not currently available in Value-Line parts
69
9-3
9-4
FRAM Controller
9-5
Built-in 2 way 4-word cache; transparent to the user, always enabled Cache helps:
Lower power by executing from SRAM Increase throughput overcoming the 8MHz limit set for FRAM accesses Increase endurance specifically for frequently accessed FRAM locations e.g. short loops (JMP$)
4 3.5 3
Active Power (uA)
RAM / 100% Cache Hit 75% Cache Hit Typical/ 66% Cache Hit 50% Cache Hit 0% Cache Hit
20
24
75
9-6
Advantage: All variables are non-volatile, no special handling required for backing up specific data Disadvantage: Uses up code space, increased power, decreased throughput if MCLK > 8MHz Advantage: Some variables may need to be volatile e.g. state machine, frequently used variables do not cause a throughput, power impact Disadvantage: User has to explicitly define segments to place variables in FRAM
77
MPU
9-7
Write Speed
9-8
Low Power
9-9
9 - 10
TI factory programming is not available for the MSP430FR57xx devices Customer and CMs should program after reflow or other soldering activity TI will provide reference documentation that should be followed during reflow soldering activity Hand soldering is not recommended. However it can be achieved by following the guidelines
Be mindful of temperature: FRAM can be effected above 260 deg C for long periods of time Using a socket to connect to evaluation board during prototyping is also a best practice
85
9 - 11
9 - 12
Capacitive Touch
Introduction
Texas Instruments ultra-low power MSP430 is a fantastic MCU to implement Capacitive Touch techniques. Its not just for BSW (Buttons, Sliders and Wheels) but can be used for other capacitive sensing applications, such as: Proximity, Grip, and Immersion. 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, well 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 Why How
is Capacitive Touch
Use TIs MSP430 Does Cap Touch Work? Sensing Details Cap Touch Topics
Capacitive
Exercise
http://www.ti.com/touch
10 - 1
Workshop Agenda
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. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. Introduction to Value Line Code Composer Studio Initialization and GPIO Analog-to-Digital Converter Interrupts and Timers Low-Power Optimization Serial Communications Grace FRAM Capacitive Touch Using Energia (Arduino)
http://www.ti.com/touch
10 - 2
Skills
Creating a CCS Project for MSP430 Launchpad(s) Basic knowledge of C language Basic understanding of using a C libraries and header files Windows (XP, 7, 8) PC with available USB port MSP430 Launchpad (v1.5) Capacitive Touch Boosterpack CCSv5.4 Grace MSP430 GUI Design Tool Cap Touch Library Cap Touch BoosterPack Demo Software (target, host) Cap Touch Pro GUI (requires Java JRE) Cap Touch Power Designer
Hardware
Software
Objectives
The user should be able to
Describe how capacitive touch sensing interfaces work List three MSP430
implement a capacitive sensing system using the TI Cap Touch Sensing library capacitive touch sensor (hardware), write the software to enable the sensor using the MSP430
10 - 3
Chapter Topics
Capacitive Touch ...................................................................................................................... 10-1 Workshop Agenda................................................................................................................... 10-2 Prerequisites, Tools and Objectives ....................................................................................... 10-3 What is Capacitive Touch ....................................................................................................... 10-5 Why Use TIs 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
10 - 4
Advantages
Higher Reliability No moving parts Longer life Better ESD & environmental 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, theres an app for that, so to speak. The technology, called Haptics, can provide a responsive feedback like weve 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, were 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 todays small, thin devices? CapTouch has enabled us to miniaturize a number of uniquely helpful (and fun) products while making them cheaper in the process.
10 - 5
Buttons, Sliders, and Wheels (nicknamed BSW) are the most obvious use of CapTouch.
Common sensors include buttons, sliders, or wheels (BSW) A button sensor requires a single element on the PCB A slider or wheel is comprised of multiple sense elements
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.
10 - 6
In fact, TIs 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.
Its hard to summarize all the places where you can use CapTouch, but heres 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?
Touch-less Dispensers
Sanitary applications Inventory Management Headsets, 3D glasses, Mice, & Illuminated Keyboards
Hopefully, in the future well be writing about your innovative new way to utilize the technology.
10 - 7
2-16 KB 512 B 2-16 KB 512 B 8-32 KB 1-2 KB 8-32 KB 1-2 KB FRAM RAM
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
The MSP430 is widely known as the most power-efficient microcontroller. But we dont stop there; by adding CapTouch sensing GPIO pins to our controllers, we take them to another level.
Current
* MSP430 Value Line using Capacitive Touch I/O running at 1MHz, 1.8V, Gate Time = 1ms
1/Scan Rate
10 - 8
Great devices notwithstanding, if you cant figure out how to use them, what good are they? Thats why TI provides a great number of demos, libraries, tools and application notes.
Application Notes
Getting Started with the MSP430 LaunchPad Workshop MSP430 Capacitive Button, Sliders and Wheels MSP430F5xx/F6xx Family Users Guide (Timer_D and TEC sections) Wireless Remote Ctlr With Capacitive Touch Pad Using MSP430F51x2 Download MSP430 Capacitive Touch Sense Software Library MSP430 Low Cost PinOsc Capacitive Touch Overview MSP430 Low Cost PinOsc Capacitive Touch Keypad Capacitive Touch Sensing, SYS/BIOS MSP430G2xx3 Cap Touch Matrix Remote
Design collateral
Free, Open source software to develop Button, Sliders, Wheels, Proximity. API abstractions for max flexibility Baseline tracking improves environmental robustness
10 - 9
Resistance
+
Voltage
Hindrance to the flow of charge Light bulb is a good example of resistance Zigzag path resulting from countless collisions with fixed atoms within the conducting material
R V
current flow
Potential energy Battery is a good example as it stores electric potential energy Current flows from battery (+) thru resistance Schematic is common way to express circuits
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.
10 - 10
Capacitance
Current only flows if Voltage in capacitor is less than voltage across battery
Capacitor is a passive component that stores energy in the form of an electrostatic field Field is created by two plates, separated by 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) Take voltage source away, capacitor holds charge like a rechargeable battery Some MSP430 development kits use a big capacitor (Super Cap) as a power source Create a circuit without the battery voltage source and the capacitor discharges Current will flow from C while enough charge remains in it
Hopefully this concept of storing and releasing energy isnt too difficult. Its 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 substances 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 todays 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.)
10 - 11
(tau).
But, whats 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.
Vs
Capacitor Charging Voltage
Consistent Time
0.63 Vs
For given values of R and C: Charging time is very precise and is described by constant () Discharge time is also precise and follows a similar curve These characteristics have often been used to establish time-bases, such as a clock
Steady State
Time Constant ()
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 dont need to use anything as prosaic as a comparator and interrupt to implement a RO, as well 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.
10 - 12
Changing the capacitance affects the oscillations A larger value for C means it takes longer to charge/discharge
Lower Capacitance
Higher Capacitance
Hopefully you will agree that this isnt 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. Hmm, what if we could find a way to force C to change? If we knew how to count oscillations, and could change the value of C, then couldnt we really make something cool thats where were going next.
10 - 13
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 dont 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 heres the cool thing, electrical circuits are not 2D, they are 3D. (Well, at least this is cool if youre not at university taking a Fields & Waves course.) What this means is that the dielectric isnt just the stuff between the two metal traces on the board, its 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 buttons 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 well finally have a way to detect when a finger presses a CapTouch button.
10 - 14
See how pushing harder covers more of the button. Therefore, more air dielectric is displaced and yes, we can detect these small changes in the resulting capacitance. If I push hard on the board, wont I end up connecting the metal traces that make up my button? Actually no, it wont. The key here is that we need to put an insulating overlay over the metal, otherwise you would be right and we might short-circuit the button. For best performance, the key is to find a very thin, insulating overlay. Finally, lets (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 were 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 its 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 were 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, youll 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.
10 - 15
Many MSP430 devices have I/O pins that contain a PinOsc feature PinOsc can implement a pin oscillator (i.e. RO on a pin) without any additional hardware Devices without this feature may require an external resistor, extra interrupt, and/or a comparator
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 its simply called Cap Sense I/O.
10 - 16
Gate Time
Gate Time is an important value in our measurement of capacitance. But before we delve into it, lets 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, its 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, thats just the name we give to the length of the measurement window. Other than using a consistent Gate Time to make sure our results are consistently accurate Gate Time factors into a design in other important ways. Longer gate times provide better results. The longer sampling time minimizes the effect of small perturbations, effectively averaging them out. Then again, longer measurement periods mean more power is used. It also means that you can scan fewer electrodes if quantity is one of your important careabouts. 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, youll see the term Gate Time used quite a bit.
10 - 17
# of elements (buttons, proximity, etc.) Gate time (how long to scan) Scan rate (how often to scan)
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. (Well see a larger drawing of these states on the next page.)
10 - 18
What information does the Power Designer tool need to know? 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.
Mode Gate Time Processing Time Sleep Time 1/Scan Rate 50ms (20Hz) 100ms (10Hz) 500ms (2Hz)
* MSP430 Value Line using Capacitive Touch I/O running at 1MHz, 1.8V, Gate Time = 1ms
10 - 19
Fixed gate time Variable counts Touch detected when fewer counts are seen Longer gate times can provide better sensitivity and less noise
Fixed number of counts Variable gate time Touch detected when gate time is longer Gate length timer must run at a higher rate (typically 8-25 MHz); thus, WDT isnt an option The higher measurement clock allows gate times to be shorter
Do you want to use a fixed gate time and count how many cycles occur? This method is called RO which is what weve 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.
10 - 20
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, lets 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
Grey line represents a series of timer count values Its been normalized to a baseline count (i.e. background cnt)
TI API functions will determine baseline/background counts (coming up) You must tune your system by providing a Threshold value a TI GUI tool can assist with this task Counts exceeding the Threshold are read as a touch
It appears that the above waveform consists of around 500 count times. That means we scanned this element 500 times. When we draw these waveforms, we often normalize the data so that the background noise is minimized. Normalization also fixes the waveform so that touches always go upward. If you looked at the Raw timer data, you would actually see the count values go down when there is a touch (since there are fewer oscillations). With that stated, we can now define Threshold as a value you pick to represent a positive touch action. By examining your test data, you need to pick a count value thats above the noise but not so high that a light finger press would be missed. Our earlier diagram helps to demonstrate this idea.
10 - 21
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.
A few more comments about the tool: Multiple channels are supported. This is critical for multi-element sensors, like wheels and sliders. The tool expects data to be sent in a specific format. You can either use the function we created for our hands-on lab exercise or write your own. The documentation provides all the details. The tool runs on Java, so youll need to have at least the JRE (Java Runtime) installed for the tool to work. Save and restore waveforms, right within the tool or export them for use in another program, like Excel. For better accuracy, you can select a point on the graph and look at the Y value to see its count value.
10 - 22
Planning
Write Code
structure.h structure.c myCode.c
A. Determine Needs B. Select Device C. Select HAL (device H/W) D. Estimate Timing
Coding
Tuning Phase
A. Responsiveness Scan rate (myCode.c) B. Resolution Gate time (structure.c) C. Feel Threshold (structure.c)
Tuning
''He who fails to plan is planning to fail'' Winston Churchill Winston, we couldnt 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. Well 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.
10 - 23
If you like charting out your development using block diagrams, you might appreciate this, more detailed, planning sequence.
Yes
No
Gate Time (resolution) time for more time for less Threshold Adjust up/down until desired feel
Tuning Phase
Done
# of Elements
Total # Elements
How would you fill out this Worksheet table, if we asked you to write a program to utilize all the features of the Capacitive Touch BoosterPack?
10 - 24
Heres 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 boards schematic diagram.)
Quantity 1 0 1 1
# of Elements 1 0 4 1 1+4+1 = 6
Which device to select? Picking a device with CapTouch I/Os 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.
Obviously, choosing a device with CapTouch I/Os will minimize the hardware requirements of your system
Device MSP430G2x02 MSP430G2x32 MSP430G2x03 MSP430G2x33 MSP430F51x1 MSP430F51x2 Flash 1-8 KB 1-8 KB RAM 256 B 256 B Capacitive Touch Buttons ADC Supported Touch I/O 16 16 24 24 29 29 32 10-bit 12-bit 10-bit 10-bit Serial (UART, I2C, SPI)
G2553
MSP430FR58XX/59xx FRAM
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/Os while being very competitively priced
10 - 25
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.
Cap Sense library defines various HAL (hardware abstraction layer) definitions They make it easy to pick your method and h/w used by the library Table reflects recommendations from the Cap Sense library authors HAL name reflects h/w choices Choose between RO and fRO How the RO is created Which timers are used
Considerations
Measurement Method
Gate Timer
10 - 26
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.
The default values are probably a good starting place. What response time is needed is 50ms appropriate in your application? Will your application be battery powered? What environmental conditions might need to be covered?
o o o
How to bond the overlay to the electrode? What other electric/magnetic fields might be present in the system? How thick is the overlay insulating layer over your sensor elements?
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 systems environment, thick overlay material, etc. you may want to alter these values. If youre 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.
10 - 27
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, lets examine what code you must either include or write to implement Capacitive Touch Sensing with the TI library Import TI_CAPT Library files Add files from library, then edit
structure.h contains library and user definitions structure.c structures defining users elements and sensors
Your code must include the following: Set clocks (as needed for timing) Call functions to establish baseline capacitance values Establish scan rate timer, then call button, wheel, and proximity check fcns Enter LPM mode between sensor scans
First thing is to add the Library files. Its 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 structs 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 youve 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.
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).
10 - 28
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 Variable externs for each of your sensors and elements
Library allocates static RAM, rather than use dynamic (malloc/free) So the library knows how much memory to allocate
b) Total # of elements
How many sensors are you defining? These are based on choices youve made, such as your HAL selection
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.
10 - 29
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)
#include structure.h // Define struct for each element in your system const struct Element middle = { Specify GPIO pin (port & bit), .threshold = 121 .maxResponse = 121+655, }; const struct Element down = { Specify GPIO pin (port & bit), .threshold = 113 .maxResponse = 113+655, };
This entire file (unlike structure.h) is custom to your application Allocate a structure for each touchpad Element and Sensor To make it easier, try copying the structure.c file from librarys example for the same HAL youve chosen: e.g. RO_PINOSC_TA0_WDTp example (easier, since you can copy/modify structs rather than create from scratch)
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
10 - 30
The second part of the structure.c file involves creating data structures for each of the Sensors 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. Its also where we define the Gate Times in our code.
structure.c (Sensors)
// Define struct for each sensor in your system // Sensors are made up of elements
const struct Sensor wheel = { .halDefinition = RO_PINOSC_TA0_WDTp, .numElements = 4, .points = 64, .sensorThreshold = 75, .baseOffset = 0, // Pointer to elements .arrayPtr[0] = &up, .arrayPtr[1] = &right, .arrayPtr[2] = &down, .arrayPtr[3] = &left, // Timer Information (SMCLK / 8192) .measGateSource = GATE_WDT_SMCLK, .accumulationCycles= WDTp_GATE_8192 }; const struct Sensor myButton = { .halDefinition = RO_PINOSC_TA0_WDTp, .numElements = 1, .baseOffset = 4, .arrayPtr[0] = &middle, // Timer Information
Continuing structure.c
The 2nd part of file allocates a structure for each Sensor Sensors are made up of 1 or more Elements (defined at the top of the file) Which HAL youve chosen How many elements in the sensor - A button has 1 - Wheels/sliders have more than 1 # of points: How many virtual points do you want the library to track (for wheels/sliders only) sensorThreshold: cumulative response required by the sensor (all elements) to declare a valid touch baseOffset : think of this as a running count of all elements (starting with 0) arrayPtr[]: address of each Element used for this sensor (in order) 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. Its 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 users finger is positioned). Finally, the .baseOffset field is also references the list of Elements.
10 - 31
main.c
As we mentioned earlier, there arent 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 Function void main(void)
{
main.c
// Turn off watchdog timer // Initialize pins for ULP // Set Timer for Scan rate
Initialize hardware Set Timer1 to interrupt CPU at Scan Rate (we chose 20Hz) Read baseline (i.e. background) capacitance for your sensor Enables interrupts (GIE) and put the CPU to sleep (LMP1) CPU wakes on Timer1 interrupt
// Establish capacitance baseline TI_CAPT_Init_Baseline( &myButton ); TI_CAPT_Update_Baseline( &MyButton, 5 ); // Background loop starts here while (1) { __bis_SR_register( LPM1_bits + GIE );
}
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. With that done, we can access the Sensors value using the appropriate function: TI_CAPT_Wheel() TI_CAPT_Slider() TI_CAPT_Button() See the input/output descriptions for each of these functions in the graphic to the right
10 - 32
Charts data from multiple sensors Visualize capacitance sensing makes it easy to find Max and Threshold values Tune system in real-time See effect of changing: Gate Time Finger pressure (feel) Touchpad size Proximity etc. Run Library function: TI_CAPT_CUSTOM() to get normalized count value, then pass to GUI Utilizes simple serial protocol for passing data to GUI Runs on Java (JRE)
If you said, The Elements 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 Sensors sensitivity by increasing the Gate Time. Heres a case where you might want to do that. Luckily, we wont see this in our upcoming lab exercise there will be some noise, but it wont 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).
Finally, how do we connect our program to the GUI tool? 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.
10 - 33
Buttons
Init/Update Baseline
Baseline
Custom
fRO_PINOSC_TA0_SW
Wheel
Slider
Button
Dominant Element
RO_PINOSC_TA0
HAL
RC_PAIR_TAO
H/W
Here is a block diagram summary of TIs 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 its 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.
Buttons
Init/Update Baseline
Baseline
Custom
Wheel
Slider
Button
Dominant Element
Slider/Wheel
RO_COMPAp_TA0_WDTp
RO_PINOSC_TA0_WDTp
RO_COMPB_TA0_WDTA
RO_COMPB_TA0_WDTA
RO_PINOSC_TA0
RC_PAIR_TAO
Calculate Delta Capacitance / Baseline Tracking Was it Custom/Raw Button touched? Filter HAL Selection Little to no Where at Binary - was abstraction (position)? button pushed? Custom is good for tuning Higher Level of Abstraction Raw lets you 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
10 - 34
Raw
Raw
Additional Topics
Connecting to sensor electrodes (i.e. touchpads) Keep the wire as short as possible as it adds to the base capacitance (C) Similarly, try to avoid sharp bends as this also affects C Avoid putting high-speed/current drive wires next to the touchpad wires Touchpad shape & size Normal solid filled circular or square pads work well The pad can have a hole drilled through it to provide backlighting without influencing the capacitive performance For scrollbar/slider, dont make the pads too big, a normal finger should be able to cover 1 touchpads PCB considerations Since Cap Sensing is often placed on top of other electronics, it is often helpful to put grounding on the underside of the PCB Overlay materials should be a good dialectric (non-conductive); and eliminate any air holes between overlay and sensor
Larger sized electrodes are easier to detect Law of diminishing returns occurs when the pad is larger than the finger touching it Thicker overlay materials reduces capacitive touch effectiveness Try counteracting smaller signals with longer gate times but increases power Bottom Line Getting more interaction between a sensor and finger provides a better signal
10 - 35
Additional Topics
http://www.ti.com/touch
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. Heres a picture of this page, but since its so small, weve repeated references to all the applications notes, user guides, and documents on the next page of this book.
Capacitive Touch
MSP430 Capacitive Touch Controllers Touch Pro GUI Touch Power Designer GUI Designer Guides Software Library Reference Designs Cap Touch BoosterPack
10 - 36
Additional Topics
Training
To learn more
Tools
Getting Started with the MSP430 LaunchPad Workshop MSP430 Touch Pro Tool MSP430 Capacitive Touch Power Designer GUI 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) MSP430 Capacitive Touch Sense Software Library 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
Design Guides
Software Library
Reference Designs
Go Read Learn more about implementing Capacitive Touch/Sensing with the MSP430!
10 - 37
Lab10a: Explore the Boosterpack Demo Lab10b: View wheel counts using the TI TouchPro GUI Tuning Tool Lab10c: Implement a simple touch key application Lab10d: (Optional) Use Grace to configure clocks/timers
Requirements
Capacitive Touch BoosterPack (430BOOST-CAPTOUCH1) available here for US$10. During Workshop Installation, you should have downloaded and installed the following: BoosterPack Users 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 Programmers 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.
10 - 38
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 Librarys 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
10 - 39
2B
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 Demos GUI tool when you are done. Also, close the Lab10a project in CCS.
10 - 40
3B
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. 1. Verify which Windows COM port your MSP430 Launchpad is using: If you havent already done this info earlier in the workshop, please open the Windows Device Manager and write down the UART COM port number. MSP430 Application UART ( COM _________ ) 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. Project Import Existing CCS Eclipse Project Import the project: C:\TI\msp430\TouchPro_1_01_00_00\32bit\TouchProTool_project_files\ examples\TouchProTool_Demo_Bit_Banging\CCS
3. Build / Load / and Run the project on your MSP430 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 the program and download it into your G2553 device. Click Run unfortunately, the current version of this demo does not utilize any LEDs, so you cannot see that its running until we get the TouchPro GUI running.
10 - 41
4. Run the MSP430 TouchPro GUI tool from the Windows Start menu:
Troubleshooting Suggestions
If your COM port doesnt 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 its 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 Launchpads COM port.
10 - 42
6. Visualize Capacitance Touch/Sensing in the TouchPro GUI. Once the tool connects, you will see a lot of noise displayed in the interface:
This is just background noise. As soon as you touch the wheel touchpad, you should see the display automatically re-scale the display. This will minimize the noise and youll see the much larger count values pertaining to your touch.
If you scroll around the wheel you should see something like this (notice the scale on the left has changed):
Notice the 4 channels of data. These are coming from the four elements that make up the scroll wheel.
Try touching on the buttons (i.e. arrows) on the wheel. You should see each channel peak with a single impulse.
Later, we will utilize this tool to help us ascertain the best Threshold value for a button.
7. Disconnect the Launchpad from the display by clicking the USB connector icon.
10 - 43
8. Save the data collected by the MSP430 TouchPro Tool. Select Save or Save As from the File menu to save the data. Later, you could open this data and view it again or you could open the data file in another program, such as Excel. Note: The GUI does not keep an indefinite amount of data. After about 500 samples it starts discarding the oldest data.
9. Terminate your Debug session. 10. Close the project. Before closing the project, you are welcome to examine the projects source code, although in the next lab we will create our own example. 11. You can also exit the GUI tool, as we wont be using this for the next exercise.
10 - 44
In this section, well 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 well 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.
10 - 45
b) Variable Names and Port/Pin#s On the bottom half of the first page, you need to create a list of variable names for each of the Sensors and Elements. We will use these names when we create data structures for each of them. The Port/Pin#s are important since we need to specify this information in the data structures of each of Element. (This is required as the Library function call needs to know which GPIO pin to scan when sensing capacitance.)
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 were not even using a slider or wheel in this part of the lab. c) Select a MSP430 device and HAL This is an easy decision for this lab exercise, since we are using the Boosterpack with the MSP430 Value-Line Launchpad. (If you still need a hint, check out what is highlighted on the worksheet.) Of course, in your own application you may decide to choose a different device based on your systems needs. For example, the MSP430G2553 does not have a USB port; if thats something you need, you might choose another device, such as the MSP430F5529. Write in your selections d) Selecting Clock, Gate, and Scan Rates Fill in the remaining portion of the worksheet 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.)
10 - 46
Capacitive Touch Planning Worksheet Sensor Type Buttons Sliders Wheels Proximity Total # Elements
Variable Names (for Sensors & Elements)
List the variable Names for Each Sensor and Element you will be using. For example, if creating a wheel sensor that contains 4 elements, the variables might look like:
myWheel_Sensor left_element up_element right_element down_element Port 2 Port 2 Port 2 Port 2 Bit 1 Bit 4 Bit 3 Bit 2
Quantity
# of Elements
Sensor Name
Element Name
GPIO Port
PIN
Planning Worksheet
Page 1
Planning Worksheet
Page 2
Capacitive Touch Planning Worksheet Sensor Type Buttons Sliders Wheels Proximity Total # Elements
Variable Names (for Sensors & Elements)
List the variable Names for Each Sensor and Element you will be using. For example, if creating a wheel sensor that contains 4 elements, the variables might look like:
myWheel_Sensor left_element up_element right_element down_element Port 2 Port 2 Port 2 Port 2 Bit 1 Bit 4 Bit 3 Bit 2
Quantity
# of Elements
Sensor Name
Element Name
GPIO Port
PIN
Planning Worksheet
Page 1
Planning Worksheet
Page 2
2. Run the MSP430 CapTouch Power Designer to estimate the power requirements.
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.
3. Finish the worksheet and close Power Designer. If you havent already done so, finish entering your selections in the Planning Worksheet. When finished, go ahead and close the Power Design tool. 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.
10 - 47
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.)
10 - 48
5. Expand the Lab10c project in the Project Explorer pane. Even though we chose the CCS Empty Project template, you should notice there are six source files already in your program.
Note, if you have completed the preceding labs in this workshop, the code we have provided should look familiar.
Lets examine the code that is already in the project: Grace folder: These files came from the Grace tool. We cheated by using this tool to create the functions needed to setup our Clocks and Scan Rate Timer. If you want see how we created these files, please refer to (Optional) Lab10d Using Grace to Configure Clocks & Timer (on page 10-66). BCSplus_init.c: This file sets up our clocks per the Planning Worksheet; MCLK = DCO = 1 MHz (Note, we discuss clocks in Chapter 3) SMCLK = DCO / 2 = 500 Khz ACLK = VLO = 12 KHz Timer1_A3_init.c: Configures Timer1_A3 to create interrupts at 20 Hz rate. This matches the 20 Hz (50ms) Scan rate described on the Planning Worksheet. We use this rate for two reasons: (1) We will flash an LED at 1Hz to indicate the system is alive; and (2) We want to scan our CapTouch sensors every 50ms. Notice in main() that we call Timer1_A3_graceInit(); this configures the timer. Looking further down in main.c, youll find the interrupt service routine (ISR). Currently, this only blinks the LED at 1Hz. Later, you will add code to scan the CapTouch button. (Note that we discussed interrupts and ISRs in Chapter 5.)
UART folder: This code was extracted from the Bit-Banging example that ships with the TouchPro Tuning Tool. Folder contains the files: uart.c, uart.h The primary function, UART_sendDataFrame(), sends formatted count data across the UARTs serial port to the TouchPro GUI. Learn more about UART serial ports in Chapter 7.
10 - 49
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. 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.
main.c:
6. Build the project. Before we add the Capacitive Touch library and code, lets get the base project built and working. Build the project by clicking on the toolbar Hammer icon.
During the build, you should have noticed an error. Apparently, the compiler cannot find a header file.
10 - 50
7. Add (-I) include search paths to your project. Add search paths to the projects Build properties. You need to add these 2 locations: Project directory Uart directory (inside the project folder)
Open the Project Properties: Right-click on the project Properties Select: Build MSP430 Compiler Include Options Then click on the: Add path button
CCS makes it easy to add a folder from the workspace, just click on the Workspace button and choose the appropriate folder.
Do this 2 times, each time selecting a different required folder. The #include search path should end up looking like this:
10 - 51
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. 9. Terminate debug and go back to editing your program. Now we can get on with adding the actual Cap Touch code.
10 - 52
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 compilers 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.
10 - 53
13. Copy structure.h and structure.c from the CapTouch Librarys Code Examples folder. Rather than create these files from scratch, were 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: <your cap touch library folder>/Code_Examples/RO_PINOSC_TA0_WDTp
14. Build your project. Now that we have added all the necessary files though we still need to edit a few of them lets build the project to make sure all the project references are correct. Oops, did you get a bunch of errors like we did?
Oh, thats right. If we look through the documentation for the library (SLAA490b.PDF; Section 3.1; Page 9), it tells us that the library requires that the GCC language extensions should be enabled for CCS.
10 - 54
15. Enable support for GCC extensions. Right-click on Project Properties Build MSP430 Compiler Advanced Options Language Options Enable support for GCC exts You may remember that one of the files we just added (structure.c) sets up a number of data structures, which well be editing in a few steps. We want this option, since it enables our program to access uninitialized structures; e.g. allowing element three to be accessed without having to access elements one and two.
http://processors.wiki.ti.com/index.php/GCC_Extensions_in_TI_Compilers
16. Try building your program again. Your program should build without errors once the GCC switch is enabled.
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.
10 - 55
Writing/Editing Code
Get your Planning Worksheet ready. Well 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 isnt required. Delete the superfluous comments at the beginning of the file (tedious to scroll thru) Eliminate all Element structs except the middle_element. Finally, well keep the middle_button sensor, but you can get rid of the other two Note: Dont accidentally delete the #include. Youll need this!
.inputPxselRegister = (unsigned char *)&P2SEL, .inputPxsel2Register = (unsigned char *)&P2SEL2, .inputBits = BIT5, // When using an abstracted function to measure the element // the 100*(maxResponse - threshold) < 0xFFFF // ie maxResponse - threshold < 655 .maxResponse = 350+655, .threshold = 350 }; //*** 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 };
10 - 56
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.
All elements are stored by the library in an array. Since we now only have 1 Element, its base offset (i.e. index) is zero. Our planning worksheet says we have a gate time of 1.024ms SMCLK = DCO (1MHz) 2 = 512 K Gate Time = SMCLK 512 = 1.024ms
10 - 57
structure.h
19. Open structure.h for editing. 20. Update the Public Globals area. Replace all the declarations listed here with two that match your needs. You should have one Element and one Sensor declaration named according to your Planning Worksheet. (These should match the structures we just declared in structure.c.) 21. Update the values in the Ram Allocation area of structure.h. a) The #define for TOTAL_NUMBER_OF_ELEMENTS should match the value on the first page of your Planning Worksheet. b) Also, make sure that the definition for RAM_FOR_FLASH is uncommented (since, in this exercise, we dont want to use dynamic memory). 22. Set the maximum number of elements per sensor definition. Calculate the maximum number of elements per sensors in our case this is easy. Its 1. So, in the Structure Array Definition area, update the definition for: #define MAXIMUM_NUMBER_OF_ELEMENTS_PER_SENSOR 1
23. Verify/update the remaining #defines 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 were not using a slider or wheel in this exercise, you can comment out their #definitions.
10 - 58
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 //****** RAM ALLOCATION ******************************************************** // TOTAL_NUMBER_OF_ELEMENTS represents the total number of elements used, even if // they are going to be segmented into separate groups. This defines the // RAM allocation for the baseline tracking. If only the TI_CAPT_Raw function // is used, then this definition should be removed to conserve RAM space. #define TOTAL_NUMBER_OF_ELEMENTS 1 // If the RAM_FOR_FLASH definition is removed, then the appropriate HEAP size // must be allocated. 2 bytes * MAXIMUM_NUMBER_OF_ELEMENTS_PER_SENSOR + 2 bytes // of overhead. #define RAM_FOR_FLASH //****** Structure Array Definition ******************************************** // This defines the array size in the sensor structure. In the event that // RAM_FOR_FLASH is defined, then this also defines the amount of RAM space // allocated (global variable) for computations. #define MAXIMUM_NUMBER_OF_ELEMENTS_PER_SENSOR 1 //****** Choosing a Measurement Method **************************************** // These variables are references to the definitions found in structure.c and // must be generated per the application. // OSCILLATOR DEFINITIONS //#define RO_COMPAp_TA0_WDTp #define RO_PINOSC_TA0_WDTp
64 65
//****** WHEEL and SLIDER ****************************************************** // Are wheel or slider representations used? //#define SLIDER //#define ILLEGAL_SLIDER_WHEEL_POSITION 0xFFFF //#define WHEEL //****************************************************************************** // End of user configuration section. //******************************************************************************
10 - 59
main.c
Were 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 sensors 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 buttons 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.
#include "CTS_Layer.h" #include "structure.h" //Access the CapTouch Library //Ref to Max # channels and Sensor variable
#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. Weve 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? Its 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).
#define #define TUNE 1 //Turn off "tuning" by setting to "0" NUMBER_OF_CHANNELS_TO_TUNE 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.
10 - 60
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.
TI_CAPT_Init_Baseline(&myButton); //Calculate buttons baseline capacitance TI_CAPT_Update_Baseline(&myButton,2); //Update the baseline
Thats 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. 29. First, declare an array to hold the timer count values. These values will be passed, via the UART, to the TouchPro GUI. As such, we need the length of the array to equal the number of Elements (i.e. electrodes) we want to tune, which just so happens to be one of the #defines we created earlier in the file.
uint16_t counts[NUMBER_OF_CHANNELS_TO_TUNE];
//Count values for TouchPro GUI
30. Use the CapTouch library to determine if the button is being pushed. If detected, light the LED. Weve already seen the code to turn the LED on/off. In fact, its 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 buttons Gate Time. If this count exceeds the Threshold, it will return 1, otherwise it returns 0.
if (TI_CAPT_Button(&myButton)) { P1OUT |= BIT0; } else { P1OUT &= ~BIT0; } //If button press is detected //Light the LED //or else //Turn off the LED
10 - 61
31. Add code to Tune the system. If tuning is enabled, we want to send count data to the TouchPro GUI. This requires two functions: (1) to get the count values; (2) send the data serially.
if (TUNE) { // Library call to measure timer counts due to capacitance TI_CAPT_Custom(&myButton, counts); // Send count value to TouchPro GUI UART_sendDataFrame(counts, NUMBER_OF_CHANNELS_TO_TUNE); }
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.
10 - 62
10 - 63
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.
10 - 64
Threshold
36. Pick a Threshold value. You want to pick a threshold that is high enough above the noise so that it doesnt trigger erroneously, but low enough not to miss any actual touches. Based on our results above, were going to pick 100. (If we wanted to allow lighter touches, maybe 80 would be better. But, for now well stick with 100.) Whats your touch number? ___________________________________________________ In other words, what Threshold value are you going to choose? 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. #define THRESHOLD 100
38. Build, Load and Run your code again. Does the LED light when you push the button? ____________________________________ Do you like the responsiveness and feel of your button? _____________________________ If youre not happy with how your button works, repeat the steps of opening up the TouchPro Tool (if you dont still have it open). Try experimenting further with how hard you press and what count value is displayed. 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 which displays the count data.
39. Terminate the active debug session using the Terminate Lab10c project.
10 - 65
5B
10 - 66
2. Open the Device Overview in the Grace configuration file. When your Grace-enabled project opens, it should default to opening in the Grace GUI. It should look like this. (If not, look for and open the file named main.cfg.)
Click on the Device Overview button to get a graphical layout of your MSP430 device:
The numbers indicate which modules (and the order) we will configure them in. To begin with, on this screen, go ahead and set the voltage correctly.
10 - 67
3. Configure the clocks BCS+ (Basic Clock System+). Click on the blue box Oscillators Basic Clock System+, which opens its configuration panel.
When using any of these modules, first of all, make sure the Enable is selected. Then click on Basic User to view:
10 - 68
4. BCS+ Power User. At first glance, the default clock options looked like they would match our needs, but to obtain a 1ms gate time, we need to get SMCLK running at half of its current speed. To do this, click the Power User button. As you can see, by changing the SMCLK Divider, we can now get it down to 500 kHz.
5. Move to the Watchdog+ Timer module. To do this, click on the Grace tab (lower-left of editing window), which will get you back to the Device Overview, where you can easily pick another module.
Once youre in the Watchdog+ module, click on the Basic User view.
10 - 69
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 were using the RO_PINOSC_T0_WDTp version of the HAL, the library functions will handle programming the Gate Timer for us. So, why did we go through this exercise? 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 didnt 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. 7. Double-check your Gate Time settings in structure.c. The clock information above, together with our selections in our structure.c, will provide us with the correct gate timing.
10 - 70
8. Finally, navigate your way over to the Timer1_A3 module. 9. Enable Timer1_A3 and go to the Basic User view. Once again, taking our cue from the Planning Worksheet, we wanted a 20 Hz Scan Rate. Selecting Interval Mode and plugging in the 50ms desired Time Period easily provides us our chosen 20 Hz clock rate.
Once again, we could have and in the past, often have figured the timing out on our own, but this is so much easier. Hint: Why did we choose Timer1? Timer1 was a convenient choice as it wasnt 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.
10 - 71
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.
10 - 72
Quantity 1
0 0 0
# of Elements
1 0 0 0 1
Total # Elements
Variable Names (for Sensors & Elements)
List the variable Names for Each Sensor and Element you will be using. For example, if creating a wheel sensor that contains 4 elements, the variables might look like:
myWheel_Sensor left_element up_element right_element down_element Port 2 Port 2 Port 2 Port 2 Bit 1 Bit 4 Bit 3 Bit 2
Sensor Name
Element Name
GPIO Port
PIN
myButton
myButton_element
Port 2
Planning Worksheet
Page 1 of 2
MS430G2553 RO_PINOSC_TA0_WDTp
1 1.024 20
0 N/A
0 N/A
Planning Worksheet
Page 2 of 2
Prerequisites
Basic knowledge of C language Basic understanding of using a C library and header files This chapter doesnt explain clock, interrupt, and GPIO features in detail, this is left to the other chapters in the MSP430 workshop Hardware Windows (XP, 7, 8) PC with available USB port MSP430 Launchpad (v1.5) Software Energia Download Launchpad drivers (Optional) MSP430ware / Driverlib
Objectives
Define Arduino and describe what is was created for Define Energia and explain what it is forked from Install Energia, open and run included example sketches Use serial communication between the board & PC Add an external interrupt to an Energia sketch Modify CPU registers from an Energia sketch Change the default system clock rate of the Launchpad from Energia
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 its opened. So the Arduino is essentially a simple computer with eyes and ears. Why is it so popular? Because the hardware is cheap, its 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 Tools
IDE: write, compile, upload
Physical Computing
Software that interacts with the real world
Code
Open-source ecosystem
Tools, Software, Hardware (Creative Commons)
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
In the end, Arudino is basically an ecosystem for easy, hardware-oriented, real-world programming. It combines the Tools, Software and Hardware for talking to the world.
1 2
http://www.wired.com/gadgetlab/2008/04/just-what-is-an/ http://en.wikipedia.org/wiki/Wiring_%28development_platform%29
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
11 - 3
Energia
Energia
/eneria/ ; energia
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
Software Wiring programming language Tools Energia IDE MSP430 LaunchPad MSP430 FRAM FraunchPad Stellaris Cortex-M4F Launchpad
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. Similar to its predecessor, it an open-sourced project. Its development is community supported, being hosted on github.com.
http://en.wikipedia.org/wiki/Energia
11 - 4
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Energia
Energia Lineage
DBN
(1990s)
Language Design By Numbers programming language Teaching experiment for non-programmers MIT (USA)
Fritzing
(2009)
EDA Tools C++ w/Qt components
Processing
(2001)
Language, Tools Processing language builds on Java, but with simplified syntax Sketchbook mini-IDE For non-programmers Former MITers (USA)
Wiring
(2003)
Language, Tools, H/W Developed for singlechip Controller Prototyping platform for quick iterative design C++ plus Wiring library Java-based IDE Columbia
Arduino
(2005)
Language, Tools, H/W Teaching, hobbyist, Rapid prototyping C/C++ plus Wiring library Java-based IDE AVR C Ivrea (Italy)
Wiring-based language (syntax and libraries), similar to C++ with some slight simplifications and mods Sketchbook (Processing-based) integrated development environment
Energia
(2012)
Language, Tools, H/W Direct fork of Arduino TI C Launchpad boards California (USA)
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 nonprogrammers 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 5
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
11 - 5
Energia
7 8
11 - 6
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Arduino programs are called sketches From the idea that were Sketching with hardware Sketches require only two functions to run cyclically: setup() loop()
Are C/C++ programs that can use Arduinos Wiring library Library included with IDE If necessary, you can access H/W specific features of C, but that hurts portability Blink is Cs Hello World ex. Wiring makes this simple Like most first examples, it is not optimized
// Most boards have LED and resistor connected // between pin 14 and ground (pinout on later slide)
#define LED_PIN 14 void setup () { // enable pin 14 for digital output pinMode (LED_PIN, OUTPUT);
void loop () { digitalWrite (LED_PIN, HIGH); // turn on LED delay (1000); // wait one second (1000ms) digitalWrite (LED_PIN, LOW); // turn off LED delay (1000); // wait one second
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? Lets examine the Blink code above: A sketch only requires two functions: o setup() a function run once at the start of a program which can be used to define initial environment settings o loop() a function called repeatedly until the board is powered off Reading and Writing pins (i.e. General Purpose Input Output GPIO) is encapsulated in three simple functions: one function defines the I/O pin, the other two let you read or write the pin. In the example above, this allows us to turn on/off the LED connected to a pin on our microcontroller. The delay() function makes it simple to pause program execution for a given number of microseconds. In fact, in the Energia implementation, the delay() function even utilizes a timer which allows the processor to go into low power mode while waiting. Finally, which not shown here, Arduino/Energia makes using the serial port as easy as using printf() in standard C programs.
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
http://arduino.cc/en/Reference/HomePage
11 - 8
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
MSP430 C Code
void main() { // Setup pin for output P1DIR = 0x40; P1OUT = 0; // Disable watchdog timer WDTCTL = WDTPW | WDTHOLD; // Setup Master Clock (MCLK) BCSCTL1 = CALBC1_16MHZ; DCOCTL = CALDCO_16MHZ; BCSCTL2 &= ~(DIVS_0); // Setup ACLK BCSCTL3 |= LFXT1S_2; while(1) { P1OUT = 0x40; P1OUT = 0; _delay_cycles(1000); } } // LED on // LED off _delay_cycles(1000); // wait 1 sec
vs
Wiring Language
void setup() { // Setup pin for output pinMode (LED_PIN, OUTPUT); }
Setup Code
void loop() {
Background Loop
}
digitalWrite (LED_PIN, HIGH); // LED on delay (1000); delay (1000); // wait 1 second digitalWrite (LED_PIN, LOW); // LED off
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
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 LEDs 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
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 MSP430s 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
Installation 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
Open Save
Installation of the tools couldnt be much simplier unzip the package thats it. (Though, if you have not already installed TIs 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 LEDs 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 LEDs and serial communications in the upcoming lab exercises.)
11 - 12
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Energia IDE
Basic Sketches
Blink is the hello world of micros BareMinimum is just setup() and loop()
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.
Energia
Home: Download: Wiki: Supported Boards: (H/W pin mapping) Getting Started: Support Forum:
Launchpad Boards
Arduino:
Energia
Home: Download: Wiki: Supported Boards: (H/W pin mapping) Getting Started: Support Forum: http://energia.nu/ http://energia.nu/download/ https://github.com/energia/Energia/wiki https://github.com/energia/Energia/wiki/Hardware https://github.com/energia/Energia/wiki/Getting-Started http://forum.43oh.com/forum/28-energia/
Launchpad Boards
MSP430: ARM Cortex-M4F: http://www.ti.com/tool/msp-exp430g2 (wiki) (eStore) Launchpad Wiki eStore
Arduino
Site: Reference: Comic book: http://www.arduino.cc/ http://arduino.cc/en/Reference/HomePage 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 well 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 workshops pre-work. If you need them and do not have network access, please check with your instructor.
Installing Energia
2. Download Energia, if you havent 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
4. Set your working folder in Energia. It makes it easier to save and open files if Energia defaults to the folder where you want to put your sketches. The easiest way to set this locations is via Energias preferences dialog: File Preferences Which opens:
11 - 18
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
5. Selecting the Serial Port Select Serial Port from the Tools menu to view the available serial ports. For Windows, they will be listed as COMXXX port and usually a higher number is the LaunchPad com port. On Mac OS X they will be listed as /dev/cu.uart-XXXX. Hint: For more on configuring your Launchpad for serial communication, see Serial-Communication.
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
11 - 20
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
2. Examine the code. Looking at the Blink sketch, we see the code we quickly examined during our chapter discussion. This code looks very much like standard C code. (In Lab11d we examine some of the specific differences between this sketch and C code.) At this point, due to their similarity to standard C language code, we will assume that you recognize most of the elements of this code. By that, we mean you should recognize and understand the following items: #define to declare symbols Functions what a function is, including: void, () and {} Comments declared here using // characters
What we do want to comment on is the names of the two functions defined here: setup(): happens one time when program starts to run loop(): repeats over and over again
This is the basic structure of an Energia/Arduino sketch. Every sketch should have at the very least these two functions. Of course, if you dont need to setup anything, for example, you can leave it empty.
/* 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); delay (1000); digitalWrite (RED_LED, LOW); delay (1000); }
// // // //
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
11 - 21
Lab 11
3. Compile and upload your program to the board. To compile and upload the Sketch to the LaunchPad click the button.
Do you see the LED blinking? What color LED is blinking? __________________________ What pin is this LED connected to? _____________________________________________ (Be aware, in the current release of Energia, this could be a trick question.) Hint: We recommend you check out the Hardware Pin Mapping to answer this last question. Theres 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. File Save As Save it to: C:\MSP430_LaunchPad\Energia\Blink_Green Hint: This will actually save the file to: 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. 5. How can you change which color LED blinks? Examine the H/W pin mapping for your board to determine what needs to change. Please describe it here: ______________________________________________________ ________________________________________________________________________ 6. Make the other LED blink. Change the code, to make the other LED blink. When youve changed the code, click the Upload button to: compile the sketch; upload the program to the processors Flash memory; and, run the program sketch. Did it work? _______________________________________________________________ (We hope so. Please ask for help if you cannot get it to work.)
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
11 - 23
Lab 11
11 - 24
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11 5. A couple more items to notice Just like standard C code, we can create variables. What is the global variable used for in this example? _________________________________________________________________________ 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.)
8. When your changes are finished, upload it to your Launchpad. Did it work? _______________________________________________________________
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
11 - 25
Lab 11
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 emulations 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
3. Download and run the sketch. With the code downloaded and (automatically) running on the Launchpad, go ahead and push the button. But, how do we know it is running? It doesnt change the LED, it only sends back the current pushbutton value over the serial port. 4. Open the serial monitor. Energia includes a simple serial terminal program. It makes it easy to view (and send) serial streams via your computer.
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. Do you see numbers in the serial monitor? ________________________________________________________________________
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
11 - 27
Lab 11
11 - 28
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
Lab 11
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.
5. Interrupt Step 1 - Configure the PushButton for input. Look back to an earlier lab if you dont remember how to do this. 6. Interrupt Step 2 Create an ISR. Add the following function to your sketch; it will be your interrupt service routine. This is about as simple as we could make it.
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 7. Interrupts Step 3 Connect the pushbutton to our ISR. You just need to add one more line of code to your setup() routine, the attachInterrupt() function. But what arguments are needed for this function? Lets look at the Arduino reference to figure it out. Help Reference Look up the attachInterrupt() function. What three parameters are required? 1. _______________________________________________________________________ 2. _______________________________________________________________________ 3. _______________________________________________________________________ One you have figured out the parameters, add the function to your setup() function. 8. Compile & download your code and test it out. Does the green RED_LED flash continuously? ____________________________________ 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. Missing the INPUT_PULLUP is especially common since most Arduino examples like the one shown on the attachInterrupt() reference page only show INPUT. This is because many boards include an external pullup resistor, Since the MSP430 contains an internal pullup, you can save money by using it instead.
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 10. Add the following code to your new sketch.
#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 MSP430s 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
11 - 32
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
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:
Clicking download combines sketch with main.cpp to create a valid c++ program
// main.cpp #include < Energia.h > int main(void) { init(); setup(); for (;;) { loop(); if (serialEventRun) { serialEventRun(); } } return 0; }
System initalization is done in wiring.c (see next slide) We have already seen setup() and loop(). This is how Energia uses them.
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
11 - 33
Lab 11
7. Follow the trail. Open wiring.c to find how init() is implemented. 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 provides the core files for device specific architectures init() is where the default initializations are handled As discussed in Ch 3 (Init & GPIO) Watchdog timer (WDT+) is disabled Clocks are initialized (DCO 16MHz) WDT+ set as interval timer
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 == FaultRoutine(); // // BCSCTL1 = CALBC1_1MHZ; // DCOCTL = CALDCO_1MHZ; // BCSCTL3 |= LFXT1S_2; IFG1 &= ~OFIFG; BCSCTL2 |= SELM_0 + DIVM_3; 0xFF) If calibration data is erased run FaultRoutine() Set range Set DCO step + modulation
9. Add the FaultRoutine() to the sketch. It is highly unlikely that you have erased the clock calibration data, but it never hurts to check for it. This fault routine simply sets the Red LED as a warning, then traps the processor in an endless loop. In real life, you would want to handle this, but this works for our training.
void FaultRoutine(void) { P1OUT = 0x01; while(1); }
10. Download and observe the blink rate of the LED. Does the LED flash more slowly? ______________________________________________
Gettings Started with the MSP430 - Using Energia (Arduino) with the MSP430
11 - 35
Lab 11
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. 14. Run the modified sketch. Can you see the LED blinking? ________________________________________________ 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 havent 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
16. Change delay() to use the VLO clock. So, in step xx we changed the CPU clock rate to be sourced from the slow VLO. But, we didnt change the clock rate used by delay(). Add the following line to your setup() function:
WDTCTL = WDTPW | WDTTMSEL | WDTCNTCL | WDTSSEL | WDT_DIV_BITS;
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. 17. Try to build your code The compile should fail, as WDT_DIV_BITS was not defined. Add the following line to the top of your sketch. Again, we stole this from wiring.c. #define WDT_DIV_BITS WDT_MDLY_0_5 18. Finally, you should be able to run and view the LED blinking slowly. If its 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.
Set SMCLK to F_CPU Set ACLK to VLO (12Khz) Clear main clock (MCLK) Use DCO for MCLK Clear divide clock bits
delay() ...
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
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
in Button, it was defined as a const integer. Both work equally well. _____________________________________________________________________
4. How is the pushbutton created/used differently from the LED? In Setup() it is configured as an input; in loop() we use digitalRead() _____________________________________________________________________
Using INPUT_PULLUP configs the pin as an input with a series pullup resitor; _____________________________________________________________________ (many TI C provide these resistors as part of their hardware design). _____________________________________________________________________
being woken up by a pushbutton interrupt. _____________________________________________________________________ (Note, we will look at this later.)
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 well 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
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