+ All Categories
Home > Documents > MSP 430 programming

MSP 430 programming

Date post: 24-Oct-2015
Category:
Upload: quoc-hieu
View: 129 times
Download: 3 times
Share this document with a friend
Description:
TI MSP430 programming tutorials
82
IEEE NITC SB presents A Workshop on MSP430 Venu S Dharan Surajnath P Muhammed Yazar Y Nijesh K U Siva Sankar A September 21, 2012
Transcript
Page 1: MSP 430 programming

IEEE NITC SBpresents

A Workshop on MSP430

Venu S DharanSurajnath P

Muhammed Yazar YNijesh K U

Siva Sankar A

September 21, 2012

Page 2: MSP 430 programming

Getting Started withMSP430 MCUs

1

Page 3: MSP 430 programming

Contents

1 Basic Electronics Circuit Components 71.1 Resistor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

1.1.1 Testing a resistor using a multimeter . . . . . . . . . . . 71.1.2 Light Dependent Resistor (LDR) . . . . . . . . . . . . . 10

1.2 Capacitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.2.1 Testing a capacitor using an multimeter . . . . . . . . . . 10

1.3 Inductor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.4 Transistor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131.5 Diode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

1.5.1 Testing a diode using a multimeter . . . . . . . . . . . . 151.5.2 Zener Diode . . . . . . . . . . . . . . . . . . . . . . . . . 151.5.3 LED - Light Emitting Diode . . . . . . . . . . . . . . . . 161.5.4 Photo Diode . . . . . . . . . . . . . . . . . . . . . . . . . 16

1.6 Integrated Crcuit (IC) . . . . . . . . . . . . . . . . . . . . . . . . 171.6.1 IC Pin Numbering . . . . . . . . . . . . . . . . . . . . . 17

1.7 Transformer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181.7.1 Retifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.7.2 Voltage Regulators . . . . . . . . . . . . . . . . . . . . . 19

1.8 Soldering Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . 201.8.1 Steps in Soldering . . . . . . . . . . . . . . . . . . . . . . 20

1.9 Multimeter and Testing Components . . . . . . . . . . . . . . . . 211.9.1 Testing transistors using multimeters . . . . . . . . . . . . 21

1.10 Relays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2 Introduction to Programming in C 242.1 Hello World Program . . . . . . . . . . . . . . . . . . . . . . . . . 242.2 Declaring Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 252.3 Basic Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

2.3.1 Program to add 2 nos. . . . . . . . . . . . . . . . . . . . . 252.4 Basic Operators in C . . . . . . . . . . . . . . . . . . . . . . . . . 26

2.4.1 Arithmatic Operators . . . . . . . . . . . . . . . . . . . . 262.4.2 Logical / Relational Operators: . . . . . . . . . . . . . . . 262.4.3 Bitwise Operators: . . . . . . . . . . . . . . . . . . . . . . 27

2.5 Control Structures: . . . . . . . . . . . . . . . . . . . . . . . . . . 27

2

Page 4: MSP 430 programming

2.5.1 Sequential Control Structure . . . . . . . . . . . . . . . . 272.5.2 Selection Control Structure . . . . . . . . . . . . . . . . . 272.5.3 Iteration / Looping . . . . . . . . . . . . . . . . . . . . . . 292.5.4 Jump Statements . . . . . . . . . . . . . . . . . . . . . . . 29

2.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302.7 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312.8 Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312.9 Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

3 An Introductory Overview 333.1 Analog and Digital Signals . . . . . . . . . . . . . . . . . . . . . . 33

3.1.1 Analog Signals . . . . . . . . . . . . . . . . . . . . . . . . 333.1.2 Digital Signals . . . . . . . . . . . . . . . . . . . . . . . . 34

3.2 The Number Systems . . . . . . . . . . . . . . . . . . . . . . . . 343.2.1 The Binary number system . . . . . . . . . . . . . . . . . 353.2.2 The Hexadecimal number system . . . . . . . . . . . . . . 35

4 Inroduction to MCUs 364.1 What is an MCU? . . . . . . . . . . . . . . . . . . . . . . . . . . 36

4.1.1 The Origin . . . . . . . . . . . . . . . . . . . . . . . . . . 364.1.2 Terms associated with the MCU . . . . . . . . . . . . . . 364.1.3 Why MCU? . . . . . . . . . . . . . . . . . . . . . . . . . . 38

4.2 Anatomy of a Simple MCU . . . . . . . . . . . . . . . . . . . . . 384.3 Hardware and Software required for an MCU . . . . . . . . . . . 40

4.3.1 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . 404.3.2 Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

5 MSP430 415.1 What is MSP430? . . . . . . . . . . . . . . . . . . . . . . . . . . 41

5.1.1 Salient Features of MSP430 . . . . . . . . . . . . . . . . . 415.2 MSP430 Value Line Series . . . . . . . . . . . . . . . . . . . . . . 425.3 Introduction to Code Composer Studio(CCS) . . . . . . . . . . . 42

5.3.1 Installing CCS . . . . . . . . . . . . . . . . . . . . . . . . 425.4 MSP430 Launchpad . . . . . . . . . . . . . . . . . . . . . . . . . 43

5.4.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435.4.2 Installation of Hardware . . . . . . . . . . . . . . . . . . . 445.4.3 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . 45

6 Programming the MSP430 466.1 Begining MSP430 Programming . . . . . . . . . . . . . . . . . . 46

6.1.1 Getting Started with CCS . . . . . . . . . . . . . . . . . . 466.1.2 Creating a New Project in CCS . . . . . . . . . . . . . . . 466.1.3 Customizing CCS . . . . . . . . . . . . . . . . . . . . . . 47

6.2 Port Programming - Basic I/O Operations . . . . . . . . . . . . . 476.2.1 Salient Features of MSP430 Ports . . . . . . . . . . . . . 476.2.2 Port Configuration . . . . . . . . . . . . . . . . . . . . . . 47

3

Page 5: MSP 430 programming

6.3 Output Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 496.3.1 Lighting an LED . . . . . . . . . . . . . . . . . . . . . . . 49

6.4 Input Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 506.4.1 Reading a switch . . . . . . . . . . . . . . . . . . . . . . . 50

6.5 Introduction to Grace . . . . . . . . . . . . . . . . . . . . . . . . 526.6 Customizing the Port - Lighting an LED . . . . . . . . . . . . . . 536.7 Implementation Using Grace - Reading the Switch . . . . . . . . 53

7 Interrupts in MSP430 557.1 What is an Interrupt? . . . . . . . . . . . . . . . . . . . . . . . . 557.2 Toggling LED Using Interrupt . . . . . . . . . . . . . . . . . . . . 56

7.2.1 Using Interrupt Flag . . . . . . . . . . . . . . . . . . . . . 567.2.2 Using General Interrupt Coding . . . . . . . . . . . . . . 57

8 Timers in MSP430 608.1 What is a Timer? . . . . . . . . . . . . . . . . . . . . . . . . . . . 608.2 Timers in MSP430 . . . . . . . . . . . . . . . . . . . . . . . . . . 608.3 Timer A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

8.3.1 Salient Features . . . . . . . . . . . . . . . . . . . . . . . . 618.3.2 Timer A Registers . . . . . . . . . . . . . . . . . . . . . . 628.3.3 Timer A Modes . . . . . . . . . . . . . . . . . . . . . . . . 658.3.4 Blinking an LED . . . . . . . . . . . . . . . . . . . . . . . 67

9 Analog to Digital Conversion(ADC) 699.1 ADCs in MSP430 . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

9.1.1 10-Bit ADC Core . . . . . . . . . . . . . . . . . . . . . . . 709.1.2 ADC Registers . . . . . . . . . . . . . . . . . . . . . . . . 709.1.3 Lighting an LED if input goes above 0.2V . . . . . . . . . 71

10 Communication Modules in MSP430 7410.1 Universal Serial Interface . . . . . . . . . . . . . . . . . . . . . . 7410.2 Universal Serial Communication Interface . . . . . . . . . . . . . 74

10.2.1 Asynchronous channel, USCI A . . . . . . . . . . . . . . . 7410.2.2 A Software UART Using Timer A . . . . . . . . . . . . . 75

4

Page 6: MSP 430 programming

List of Figures

1.1 Electronics - The Level of Abstraction . . . . . . . . . . . . . . . 81.2 Resistor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.3 Resistor - Color Code . . . . . . . . . . . . . . . . . . . . . . . . 91.4 LDR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.5 Electrolytic Capacitor . . . . . . . . . . . . . . . . . . . . . . . . 111.6 Capacitor - Value . . . . . . . . . . . . . . . . . . . . . . . . . . 111.7 Inductors - Types . . . . . . . . . . . . . . . . . . . . . . . . . . 121.8 Transistors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131.9 Transistor - Symbols . . . . . . . . . . . . . . . . . . . . . . . . . 131.10 Transistor - Packages . . . . . . . . . . . . . . . . . . . . . . . . 141.11 Zener Diode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.12 Zener Diode - Regulator Circuit . . . . . . . . . . . . . . . . . . . 161.13 LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161.14 IC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171.15 Transformer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181.16 Half Wave Rectifier . . . . . . . . . . . . . . . . . . . . . . . . . . 191.17 Bridge Rectifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.18 Voltage Regulator - 5V regulator(IC7805) . . . . . . . . . . . . . 191.19 Soldering Tools - Iron and Solder . . . . . . . . . . . . . . . . . . 201.20 Digital Multimeter (DMM) . . . . . . . . . . . . . . . . . . . . . 211.21 Transitor Testing using DMM . . . . . . . . . . . . . . . . . . . . 221.22 Relay - Schematic . . . . . . . . . . . . . . . . . . . . . . . . . . 231.23 Relay Switch - Circuit Diagram . . . . . . . . . . . . . . . . . . . 23

3.1 An analog signal . . . . . . . . . . . . . . . . . . . . . . . . . . . 333.2 A discterte analog signal . . . . . . . . . . . . . . . . . . . . . . . 343.3 A quantized digital signal . . . . . . . . . . . . . . . . . . . . . . 343.4 Hexadecimal to Binary Conversion Table . . . . . . . . . . . . . . 35

4.1 Generalized Functional Block Diagram of a MCU . . . . . . . . . 374.2 PortA of the popular atmega16 MCU . . . . . . . . . . . . . . . 374.3 System Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384.4 Components of a MCU . . . . . . . . . . . . . . . . . . . . . . . . 384.5 Arduino - A popular open-source single-board microcontroller . . 40

5

Page 7: MSP 430 programming

5.1 MSP430 popular packages . . . . . . . . . . . . . . . . . . . . . . 425.2 CCS Installation - Step1 . . . . . . . . . . . . . . . . . . . . . . . 435.3 CCS Installation - Step2 . . . . . . . . . . . . . . . . . . . . . . . 435.4 MSP430 Launchpad . . . . . . . . . . . . . . . . . . . . . . . . . 44

6.1 New CCS Project . . . . . . . . . . . . . . . . . . . . . . . . . . . 466.2 Connecting an LED . . . . . . . . . . . . . . . . . . . . . . . . . 506.3 Interfacing an Switch . . . . . . . . . . . . . . . . . . . . . . . . . 516.4 Interfacing an Switch . . . . . . . . . . . . . . . . . . . . . . . . . 526.5 Welcome to Grace . . . . . . . . . . . . . . . . . . . . . . . . . . 52

8.1 TACTL Register . . . . . . . . . . . . . . . . . . . . . . . . . . . 628.2 TAR Register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638.3 TACCRx Register . . . . . . . . . . . . . . . . . . . . . . . . . . 638.4 TAIV Register . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638.5 TACCTLx Register . . . . . . . . . . . . . . . . . . . . . . . . . . 648.6 Up Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658.7 Continuous Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . 668.8 Up/Down Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

9.1 ADC10 Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . 709.2 ADC10CTL0 Register . . . . . . . . . . . . . . . . . . . . . . . . 71

10.1 UART Bits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

6

Page 8: MSP 430 programming

Chapter 1

Basic Electronics CircuitComponents

1.1 Resistor• Resistor is the electronic component used to reduce the flow of current.

• Resistors are available at 14 , 1

2 , 1, 2, 4 watts

• We need to select the appropriate value depending upon the voltage dropand current flowing through it.

• Usual circuits working fewer than 5 to 25 volts, we use 14 W resistors which

are usually small in size compared to others.

• The value of resistor can be calculated using the color codes given init,refer Fig 1.1.

• Variable resistors are those resistors whose values can be changed.Theyare of mainly two types:

1. Preset Type2. Potentiometer Type

• Variable resistors are characterized by the maximum resistance it offersand mainly used for making potential divider arrangements.

1.1.1 Testing a resistor using a multimeter– Select the resistance range in the multimeter.– Check the resistor and get the resistance reading value from it.– Compare that value with the one given in the color code. If both

the values remain same within the tolerance range, then it is workingfine.

7

Page 9: MSP 430 programming

Figure 1.1: Electronics - The Level of Abstraction

8

Page 10: MSP 430 programming

Figure 1.2: Resistor

Figure 1.3: Resistor - Color Code

9

Page 11: MSP 430 programming

1.1.2 Light Dependent Resistor (LDR)

LDR or Light Dependent Resistor is a component whose resistance changeswith the intensity of light falling into it. So this component is being usedas light sensors / detectors.

Figure 1.4: LDR

1.2 Capacitor• Capacitor is the component which could store electric charge in it for a

short time.

• The value of a capacitor is measured in farads, since it is a large unit wemainly use microfarads / nanofarads / pico farads for normal use.

• They are of mainly two types:1. Electrolytic Type: Electrolytic capacitors have polarity and higher

capacitance values compared to the other one. We need to connectit with the correct polarity else di-electric breakdown could happenand this could damage the device. The working voltage given in thecapacitor and it is the maximum voltage under which we could useit safely.

2. Disk Type: They have comparatively lower capacitance (in pFrange)and usually don’t have any polarity. Values are given in anumber code somewhat similar to the resistor color codes.

• Variable Capacitors like Trimmers / Gang Condensers etc are used incircuits like radio tuning (Eg. for changing the natural frequency of anLC circuit)

1.2.1 Testing a capacitor using an multimeter

(Works only for electrolytic capacitors with large capacitance and shouldbe tested with an analog multimeter)

10

Page 12: MSP 430 programming

Figure 1.5: Electrolytic Capacitor

– Select the resistance range in the multimeter.– First short circuit the two leads of the capacitor to avoid any charges

residing in it.– Compare that value with the one given in the color code. If both

the vaules remain same within the tolerance range, then it is workingfine.

– Connect the probes of the multimeter into the terminals and at thatmoment you could see a deflection and the pointer coming back. Thisis because at the instant when we connect the probes to the terminalof capacitor there will be a potential difference and charging currentflows. After on, the capacitor gets into steady state and no currentflows.

Figure 1.6: Capacitor - Value

11

Page 13: MSP 430 programming

1.3 Inductor• An inductor (also choke, coil or reactor) is a passive two-terminal electri-

cal component that stores energy in its magnetic field. For comparison,capacitor stores energy in an electric field and a resistor does not storeenergy but rather dissipates energy as heat.

• Any conductor has inductance. An inductor is typically made of a wireor other conductor wound into a coil, to increase the magnetic field.

• Unit of inductance is henry but we usually use inductors of milli-henryvalue.

• When an inductor is connected to a circuit the moment when we switchon the circuit, the current will be zero and when we switch off the circuit,at that moment it will have the same current as before. It is the electricalanalogue of inertia in mechanical systems.

Figure 1.7: Inductors - Types

12

Page 14: MSP 430 programming

1.4 Transistor• A transistor is a semiconductor device used to amplify and switch elec-

tronic signals and power. It is composed of semiconductor material withat least three terminals for connection to an external circuit.

• A voltage or current applied to one pair of the transistor’s terminalschanges the current flowing through another pair of terminals. As the con-trolled (output) power can be higher than the controlling (input) power,a transistor can amplify a signal.

• The transistor is a fundamental building block of modern electronic de-vices, and is ubiquitous in modern electronic systems.

Figure 1.8: Transistors

Figure 1.9: Transistor - Symbols

13

Page 15: MSP 430 programming

Figure 1.10: Transistor - Packages14

Page 16: MSP 430 programming

1.5 Diode• In electronics, a diode is a two-terminal electronic component with asym-

metric transfer characteristic, with low (ideally zero) resistance to currentflow in one direction, and high (ideally infinite) resistance in the other.Asemiconductor diode, the most common type today, is a crystalline pieceof semiconductor material with a p-n junction connected to two electricalterminals.

• The most common function of a diode is to allow an electric current topass in one direction (called the diode’s forward direction), while blockingcurrent in the opposite direction (the reverse direction). Thus, the diodecan be viewed as an electronic version of a check valve.

• In a diode, the terminal near which a line is there will be cathode and theother one will be anode.

• Diode is commonly used for rectification (Converting AC to DC)

1.5.1 Testing a diode using a multimeter

– Connect the diode terminals to a multimeter probe.– When it is being forward biased, it should show very low resistance

and in the other case, it should show high resistance.

1.5.2 Zener Diode

– A zener diode is a special kind of diode which allows current to flowin the forward direction in the same manner as an ideal diode, butwill also permit it to flow in the reverse direction when the voltageis above a certain value known as the breakdown voltage, zener kneevoltage or zener voltage.

– Common applications include providing a reference voltage for volt-age regulators, or to protect other semiconductor devices from mo-mentary voltage pulses.

Figure 1.11: Zener Diode

15

Page 17: MSP 430 programming

Figure 1.12: Zener Diode - Regulator Circuit

1.5.3 LED - Light Emitting Diode

Figure 1.13: LED

1.5.4 Photo Diode• A photodiode is a type of photo detector capable of converting light into

either current or voltage, depending upon the mode of operation. Thecommon, traditional solar cell used to generate electric solar power is alarge area photodiode.

• Photodiodes are similar to regular semiconductor diodes except that theymay be either exposed (to detect vacuum UV or X-rays) or packaged witha window or optical fiber connection to allow light to reach the sensitivepart of the device.

16

Page 18: MSP 430 programming

• Many diodes designed for use specifically as a photodiode use a PIN junc-tion rather than a p-n junction, to increase the speed of response. Aphotodiode is designed to operate in reverse bias.

1.6 Integrated Crcuit (IC)• IC or integrated circuit is a silicon chip in which millions of components

like resistors, capacitors and transistors embedded onto it.

• The first integrated circuit was developed in the 1950s by Jack Kilby ofTexas Instruments and Robert Noyce of Fairchild Semiconductor

• Integrated circuits are used for a variety of devices, including micropro-cessors, audio and video equipment, and automobiles.

• Integrated circuits are often classified by the number of transistors andother electronic components they contain as SSI, LSI, MSI, VLSI andULSI.

• We should be very careful while using and soldering ICs and should recheckthat you are providing the correct working voltage for the IC as there aremuch chances for the IC’s to burn off. Even for small surface mount ICsthe static charge residing in your body could destroy them.

• Usually people use extra base for soldering and then put the IC into thatafter soldering the base.

• Inductor is a component that cannot be integrated into an IC.

1.6.1 IC Pin Numbering

The pins are numbered anti-clockwise around the IC (chip) starting nearthe notch or dot.

Figure 1.14: IC

17

Page 19: MSP 430 programming

1.7 Transformer• A transformer is a device that transfers electrical energy from one circuit to

another through inductively coupled conductors-the transformer’s coils. Avarying current in the first or primary winding creates a varying magneticflux in the transformer’s core and thus a varying magnetic field throughthe secondary winding. This varying magnetic field induces a varyingelectromotive force (EMF), or voltage, in the secondary winding. Thiseffect is called inductive coupling.

• If a load is connected to the secondary, current will flow in the secondarywinding, and electrical energy will be transferred from the primary circuitthrough the transformer to the load. In an ideal transformer, the inducedvoltage in the secondary winding (Vs) is in proportion to the primary volt-age (Vp) and is given by the ratio of the number of turns in the secondary(Ns) to the number of turns in the primary (Np) as follows:

Vs

Vp= Ns

Np(1.1)

• By appropriate selection of the ratio of turns, a transformer thus enablesan alternating current (AC) voltage to be stepped up by making Ns greaterthan Np, or stepped down by making Ns less than Np. The windings arecoils wound around a ferromagnetic core, air-core transformers being anotable exception.

• We usually characterize the transformer by the primary and secondaryvoltages and also the current flowing through the secondary.

• Usually there are two types of transformers: Single tapped and centraltapped transformer.

• In power eliminators with multiple voltage outputs, we use multi-tappedtransformers.

Figure 1.15: Transformer

18

Page 20: MSP 430 programming

1.7.1 Retifiers

Figure 1.16: Half Wave Rectifier

Figure 1.17: Bridge Rectifier

1.7.2 Voltage RegulatorsRegulators are used to give a particular voltage output if we give a voltage inputabove that voltage an well within a range.

Figure 1.18: Voltage Regulator - 5V regulator(IC7805)

19

Page 21: MSP 430 programming

1.8 Soldering BasicsSoldering is a process in which two or more metal items are joined together bymelting a filler metal (solder) into the joint, the filler metal having a lower melt-ing point than the work piece. Soldering differs from welding in that solderingdoes not involve melting the work pieces.

• Soldering Iron : Soldering Iron is the main equipment required for solder-ing. It is characterized in watts. Irons of the 15W to 30W range are goodfor most electronics/printed circuit board work.

• Solder and Flux : Solder is a metal or metallic alloy used, when melted,to join metallic surfaces together. The most common alloy is some com-bination of tin and lead. Flux cleans oxides of the surfaces to be soldered.

1.8.1 Steps in Soldering– Before use, a new soldering tip, or one that is very dirty, must be

tinned. Tinning is the process of coating a soldering tip with a thincoat of solder. This aids in heat transfer between the tip and thecomponent you are soldering.

– Warm up the soldering iron or gun thoroughly. Make sure that ithas fully come to temperature because you are about to melt a lot ofsolder on it. This is especially important if the iron is new because itmay have been packed with some kind of coating to prevent corrosion.

– Thoroughly coat the soldering tip in solder. It is very important tocover the entire tip. You will use a considerable amount of solderduring this process and it will drip, so be ready. If you leave anypart of the tip uncovered it will tend to collect flux residue and willnot conduct heat very well, so run the solder up and down the tipand completely around it to totally cover it in molten solder.

Figure 1.19: Soldering Tools - Iron and Solder

20

Page 22: MSP 430 programming

1.9 Multimeter and Testing Components• A multimeter or a multi-tester, also known as a VOM (Volt-Ohm meter),

is an electronic measuring instrument that combines several measurementfunctions in one unit. A typical multimeter may include features such asthe ability to measure voltage, current and resistance, continuity, capaci-tance and also for identifying terminals of transistor.

• Multimeters are of two types: Digital and Analog

• All digital multimeters(DMM) contain a battery to power the display sothey use virtually no power from the circuit under test. This means thaton their DC voltage ranges they have a very high resistance and they arevery unlikely to affect the circuit under test.

• Analog meters take a little power from the circuit under test to operatetheir pointer. They must have a high sensitivity of at least 20k/V or theymay upset the circuit under test and give an incorrect reading.

• A digital multimeter is the best choice for your first multimeter; even thecheapest will be suitable for testing simple projects.

Figure 1.20: Digital Multimeter (DMM)

1.9.1 Testing transistors using multimeters

– Set the meter to its ohms range - any range should do, but the middleohms range if several are available is probably best.

21

Page 23: MSP 430 programming

– Connect the base terminal of the transistor to the terminal markedpositive (usually colored red) on the multimeter.

– Connect the terminal marked negative or common (usually coloredblack) to the collector and measure the resistance. It should readopen circuit (there should be a deflection for a PNP transistor).

– With the terminal marked positive still connected to the base, repeatthe measurement with the positive terminal connected to the emitter.The reading should again read open circuit (the multimeter shoulddeflect for a PNP transistor).

– Now reverse the connection to the base of the transistor, this timeconnecting the negative or common (black) terminal of the analoguetest meter to the base of the transistor.

– Connect the terminal marked positive, first to the collector and mea-sure the resistance. Then take it to the emitter. In both cases themeter should deflect (indicate open circuit for a PNP transistor).

– It is next necessary to connect the meter negative or common to thecollector and meter positive to the emitter. Check that the meterreads open circuit. (The meter should read open circuit for bothNPN and PNP types.

– Now reverse the connections so that the meter negative or common isconnected to the emitter and meter positive to the collector. Checkagain that the meter reads open circuit.

– If the transistor passes all the tests then it is basically functional andall the junctions are intact.

Figure 1.21: Transitor Testing using DMM

22

Page 24: MSP 430 programming

1.10 Relays• Relays are switching components which could be turned on / off by giving

a voltage across that.

• There are two types of relays:

1. Industrial Relay : Used to drive High current devices / circuits.2. Sugar Cube Relays: Small Circuit Relays which could be placed in

circuits and used for switching low power devices / circuits

Figure 1.22: Relay - Schematic

Figure 1.23: Relay Switch - Circuit Diagram

23

Page 25: MSP 430 programming

Chapter 2

Introduction toProgramming in C

2.1 Hello World ProgramC programming Language was introduced in the year of 1972 by Dennis Ritchieof AT&T Bell Laboratories. Let’s start our first program, the traditional HelloWorld!.. Program

/*Program to Print Hello World*/#include<stdio.h>void main( )

printf("Hello World!..");

• Here the things given inside /* */ are called comments which will beignored by the compiler during compilation time.

• When we write the pre-processor directive #include<stdio.h> our pre-processor will also include the header file stdio.h which contains the defi-nitions for standard input output functions. So if we include stdio.h in ourprogram, we will be able to use those standard functions in our program.Similarly there are also many standard and user defined header files andif we include them in our program we will be able to use the functionsdefined int that in our program.

• Every C program starts its execution from main( ) function and we docall other user defined or standard library functions inside our main( )function. We do write all our programs also inside the main( ) .

• Every C statements terminates with a semicolon(;).

24

Page 26: MSP 430 programming

• printf( ) is the standard library function we use to print something intothe console.

2.2 Declaring Variables• Variables are the programming elements which we refer to store some data

in the Main Memory.

• The basic syntax for declaring and initializing variable is:<data type> variable name = <value>Ex.

int myVar = 5; char character;character = ’A’;float x = 11.234;

2.3 Basic Data Types• int is used to define integer numbers. Ex. int x = 6;

• float is used to define floating point numbers. Ex. float y = 3.231;

• double is used to define BIG floating point numbers. It reserves twice thestorage for the number. On PCs this is likely to be 8 bytes.Ex. double z = 234.2376546;

• char defines characters and they are usually enclosed in a single quotesand they could hold onle a single character values.Ex. char newChar = ’A’;For storing strings, we use array of characters and they are being termi-nated by null character ’\0’.Ex. char name = ’R’,’a’,’m’,’\0’;

2.3.1 Program to add 2 nos./*Program to add 2 numbers*/#include<stdio.h>void main( )

int x, y, sum;printf("Enter two numbers : ");scanf("%d %d", &x, &y); //Accepting nos.sum = x + y; //Adding those nos.printf("Sum is %d", sum); //Printing the sum.

25

Page 27: MSP 430 programming

2.4 Basic Operators in CLet,int A = 10, int B = 20;

2.4.1 Arithmatic Operators

Sl.no Operator Description Example1 + Adds two operands A + B will give 302 - Subtracts second operand from the first A - B will give -103 * Multiply both operands A * B will give 2004 Divide numerator by denominator B / A will give 25 % Modulus Operator and remainder after an integer division B % A will give 06 ++ Increment operator, increases integer value by one B % A++ will give 117 - - Decrement operator, decreases integer value by one B % A– will give 9

2.4.2 Logical / Relational Operators:

Sl.no Operator Description Example1 = = Checks if the value of two operands are equal or not, A == B is not true.

if yes then condition becomes true.2 != Checks if the value of two operands are equal or not, A != B is true.

if values are not equal then condition becomes true.3 > Checks if the value of left operand is greater than the A > B is not true.

value of right operand, if yes then condition becomes true.4 < Checks if the value of left operand is less than the A < B is true.

value of right operand, if yes then condition becomes true.5 >= Checks if the value of left operand is greater than or equal to A >= B is not true.

thevalue of right operand, if yes then condition becomes true.6 <= Checks if the value of left operand is less than or equal to A <= B is true.

thevalue of right operand, if yes then condition becomes true.7 && Called Logical AND operator. If both the operands are non-zero A && B is true.

then condition becomes true.8 ‖ Called Logical OR operator. If any of the two operands A ‖ B is true.

are non-zero then condition becomes true.Called Logical NOT Operator. Use to reverses the logical

9 ! state of its operand. If a condition is true !(A && B) is false.true then Logical NOT operator will make it false.

26

Page 28: MSP 430 programming

A logical operator operated between two relational or logical expressions andreturns a logical value.1. && Logical AND2. ‖ Logical OR3. ! Logical Negation / NOT

2.4.3 Bitwise Operators:Bitwise operator works on bits and performs bit by bit operation.

Assume if A = 60; and B = 13; Now in binary format they will be as follows:A = 0011 1100B = 0000 1101

A&B 0011 1100 Bitwise AND OperationA|B 0011 1101 Bitwise OR OperationAˆB 0011 0001 Bitwise XOR Operation∼A 1100 0011 Bitwise Negation Operation

>> Left Shift Operator<< Right Shift Operator

NB: Please make yourself very clear about bitwise operators as we use themmuch frequently while programming the microcontrollers.

sizeof()- operator is used to get the size (in bytes) which a variable or adata type takes in memory.

2.5 Control Structures:2.5.1 Sequential Control StructureEx: Usual programs in which we execute statements one after the other.

2.5.2 Selection Control StructureIf statements in which a condition is being checked and if it is true certain setof statements will get executed.

Simple if statement

if (condition)

27

Page 29: MSP 430 programming

--Statements--

If-Else Statements

if(condition)

--Statements--else

--Statements--

If-Else Statements

if(condition1)

--Statements--else if(condition2)

--Statements--else

--Statements--

Switch Statements

switch(expression)case const1: --Statements-

break;case const2: --Statements-

break;case const3: --Statements-

break;

default: --Statements-break;

28

Page 30: MSP 430 programming

2.5.3 Iteration / LoopingFor Loop

for (initialization; condition ; update expression)

--Loop Body--Ex:for(int i = i; i<=10 ; i++) /*Printing Multiplication Table of 5 */

printf("%d x 5 = %d", i, i*5);

While Loop Loop Body will get executed till the condition goes false

while(condition)

--Loop Body --

Do-While Loop It is an exit controlled loop, i.e. the loop body is executedat least once even if the condition is always being false.

do

--Loop Body -- while (condition);

2.5.4 Jump StatementsBreak Statement If we place a break statement inside a loop after checkinga condition and if it goes right, the control will come out of the loop.

Ex:for(int i = i; i<=10 ; i++) /*Printing Multiplication Table of 5 */

printf("%d x 5 = %d", i, i*5);if(i == 5)

break;/*Here the loop will print only till 25 and later on i becomes 5 and it breaks the loop*/

Jump Statement If we place a continue statement inside a loop after check-ing a condition and if it goes right, the control leave rest of the loop body,update the loop variable and then continue the loop.

29

Page 31: MSP 430 programming

for(int i = i; i<=10 ; i++) /*Printing Multiplication Table of 5 */

printf("%d x 5 = %d", i, i*5);if(i == 5)

break;/*Here the loop will not print 5*5 */

2.6 FunctionsFunctions are one of the most commonly used features in the C Programminglanguage. It helps users to separate blocks of codes which could be reused againand again. A program using functions may look something like this:

int myFunction(int , int);void main( )

------------------

int myFunction(int x, int y)

int z;z = (x+y)*x;return z;

• Here the line int myFunction(int,int);is called function prototyping ordeclaration where we do tells the compiler that a function with a namemyFunction exists and it takes two integer arguments. We need to addthis if we define the function just after the main().

• After the main(),we have defined the function myFunction() and thefunction body.

• The general syntax of defining a function is:

<return-type> <function-name>(<parameter-list>)

--Function Body--

• Return-type is the data type of value returned by a function to the calledprogram.

• If a function does not return a value, we do give its return type as void.Example for functions:

30

Page 32: MSP 430 programming

int factorial(int x)

if(x == 1 || x ==0)return 1;

elsereturn (x * factorial(x -1) );

• This is an example of a recursive function which does call itself, which is apowerful programming technique but it is least preferred in the embeddedprogramming as it takes a lot of system stack and memory and this is amain constraint in embedded systems.

2.7 Arrays• Arrays are continuous storage locations in memory which could be referred

under a common name and could be used to store a collection of data ofsame data types.

• The syntax for declaration of array is:<data-type> <array-name>[<number-of elements>];

Ex: int nos[20];char name[30];

• The indexing of array starts from 0, so if we want to access the firstelement, we give array[0];.

• There is no basic data type in C for storing strings, so we use array ofcharacters for storing string. The end of the string should have a nullcharacter .i.e. ’\0’.

2.8 Structures• Structures are user defined data types which could be used to group dif-

ferent data-types under a common name.

Ex:struct student

int roll_no;char name[20];char place[20];int age;

;

31

Page 33: MSP 430 programming

• We create the elements of an array as follows:struct student s;.

• We use dot( . ) operator to access each element in a structure.Eg: s.age = 15;

n = s.roll_no;

2.9 Pointers• Pointers are special variables which do hold the address of another vari-

able.

Ex:int num = 25;int * ptr ; /* Declaring a pointer variable ptr */ptr = &num; /* Assigning the address of variable num to ptr */print("%d", *ptr); /* Printing the value at the address in ptr through dereferencing*/

• Here we have created an integer num and a pointer variable ptr whichcould hold the address of a integer variable.

• We use dot(.) operator to access each element in a structure.

• Using the dereferencing or value at operator (*) we have printed the valuecontained at the in ptr, which is equivalent as the value of num as ptr nowhas the address of variable num.

32

Page 34: MSP 430 programming

Chapter 3

An Introductory Overview

3.1 Analog and Digital SignalsA signal as referred to in communication systems, signal processing, and elec-trical engineering ”is a function that conveys information about the behavior orattributes of some phenomenon” — WikipediaIn nature, any measurable quantity in time or in space can be considered asignal.

3.1.1 Analog SignalsAn analog or analogue signal is any continuous signal for which the timevarying feature (variable) of the signal is a representation of some other timevarying quantity, i.e., analogous to another time varying signal. For example,in an analog audio signal, the instantaneous voltage of the signal varies contin-uously with the pressure of the sound waves.

Figure 3.1: An analog signal

33

Page 35: MSP 430 programming

3.1.2 Digital SignalsA discrete analog signal can be obtained by acquiring values of an analogsignal at constant or variable rate. This process is called sampling

Figure 3.2: A discterte analog signal

The information contained in the signal only can be used by a computerif an amplitude conversion from the analogue domain to the digital domain isperformed.

Figure 3.3: A quantized digital signal

3.2 The Number SystemsA numeral system (or system of numeration) is a writing system for express-ing numbers, that is a mathematical notation for representing numbers of agiven set, using digits or other symbols in a consistent manner.

For example, in the decimal system (base 10), the numeral 4327 means(4 x 103) + (3 x 102) + (2 x 101) + (7 x 100), noting that 100 = 1.

34

Page 36: MSP 430 programming

3.2.1 The Binary number system• The binary numeral system, or base-2 number system, represents

numeric values using two symbols: 0 and 1.

• More specifically, the usual base-2 system is a positional notation with aradix of 2.

• Because of its straightforward implementation in digital electronic cir-cuitry using logic gates, the binary system is used internally by almost allmodern computers.

3.2.2 The Hexadecimal number system• In mathematics and computer science, hexadecimal (also base 16, or

hex) is a positional numeral system with a radix, or base, of 16.

• It uses sixteen distinct symbols, most often the symbols 0 to 9 to rep-resent values zero to nine, and A,B,C,D,E,F to represent values ten tofifteen. For example, the hexadecimal number 2AF3 is equal, in decimal,to (2*163) + (10*162) + (15*161) + (3*160), or 10995.

Figure 3.4: Hexadecimal to Binary Conversion Table

35

Page 37: MSP 430 programming

Chapter 4

Inroduction to MCUs

4.1 What is an MCU?”A microcontroller (sometimes abbreviated µC, uC or MCU) is a small com-puter on a single integrated circuit containing a processor core, memory, andprogrammable input/output peripherals” – Wikipedia.

4.1.1 The Origin• A controller is used to control some process. At one time, controllers

were built exclusively from logic components, and were usually large,heavy boxes.

• Later on, microprocessors were used and the entire controller couldfit on a small circuit board. This is still common one can find manycontrollers powered by one of the many common microprocessors.

• As the process of miniaturization continued, all of the components neededfor a controller were built right onto one chip. A one chip computer, ormicrocontroller was born.

• A microcontroller is a highly integrated chip, which includes on singlechip, all or most of the parts needed for a controller. The microcon-troller typically includes:CPU (Central Processing Unit), RAM (RandomAccess Memory), EPROM/PROM/ROM (Erasable Programmable ReadOnly Memory), I/O (input/output) serial and parallel, timers, interruptcontroller.

4.1.2 Terms associated with the MCU• Registers : In computer architecture, a processor register is a small

amount of storage available as part of a CPU or other digital processor.

36

Page 38: MSP 430 programming

Figure 4.1: Generalized Functional Block Diagram of a MCU

Such registers are (typically) addressed by mechanisms other than mainmemory and can be accessed more quickly.They provide a way to physi-cally manipulate data in the real world as indicated by computer programinstructions. Registers are such data areas that are physically located onthe processor.Registers are of different sizes such as 8-bit registers,16-bitregisters etc. Ex: General Purpose Registers (GPR), Segment Registers,Extended Architecture Registers, System Registers.

• Ports: A combination of pins in a MCU is known as a port. The config-uration of ports may vary from manufacturer to manufacturer.8-bit portsare generally seen in MCUs.

Figure 4.2: PortA of the popular atmega16 MCU

• Clock: To keep the whole system synchronized. It may be generatedinternally or obtained from a crystal or external source; modern MCUsoffer considerable choice of clocks.

• Address buses : In computer architecture, a bus is a subsystem thattransfers data between components inside a computer, or between com-puters. An address bus is a computer bus (a series of lines connecting twoor more devices) that is used to specify a physical address.In computing,a physical address (also real address, or binary address), is a memoryaddress that is represented in the form of a binary number.

37

Page 39: MSP 430 programming

Figure 4.3: System Bus

4.1.3 Why MCU?• A microcontroller is not just a CPU. It usually incorporates a range of

peripherals, besides the memory and storage needed to operate.

• MCUs help us to easily accomplish hectic tasks with lesser hardware dueto their access to multiple external peripherals.

• Implementations done with the help of MCUs have a better success ratesthan the circuits that are developed from scratch.

It is important to note that a wide array of microcontrollers exist, somerivaling or surpassing the capabilities of full fledged computers in the 70s, 80s,and maybe even 90s. UV Erasure of microcontroller and ROM are today mostlya thing of the past.With the advent of Flash memory, the microcontroller can be programmedhundred of thousands of times without any problems. Also, they incorporatea wide array of modules such Analog to Digital Converters, USB, PWM, andWireless transceivers, enabling integration into any kind of application.

4.2 Anatomy of a Simple MCU

Figure 4.4: Components of a MCU

• CPU:

38

Page 40: MSP 430 programming

1. Arithmetic logic unit (ALU), which performs computation.2. Registers needed for the basic operation of the CPU, such as program

counter (PC), stack pointer (SP), and status register (SR).3. Further registers to hold temporary results.4. Instruction decoder and other logic to control the CPU, handle resets,

and interrupts, and so on.

• Memory for the program : Non-volatile (read-only memory, ROM),meaning that it retains its contents when power is removed.

• Memory for data : Known as random-access memory (RAM) and usu-ally volatile.

• Input and output ports : To provide digital communication with theoutside world.

• Address and data buses : To link these subsystems to transfer dataand instructions.

• Clock : To keep the whole system synchronized. It may be generatedinternally or obtained from a crystal or external source; modern MCUsoffer considerable choice of clocks.

• Timers : Most microcontrollers have at least one timer because of thewide range of functions that they provide.

• Watchdog timer : This is a safety feature, which resets the processor ifthe program becomes stuck in an infinite loop.

• Communication interfaces : A wide choice of interfaces is availableto exchange information with another IC or system. They include se-rial peripheral interface (SPI), inter-integrated circuit (IšC or IIC), asyn-chronous (such as RS-232), universal serial bus (USB), controller areanetwork (CAN), ethernet, and many others.

• Non-volatile memory for data : This is used to store data whose valuemust be retained when power is removed. Serial numbers for identificationand network addresses are two obvious candidates.

• Analog-to-digital converter : This is very common because so manyquantities in the real world vary continuously.

• Digital-to-analog converter : This is much less common, because mostanalog outputs can be simulated using PWM.

• Real-time clock: : These are needed in applications that must trackthe time of day. Clocks are obvious examples but data loggers are also animportant case.

39

Page 41: MSP 430 programming

4.3 Hardware and Software required for an MCUComparing a MCU controlled device to a human,the electronics part can beconsidered as the body and programming the brain.Since these two arehighly interdependent, neither of them can be neglected.

4.3.1 Hardware• An Embedded Microcontroller

• Microcontroller Support Circuitry: A single-board microcontroller isa microcontroller built onto a single printed circuit board. This boardprovides all of the circuitry necessary for a useful control task: micro-controller, I/O circuits, clock generator, stored program memory and anysupport ICs necessary. The intention is that the board is immediately use-ful to an application developer, without needing to spend time and effortin developing the controller hardware.

Figure 4.5: Arduino - A popular open-source single-board microcontroller

• Application Specific Circuitry: This circuit specifes the elements thatare required for interfacing and implementing a problem statement usingthe MCU. These include sensors, motors, different kinds of recievers andtransmitters etc.

4.3.2 Software• Programming/Debugging interface for the Microcontroller: The

Programming/Debugging interface is the most often ignored element ofthe system, but it is a very important factor.With just Programming ca-pabilities, we can download a firmware image into the microcontroller.However, Debugging is often a necessity since no person can write per-fectly good code and ensure it can run correctly.

40

Page 42: MSP 430 programming

Chapter 5

MSP430

5.1 What is MSP430?The MSP430 is a mixed-signal microcontroller family from Texas In-struments. Built around a 16-bit CPU, the MSP430 is designed for low costand, specifically, low power consumption embedded applications. –Wikipedia

The letters MSP stand for mixed signal processor, which is a reminderthat many practical applications require analog inputs. The MSP430 was intro-duced in the late 1990s.

5.1.1 Salient Features of MSP430• Max 256kB Flash memory

• Max 128kB RAM memory

• Better EM Compatibility

• Extremely lower power consumption for portable applications

• Low cost JTAG debugger

• Can execute upto 8 mips in 8 MHz

• MSP430 has 16 bit bus

• 12bit ADC provision

• Low cost development tools

• USB,Ethernet,UART,USART,I2C and many more accessible peripherals

41

Page 43: MSP 430 programming

Figure 5.1: MSP430 popular packages

5.2 MSP430 Value Line Series

5.3 Introduction to Code Composer Studio(CCS)Code Composer Studio is a complete, integrated development environ-ment (IDE) that supports the LaunchPad ecosystem, as well as the rest ofTexas Instruments Embedded Processors portfolio. This tool enables developersto program, debug and compile code directly into your LaunchPad evaluationkits.

Integrated development environment for TI embedded processors

• Includes debugger, compiler, editor, simulator, OS.

• The IDE is built on the Eclipse open source software framework.

• Extended by TI to support device capabilities.

5.3.1 Installing CCS• Step 1: Run the tutourial DVD.

• Step 2: Select Main IDE Tool on the home page.

• Step 3: Select CCS on the next page & click on the Installation Toolto run the setup of CCS.

• Step 4: Proceed manually to install the IDE.

42

Page 44: MSP 430 programming

Figure 5.2: CCS Installation - Step1

Figure 5.3: CCS Installation - Step2

Once installed, the IDE should find the MSP-EXP430G2 LaunchPad asUSB:HID debugging interface. Now all is set for developing MSP430G2xxbased application on the LaunchPad.

5.4 MSP430 LaunchpadThe MSP-EXP430G2 low-cost experimenter board called LaunchPad is acomplete development solution for the new Texas Instruments MSP430G2xxseries.The MSP-EXP430G2 uses the IAR Embedded Workbench Integrated De-velopment Environment (IDE) or Code Composer Studio (CCS) towrite, download, and debug an application.

5.4.1 Features• USB debugging and programming interface featuring a driverless installa-

tion.

• Supports all MSP430G2xx and MSP430F20xx devices in PDIP14 or

43

Page 45: MSP 430 programming

PDIP20 packages.

• Two general-purpose digital I/O pins connected to green and red LEDsfor visual feedback.

• Two push button for user feedback and device reset.

• Easily accessible device pins for debugging purposes.

• High-quality 20-pin DIP socket for an easy plug-in or removal of the targetdevice.

Figure 5.4: MSP430 Launchpad

5.4.2 Installation of HardwareConnect the EXP430G2 LaunchPad socket board with the enclosed USBcable to a PC. The driver installation starts automatically.If prompted for software, allow Windows to install the software automatically.This is possible only if either IAR KickStart or Code Composer Studiois already installed.

44

Page 46: MSP 430 programming

5.4.3 Getting StartedAs soon as the Launchpad is connected to the PC for the first time, a demoapplication already installed onto the MSP430G2231 starts execution.The demo application starts with an LED toggle to show the device is alive.

Demo Application, Internal Temperature Measurement

• When LaunchPad is connected via USB, the demo starts with an LEDtoggle sequence.

• Pressing button P1.3 switches the application to a temperature measure-ment mode.A reference temperature is taken at the beginning of this mode.

• The LEDs of the LaunchPad signal a rise or fall in temperature by varyingthe brightness of the on-board red or green LED. respectively.

45

Page 47: MSP 430 programming

Chapter 6

Programming the MSP430

6.1 Begining MSP430 Programming6.1.1 Getting Started with CCSWhen CCS starts up for the first time, it prompts to select a workspace on awindow named Workspace Launcher. Click OK to proceed.

6.1.2 Creating a New Project in CCS• Step1 : Run Code Composer Studio(CCS)

• Step2 : Select File I New I CCS Project

• Step3 : Fill in the Projet Name and select the Device that is used. TheDevice inherently found in a new Launchpad is MSP430G2231.

Figure 6.1: New CCS Project

46

Page 48: MSP 430 programming

• Step4 : Select Empty Project from Project templates and examplesand Finish

main.c I Main routine where the C coding for the application is specified.Path:Created automatically when a project is created and saved in the workspace

6.1.3 Customizing CCSFrequently used terms of CCS are listed below:

• Project Explorer: Presents an one shot view of all the Projects that arecurrrenly under processing by CCS.Path:View I Project Explorer

• Debug: Debugs the code and loads it onto the targrt device. Debug iconis directly available on the main toolbar of CCS.Path:View I Debug

• Problems: Displays warnings and error messages in CCS.Path:View I Problems

• Console: Displays current activity and status in CCS.Path:View I Console

6.2 Port Programming - Basic I/O Operations6.2.1 Salient Features of MSP430 Ports• Independently programmable

• Combined input, output, and interrupt conditions

• Edge-selectable interrupt inputs for all bits of ports

• Read/write access to port-control registers supported by all two or one-address instructions

• Each I/O has an individually programmable pullup/pulldown resistor

6.2.2 Port ConfigurationThe configuration of the port operations are defined in software using the fol-lowing registers:

• Direction Registers (PxDIR): Read/write 8-bit registers, which se-lects the direction of the corresponding I/O pin, regardless of the selectedfunction of the pin (general purpose I/O or as a special function I/O).

47

Page 49: MSP 430 programming

PxDIR configuration:

– Bit = 1: The port pin is set up as an output;– Bit = 0: the port pin is set up as an input.

• Input Registers (PxIN): Each bit of these read-only registers reflectsthe input signal at the corresponding I/O pin (pin configured as generalpurpose I/O).

PxIN configuration:

– Bit = 1: The input is high.– Bit = 0: The input is low.

• Output Registers (PxOUT): The output registers are read-write. Eachbit of these registers reflects the value written to the corresponding outputpin.

PxOUT configuration:

– Bit = 1: The output is high.– Bit = 0: The output is low.

• Pull-up/Pull-down Resistor Enable Registers (PxREN): Each bitof this register enables or disables the pullup/pulldown resistor of the cor-responding I/O pin.

PxREN configuration:

– Bit = 1: Pullup/pulldown resistor enabled.– Bit = 0: Pullup/pulldown resistor disabled.

• Function Select Registers(PxSEL) and (PxSEL2): Selects alternatefunctions for the particular pin of a port. NB: The different functions aredevice dependent. Check datasheet for details.

PxSEL PxSEL2 Pin Function0 0 Selects general-purpose I/O function0 1 Selects the primary peripheral module function1 0 Reserved (See device-specific data sheet)1 1 Selects the secondary peripheral module function

• Interruptible ports (P1 and P2): Each pin of ports P1 and P2 isable to generate an interrupt request (pin is interruptible) and is config-ured using the PxIFG, PxIE, and PxIES registers.

48

Page 50: MSP 430 programming

Interrupt Enable (PxIE) : Read-write register to enable interrupts onindividual pins. Each PxIE bit enables the interrupt request associatedwith the corresponding PxIFG interrupt flag. Writing to PxOUT and/orPxDIR can result in setting PxIFG.

– Bit = 1: The interrupt is enabled.– Bit = 0: The interrupt is disabled.

Interrupt Edge Select Registers (PxIES) : This read-write registerselects the transition on which an interrupt occurs for the correspondingI/O pin (if PxIE and GIE are set).

– Bit = 1: Interrupt flag is set on a high-to-low transition.– Bit = 0: Interrupt flag is set on a low-to-high transition.

Interrupt Flag Registers (PxIFG) :The bit of this read-write reg-ister is set automatically when the programmed signal transition (edge)occurs on the corresponding I/O pin, provided that the correspondingPxIE bit and the GIE bit are set.

– Bit = 1: An interrupt is pending.– Bit = 0: No interrupt is pending.

6.3 Output Operations6.3.1 Lighting an LEDProgram

#include <msp430G2231.h>

void main(void)WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timerP1DIR = 0x01; // Set pin1 (P1.0)to output, 0b00000001P1OUT = 0x01; // LED1 (P1.0) onwhile(1)

49

Page 51: MSP 430 programming

Figure 6.2: Connecting an LED

Working

• P1DIR= 0x01;sets the 0th bit of PORT1 as output pin.

• Using the command P1OUT= 0x01;we do assign a high voltage to the 0thbit of PORT1 and so the LED keeps on lighting.

• The output coming from the µC is 5V and the LED needs just a 2 to 3V voltage. A 270Ω resistor to reduce the drop across LED. This is doneinternally in the Launchpad.

• Here you can see unlike the usual C-Program which goes sequentiallyand terminated after certain number of steps, the programs for a µC aregenerally written inside or are terminated by an infinite loop so that itgets executed infinitely.

6.4 Input Operations6.4.1 Reading a switchProgram

#include <msp430G2231.h>

void main(void)#define LED1 BIT0#define SWITCH BIT3

WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer

P1REN = SWITCH; //Internal pull up resistor for P1.3P1OUT = SWITCH; //Enabling internal pull up resistor for P1.3

50

Page 52: MSP 430 programming

P1DIR = LED1; // Set pin1 (P1.0) with to output , 0b00000001P1OUT |= LED1; // Set P1.0 high

while(1)

if ((P1IN & SWITCH) == 0) // Is button down?P1OUT |= LED1; // Yes: Turn LED1 onelseP1OUT &= ˜LED1; // No: Turn LED1 off

Figure 6.3: Interfacing an Switch

Working

• Assign LED1 to 0th pin and SWITCH to 3rd pin.

• P1REN= SWITCH; P1OUT= SWITCH; These two statements enables an in-ternal pull-up resistor for P1.0.

• An internal pullup resistor connects the PIN to the supply voltage(5V).

• P1IN& SWITCH compares the P1IN register and the current state of BIT3of Port1. If the comparison yields to be true the LED is switched ON elseit is switched OFF.

51

Page 53: MSP 430 programming

Figure 6.4: Interfacing an Switch

6.5 Introduction to GraceGrace is a free, graphical user interface that generates source code and

eliminates manual peripheral configuration.

As an MSP430 developer allows Grace you to generate the peripheral’ssetup code within minutes. This will save you much of the work of poringthrough user guides and copying code examples and allow you to focus on themore important aspects of your application.

Figure 6.5: Welcome to Grace

52

Page 54: MSP 430 programming

6.6 Customizing the Port - Lighting an LED• Step1 : Run Code Composer Studio(CCS)

• Step2 : Select File I New I CCS Project

• Step3 : Fill in the Projet Name and select the Device that is used. TheDevice inherently found in a new Launchpad is MSP430G2231.

• Step4 : Select Empty Grace(MSP430) project from Project tem-plates and examples and Finish.

• Step5 : Grace Configuration Steps

– Click Device Overview– Select VCC

– Basic Clock I Power User I Set DCO,SMCLK & ACLK– PortP1 I Pinout TSSOP/PDIP I P1.0 I GPIO Output– Inside the main function write

while(1)P1OUT = 0xFF;

6.7 Implementation Using Grace - Reading theSwitch

• Step1 : Run Code Composer Studio(CCS)

• Step2 : Select File I New I CCS Project

• Step3 : Fill in the Projet Name and select the Device that is used. TheDevice inherently found in a new Launchpad is MSP430G2231.

• Step4 : Select Empty Grace(MSP430) project from Project tem-plates and examples and Finish.

• Step5 : Grace Configuration Steps

– Click Device Overview– Select VCC

– Basic Clock I Power User I Set DCO,SMCLK & ACLK– PortP1 I Pinout TSSOP/PDIP I P1.0 I GPIO Output– P1/P2 I Basic User∗ Resistor Enable Register - Set BIT3

53

Page 55: MSP 430 programming

∗ OutPut Register - Set BIT3∗ click CheckBox - Set BIT3

– Inside the main function write

while(1)if ((P1IN & BIT3) == 0) // Is button down?P1OUT |= BIT0; // Yes: Turn LED1 onelseP1OUT &= ŸLED1; // No: Turn LED1 off

54

Page 56: MSP 430 programming

Chapter 7

Interrupts in MSP430

7.1 What is an Interrupt?In a microcontroller or in any microprocessor, we could check the status of adevice or input from a pin in two different ways:

• Polling

• Interrupt Method

In polling the µC periodically check for the input or status flags from the ex-ternal peripheral to get the status of its working.The microcontroller will drawa lot of current since the CPU must act and use the hardware continuously todo the polling.

In the case of interrupt method when the external (or even internal) periph-eral needs the attention of the processor, it will trigger an interrupt and theprocessor will stop execution of the current statements and store the presentprogram address in system stack, execute a set of codes called ISR (InterruptService Routine) associated with the particular interrupt and restores the lastlyexecuted program from stack and continues its work.

In general there are three types of interrupts:

• System Reset: System Reset interrupts simply occur because of any of theconditions that resets the microcontroller.

• Non-maskable Interrupts (NMI): Mask ability refers to the fact that theseinterrupts cannot be disabled collectively and must be disabled and en-abled individually. These are interrupts in the category where the errorcan possible be handled without a reset.

• Maskable Interrupts

55

Page 57: MSP 430 programming

To use the interrupt, we need the following procedure:

1. Setup the interrupt you wish and its conditions

2. Enable the interrupt/s

3. Write the interrupt handler

7.2 Toggling LED Using Interrupt7.2.1 Using Interrupt FlagProgram

#include "msp430G2231.h"

volatile unsigned int i; // volatile to prevent optimization

void main(void)WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer

// Configure LED on P1.0P1DIR = BIT0; // P1.0 outputP1OUT &= ˜BIT0; // P1.0 output LOW, LED Off

// Configure Switch on P1.3P1REN |= BIT3; // P1.3 Enable Pullup/PulldownP1OUT = BIT3; // P1.3 pullupP1IES |= BIT3; // P1.3 Hi/lo edgeP1IFG &= ˜BIT3; // P1.3 IFG cleared just in case

while(1)if(P1IFG & BIT3) // P1.3 IFG clearedP1IFG &= ˜BIT3; // P1.3 IFG clearedP1OUT ˆ= BIT0; // Toggle LED at P1.0

Working In this case an interrupt handler that is called whenever the inter-rupt occurs ia absent. Rather, the CPU continuously polls for the flag to see ifthe interrupt occurred.

56

Page 58: MSP 430 programming

Advantages: Correctly toggles the LED only when the switch is pressed anddonŠt have the continuous toggle issue since not until the next transition do wetoggle the LED.

Disadvantages: The CPU still works too hard on something trivial likepolling and still wastes energy.

• LED is connected to 0th pin and SWITCH to 3rd pin internally in theLaunchpad.

• The configuration of the LED pin is quite simple. It is the configurationof the switch that is important. First, we enable the pullup resistor byusing P1REN and P1OUT.

• Enable the interrupt transition condition on P1.2 using P1IES (P1IES &= BIT3;).

• The condition of the interrupt can be controlled by P1IES, whether theinterrupt should occur on the rising edge (0 to 1) or on the falling edge(1to 0). Only transitions cause interrupts not just static levels.

• An important part of the code is clearing the interrupt flag for the pin.This ensures any previous flags set are cleared and prevents an immediatejump into the interrupt handler when we interrupts are activated.P1IFG &= BIT3; resets the interrupt flag.

7.2.2 Using General Interrupt CodingProgram

#include "msp430G2231.h"

volatile unsigned int i; // volatile to prevent optimization

void main(void)WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer

// Configure LED on P1.0P1DIR = BIT0; // P1.0 output

P1OUT &= ˜BIT0; // P1.0 output LOW, LED Off

// Configure Switch on P1.2P1REN |= BIT3; // P1.3 Enable Pullup/PulldownP1OUT = BIT3; // P1.3 pullupP1IE |= BIT3; // P1.3 interrupt enabledP1IES |= BIT3; // P1.3 Hi/lo falling edgeP1IFG &= ˜BIT3; // P1.3 IFG cleared just in case

57

Page 59: MSP 430 programming

_EINT(); \\enable general interrupts GIE = 1 emulated

while(1)// Execute some other code

// Port 1 interrupt service routine#pragma vector=PORT1_VECTOR__interrupt void Port_1(void)P1OUT ˆ= BIT0; // Toggle LED at P1.0P1IFG &= ˜BIT3; // P1.3 IFG cleared

Working -General Interrupt Coding

• Terms associated with an interrupt:

– Interrupt service routine(ISR):The code segment that is excecutedas soon as an interrupt is triggered.

– Interrupt Vector :The address of an ISR is its vector.– Interrupt Vector Table:The defined memory address where ISR ad-

dress is stored.

• The general interrupts are activated using _EINT() , by setting generalinterrupt enable (GIE) i.e. GIE = 1.

• Setting the line with P1IE alone cannot trigger an interrupt, besausethese are maskable interrupts. Although these interrupts are controlledindividually, a second layer exists which can enable or disable them to-gether. Therefore, we must disable the masking to allow interrupts torun.

• _DINT(); GIE flag is cleared, disabling general interrupts.

• The MSP430 uses vectored interrupts, which means that it is stored ina vector table at a defined address in memory.

• For interrupt coding, two additions are required for the ISR. First is the#pragma line, which associates the function with a particular interruptvector. The second is the __interrupt keyword at the beginning of theline that names the function.

• Interrupt initialization of port1 is given by

58

Page 60: MSP 430 programming

#pragma vector=PORT1_VECTOR__interrupt void Port_1(void)

• Switch Debouncing: Switches are not perfect. It is possible that themechanical system inside it will toggle several times when the user presseson it and this is causes unwanted triggering of interrupt enabled pins. Thiseffect is appropriately called bouncing.

• A small delay of 50mS would probably suffice to prevent and bouncingproblems. Debouncing is not implemented here since the performance ofthe switch on the launchpad is not that bad.

Implementation Using Grace

• Step1 : Run Code Composer Studio(CCS)

• Step2 : Select File I New I CCS Project

• Step3 : Fill in the Projet Name and select the Device that is used. TheDevice inherently found in a new Launchpad is MSP430G2231.

• Step4 : Select Empty Grace(MSP430) project from Project tem-plates and examples and Finish.

• Step5 : Grace Configuration Steps

– Click Device Overview– Select VCC

– Basic Clock I Power User I Set DCO,SMCLK & ACLK– PortP1 I Pinout TSSOP/PDIP I P1.0 I GPIO Output– P1/P2 I Basic User∗ Resistor Enable Register - Set BIT3∗ OutPut Register - Set BIT3∗ click CheckBox - Set BIT3∗ Interrupt Enable Register - Set BIT3∗ Interrupt Edge Select Register - Set BIT3

– Write the name of the interrupt handler eg: button\_pushed. Afterthe main function write as a seperate function.

void button_pushed(void)P1OUT Ĺ= BIT0; // Toggle LED at P1.0P1IFG &= ŸBIT3; // P1.3 IFG cleared

59

Page 61: MSP 430 programming

Chapter 8

Timers in MSP430

8.1 What is a Timer?Timer is a specialized type of clock for measuring time intervals. A timer whichcounts upwards from zero for measuring elapsed time is often called a stopwatch.Eg. hourglass.Embedded Systems typically digital counters that either increment or decrementat a fixed frequency, which is often configurable. Timers are the one of the mostcommonly used complex peripheral in a microcontroller. They are used forgetting time periods, generating pulse signals and also for measuringtime period of pulses.

8.2 Timers in MSP430• Watchdog timer :

– Included in all devices (newer ones have the enhanced watchdogtimer+).

– It protects the system against malfunctions but it can instead be usedas an interval timer if this protection is not needed.

• Real-time clock: In which the basic timer has been extended to providea real-time clock in the most recent MSP430x4xx devices.

• Timer A:

– Provided in all devices and is much more versatile than the simplertimers just listed.

– Timer A can handle external inputs and outputs directly to measurefrequency, time-stamp inputs, and drive outputs at precisely specifiedtimes, either once or periodically.

60

Page 62: MSP 430 programming

– There are internal connections to other modules so that it can mea-sure the duration of a signal from the comparator, for instance.

– It can also generate interrupts.We will use a few of its capabilitiesand most of this chapter is devoted to Timer A.

• Timer B:

– Included in larger devices of all families.– It is similar to Timer A with some extensions that make it more

suitable for driving outputs such as pulse-width modulation.– It lacks a feature of sampling inputs in Timer A that is useful in

communication.

8.3 Timer A8.3.1 Salient Features• 16-bit Counter

• Modes of operation

– Stop– Up– Continuous– Up/Down

61

Page 63: MSP 430 programming

8.3.2 Timer A Registers

Figure 8.1: TACTL Register

Timer A Control Register(TACTL)

62

Page 64: MSP 430 programming

Figure 8.2: TAR Register

Timer A Register(TAR)

Figure 8.3: TACCRx Register

Timer A Capture/Compare Register x(TACCRx)

Figure 8.4: TAIV Register

Timer A Interrupt Vector (TAIV)

63

Page 65: MSP 430 programming

Figure 8.5: TACCTLx Register

Timer A Capture/Compare Control Register x(TACCTLx)

64

Page 66: MSP 430 programming

8.3.3 Timer A Modes

The timer has four modes of operation. The operating mode is selectedwith the MCx bits.

MCx Mode Description00 Stop The timer is halted01 Up The timer repeatedly counts from zero to the value of TACCR010 Continuous The timer repeatedly counts from zero to 0FFFFh11 Up/down The timer repeatedly counts from zero up to the value of TACCR0 and back down to zero

Figure 8.6: Up Mode

65

Page 67: MSP 430 programming

Figure 8.7: Continuous Mode

Figure 8.8: Up/Down Mode

66

Page 68: MSP 430 programming

8.3.4 Blinking an LEDProgram

#include <msp430g2231.h>

void main(void)

WDTCTL = WDTPW + WDTHOLD; // Stop WDTP1DIR |= 0x01; // P1.0 outputCCTL0 = CCIE; // CCR0 interrupt enabledCCR0 = 50000; // Setting count valueTACTL = TASSEL_2 + MC_2; // SMCLK, contmode_EINT();

// Timer A0 interrupt service routine#pragma vector=TIMERA0_VECTOR__interrupt void Timer_A (void)

P1OUT ˆ= BIT0; // Toggle P1.0CCR0 += 50000; // Add Offset to CCR0

Working

• CCTL0= CCIE; sets when the interrupt Timer A overflows, i.e. when thecount value crosses 0xFFFF.

• CCR0= 50000 sets an offset to the count value, forcing the counter to startfrom this count value.

• TACTL= TASSEL_2+ MC_2 presents the standard setting of the clock of thecounter, for more details about the register refer fig 8.1.

• Set the Global Interrupt Enable(GIE) as this interrupt is maskable.

• ISR for toggling the LED should be calibrated.

Implementation Using Grace

• Step1 : Run Code Composer Studio(CCS)

• Step2 : Select File I New I CCS Project

• Step3 : Fill in the Projet Name and select the Device that is used. TheDevice inherently found in a new Launchpad is MSP430G2231.

67

Page 69: MSP 430 programming

• Step4 : Select Empty Grace(MSP430) project from Project tem-plates and examples and Finish.

• Step5 : Grace Configuration Steps

– Click Device Overview– Select VCC

– Basic Clock I Power User I Set DCO,SMCLK & ACLK– PortP1 I Pinout TSSOP/PDIP I P1.0 I GPIO Output– Timer0 A2 I Basic User∗ Type in timer period in milli-seconds∗ Enable timer interrupt∗ Type name of interrupt handler eg: timeSet

– Write the name of the interrupt handler eg: button\_pushed. Afterthe main function write as a seperate function.

void timed(void)P1OUT ˆ= BIT0; // Toggle P1.0

68

Page 70: MSP 430 programming

Chapter 9

Analog to DigitalConversion(ADC)

An analog-to-digital converter (abbreviated ADC, A/D or A to D) is adevice that uses sampling to convert a continuous quantity to a discrete timerepresentation in digital form. The reverse operation is performed by a digital-to-analog converter (DAC)

The world around us is analog in nature and the microcontroller usuallyunderstands only digital information i.e. Whether input is there or not. Thereis a built in Analog to Digital converter inside the microcontroller which couldbe used to read the input voltage given to the ADC pins of the µC. ADC is adevice which converts the analog waveform at the input to the equivalent rep-resentation in the digital domain.

9.1 ADCs in MSP430The ADC10 module is a high-performance 10-bit analog-to-digital converter.This chapter describes the operation of the ADC10 module of the 2xx family ingeneral.

• Greater than 200-ksps maximum conversion rate

• Monotonic 10-bit converter with no missing codes

• Sample-and-hold with programmable sample periods

• Conversion initiation by software or Timer A

• Software selectable on-chip reference voltage generation (1.5 V or 2.5 V)

• Software selectable internal or external reference

69

Page 71: MSP 430 programming

• Up to eight external input channels (twelve on MSP430F22xx devices)

• Conversion channels for internal temperature sensor, VCC, and externalreferences

• Selectable conversion clock source

• Single-channel, repeated single-channel, sequence, and repeated sequenceconversion modes

• ADC core and reference voltage can be powered down separately

• Data transfer controller for automatic storage of conversion results

9.1.1 10-Bit ADC Core• The ADC core converts an analog input to its 10-bit digital representation

and stores the result in the ADC10MEM register.

• The core uses two programmable/selectable voltage levels (VR+ and VR−)to define the upper and lower limits of the conversion.

• Conversion Clock Selection: The ADC10CLK is used both as the con-version clock and to generate the sampling period. The ADC10 sourceclock is selected using the ADC10SSELx bits and can be divided from1 to 8 using the ADC10DIVx bits.

9.1.2 ADC Registers

Figure 9.1: ADC10 Registers

70

Page 72: MSP 430 programming

Figure 9.2: ADC10CTL0 Register

ADC10 Control Register 0

9.1.3 Lighting an LED if input goes above 0.2VProgram

#include "msp430g2231.h"

void main(void)

71

Page 73: MSP 430 programming

WDTCTL = WDTPW + WDTHOLD; // Stop WDTADC10CTL0 = SREF_1 + ADC10SHT_2 + REFON + ADC10ON + ADC10IE;__enable_interrupt(); // Enable interrupts.TACCR0 = 30; // Delay to allow Ref to settleTACCTL0 |= CCIE; // Compare-mode interrupt.TACTL = TASSEL_2 | MC_1; // TACLK = SMCLK, Up mode.LPM0; // Wait for delay.TACCTL0 &= ˜CCIE; // Disable timer Interrupt__disable_interrupt();ADC10CTL1 = INCH_1; // input A1ADC10AE0 |= 0x02; // PA.1 ADC option selectP1DIR |= 0x01; // Set P1.0 to output direction

for (;;)

ADC10CTL0 |= ENC + ADC10SC; // Sampling and conversion start__bis_SR_register(CPUOFF + GIE); // LPM0, ADC10_ISR will force exiif (ADC10MEM < 0x88) // ADC10MEM = A1 > 0.2V?

P1OUT &= ˜0x01; // Clear P1.0 LED offelse

P1OUT |= 0x01; // Set P1.0 LED on

// ADC10 interrupt service routine#pragma vector=ADC10_VECTOR__interrupt void ADC10_ISR (void)

__bic_SR_register_on_exit(CPUOFF); // Clear CPUOFF bit from 0(SR)

#pragma vector=TIMERA0_VECTOR__interrupt void ta0_isr(void)

TACTL = 0;LPM0_EXIT; // Exit LPM0 on return

Working

• Timer A is used for ADC sampling and low power implementation.

• ADC10CTL0 is used to configure reference voltage to 1.5V.

• ADC input pin is continuously sampled and converted to digital form.

72

Page 74: MSP 430 programming

• ADC10MEM has the converted binary value, which is compared with thebinary equivalent of 0.2V.

• Set LED if the sampled value is greater than 0.2V.

• The timer and ADC interrupts are set for sampling and to know the endof ADC conversion.

73

Page 75: MSP 430 programming

Chapter 10

Communication Modules inMSP430

10.1 Universal Serial InterfaceThe universal serial interface (USI) is a lightweight module, which is included inthe small F20x2 and F20x3 devices. It is much less grand than its name mightimply.

10.2 Universal Serial Communication InterfaceRecent, larger devices in the MSP430F2xx and MSP430F4xx families containone or more universal serial communication interface (USCI) modules.

10.2.1 Asynchronous channel, USCI A:Acts as a universal asynchronous receiver/ transmitter (UART) to support theusual RS-232 communication. It can detect the baud rate of an incoming signal,which enables its use on a local interconnect network (LIN).

Figure 10.1: UART Bits

74

Page 76: MSP 430 programming

10.2.2 A Software UART Using Timer AProgram

void main(void)

WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer

DCOCTL = 0x00; // Set DCOCLK to 1MHzBCSCTL1 = CALBC1_1MHZ;DCOCTL = CALDCO_1MHZ;

P1OUT = 0x00; // Initialize all GPIOP1SEL = UART_TXD + UART_RXD; // Timer function for TXD/RXD pinsP1DIR = 0xFF & ˜UART_RXD; // Set all pins but RXD to outputP2OUT = 0x00;P2SEL = 0x00;P2DIR = 0xFF;

__enable_interrupt();

TimerA_UART_init(); // Start Timer_A UARTTimerA_UART_print("G2xx1 TimerA UART\r\n");TimerA_UART_print("READY.\r\n");

for (;;)

// Wait for incoming character//__bis_SR_register(LPM0_bits);

//------------------------------------------------------------------------------// Function configures Timer_A for full-duplex UART operation//------------------------------------------------------------------------------void TimerA_UART_init(void)

TACCTL0 = OUT; // Set TXD Idle as Mark = ’1’TACCTL1 = SCS + CM1 + CAP + CCIE; // Sync, Neg Edge, Capture, IntTACTL = TASSEL_2 + MC_2; // SMCLK, start in continuous mode

//------------------------------------------------------------------------------// Outputs one byte using the Timer_A UART//------------------------------------------------------------------------------void TimerA_UART_tx(unsigned char byte)

75

Page 77: MSP 430 programming

while (TACCTL0 & CCIE); // Ensure last char got TX’dTACCR0 = TAR; // Current state of TA counterTACCR0 += UART_TBIT; // One bit time till first bitTACCTL0 = OUTMOD0 + CCIE; // Set TXD on EQU0, InttxData = byte; // Load global variabletxData |= 0x100; // Add mark stop bit to TXDatatxData <<= 1; // Add space start bit

//------------------------------------------------------------------------------// Prints a string over using the Timer_A UART//------------------------------------------------------------------------------void TimerA_UART_print(char *string)

while (*string) TimerA_UART_tx(*string++);

//------------------------------------------------------------------------------// Timer_A UART - Transmit Interrupt Handler//------------------------------------------------------------------------------#pragma vector = TIMERA0_VECTOR__interrupt void Timer_A0_ISR(void)

static unsigned char txBitCnt = 10;

TACCR0 += UART_TBIT; // Add Offset to CCRxif (txBitCnt == 0) // All bits TXed?

TACCTL0 &= ˜CCIE; // All bits TXed, disable interrupttxBitCnt = 10; // Re-load bit counter

else

if (txData & 0x01) TACCTL0 &= ˜OUTMOD2; // TX Mark ’1’

else

TACCTL0 |= OUTMOD2; // TX Space ’0’txData >>= 1;txBitCnt--;

76

Page 78: MSP 430 programming

NOTES

77

Page 79: MSP 430 programming

NOTES

78

Page 80: MSP 430 programming

NOTES

79

Page 81: MSP 430 programming

NOTES

80

Page 82: MSP 430 programming

NOTES

81


Recommended