Вы находитесь на странице: 1из 39

Part 1

Hey folks, I know you have a habit of seeing AVR microcontrollers related tutorials
on maxEmbedded, but trust me, maxEmbedded is going to be full of surprises.
This is my first post and it is going to be about MSP430, a 16 bit microcontroller
family by Texas Instruments.
Pre-requisites: Basic knowledge of micro-controllers and embedded systems,
Familiarity with terminologies related to computer architecture.

Contents

MSP430 An Introduction

What MSP430 has in package?

Central Processing Unit

Memory

Clock

General Pin Configuration of MSP430

Software Support and Development Environment

IAR Embedded Workbench

Code Composer Studio

MSP430 Evaluation Modules and Development Boards

MSP430 LaunchPad

MSP430 An Introduction
MSP430 interesting name, isnt it? Want to know what it stands for? Well, MSP
stands for Mixed Signal Processing. There are three types of signal processing
techniques we generally deal with, namely, Analog signal processing, Digital signal
processing and Mixed signal processing. Thus, the MSP430 family supports Mixed
Signal Processing, making your tasks easier. To have a fuller idea about the
nomenclature
of
the
MSP
family
check
out this wikipedia
page.

What MSP430 has in package?

Recently, Apple Inc. launched its new Apple iPhone 5S, which runs on a 64-bit
Micro-Processor Unit, the first of its kind mobile phone to run on a 64-bit
architecture. The earlier ones used a 32-bit architecture. To know more about what
8 bit or 16 bit micro-controllers actually mean, read Mayanks post on basics of
microcontrollers. an MSP Micro-Controller is a 16 bit Micro-Controller, which
means that it has 16 bit wide address and data buses. So, in a laymans language,
we can say that MSP is twice as fast as the AVR, in terms of processing (not
always the case though). You can roughly relate this to your computer, which is
probably a 32-bit or 64-bit machine. It may look confusing to a person who has a
habit of using 8 bit controllers, but the fact is that it is much more convenient to use
a 16 bit controller. Let us look at some highlights of the MSP430 family:

Von Neumann Architecture: It is modern processor architecture which has


shared memory for both data and instructions. This is in contrast to Harvard
architecture, which has separate memories for instructions and data. In some
systems having Harvard Architecture, instructions memory can be Read only
memory.

The

following

diagram

shows

architecture and Von Neumann architecture.

the

difference

between Harvard

Types of Architecture (Click to Enlarge)

RISC architecture: RISC expands to ReducedInstruction Set Computer. In simple


language, hardware simplicity has been compromised to provide software
simplicity.

Bus width: 16 bit address and data buses.

Memory access range: 16-bit Micro Controller Unit, hence it can address 216 = 64
kB of memory.

Several low power modes: typical being 1A, 3.3 volts consumption in idle mode.

It has an internal Digitally Controlled Oscillator(DCO) oscillating at 1 MHz.


An External Crystal Oscillator can also be used. MSP Controllers should be
made to work at 32.768 kHz, when we need to provide a very accurate timer. This
is because when we use 32.768 kHz, by the time the timer overflows, it is exactly
and accurately 1 second. Can anybody figure out why?

Timers available with PWM (Pulse Width Modulation)

Selection of Analog to Digital Converter with a resolution of 10/12/14/16 bit.

Central Processing Unit


The general purpose of any CPU is to execute the instructions and store data in
the memory. For that, it takes help of the ALU Arithmetic Logic Unit, which
performs all the calculation and computation for the CPU.
Lets consider a CPU-industry analogy. Whole process of CPU works like
an industry; just consider you have an industry for manufacturing goods. For that
you need raw materials which are provided by a store calledmemory. Now the raw
material is brought to the industry by a transport facility called data bus. Now the
question arises, how will one know about which raw material you need or where it
is placed and when do you need it? These are managed with two transport
facilities namely control bus and address bus. Now, with the help of tools and
machines called ALU, you have made the goods and you have to transport it back
to store which is again done by data bus.
To control any operation, we need some special memory units, which holds which
work to be done next and how it should be done etc. These memory units are
present in CPU and are called registers. Registers are small size memory units
which can be well described as the set of cells where each cell can hold one bit
data i.e. either 0 or 1. For more generalized idea about registers, go ahead and
read the first half of Mayankspost, and then get back here. The width of registers
in MSP430 is 16 bit which means each of the register can hold 16 bits of data. If
you have worked with AVR, CPU register holds 8 bits of data. But in MSP430, CPU
registers are 16 bits wide.
Some of the registers which is used by CPU very frequently are as follows

Program Counter, PC/R0

Stack Pointer, SP/R1

Status Register, SR/R2

Constant Generator, CG2/R3

General Purpose Registers, R4 to R15

Memory
We get 64kB of memory space in MSP430 i.e. address range
is 0x0000 to 0xFFFF which has been divided into several types of memories. So, we
will have a brief look on the types of memory, we get in MSP430

Special Function Registers: It is mostly used to enable the registers which are
associated with particular functions. For example, there is a register TACCR which
is related to Timer A of MSP430. Setting some bits of this register can enable or
disable timers and its modes.

Peripheral Registers: These are actually used for communication between CPU
and peripherals but are not used much a general user.

RAM Random Access Memory: All of us pretty aware of this type of memory. It
is the memory space where variables are stored for operations.

Bootstrap Loader: Now this is something which connects your controller with your
personal computer. It contains the program to communicate using a serial protocol.

Information Memory: It is flash memory which is used for storage of non-volatile


data. It may have some kind of serial code to identify the equipment.

Code Memory: As the name says, from where your controller reads the
executable code or some constant values.

Interrupt and Reset Vectors: This memory is utilized for handling interrupts or
exceptions when normal operation of processor is interrupted. Reset is example of
interrupt which has the highest position in Interrupt vector table. Vector table will be
explained in future posts.
All the members of MSP430 family almost have similar memory map which is
shown in the following figure.

MSP Memory Map (Click to Enlarge)

Clock
When you buy a laptop or a personal computer, the sales person says it has i32310m, 2.1 GHz, RAM 4 GB etc. But what is this 2.1 GHz? It is clock of the
computer which wakes the computer 2.1 giga (billion) times a second. Faster the
clock, faster will be your computer. The foremost purpose of clock in any
embedded device is to synchronize the processes. There are three types of clock
in MSP430 family:
1. Master clock, MCLK: As name says, it is used by CPU and a few peripherals.
2. Subsystem Master Clock, SMCLK: It is distributed to peripherals.
3. Auxiliary clock, ACLK: It is also devoted to peripherals.
ACLK comes from low frequency crystal oscillator, typically at 32 KHz attached
externally. Both MCLK and SMCLK are supplied by an internal digitally controlled
oscillator (DCO) which usually generates pulse of 1 MHz.

General Pin Configuration of MSP430

The following diagram show the pin configuration of 14 and 20 pin DIP of
MSPG2xx. Most of the members of MSP430 family share similar pin
configurations. 14 pin and 20 pin Dual Inline Package (DIP) ICs have been shown
in the following picture.

MSP430 General Pin Configuration

SMD (Surface Mounted Device) ICs for these microcontrollers are also available
and are very useful if you want to make your circuit really small. If you are not
familiar with SMD components, you can estimate the size of SMD component by
following picture of two MSP ICs.

MSP430G2102 SMD ICs

Yeah, these are MSP430G2102 ICs on my finger tip!

Software Support and Development


Environment
Consider the CPU-industry analogy once again. CPU is the hardware, just like
industry is the place where you can find machines and tools, but to run that
machinery you need engineers and workers there. Similarly, for a CPU to work, it
needs software. In case of a PC, it is Operating System (OS) which tells CPU
about the work to be done, priorities to be set, interrupts to respond, etc. For a
microcontroller to work, no such operating system exists (well actually, there are
some, like FreeRTOS, where RTOS stands for Real Time Operating System,
which is designed to operate on bare hardware like microcontrollers). We write the
instructions in form of assembly language or some high level language like C/C++
to tell the CPU of microcontroller how to operate. So, it is basically like you are
making your own small sized computer, which can serve you for a particular task.
Does it sound interesting?
Now the question is, where you are going to write the code and how you are going
to transfer this code to your hardware? Also, it is not like just writing the code. If
you have worked with microcontrollers before, you must be familiar with
terminologies like code building, compilation, debugging, simulation, etc. You can

have a look at the microcontroller based development process at the end


of this post by Mayank. Though it mostly deals with AVR microcontrollers, the
concepts hold good for any microcontroller, even MSP! Well, these are the
necessary steps before you burn your controller with your code. Usually, these all
steps are combined into an Integrated Development Environment (IDE). It keeps all
paths of your linkers, libraries, source files etc. Sometimes, Flash Programmer
which downloads or burns the code into the IC comes with IDE itself. Those who
have worked with AVR must have worked with software like AVRDude or eXtreme
Burner, to burn their code into controllers. To build and burn the codes in MSP430,
there are two major IDEs are available.

IAR

Embedded

Workbench

Kickstart: I

personally like this one, so, I will be writing my future posts on this only. It can be
bought from IAR Workbenchs website but its limited versions are also available in
two ways. One is limited version which stays for 30 days; another is a version with
more limitations but with no time limit. I will suggest readers to subscribe the limited
version with no time limit. The main limitation of this version is code limit which is
limited to 4 KB of C code which is enough for learning purposes. To know more
and download the software, visit IAR systems web page.

Code Composer Essential Evaluation: Those


who have worked with Code Composer Studio for its DSP chips, then you can
estimate its working. Anyways, free version of CCS is made available by Texas
Instruments, but code size is limited to 16KB of C code. Its installation file size is
around 2 GB in comparison with IAR which has size of around 300 MB. To know
more about CCS and download the software, visit TIs webpage.

Please note that, you may get problems while trying to install either of the above
software with Windows 8, but both of them work perfectly fine in Windows 7 and
Linux.

MSP430 Evaluation Modules and


Development Boards
Now that you have gotten a little idea about MSP430, its time to get your hands on
some of the development boards and platforms. Texas Instruments sells the
MSP430 development board with the name LaunchPad. Two types of LaunchPad
are commonly available for beginners by TI. One is MSP430G2 Value Line
LaunchPad and another is MSP430F5529 USB LaunchPad. MSP430F5 series is
more advanced as compared to MSP430G2 series in terms of more flash memory,
more space for RAM, Timers and 12-bit ADC resolution as compared to 10-bit
resolution of MSP430G2 series etc. The full comparison between these two
LaunchPad is given in detail here by Texas Instruments.

The MSP430 Launchpad we will be working with

MSP430G2 Value Line LaunchPad is the cheapest development board available


by Texas Instrument. And it comes with 14 and 20 pin DIP target socket in which
you can drop any 14 or 20 pin DIP MSP430 device and start developing your
application. After you program the device, you can use it as a standalone system
and put it in custom printed circuit board or breadboard. You can go for
MSP430F5529 USB Launch pad if you need more number of General Purpose
Input/Output (GPIO) pins, better ADC resolution, more RAM etc. It clearly depends
upon the application where you are going to use the controller. You can buy any of
these LaunchPad by Texas Instruments here.

So, readers, that was all about the basics of MSP430. Hope you liked my first post.
Dont forget to tell me about your views. I am waiting for your comments and
queries. And subscribe to maxEmbedded to stay updated!

comments

I/O Port Operations in MSP430


Hello friends, here comes the second post about MSP430. In this post, we will see
how input-output operations work in MSP430. We will also write a sample code to
glow LEDs connected to pins of MSP430G2553.

Contents

I/O Operations! Why and what?

Memory Mapping

C Programming Language

Logical and Bitwise Operators

Bit Masking

Data Types

Do It Yourself

I/O Operations! Why and what?


In my previous post, I discussed about the architecture of MSP430 microcontroller.
It is a small computer-on-chip just like other microcontrollers. When, we think of a
personal computer, we usually get an image of a desktop or laptop computer in our
mind. These computers generally have keyboard and mouse as input devices and
monitor or screen as output device. Through all these devices, a computer
interacts with the outer world. Then, what does a microcontroller uses to interact
with outer environment (or users)? The answer is ports. All the sensors, and other
input-output devices are connected to microcontroller through a set of pins, called
ports. If you have worked with AVR, you must be familiar with port names PORTA,
PORTB, etc. But Texas Instruments use numeric listing instead of letters. The port

name starts as P1, P2 and so on. There is no P0. Each port has eight pins. All pins
of a port might not be available for user. Some pins are internally connected to the
controller.

Memory Mapping
I mentioned in my previous post that, to access a byte from memory of a computer,
there is always anaddress. It means that, to fetch any data or instruction from
memory, CPU makes use of address of that data or instruction. Now, the question
arises is- How does the CPU of MSP430 access ports of the controller? The
answer is simple. CPU considers ports as memory registers. Each port is a byte in
the memory, and eachpin of the port represents a bit of that register. The registers
assigned to the port are called peripheral registers. This is called Memory Mapping
of input-output. These registers can be read, written and modified. Moreover,
arithmetic operations can also be performed. But, how do we decide that whether a
port is to used as input or output? For this purpose, there are three types of
registers associated with each port.
1. PxIN
2. PxOUT
3. PxDIR

Here x is the port number (remember, P1, P2, etc?). For example, when x is 1, it
becomes P1IN, P1OUT and P1DIR. The keywords IN, OUT and DIR expands to
input, output and direction respectively.

Port Registers in MSP430

Setting P1DIR to one (1, HIGH) configures the pins of port 1 as output and clearing
the P1DIR register to zero (0, LOW) makes the pins of port 1 as input which is also
the default. This way, DIR gives direction of operation to the ports. It is similar to
the DDRx register of AVR. Each pin or bit of the port can be configured individually.

It is not necessary to make all pins of the port behave in same way. Now let us look
at the example:
P2DIR = 0xB1;
// This is in hexadecimal form
P2DIR = 0b10110001; // Binary representation
The above two statements are equivalent to each other. Both can be used to make
0th, 4th, 5th and 7thpin of port 2 as output pin. You would have already noticed, we
count from LSB (0th bit) to MSB (7th bit). This is a convention in logic design. Now,
after setting the pins as output pin, we can assign values to them in following way.
P2OUT = 0x08;
// This is in hexadecimal form
P2OUT = 0b1000;

// Binary representation

This will set (to 1) the 4th pin of port 2. If we try to give an output to the pin or port
which has not been assigned as output port using DIR, then the value we give is
stored in PxOUT register and is passed to the port when it is assigned as output
port. Please, keep it in mind that, in general digital logic language, setting a bit
means giving logic 1 (or HIGH) to the bit and clearing a bit means giving logic 0 (or
LOW) the bit.

C Programming Language
In my earlier post, I mentioned that MSP430 can be programmed using assembly
language and C programming language. Most of us are familiar with C
programming language for obvious reasons. Its simplicity, ease of understanding
and programming, user defined types, flexibility and data structures make it much
better than assembly language. Thus, we will be programming the MSP430 using
C language only. This language is used by many other microcontrollers as well
because it is efficient and easy to debug and supports the modern controllers
architecture. Here, I am assuming that if you are aware of basic C programming
language. If not, please stop here, read a little about C, and then come back! Now,
let us look at some aspects of the C programming language which we will deal with
in future posts. NOTE: This section does NOT teaches you how to program using
C. You should be familiar with it by now. If not, take a break! This section teaches
how to use C specific to embedded systems requirement.

Logical and Bitwise Operators


A lot of people easily get confused with these two kinds of operators. Let me
explain you with examples one by one.

Logical Operators
Logical operator, as the name says logical, gives only one bit logical output.
Consider the following example
A = 0x11;
B = 0x00;
C = 0x01;
D = 0x00;
E = A && B;

// E = 0

F = A && C;

// F = 1

G = A || B;

// G = 1

H = A || C;

// H = 1

I = B || D;

// I = 0

Here, && and || are the logical operators and are used to perform logical
AND and logical OR operations respectively. For logical operators, result is ZERO if
and only if

for logical AND, any one of the operands is exactly zero.

for logical OR, both the operands are exactly zero.

For all other cases, the result is always ONE.

Bitwise Operators
Bitwise operator, as the name says, does bitwise operation. Look at the following
examples.
A = 0x4B;
// A = 0b1001011
B = 0x19;

// B = 0b0011001

C = 0x2A;

// C = 0b0101010

D = A & B;

// D = 0x09 = 0b0001001

E = A | B;

// E = 0x6B = 0b1101011

Here, & and | are bitwise AND and bitwise ORoperators respectively. The result is
the bit by bit result of the AND and OR operations on the operands.

Accessing Individual Bits (Masking)


Byte is generally used as the smallest entity in microcontrollers. However, many
times we need to test or modify individual bits of the controller. There are many
ways by which a user can access the bits or the port. We always tend to use the
optimized code for a program, thus it is always better to declare a BIT before

starting the main code of program. You can declare it globally outside
the main() as
int BIT3 = 0b00001000;
Or else, a better way would be to define it as a macro (recommended) as follows
#define BIT3 0b00001000
Its not necessary to have a name like BIT3, but it is always advised to name it
something that can be related to easily. And make sure the name you choose is
not a reserved keyword. This selection of individual bits is called masking. Now, if
we do bitwise AND operation P13 = P1IN & BIT3, it will make all pins of P1 zero
except for bit 3 because x & 0 = 0 and x & 1 = x. Similarly, x | 0 = x and x | 1
= 1. So, P2OUT = P2OUT | BIT3 will set the bit 3 of P2, leaving the values of other
bits unchanged. Thus, we can use the following way to read and to write a bit:
1
2

if( ( P1IN & BIT3 ) == 0 ) //

Reading the BIT3 of port 1, checking if it is logic

P2OUT = P2OUT | BIT3;

// this can also be written as P2OUT |= BIT3

// Setting up BIT3 of P2. i.e. writing the individual bi

6
7
8

else
{
P2OUT &= ~BIT3;

// Clearing the BIT3 of P2, if BIT3 of P1 is high.

10

If we observe the above code, it is nothing more than the operation of a switch
which is connected to BIT3 of P1 and LED which is connected to BIT3 of P2.

Port Operation Example. Note: x is just a representation, it could be either 0 or 1 depending upon the previous
state.

Now, let us look at the above code once again line by line

The first statement uses if condition. If the condition is true i.e. if BIT3 of P1 is low, the
statements within the curly braces {} will be executed. In other words, if a switch
connected to P1.3 is closed i.e. P1.3 is grounded, it will make P2.3 HIGH. If an LED is
connected to P2.3, it will NOT glow (assuming LED is connected in active low
configuration). The LED will glow only if the PIN is logically LOW. The following diagram
might help you understanding the basic difference between active low and active high pin.

Active High and Active Low

On the contrary, if the condition of if statement is false, it will execute


the else statement and make P2.3 logic LOW, and this time the LED connected to P2.3
will glow.

What if we want to toggle the output bit every time?? Then in that case, we can use
following statement (why?). Hint- ^ stands for XOR operation.
P2OUT = P2OUT ^ BIT3;
P2OUT ^= BIT3;

// Same as above

Data Types
While using C or C++ language, we use int or char. Similarly, for MSP430 (and
other microcontrollers as well), a 16-bit microcontroller, there are few other types of
commonly used data types. char and int can be used for declaration of counter
variable. Their sizes are 1 byte and 2 bytes respectively. int8_t and uint8_tare
used to declare signed and unsigned 8-bit integers
respectively. int16_t and uint16_t are used to declare signed and unsigned 8-bit
integers respectively. These typedef variables are also available in C, defined
in stdint.h. Refer to this document for more information.

Why do we need special data types?


This is something which every rookie wonders about. The answer is necessity.
When you are writing a program to be executed on your laptop/computer, you are
least bothered about how much size it occupies. For instance, when you declare a
variable as int, do you know how much space it occupies in memory? Is it 2 bytes
or 4 bytes? Whats the size of unsigned short int 1 byte, 2 bytes or 4 bytes?
How about long int 4 bytes or 8 bytes? You dont know! Frankly speaking, it
depends upon the compiler and your implementation. The C standard specifies
only minimum size of int data types. For instance, the C standard says that

an int data type must have a minimum size of 16 bits (2 bytes). This means that,
depending upon the compiler, it could be 2 bytes, 4 bytes or even 8 bytes! In
embedded systems, you have to deal closely with the hardware. For example, you
have to implement an 8-bit counter, you which, you need to count only up to 8 bits.
Can you declare your variable as unsigned short int and depend upon your
compiler to accurately store it as 8 bits? Or for example, your microcontroller has
an ADC which converts analog input signals to digital with a precision of 10 bits.
Could you declare your variable as int and wait for compiler to do the conversion
for you? Heck NO!
You need fixed-width integer sizes, wherein you know exactly how much size your
variable is gonna occupy! These are defined in stdint.h C header file. Whenever
you use uint8_t data type, your variable can hold unsigned values of 8 bit (1 byte)
sizes only, no matter which compiler compiles it! So if you define your variable
as int32_t rather than long int, you know that its gonna occupy 4 bytes, no
matter what, whereas in the latter case, it could have been either 4 bytes or 8 bytes
depending upon the compiler.
As a kid when you would be in a candy store, you must have heard your mom
saying to you take only what you need. The same goes here. For example, you
need a counter to count up to 200. What would you define it as? Would you define
it as int, or short int, orunsigned short int, or int8_t, or uint8_t, oruint16_t,
or what? Remember that int and short int are at least 16 bits wide. But you
simply need to count up to 200, which is only 8 bits. This is where take-only-whatyou-need concept chips in. If you can count perfectly using an 8-bit variable, why
do you want to take a 16-bit one? Its a waste of space, and you should know that
in embedded systems, memory is very limited. So ideally, ones choice would
be uint8_t (why not int8_t?). But these days, compilers have also become smart.
They know how to optimize your codeand cut down the size of variables as and
often required.

Do It Yourself
Now that we know the basic aspect of C programming language to write a simple
program, as a quiz, please write a simple program for MSP430G2553 to glow
LEDs connected 2nd and 5th pins of port 1. Even though the code is attached right
up front, I request you to solve it to the best of your ability.
#include <msp430g2553.h>
void main (void)

{
WDTCTL=WDTPW|WDTHOLD;
P2DIR=0x15;
output
P2OUT=0x05;
at 2nd pin off (active low)
while(1);
}

// Watchdog timer off


// IMP: Making 4th and 2nd pin of P1 to
// IMP: Making LED at 4th Pin glow and LED
// Infinite loop

Dont worry if you are confused with the code. If you got the two highlighted lines
correct (commented with IMP:), thats all you need for now! We will discuss the
concepts related to header file and watchdog timer in future posts. In next post, we
will see how we can use IDE for MSP430 to build and compile this code, and kick
off with a hello world program. This was all about basic input-output operations in
MSP430.
I hope you enjoyed the reading. I am waiting for your comments, queries and
suggestions. And please subscribe to maxEmbedded to stay updated!

USANDO IAR

About IAR Embedded Workbench


I mentioned earlier that EW430 software comes for free in two versions. While one
is a time limited version which stays for 30 days (after which youll need to pay to
use it), the other one is code size limited but with no time limit. I would suggest
readers to subscribe to the code size limited version with no time limit, wherein the
code size is limited to 4 KB of C code, which is more than enough for our learning
process.
IAR Embedded Workbench is available for a vast range of processors and
controllers which includes ARM and AVR as well. I personally prefer it over Code
Composer Essential IDE because I found EW430 a tad easier to use and predict
for new users. If you have worked with Code Compressor Studio before, you might
find Code Composer Essential familiar to work with.

Installation and Getting Started


1. The very first task is to install EW430 on your computer. It is compatible with both
Windows 7 and Windows 8. You can download it from here.
2. Now, open up the downloaded .exe file and install the software. It should not take more
than fifteen minutes.
3. After installing, go ahead and open up IAR Embedded Workbench. When you open it up, a
dialog box called IAR License Manager will automatically pop up asking for a license key.
Even if it doesnt pop up automatically, go to start and search for IAR License Manager.
4. Click on register, it will require internet connection. Follow up the easy steps and register
for code limited version of IAR. It will ask you some general questions like your name,
institution or companys name and about the project you want to build using EW430. Just
answer all questions and give your correct email address.
5. After completing all such formalities, you will receive the license key in the email you
registered with. Copy and paste the key into the license manager and here you are ready
to start with MSP430! Woohoo!

The above steps are required for the first use of the software. After that, you can
directly open the IAR Embedded Workbench (henceforth mentioned as EW430).
The window of EW430 is usually divided into three parts. We will look at them one
by one.

Workspace Window
The EW430 Workspace Window looks something like this. If the image is too small
to view, click on it to enlarge.

IAR Windows (Click to Enlarge)

The top left pane in the IAR window is workspace. This is where the IDE keeps
track of all the source code, linker, libraries and dependencies. You can see and
access the source code (usually .c or .asm files), header and library files (usually .h
files) being used in compiling and building your project. Generally, the workspace
area is in collapsed (or compact or aggregated) form by default, but in the figure I
have expanded the tree. The workspace simplifies things for you (a lot, especially
when managing/handling files is concerned) when you are working on more than
one project. In the image above, you can see the currently selected project in bold,
underneath which you can find the source codes, libraries and linker files.

Editor Window
So.. any guesses??! Yes, you correct! It is the big white space where we write the
code. It goes without saying that it is the top right pane covering most of the area.
Remember that code is poetry you write code, and youll have to love writing it as
well. This is why you can customize it to suit your needs (and eyes, and fall in love
with it)! You can change the font type, font size, color scheme and tons of other
features by going toTools > Options > Editor > Expand Editor and play around. You
can also open multiple editor windows in a project and save them in your project
directory, or replace them with the current one anytime you want. The editor
window also comes in handy during simulation of the code.

Message Window
The message window usually shows the errors and warnings during building.
Clicking the error will move the cursor to the line in the code where the error has
occurred.

Going about your First Project Hello


World!
If you are working on MSP430 for the first time, creating your first project will surely
titillate you. So, without taking much time, lets go about your Hello World
project step by step.

Step 1 Create New Project


Open IAR Embedded Workbench. Go to Project > Create New Project. A dialog
box will appear. We will write the code in C language, hence expand C and click
on main. Click OK and usual Save as window will appear. Create a
separate directory where you can save all your projects, and save each project and
associated files in a separate folder inside it. Trust me, it helps!

IAR Create New Project (Click to Enlarge)

Step 2 Workspace and Editor appears


The window containing the workspace and the editor space will appear. The
window is shown below. You can also see some lines of code already written for
you in the editor.

IAR Initial Window (Click to Enlarge)

Step 3 Write Code


Please make sure youve read and understood theprevious post before you even
continue to read further. Lets write our first program to light up the two LEDs on
the MSP430 Launchpad. If you notice, the red LED (LED1) is connected to P1.0
and the green LED (LED2) is connected to P1.6. Both of them are in active high
configuration.
Thus, all you need to do is to add the following two lines of code.
P1DIR = 0xFF; // Making port 1 output ports
P1OUT = 0x41; // Making pins P1.0 and P1.6 high

The overall code would look somewhat like this:


#include "io430.h"

int main (void)


{
// Stop Watchdog Timer to prevent timeout reset
// We'll learn about it a little later
// For now, just keep in mind that it is needed
// for most MSP430 projects
WDTCTL = WDTPW + WDTHOLD;

// WDTCTL = WDTPW | WDTHOLD; would work as well

P1DIR = 0xFF; // Making port 1 output ports


P1OUT = 0x41; // Making pins P1.0 and P1.6 high
}

Just make sure, you save the source code every time you make any changes to
that.
To get the hexadecimal equivalent of your binary number, you can make use of
Windows Calculator. Youll need to change its view to Programmer. Click on the
bits you want to set and change the result type from Decimal to Hexadecimal and
youll get the required hexadecimal equivalent of 01000001. For instance, look at
the image below.

Calculating Hex Value

Step 4 Choose your Device


Now, go to Project > Options, and then select General Options under Category.
This is where you get to choose the device you are using. I am using
MSP430G2131 which is present on the Launchpad.

IAR Choose Device (Click to Enlarge)

Now click on the Debugger category. This is required for us to step through and
control the execution of the code. We have two types of debugger in this IDE.

Simulator: It runs entirely on our computer and dont need any external hardware. It
shows the results based on the features of devices that it models. It is unsuitable if we
want to work with external signal interacting with the device.

Emulator: It looks similar to simulator on computer but the program runs on a real
device. To achieve this, we need a separate piece of hardware, called emulation tool,
along with the microcontroller were using. MSP430G2 LaunchPad is a pretty good choice
since it features on-board emulator. It also has some side effects that come into picture
when we use timers and interrupts, but lets not worry about it now.

We will deal with both simulator and FET debugger, but lets proceed with
simulator, and then click OK.

Step 5 Save and Compile your Code


If you havent done so already, save the project and your code. You can choose
any fancy name you like (its your project after all). We will now compile our code.
Go to Project > Compile or simply press Ctrl+F7. You should see some messages
in the message window show up. If you have followed everything like a nice little
kid up until now, there shouldnt be any error or warning; and you should
see something similar to this:

IAR Successful Build (Click to Enlarge)

Step 5A
But you know, since life isnt always fair and since Murphys Law always holds
good, you might and willcome across errors and warnings sooner or later. Even
though we secretly wish that you may never have to see this step again, we would
still like to show you how it looks to get an error! Lets introduce an (obviously
intentional) error and see what happens. Lets say you misspelled P1DIR and
wrote P1DRI instead. Upon compiling, you should get an error as shown in the
figure below. Double clicking the error in message window will automatically
position the cursor to the erroneous line. Now go ahead, fix it if you can! And dont
just fix it, re-compile it as well!

IAR Unsuccessful Build (Click to Enlarge)

Step 6 Build your Code


Now that we have our source code ready and compiled, the next step is
to make the code. Go to Projects > Make or press F7 to make the code. This
will build your code and update your built tree in workspace. You shouldnt see any
errors with the program in context, but in case you get any error, please comment
below the post. And please do not post any source code in the comment. If you
absolutely need to share your code with us, use pastebin.com and share the link.
Thank you for your cooperation.

Step 7 Debug/Simulate your Code


The next step is to debug the code we just made (or built). Since, we chose
simulator in step 4, we dont need any hardware and we can see the state of
registers in the IDE itself.

Click on Project > Download and Debug. You will see a new window pop up towards the
right side of your screen. This partition, called Disassembly, will show the assembly
language equivalent of your C code. This is what the compiler has generated for you.

We also want to check the status of the registers changing with each line getting executed.
For that, click on View > Registers. Again, a new partition on the right pops up and will
show you the status of registers. By default, it displays the CPU registers, which you can
change to Port1/2 to analyze.

The green colored highlighted line on the editor window indicates the next line to be
executed. At this stage, your window should look something like this:

IAR Code Debugging (Click to Enlarge)

Step 8 Step Through your Code


Once you enter debug mode, you can see a new debug toolbar appear in your
IDE. Click on the Step-in button in the toolbar and you will see the highlighted line
getting executed and states of registers getting changed in the Register partition.
You can also debug using step-into, step-over, and step-out buttons, but they are
useless for this example. They are useful for playing around when you have
several function calls in your program. Well skip them for now in order to keep
things simple and straight. However we do encourage you to try them out as well.
In case of any questions, you can use the discussion panel below this post.
Once you are done observing the outputs in register window, you can stop
debugging and get back to your editor window for some more fun.

Step 9 Connect your Hardware


Now, lets debug using the emulator. Remember in step 4 we mentioned the need
for a hardware in order to emulate? Connect your LaunchPad to your computer
using mini-USB cable provided with it. Your computer shouldnt show any error in
getting the device connected, since the drivers should have been installed while
you were installing IAR EW430. Once connected, go to Project > Options and
change the Debuggerdriver to FET Debugger and click OK.

Step 10 Debug/Emulate your Code


Again, go to Project >Download and Debug. It will initialize your device and check
the connections first. Sometimes, it might give you some type of fatal errors, which
means your emulation hardware is not connected to MSP430. If it says,
communication error, it means that your Rx and Tx pins are not connected.
Note: If you are working on MSP430G2 LaunchPad, make sure you connect
all the five jumpers between emulation and MSP430G2 device.
Soon enough, your code will be ready for debugging. Just click on the stepin button line by line or if you are eager to see your code working directly, then let it
go for a free run by clicking the GO button. And dont forget to share your
excitement with us when you see the LEDs glowing on your board.

Lets blink some LEDs now!


Well, up until now, we were merely glowing the two LEDs. Now lets blink one of
them. Modify the code to the following and repeat all the steps. This code blinks
the red LED (LED1) on the LaunchPad.
1

// This code blinks the red LED (LED1)

// connected to P1.0

#include "io430.h"

4
5

int main(void)
{
int i;

6
7
// stop watchdog timer

WDTCTL = WDTPW | WDTHOLD;

9
10

// set up P1.0 (LED1) as output

11

P1DIR = 0x01;

12
13

// intialize P1.0 (LED1) to 0 (off)

14

P1OUT = 0x00;

15
// loop forever

16

for(;;) {

17

// toggle LED1 on P1.0

18

P1OUT ^= 0x01;

19
// wait! we need to see it at least

20

for (i = 0; i < 0x6000; i++);

21
22

}
}

23
24

The Infinite Loop


Notice the use of an infinite loop in the program. No, this is not an error, and yes, it
is intentional. You surely dont want your LED to stop blinking after some time, do

you? This goes on with most of the embedded systems application. You want your
application to run forever (until the system is rebooted, or some interrupt occurs).
For example, you want the engine control unit to control the throttle of your car for
as long as the engine is running. What would happen if it stops working after you
have driven a couple of miles?

The Delay
With the implementation of loops in any embedded system comes the topic delay.
In this case, we want us to see the LED blinking. Thus you should give enough
delay for the LED to turn on and off. In fact, LEDs can be operated at a much much
higher frequency as well (and it works perfectly fine), its just that our eyes are too
slow to notice them. So give enough delay to see it blink. However, delay plays a
much higher and important role in embedded systems. In fact, embedded systems
is all about constraining your execution to meet specific timing deadlines.
Discussion on this topic is out of scope of this post. May be sometime later when
we discuss about real-time embedded systems, well have a post dedicated to this.
Till then, enjoy!

More Blinking Patterns


Sure! Go ahead and try out blinking LED2 as well, and try out different blinking
patterns as well with different delays. Feel free to share your experience with us
down below.

Summary
In this post, we learned how to use one of the available software tools (IAR
Embedded Workbench) for compiling, building and debugging code for MSP430.
We also learned how to blink LEDs and perform some basic I/O port operations
using MSP430.
Thats it for now! Feel free to share your thoughts down below! And please do not
post any source code in the comment. If you absolutely need to share your code
with us, use pastebin.com and share the link. Thank you for your cooperation.

Вам также может понравиться