The basics of application development on an MSP430 16-bit MCU - Part 2 - Embedded.com

The basics of application development on an MSP430 16-bit MCU – Part 2

Editor’s Note: In the second of a two-part tutorial excerpted from MSP430 Microcontroller Basics , by John H. Davies, the author describes use of IAR’s free Embedded Workbench Kickstart IDE to develop a simple in both assembler and the C language on the Texas InstrumentsMSP430 16- bit MCU.

Using the IAR Embedded Workbench kickstart IDE described in Part 1 , I will here work through the simple example that lights LEDs in a constant pattern using both C and assembly language. Kickstart will inevitably have been updated by the time that you follow these instructions but I hope that the main points remain valid.

Before you run Kickstart, create a new directory (folder) on your hard disk to contain the ?les for the project.

Start Kickstart. To begin from a fresh state, select Window > Close All Editor Tabs to empty the editor window and File > Close Workspace to create a new, empty workspace.

Create a new project with Project > Create New Project…. You will see the dialog box in Figure 3 . Under Project templates, expand the tree for C and select main. There are no templates for speci?c devices. The Tool chain at the top should show MSP430 but you should not have to select this unless you have versions of IAR Embedded Workbench for other processors installed. Click OK .You will see the usual Save As dialog box.

Navigate to your new directory, give the project a name such as first, and click OK . Your screen will be laid out as in Figure 1 in Part 1 but the contents of the windows will differ in detail.

Con?gure the project by selecting the name of the project in the Workspace window and choose Project > Options… from the menu. You will be presented with a complicated dialog box, which has a Category list on the left and a set of tabs for each category. We can ignore most of them but some are essential:

  • Select the category General Options and Target tab if not already shown. Choose your device by clicking on the button and working down the hierarchical pop-up menu as shown in Figure 4.
  • Select the Debugger category and activate the Setup tab if necessary. Choose Simulator from the Driver drop-down list if this is not already shown. See Figure 5.

This completes the minimal con?guration of the project so click OK. There are plenty of further choices if you wish to explore. I suggest some of these later.

 

Figure 3: Create New Project dialog bo x for a project using C.

Delete the existing text from the editor window for main.c and type (or copy and paste) your program instead.

Keep the window for main.c active and select Project > Compile from the menu. Before EW430 starts the compiler, it presents you with a dialog box for Save Workspace As . I called it kickstart . If all goes well, you will see messages like those in Figure 1 in Part 1.

Figure 4 : Project options dialog box, showing the tab and pop-up menu for selecting the target device.

Figure 5 : Project options dialog box, showing the tab for the debugger .

If there is an error, you will see something like Figure 6 . A red circle with a white cross marks the offending line in the editor window and the error is explained in the messages window. If both are not visible, use the menu item Edit > Next Error/Tag to step through the errors and correct them.

Build the project by selecting Project > Make from the menu. This compiles all ?les that have been modi?ed since the project was last made and links them. In fact it is usually a better idea to do this than compile ?les individually.

This completes the steps necessary to generate the application, which is now ready for debugging.

You may prefer to change the name of the C ?le to something more descriptive than main.c and have to do this if you keep several projects in the same directory. It is slightly clumsy and takes a few steps:

  • Make the window for main.c active and choose File > Save As… from the menu.
Figure 6: An error reported when main.c is compiled.
  • Give the ?le a more illuminating name, such as ledson.c, including the extension.c , and save it.
  • This changes the name on the tab in the editor window but the project still containsmain.c , which must also be changed.
  • Select the name of the project in the Workspace window, right-click to bring up the contextual menu and move down to the Add item. This expands into a list of ?les to add, one of which should be Add “ledson.c” as in Figure 7 . Select this.
  • Select main.c in the Workspace window and choose Project > Remove from the main menu. You will be asked to con?rm that you want to remove the item from the project: Click Yes. The ?le is not destroyed and you can add it back later if you wish.
  • Select Project > Make to rebuild the project with the new ?le.
Figure 7: Contextual menu for adding ledson.c to the project.

Congratulations! The debugger is next. The IAR C-SPY Debugger can run in two modes, selected with the Debugger category of the project options:

  • The simulator is a program that runs entirely on the PC and models the behavior of certain aspects of the MSP430. No hardware is needed (no MSP430) and the simulator gives complete insight into those features that it models. However, it does not include the peripherals and is unsuitable for investigating the interaction between the MSP430 and its external signals.
  • The emulator looks almost identical on the PC but the MSP430 runs its program itself. The full resources of the microcontroller are available and it can react to all aspects of its working environment. The debugger can stop the CPU and read back the state of any register to the PC so that you can examine any aspect of the program. Unfortunately debugging has some side effects and can be tricky when some peripherals, such as timers, continue to run while the CPU is stopped.

We start with the simulator and explore the emulator later.

Debugging with the C-SPY simulator
The IAR C-SPY Simulator models the CPU but excludes most peripherals. On the other hand, it can simulate interrupts from all sources, which is often enough. Of course ledson.c is so simple that we need only the CPU and the input/output ports.

Start the simulator from the menu with Project > Debug . Your project will be rebuilt if it is not already up to date and you will see a screen slightly simpler than Figure 8. Overall, EW430 looks much the same when debugging as it does for editing the program: It is not like some older debuggers that run as completely separate applications. There is an extra Simulator menu but the most obvious new feature is a Disassembly window, which shows the assembly code that corresponds to each line of C code. Most of this vanishes off the right-hand edge of the window—a large screen is a tremendous boon for debugging. There is also a new toolbar for the debugger.

 

Figure 8 : Simulation of ledson.c.


The debugger offers many ways to look inside the processor. The most useful for this simple program is the Register window, which is brought up by choosing View > Register from the menu. The window has a drop-down list at the top to select various sets of registers inside the particular device. By default it shows the registers inside the CPU butI chose Port 1/2 in Figure 8. This shows that all registers contain 0x00 initially, which is slightly misleading. Some of the registers are initialized this way, such as the direction registers P1DIR and P2DIR. Others, however, are not initialized and may contain anything. These include P1OUT and P2OUT. 

This program is so short that it is trivial to step through it line by line. Use Debug > Step Into for this.The green highlight with an arrow in the margin shows the nextline to be executed. It moves down after each step in both the ledson.c and Disassembly windows:

  • Nothing obvious happens after writing to WDTCTL, which stops the watchdog. You can change the Register window to Watchdog Timer if you want to check that this statement works.
  • The next line con?gures the direction of port 2 by writing to P2DIR. You can see the value change in the Register window and P2DIR is highlighted in red to draw attention to the new value.
  • P2OUT is highlighted in the Register window after the next step, which would light an LED if the program were running on the demonstration board.
  • Further steps have no apparent effect because the program is now trapped in an in?nite, empty loop. A CYCLECOUNTER in CPU Registers in the Register window increases by 2 every time a step is taken. This is the number of CPU cycles needed to execute a jmp instruction, which is the assembly language that results from the empty loop for (;;) {}.


One of the most useful methods of debugging a program is to set a breakpoint . This is a condition under which the processor halts so that you can examine it. The most simple breakpoint is a Code Breakpoint, which causes execution to halt at a particular line. It is hardly worthwhile in so short a program but I explain it nonetheless. First, choose Debug > Reset from the menu to simulate a reset of the device. (I notice that this does not clear P2DIR, which it should do. For a thorough reset you should leave debugging mode with Debug > Stop Debugging and restart the debugger.)

Next, click in the line of ledson.c with P2OUT and choose Edit > Toggle Breakpoint from the menu. The line becomes highlighted in red with a big red blob in the margin in both the ledson.c and Disassembly windows. Now run the program without stepping with Debug > Go . The simulator runs (for all of two lines) until it hits the breakpoint and stops before executing the highlighted line. This is shown in Figure 9 .

 

Figure 9: Simulation of ledson.c with a breakpoint .


An invisible breakpoint is used whenever you start debugging a C program. This is because the compiler generates code to initialize the processor before it is ready to execute your program. For example, static and global variables must be initialized and the stack must be set up. The debugger therefore sets a breakpoint at the start of your main() function so that it stops there after it has performed the initialization. This is the signi?cance of the Run to main item in the dialog box for the Debugger options in Figure 5 .

Another useful trick if you want to examine a particular part of a program is to click in the ?rst line of interest and choose Debug > Run to Cursor . This again sets a breakpoint, runs to the breakpoint and removes it.

Select Debug > Stop Debugging when you have ?nished. Simulation has the great advantages that you get a perfect view into the device and that no hardware is needed. Unfortunately it is slow, does not include most peripherals, and cannot be used to investigate the interaction between the microcontroller and the surrounding components. This requires emulation instead.

The IAR C-SPY Debugger
The IAR C-SPY Debugger can run in two modes, selected with the Debugger category of the project options:

  • The Simulator is a program that runs entirely on the PC and models the behavior of certain aspects of the MSP430. No hardware is needed (no MSP430) and the simulator gives complete insight into those features that it models. However, it does not include the peripherals and is unsuitable for investigating the interaction between the MSP430 and its external signals.
  • The Emulator looks almost identical on the PC but the MSP430 runs its program itself. The full resources of the microcontroller are available and it can react to all aspects of its working environment. The debugger can stop the CPU and read back the state of any register to the PC so that you can examine any aspect of the program. Unfortunately debugging has some side effects and can be tricky when some peripherals, such as timers, continue to run while the CPU is stopped.

We start with the simulator and explore the emulator later.

Debugging with the C-SPY simulator
TheIAR C-SPY Simulator models the CPU but excludes most peripherals. Onthe other hand, it can simulate interrupts from all sources, which isoften enough. Of course ledson.c is so simple that we need only the CPU and the input/output ports.

Startthe simulator from the menu with Project > Debug. Your project willbe rebuilt if it is not already up to date and you will see a screenslightly simpler than Figure 8 . Overall, EW430 looks much thesame when debugging as it does for editing the program: It is not likesome older debuggers that run as completely separate applications. Thereis an extra Simulator menu but the most obvious new feature is aDisassembly window, which shows the assembly code that corresponds toeach line of C code. Most of this vanishes off the right-hand edge ofthe window—a large screen is a tremendous boon for debugging. There isalso a new toolbar for the debugger.

Figure 8: Simulation of ledson.c .

Thedebugger offers many ways to look inside the processor. The most usefulfor this simple program is the Register window, which is brought up bychoosing View > Register from the menu. The window has a drop-downlist at the top to select various sets of registers inside theparticular device. By default it shows the registers inside the CPUbut I chose Port 1/2 in Figure 8 . This shows that all registerscontain 0x00 initially, which is slightly misleading. Some of theregisters are initialized this way, such as the direction registersP1DIR and P2DIR. Others, however, are not initialized and may containanything. These include P1OUT and P2OUT.

This program is so shortthat it is trivial to step through it line by line. Use Debug > StepInto for this. The green highlight with an arrow in the margin showsthe nextline to be executed. It moves down after each step in both the ledson.c and Disassembly windows:

  1. Nothing obvious happens after writing to WDTCTL, which stops the watchdog. You can change the Register window to Watchdog Timer if you want to check that this statement works.
  2. The next line con?gures the direction of port 2 by writing to P2DIR. You can see the value change in the Register window and P2DIR is highlighted in red to draw attention to the new value.
  3. P2OUT is highlighted in the Register window after the next step, which would light an LED if the program were running on the demonstration board.
  4. Further steps have no apparent effect because the program is now trapped in an in?nite, empty loop. A CYCLECOUNTER in CPU Registers in the Register window increases by 2 every time a step is taken. This is the number of CPU cycles needed to execute a jmp instruction, which is the assembly language that results from the empty loop for (;;) {} .

Oneof the most useful methods of debugging a program is to set abreakpoint. This is a condition under which the processor halts so thatyou can examine it. The most simple breakpoint is a Code Breakpoint,which causes execution to halt at a particular line. It is hardlyworthwhile in so short a program but I explain it nonetheless. First,choose Debug > Reset from the menu to simulate a reset of the device.(I notice that this does not clear P2DIR, which it should do. For athorough reset you should leave debugging mode with Debug > StopDebugging and restart the debugger.)

Next, click in the line ofledson.c with P2OUT and choose Edit > Toggle Breakpoint from themenu. The line becomes highlighted in red with a big red blob in themargin in both the ledson.c and Disassembly windows. Now run the programwithout stepping with Debug > Go. The simulator runs (for all of twolines) until it hits the breakpoint and stops before executing thehighlighted line. This is shown in Figure 9 .

Figure 9: Simulation of ledson.c with a breakpoint.

Aninvisible breakpoint is used whenever you start debugging a C program.This is because the compiler generates code to initialize the processorbefore it is ready to execute your program. For example, static andglobal variables must be initialized and the stack must be set up. Thedebugger therefore sets a breakpoint at the start of your main()function so that it stops there after it has performed theinitialization. This is the signi?cance of the Run to main item in thedialog box for the Debugger options in Figure 5 .

Anotheruseful trick if you want to examine a particular part of a program is toclick in the ?rst line of interest and choose Debug > Run to Cursor.This again sets a breakpoint, runs to the breakpoint and removes it.

SelectDebug > Stop Debugging when you have ?nished. Simulation has thegreat advantages that you get a perfect view into the device and that nohardware is needed. Unfortunately it is slow, does not include mostperipherals, and cannot be used to investigate the interaction betweenthe microcontroller and the surrounding components. This requiresemulation instead.

Debugging with the emulator
In thiscase the program runs at full speed on the target MSP430 in its system.It requires a program on the PC, called the C-SPY FET Debugger, and aninterface to communicate between the PC and the JTAG interface of theMSP430. TI names this interface a ?ash emulation tool or FET but it iscommonly called a pod or wiggler.

A decade or so ago, few smallmicrocontrollers could be debugged in this way. An expensive piece ofequipment called an emulator was used instead. It was connected to theprinted circuit board instead of the microcontroller itself and behavedin exactly the same way from the point of view of the system. However,all aspects of the emulator could be controlled and interrogated by acomputer—breakpoints could be set, memory viewed, and so on.

Modernmicrocontrollers such as the MSP430 can be debugged in the same waybecause they contain an embedded emulation module (EEM). This approachis called in-circuitemulation (ICE) to emphasize that the debugger usesthe actual device in its working environment.

There is no needfor a separate emulator in most applications. The capabilities of theEEM vary between devices. For example, smaller devices can set only twobreakpoints in the emulator but larger ones permit up to eight. The EEMcommunicates with the outside world through JTAG. There are two steps inusing the debugger as an emulator: recon?guring EW430 and connectingthe FET or similar interface. First, the software:

Open the project options, go to the Debugger category (Figure 5 ) and change the Driver to FET Debugger.

Select the FET Debugger category and choose the Setup tab, shown in Figure 10 .Several items here may need to be checked: The Connection means theinterface between your computer and the JTAG connection. I show this fora TI USB interface. The box with Automatic is to select the virtual COMport used by the FET and should not need to be changed (other USBinterfaces may not need this option). The list below it is needed onlyif your interface connects to a parallel port.

Figure 10: Con?guration of FET debugger for four-wire JTAG and a Texas Instruments USB interface.

TheDebug protocol applies only to devices that offer a choice of the fullJTAG or Spy-Bi-Wire interfaces, such as the F20xx. It is thereforedimmed in Figure 10 . If ledson.c were adapted for something like an eZ430–F2013 tool, the dialog box would appear as in Figure 11 .The eZ430–F2013 behaves as a TI USB interface but uses Spy-Bi-Wire.This is the default for a F20xx but can be overridden if you wish to usethe four-wire interface instead.

Figure 11: Con?guration of FET debugger for Spy-Bi-Wire and an eZ430–F2013 tool.

Click OK when you have ?nished.

Connectingthe hardware is easy: Plug in the cables. The only dif?culty may bethat some demonstration boards use a bare header for the 14-pin JTAGconnection, which means that it is possible to connect the plug thewrong way around. The red side of the ribbon cable between the interfaceand the JTAG plug should be next to pin 1 of the header, which shouldbe marked in some way. Do not forget to apply power to the target boardas well, unless it takes it from the JTAG cable.

Back in EW430,select Project > Debug from the menu to start the debugger. If thisis the ?rst time that you used the JTAG interface or if you have justupdated EW430, you may see a message asking you if you wish to updatethe ?rmware of FET.

You should probably agree to this. If all iswell, a few messages will ?ash on the screen as your program isdownloaded into the MSP430. If it does not, you are in trouble. (Ialways dread such problems when running classes with microcontrollers.)Here are few suggestions if something goes wrong:

  • A TI FET has two LEDs to show when it is powered and communicating, which might help to localize the problem.
  • If you get an alert that starts Fatal error: Failed to initialize you probably forgot to plug the FET into your computer. The alert suggests some other possibilities.
  • Another alert with The debugging session could not be started may mean that there is no connection between the FET and device.
  • An alert with Fatal error: Failed to write memory at 0xFFFE or Fatal error: External voltage too low may mean that the MSP430 is not powered.
  • Check that all connections are secure and correctly oriented, that there is a microcontroller in the target board (has it come loose in a socket, for instance, or been installed the wrong way around?), and that power is applied (use a voltmeter to check—batteries might have run down).
  • Consult “Frequently Asked Questions” in the MSP-FET430 Flash Emulation Tool (FET) User’s Guide (slau138). 
  • If your target board is powered by the JTAG interface rather than its own power supply, check the signal connections carefully. The FET uses one wire to sense the voltage of the target board and a separate one to deliver power if desired. There are diagrams in the FET User’s Guide .

Ifall these fail, shut down your computer, take a walk to calm down, andcheck everything again when you return. After that I can only resort tothe usual feeble suggestions: try a new MSP430 in case it has beendamaged (always a good excuse when students are involved, if oftenunfair), reinstall the software, and so on.

Assuming thateverything works—and it almost always does, despite the formidable listof possible problems—you will see a screen like Figure 12 . Itlooks almost the same as that for the simulator but the Simulator menuhas changed to Emulator. There is also a further toolbar, which I movednext to that from the simulator. You can step through the program, setbreakpoints, and so on in exactly the same way. The difference is thatthe program is now executed on the MSP430 itself. This means that theLED(s) may light up as soon as their pins are con?gured as outputs bywriting to P2DIR. They should show the desired pattern after the writeto P2OUT.

Figure 12: Debugging ledson.c with the emulator.

Emulationmay seem slower than simulation because the contents of all theregisters displayed on the screen must be read out through the JTAGinterface whenever the CPU stops. You can use the interface in theopposite direction too. Try changing the value of P2OUT in the debuggerand you should see the LEDs change in response. The current value ofP2OUT is visible in the Register window and you can also check it bymaking the ledson.c window active and hovering the mouse over P2OUT. Fortips on more advanced debugging see the application note Advanced Debugging Using the Enhanced Emulation Module (EEM) (slaa263).

Developing a project in assembly language
Youcreate a project that uses only assembly language in almost exactly thesame way. Expand the asm tree in the Create New Project dialog box (Figure 3 above) and select asm . A project is created with the ?le asm.s43 in assembly language. Set the project options in the same way as for C,which should require only selecting the appropriate target device.Build the project in the same way as well (the menu item is still calledCompile even for the assembler).

Simulate the program as before.You may get a Stack Warning error, which can be ignored because thistrivial program does not use the stack. Open a Register window, selectPort 1/2, and step through it exactly as for the program in C. Changethe project options to use the FET Debugger instead and you will ?ndthat it works in the same way as well.

The debugger shows aDisassembly window, which might seem rather pointless when the source isin assembly language but in fact has some instructive features. Forexample, the label Reset: appears above the address 0xF000, which iswhere we directed the assembler to store the program at the start of the?ash memory. You can see this explicitly by choosing View > Memory,which opens another window to show the contents of memory.

SelectFLASH from the drop-down Memory list and 2x Units from the unnameddrop-down list of options. This shows the contents of the memory in16-bit words, starting from the lowest addresses in ?ash memory.(Instructions and addresses are stored in 16-bit words, hence thischoice.) You will see the binary machine code for the few instructionsin the program. All the unused entries memories contain 0xFFFF becausethis is the erased state of ?ash memory—not 0.

Figure 13: Debugging ledsasm.s43 with the emulator.

Nowscroll down to the highest addresses in memory. The very last word, at0xFFFE and 0xFFFF, holds the reset vector—the address at which executionshould start. You should see 0xF000 stored here as in Figure 13 .You could try increasing the address in the ORG 0xF000 directive alittle and rebuilding the project. This causes the program to be storedat higher addresses and changes the reset vector to match.

Read Part 1 of this article

John M. Davies ishead of the Aerospace Engineering Teaching Discipline in the School ofEngineering at the University of Glagow, United Kingdom. He previouslytaught at Cambridge University and Ohio State University. In addition tomicroprocessor development, his research interests and publicationscover a wide range including physics, elasticity and electronics, mainlycentered around semiconducting heterostructures.

Used with permission from Newnes, a division of Elsevier, Copyright 2010, this article was excerpted from MSP430 Microcontroller Basics , by John H. Davies.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.