You are on page 1of 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

Getting Started with MSP430 MCUs

Contents
1 Basic Electronics Circuit Components 1.1 Resistor . . . . . . . . . . . . . . . . . . . . . . . 1.1.1 Testing a resistor using a multimeter . . 1.1.2 Light Dependent Resistor (LDR) . . . . 1.2 Capacitor . . . . . . . . . . . . . . . . . . . . . . 1.2.1 Testing a capacitor using an multimeter . 1.3 Inductor . . . . . . . . . . . . . . . . . . . . . . . 1.4 Transistor . . . . . . . . . . . . . . . . . . . . . . 1.5 Diode . . . . . . . . . . . . . . . . . . . . . . . . 1.5.1 Testing a diode using a multimeter . . . 1.5.2 Zener Diode . . . . . . . . . . . . . . . . 1.5.3 LED - Light Emitting Diode . . . . . . . 1.5.4 Photo Diode . . . . . . . . . . . . . . . . 1.6 Integrated Crcuit (IC) . . . . . . . . . . . . . . . 1.6.1 IC Pin Numbering . . . . . . . . . . . . 1.7 Transformer . . . . . . . . . . . . . . . . . . . . . 1.7.1 Retiers . . . . . . . . . . . . . . . . . . 1.7.2 Voltage Regulators . . . . . . . . . . . . 1.8 Soldering Basics . . . . . . . . . . . . . . . . . . 1.8.1 Steps in Soldering . . . . . . . . . . . . . 1.9 Multimeter and Testing Components . . . . . . . 1.9.1 Testing transistors using multimeters . . . 1.10 Relays . . . . . . . . . . . . . . . . . . . . . . . . 2 Introduction to Programming in C 2.1 Hello World Program . . . . . . . . . . 2.2 Declaring Variables . . . . . . . . . . . 2.3 Basic Data Types . . . . . . . . . . . . 2.3.1 Program to add 2 nos. . . . . . 2.4 Basic Operators in C . . . . . . . . . . 2.4.1 Arithmatic Operators . . . . . 2.4.2 Logical / Relational Operators: 2.4.3 Bitwise Operators: . . . . . . . 2.5 Control Structures: . . . . . . . . . . . 7 7 7 10 10 10 12 13 15 15 15 16 16 17 17 18 19 19 20 20 21 21 23 24 24 25 25 25 26 26 26 27 27

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

2.6 2.7 2.8 2.9

2.5.1 Sequential Control Structure 2.5.2 Selection Control Structure . 2.5.3 Iteration / Looping . . . . . . 2.5.4 Jump Statements . . . . . . . Functions . . . . . . . . . . . . . . . Arrays . . . . . . . . . . . . . . . . . Structures . . . . . . . . . . . . . . . Pointers . . . . . . . . . . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

27 27 29 29 30 31 31 32 33 33 33 34 34 35 35 36 36 36 36 38 38 40 40 40 41 41 41 42 42 42 43 43 44 45 46 46 46 46 47 47 47 47

3 An Introductory Overview 3.1 Analog and Digital Signals . . . . . . . . 3.1.1 Analog Signals . . . . . . . . . . 3.1.2 Digital Signals . . . . . . . . . . 3.2 The Number Systems . . . . . . . . . . 3.2.1 The Binary number system . . . 3.2.2 The Hexadecimal number system

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

4 Inroduction to MCUs 4.1 What is an MCU? . . . . . . . . . . . . . . . 4.1.1 The Origin . . . . . . . . . . . . . . . 4.1.2 Terms associated with the MCU . . . 4.1.3 Why MCU? . . . . . . . . . . . . . . . 4.2 Anatomy of a Simple MCU . . . . . . . . . . 4.3 Hardware and Software required for an MCU 4.3.1 Hardware . . . . . . . . . . . . . . . . 4.3.2 Software . . . . . . . . . . . . . . . . . 5 MSP430 5.1 What is MSP430? . . . . . . . . . . . . . . . 5.1.1 Salient Features of MSP430 . . . . . . 5.2 MSP430 Value Line Series . . . . . . . . . . . 5.3 Introduction to Code Composer Studio(CCS) 5.3.1 Installing CCS . . . . . . . . . . . . . 5.4 MSP430 Launchpad . . . . . . . . . . . . . . 5.4.1 Features . . . . . . . . . . . . . . . . . 5.4.2 Installation of Hardware . . . . . . . . 5.4.3 Getting Started . . . . . . . . . . . . . 6 Programming the MSP430 6.1 Begining MSP430 Programming . . . . . 6.1.1 Getting Started with CCS . . . . . 6.1.2 Creating a New Project in CCS . . 6.1.3 Customizing CCS . . . . . . . . . 6.2 Port Programming - Basic I/O Operations 6.2.1 Salient Features of MSP430 Ports 6.2.2 Port Conguration . . . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

6.3 6.4 6.5 6.6 6.7

Output Operations . . . . . . . . . . . . . . . . . . 6.3.1 Lighting an LED . . . . . . . . . . . . . . . Input Operations . . . . . . . . . . . . . . . . . . . 6.4.1 Reading a switch . . . . . . . . . . . . . . . Introduction to Grace . . . . . . . . . . . . . . . . Customizing the Port - Lighting an LED . . . . . . Implementation Using Grace - Reading the Switch

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

49 49 50 50 52 53 53 55 55 56 56 57 60 60 60 61 61 62 65 67 69 69 70 70 71 74 74 74 74 75

7 Interrupts in MSP430 7.1 What is an Interrupt? . . . . . . . . . . 7.2 Toggling LED Using Interrupt . . . . . . 7.2.1 Using Interrupt Flag . . . . . . . 7.2.2 Using General Interrupt Coding 8 Timers in MSP430 8.1 What is a Timer? . . . . . 8.2 Timers in MSP430 . . . . 8.3 Timer A . . . . . . . . . . 8.3.1 Salient Features . . 8.3.2 Timer A Registers 8.3.3 Timer A Modes . . 8.3.4 Blinking an LED . 9 Analog to 9.1 ADCs 9.1.1 9.1.2 9.1.3

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

Digital Conversion(ADC) in MSP430 . . . . . . . . . . . . . . . 10-Bit ADC Core . . . . . . . . . . . ADC Registers . . . . . . . . . . . . Lighting an LED if input goes above

. . . . . . . . . 0.2V

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

10 Communication Modules in MSP430 10.1 Universal Serial Interface . . . . . . . . . 10.2 Universal Serial Communication Interface 10.2.1 Asynchronous channel, USCI A . . 10.2.2 A Software UART Using Timer A

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

List of Figures
1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.17 1.18 1.19 1.20 1.21 1.22 1.23 3.1 3.2 3.3 3.4 4.1 4.2 4.3 4.4 4.5 Electronics - The Level of Abstraction . . Resistor . . . . . . . . . . . . . . . . . . . Resistor - Color Code . . . . . . . . . . . LDR . . . . . . . . . . . . . . . . . . . . . Electrolytic Capacitor . . . . . . . . . . . Capacitor - Value . . . . . . . . . . . . . Inductors - Types . . . . . . . . . . . . . Transistors . . . . . . . . . . . . . . . . . Transistor - Symbols . . . . . . . . . . . . Transistor - Packages . . . . . . . . . . . Zener Diode . . . . . . . . . . . . . . . . . Zener Diode - Regulator Circuit . . . . . . LED . . . . . . . . . . . . . . . . . . . . . IC . . . . . . . . . . . . . . . . . . . . . . Transformer . . . . . . . . . . . . . . . . . Half Wave Rectier . . . . . . . . . . . . . Bridge Rectier . . . . . . . . . . . . . . . Voltage Regulator - 5V regulator(IC7805) Soldering Tools - Iron and Solder . . . . . Digital Multimeter (DMM) . . . . . . . . Transitor Testing using DMM . . . . . . . Relay - Schematic . . . . . . . . . . . . . Relay Switch - Circuit Diagram . . . . . . An analog signal . . . . . . . . . . . . . . A discterte analog signal . . . . . . . . . . A quantized digital signal . . . . . . . . . Hexadecimal to Binary Conversion Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 9 9 10 11 11 12 13 13 14 15 16 16 17 18 19 19 19 20 21 22 23 23 33 34 34 35 37 37 38 38 40

Generalized Functional Block Diagram of a MCU . . . . . . . PortA of the popular atmega16 MCU . . . . . . . . . . . . . System Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . Components of a MCU . . . . . . . . . . . . . . . . . . . . . . Arduino - A popular open-source single-board microcontroller

5.1 5.2 5.3 5.4 6.1 6.2 6.3 6.4 6.5 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 9.1 9.2

MSP430 popular packages CCS Installation - Step1 . CCS Installation - Step2 . MSP430 Launchpad . . . New CCS Project . . Connecting an LED Interfacing an Switch Interfacing an Switch Welcome to Grace . TACTL Register . TAR Register . . . TACCRx Register TAIV Register . . TACCTLx Register Up Mode . . . . . Continuous Mode . Up/Down Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

42 43 43 44 46 50 51 52 52 62 63 63 63 64 65 66 66 70 71 74

ADC10 Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . ADC10CTL0 Register . . . . . . . . . . . . . . . . . . . . . . . .

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

Chapter 1

Basic Electronics Circuit Components


1.1 Resistor

Resistor is the electronic component used to reduce the ow of current.


1 Resistors are available at 1 4 , 2 , 1, 2, 4 watts

We need to select the appropriate value depending upon the voltage drop and current owing through it. Usual circuits working fewer than 5 to 25 volts, we use are usually small in size compared to others.
1 4

W resistors which

The value of resistor can be calculated using the color codes given in it,refer Fig 1.1. Variable resistors are those resistors whose values can be changed.They are of mainly two types: 1. Preset Type 2. Potentiometer Type Variable resistors are characterized by the maximum resistance it oers and 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 working ne.

Figure 1.1: Electronics - The Level of Abstraction

Figure 1.2: Resistor

Figure 1.3: Resistor - Color Code

1.1.2

Light Dependent Resistor (LDR)

LDR or Light Dependent Resistor is a component whose resistance changes with the intensity of light falling into it. So this component is being used as 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 we mainly 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 connect it with the correct polarity else di-electric breakdown could happen and this could damage the device. The working voltage given in the capacitor and it is the maximum voltage under which we could use it safely. 2. Disk Type: They have comparatively lower capacitance (in pF range)and usually dont have any polarity. Values are given in a number code somewhat similar to the resistor color codes. Variable Capacitors like Trimmers / Gang Condensers etc are used in circuits like radio tuning (Eg. for changing the natural frequency of an LC circuit)

1.2.1

Testing a capacitor using an multimeter

(Works only for electrolytic capacitors with large capacitance and should be tested with an analog multimeter) 10

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 working ne. Connect the probes of the multimeter into the terminals and at that moment you could see a deection and the pointer coming back. This is because at the instant when we connect the probes to the terminal of capacitor there will be a potential dierence and charging current ows. After on, the capacitor gets into steady state and no current ows.

Figure 1.6: Capacitor - Value

11

1.3

Inductor

An inductor (also choke, coil or reactor) is a passive two-terminal electrical component that stores energy in its magnetic eld. For comparison, capacitor stores energy in an electric eld and a resistor does not store energy but rather dissipates energy as heat. Any conductor has inductance. An inductor is typically made of a wire or other conductor wound into a coil, to increase the magnetic eld. Unit of inductance is henry but we usually use inductors of milli-henry value. When an inductor is connected to a circuit the moment when we switch on the circuit, the current will be zero and when we switch o the circuit, at that moment it will have the same current as before. It is the electrical analogue of inertia in mechanical systems.

Figure 1.7: Inductors - Types

12

1.4

Transistor

A transistor is a semiconductor device used to amplify and switch electronic signals and power. It is composed of semiconductor material with at least three terminals for connection to an external circuit. A voltage or current applied to one pair of the transistors terminals changes the current owing through another pair of terminals. As the controlled (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 devices, and is ubiquitous in modern electronic systems.

Figure 1.8: Transistors

Figure 1.9: Transistor - Symbols

13

14 Figure 1.10: Transistor - Packages

1.5

Diode

In electronics, a diode is a two-terminal electronic component with asymmetric transfer characteristic, with low (ideally zero) resistance to current ow in one direction, and high (ideally innite) resistance in the other.A semiconductor diode, the most common type today, is a crystalline piece of semiconductor material with a p-n junction connected to two electrical terminals. The most common function of a diode is to allow an electric current to pass in one direction (called the diodes forward direction), while blocking current in the opposite direction (the reverse direction). Thus, the diode can 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 the other one will be anode. Diode is commonly used for rectication (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 ow in the forward direction in the same manner as an ideal diode, but will also permit it to ow in the reverse direction when the voltage is above a certain value known as the breakdown voltage, zener knee voltage or zener voltage. Common applications include providing a reference voltage for voltage regulators, or to protect other semiconductor devices from momentary voltage pulses.

Figure 1.11: Zener Diode

15

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. The common, traditional solar cell used to generate electric solar power is a large area photodiode. Photodiodes are similar to regular semiconductor diodes except that they may be either exposed (to detect vacuum UV or X-rays) or packaged with a window or optical ber connection to allow light to reach the sensitive part of the device.

16

Many diodes designed for use specically as a photodiode use a PIN junction rather than a p-n junction, to increase the speed of response. A photodiode 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 rst integrated circuit was developed in the 1950s by Jack Kilby of Texas Instruments and Robert Noyce of Fairchild Semiconductor Integrated circuits are used for a variety of devices, including microprocessors, audio and video equipment, and automobiles. Integrated circuits are often classied by the number of transistors and other electronic components they contain as SSI, LSI, MSI, VLSI and ULSI. We should be very careful while using and soldering ICs and should recheck that you are providing the correct working voltage for the IC as there are much chances for the ICs to burn o. Even for small surface mount ICs the static charge residing in your body could destroy them. Usually people use extra base for soldering and then put the IC into that after 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 near the notch or dot.

Figure 1.14: IC

17

1.7

Transformer

A transformer is a device that transfers electrical energy from one circuit to another through inductively coupled conductors-the transformers coils. A varying current in the rst or primary winding creates a varying magnetic ux in the transformers core and thus a varying magnetic eld through the secondary winding. This varying magnetic eld induces a varying electromotive force (EMF), or voltage, in the secondary winding. This eect is called inductive coupling. If a load is connected to the secondary, current will ow in the secondary winding, and electrical energy will be transferred from the primary circuit through the transformer to the load. In an ideal transformer, the induced voltage in the secondary winding (Vs ) is in proportion to the primary voltage (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: Ns Vs = Vp Np (1.1)

By appropriate selection of the ratio of turns, a transformer thus enables an alternating current (AC) voltage to be stepped up by making Ns greater than Np, or stepped down by making Ns less than Np . The windings are coils wound around a ferromagnetic core, air-core transformers being a notable exception. We usually characterize the transformer by the primary and secondary voltages and also the current owing through the secondary. Usually there are two types of transformers: Single tapped and central tapped transformer. In power eliminators with multiple voltage outputs, we use multi-tapped transformers.

Figure 1.15: Transformer

18

1.7.1

Retiers

Figure 1.16: Half Wave Rectier

Figure 1.17: Bridge Rectier

1.7.2

Voltage Regulators

Regulators are used to give a particular voltage output if we give a voltage input above that voltage an well within a range.

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

19

1.8

Soldering Basics

Soldering is a process in which two or more metal items are joined together by melting a ller metal (solder) into the joint, the ller metal having a lower melting point than the work piece. Soldering diers from welding in that soldering does not involve melting the work pieces. Soldering Iron : Soldering Iron is the main equipment required for soldering. It is characterized in watts. Irons of the 15W to 30W range are good for 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 combination 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 thin coat of solder. This aids in heat transfer between the tip and the component you are soldering. Warm up the soldering iron or gun thoroughly. Make sure that it has fully come to temperature because you are about to melt a lot of solder on it. This is especially important if the iron is new because it may have been packed with some kind of coating to prevent corrosion. Thoroughly coat the soldering tip in solder. It is very important to cover the entire tip. You will use a considerable amount of solder during this process and it will drip, so be ready. If you leave any part of the tip uncovered it will tend to collect ux residue and will not conduct heat very well, so run the solder up and down the tip and completely around it to totally cover it in molten solder.

Figure 1.19: Soldering Tools - Iron and Solder

20

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 measurement functions in one unit. A typical multimeter may include features such as the ability to measure voltage, current and resistance, continuity, capacitance 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 so they use virtually no power from the circuit under test. This means that on their DC voltage ranges they have a very high resistance and they are very unlikely to aect the circuit under test. Analog meters take a little power from the circuit under test to operate their pointer. They must have a high sensitivity of at least 20k/V or they may upset the circuit under test and give an incorrect reading. A digital multimeter is the best choice for your rst multimeter; even the cheapest 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 middle ohms range if several are available is probably best.

21

Connect the base terminal of the transistor to the terminal marked positive (usually colored red) on the multimeter. Connect the terminal marked negative or common (usually colored black) to the collector and measure the resistance. It should read open circuit (there should be a deection for a PNP transistor). With the terminal marked positive still connected to the base, repeat the measurement with the positive terminal connected to the emitter. The reading should again read open circuit (the multimeter should deect for a PNP transistor). Now reverse the connection to the base of the transistor, this time connecting the negative or common (black) terminal of the analogue test meter to the base of the transistor. Connect the terminal marked positive, rst to the collector and measure the resistance. Then take it to the emitter. In both cases the meter should deect (indicate open circuit for a PNP transistor). It is next necessary to connect the meter negative or common to the collector and meter positive to the emitter. Check that the meter reads open circuit. (The meter should read open circuit for both NPN and PNP types. Now reverse the connections so that the meter negative or common is connected to the emitter and meter positive to the collector. Check again that the meter reads open circuit. If the transistor passes all the tests then it is basically functional and all the junctions are intact.

Figure 1.21: Transitor Testing using DMM

22

1.10

Relays

Relays are switching components which could be turned on / o 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

Chapter 2

Introduction to Programming in C
2.1 Hello World Program

C programming Language was introduced in the year of 1972 by Dennis Ritchie of AT&T Bell Laboratories. Lets start our rst program, the traditional Hello World!.. Program /*Program to Print Hello World*/ #include<stdio.h> void main( ) { printf("Hello World!.."); } Here the things given inside /* */ are called comments which will be ignored by the compiler during compilation time. When we write the pre-processor directive #include<stdio.h> our preprocessor will also include the header le stdio.h which contains the denitions for standard input output functions. So if we include stdio.h in our program, we will be able to use those standard functions in our program. Similarly there are also many standard and user dened header les and if we include them in our program we will be able to use the functions dened int that in our program. Every C program starts its execution from main( ) function and we do call other user dened 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

printf( ) is the standard library function we use to print something into the 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


Ex. int x = 6; Ex. float y = 3.231;

int is used to dene integer numbers. oat is used to dene oating point numbers.

double is used to dene BIG oating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes. Ex. double z = 234.2376546; char denes characters and they are usually enclosed in a single quotes and they could hold onle a single character values. Ex. char newChar = A; For storing strings, we use array of characters and they are being terminated 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); sum = x + y; printf("Sum is %d", sum); }

//Accepting nos. //Adding those nos. //Printing the sum.

25

2.4

Basic Operators in C

Let, int A = 10, int B = 20;

2.4.1
Sl.no 1 2 3 4 5 6 7

Arithmatic Operators
Description Adds two operands Subtracts second operand from the rst Multiply both operands Divide numerator by denominator Modulus Operator and remainder after an integer division Increment operator, increases integer value by one Decrement operator, decreases integer value by one Example A + B will give 30 A - B will give -10 A * B will give 200 B / A will give 2 B % A will give 0 B % A++ will give 11 B % A will give 9

Operator + * % ++ --

2.4.2
Sl.no 1 2 3 4 5 6 7 8

Logical / Relational Operators:


Description Checks if the value of two operands are equal or not, if yes then condition becomes true. Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is greater than or equal to thevalue of right operand, if yes then condition becomes true. Checks if the value of left operand is less than or equal to thevalue of right operand, if yes then condition becomes true. Called Logical AND operator. If both the operands are non-zero then condition becomes true. Called Logical OR operator. If any of the two operands are non-zero then condition becomes true. Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true true then Logical NOT operator will make it false. Example A == B is not true. A != B is true. A > B is not true. A < B is true. A >= B is not true. A <= B is true. A && B is true. A B is true.

Operator == != > < >= <= &&

!(A && B) is false.

26

A logical operator operated between two relational or logical expressions and returns a logical value. 1. && Logical AND 2. Logical OR 3. ! 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 1100 B = 0000 1101 A&B A|B AB A 0011 0011 0011 1100 1100 1101 0001 0011 Bitwise AND Operation Bitwise OR Operation Bitwise XOR Operation Bitwise Negation Operation

>> <<

Left Shift Operator Right Shift Operator

NB: Please make yourself very clear about bitwise operators as we use them much frequently while programming the microcontrollers. sizeof()- operator is used to get the size (in bytes) which a variable or a data type takes in memory.

2.5
2.5.1

Control Structures:
Sequential Control Structure

Ex: Usual programs in which we execute statements one after the other.

2.5.2

Selection Control Structure

If statements in which a condition is being checked and if it is true certain set of statements will get executed. Simple if statement if (condition) { 27

--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: --Statementsbreak; case const2: --Statementsbreak; case const3: --Statementsbreak; default: --Statementsbreak; }

28

2.5.3

Iteration / Looping

For 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 executed at least once even if the condition is always being false. do { --Loop Body -} while (condition);

2.5.4

Jump Statements

Break Statement If we place a break statement inside a loop after checking a 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 checking 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

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

Functions

Functions are one of the most commonly used features in the C Programming language. It helps users to separate blocks of codes which could be reused again and 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 or declaration where we do tells the compiler that a function with a name myFunction exists and it takes two integer arguments. We need to add this if we dene the function just after the main(). After the main(),we have dened the function myFunction() and the function body. The general syntax of dening 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 called program. If a function does not return a value, we do give its return type as void. Example for functions: 30

int factorial(int x) { if(x == 1 || x ==0) return 1; else return (x * factorial(x -1) ); } This is an example of a recursive function which does call itself, which is a powerful programming technique but it is least preferred in the embedded programming as it takes a lot of system stack and memory and this is a main 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 of same 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 rst element, we give array[0];. There is no basic data type in C for storing strings, so we use array of characters for storing string. The end of the string should have a null character .i.e. \0.

2.8

Structures

Structures are user dened data types which could be used to group different data-types under a common name. Ex: struct student { int roll_no; char name[20]; char place[20]; int age; };

31

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 variable.

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 which could 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 value contained at the in ptr, which is equivalent as the value of num as ptr now has the address of variable num.

32

Chapter 3

An Introductory Overview
3.1 Analog and Digital Signals

A signal as referred to in communication systems, signal processing, and electrical engineering is a function that conveys information about the behavior or attributes of some phenomenon Wikipedia In nature, any measurable quantity in time or in space can be considered a signal.

3.1.1

Analog Signals

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

Figure 3.1: An analog signal

33

3.1.2

Digital Signals

A discrete analog signal can be obtained by acquiring values of an analog signal 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 computer if an amplitude conversion from the analogue domain to the digital domain is performed.

Figure 3.3: A quantized digital signal

3.2

The Number Systems

A n umeral system (or system of numeration) is a writing system for expressing numbers, that is a mathematical notation for representing numbers of a given 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

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 specically, the usual base-2 system is a positional notation with a radix of 2. Because of its straightforward implementation in digital electronic circuitry using logic gates, the binary system is used internally by almost all modern 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 represent values zero to nine, and A,B,C,D,E,F to represent values ten to fteen. 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

Chapter 4

Inroduction to MCUs
4.1 What is an MCU?

A microcontroller (sometimes abbreviated C, uC or MCU) is a small computer on a single integrated circuit containing a processor core, memory, and programmable 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 could t on a small circuit board. This is still common one can nd many controllers powered by one of the many common microprocessors. As the process of miniaturization continued, all of the components needed for a controller were built right onto one chip. A one chip computer, or microcontroller was born. A microcontroller is a highly integrated chip, which includes on single chip, all or most of the parts needed for a controller. The microcontroller typically includes:CPU (Central Processing Unit), RAM (Random Access Memory), EPROM/PROM/ROM (Erasable Programmable Read Only Memory), I/O (input/output) serial and parallel, timers, interrupt controller.

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

Figure 4.1: Generalized Functional Block Diagram of a MCU Such registers are (typically) addressed by mechanisms other than main memory and can be accessed more quickly.They provide a way to physically manipulate data in the real world as indicated by computer program instructions. Registers are such data areas that are physically located on the processor.Registers are of dierent sizes such as 8-bit registers,16-bit registers 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 conguration of ports may vary from manufacturer to manufacturer.8-bit ports are generally seen in MCUs.

Figure 4.2: PortA of the popular atmega16 MCU Clock : To keep the whole system synchronized. It may be generated internally or obtained from a crystal or external source; modern MCUs oer considerable choice of clocks. Address buses : In computer architecture, a bus is a subsystem that transfers data between components inside a computer, or between computers. An address bus is a computer bus (a series of lines connecting two or more devices) that is used to specify a physical address.In computing, a physical address (also real address, or binary address), is a memory address that is represented in the form of a binary number.

37

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 due to their access to multiple external peripherals. Implementations done with the help of MCUs have a better success rates than the circuits that are developed from scratch. It is important to note that a wide array of microcontrollers exist, some rivaling or surpassing the capabilities of full edged computers in the 70s, 80s, and maybe even 90s. UV Erasure of microcontroller and ROM are today mostly a thing of the past. With the advent of Flash memory, the microcontroller can be programmed hundred of thousands of times without any problems. Also, they incorporate a wide array of modules such Analog to Digital Converters, USB, PWM, and Wireless transceivers, enabling integration into any kind of application.

4.2

Anatomy of a Simple MCU

Figure 4.4: Components of a MCU CPU:

38

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 usually volatile. Input and output ports : To provide digital communication with the outside world. Address and data buses : To link these subsystems to transfer data and instructions. Clock : To keep the whole system synchronized. It may be generated internally or obtained from a crystal or external source; modern MCUs oer considerable choice of clocks. Timers : Most microcontrollers have at least one timer because of the wide range of functions that they provide. Watchdog timer : This is a safety feature, which resets the processor if the program becomes stuck in an innite loop. Communication interfaces : A wide choice of interfaces is available to exchange information with another IC or system. They include serial peripheral interface (SPI), inter-integrated circuit (IC or IIC), asynchronous (such as RS-232), universal serial bus (USB), controller area network (CAN), ethernet, and many others. Non-volatile memory for data : This is used to store data whose value must be retained when power is removed. Serial numbers for identication and network addresses are two obvious candidates. Analog-to-digital converter : This is very common because so many quantities in the real world vary continuously. Digital-to-analog converter : This is much less common, because most analog outputs can be simulated using PWM. Real-time clock: : These are needed in applications that must track the time of day. Clocks are obvious examples but data loggers are also an important case.

39

4.3

Hardware and Software required for an MCU

Comparing a MCU controlled device to a human,the electronics part can be considered as the body and programming the brain .Since these two are highly interdependent, neither of them can be neglected.

4.3.1

Hardware

An Embedded Microcontroller Microcontroller Support Circuitry: A single-board microcontroller is a microcontroller built onto a single printed circuit board. This board provides all of the circuitry necessary for a useful control task: microcontroller, I/O circuits, clock generator, stored program memory and any support ICs necessary. The intention is that the board is immediately useful to an application developer, without needing to spend time and eort in developing the controller hardware.

Figure 4.5: Arduino - A popular open-source single-board microcontroller Application Specic Circuitry: This circuit specifes the elements that are required for interfacing and implementing a problem statement using the MCU. These include sensors, motors, dierent kinds of recievers and transmitters etc.

4.3.2

Software

Programming/Debugging interface for the Microcontroller: The Programming/Debugging interface is the most often ignored element of the system, but it is a very important factor.With just Programming capabilities, we can download a rmware image into the microcontroller. However, Debugging is often a necessity since no person can write perfectly good code and ensure it can run correctly.

40

Chapter 5

MSP430
5.1 What is MSP430?

The MSP430 is a mixed-signal microcontroller family from Texas Instruments. Built around a 16-bit CPU, the MSP430 is designed for low cost and, specically, low power consumption embedded applications. Wikipedia The letters MSP stand for mixed signal processor, which is a reminder that many practical applications require analog inputs. The MSP430 was introduced 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,I2 C and many more accessible peripherals

41

Figure 5.1: MSP430 popular packages

5.2 5.3

MSP430 Value Line Series Introduction to Code Composer Studio(CCS)

Code Composer Studio is a complete, integrated development environment (IDE) that supports the LaunchPad ecosystem, as well as the rest of Texas Instruments Embedded Processors portfolio. This tool enables developers to program, debug and compile code directly into your LaunchPad evaluation kits. 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 Tool to run the setup of CCS. Step 4: Proceed manually to install the IDE. 42

Figure 5.2: CCS Installation - Step1

Figure 5.3: CCS Installation - Step2 Once installed, the IDE should nd the MSP-EXP430G2 LaunchPad as USB:HID debugging interface. Now all is set for developing MSP430G2xx based application on the LaunchPad.

5.4

MSP430 Launchpad

The MSP-EXP430G2 low-cost experimenter board called LaunchPad is a complete development solution for the new Texas Instruments MSP430G2xx series. The MSP-EXP430G2 uses the IAR Embedded Workbench Integrated Development Environment (IDE) or Code Composer Studio (CCS) to write, download, and debug an application.

5.4.1

Features

USB debugging and programming interface featuring a driverless installation. Supports all MSP430G2xx and MSP430F20xx devices in PDIP14 or

43

PDIP20 packages. Two general-purpose digital I/O pins connected to green and red LEDs for 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 target device.

Figure 5.4: MSP430 Launchpad

5.4.2

Installation of Hardware

Connect the EXP430G2 LaunchPad socket board with the enclosed USB cable 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 Studio is already installed.

44

5.4.3

Getting Started

As soon as the Launchpad is connected to the PC for the rst time, a demo application 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 LED toggle sequence. Pressing button P1.3 switches the application to a temperature measurement 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 varying the brightness of the on-board red or green LED. respectively.

45

Chapter 6

Programming the MSP430


6.1
6.1.1

Begining MSP430 Programming


Getting Started with CCS

When CCS starts up for the rst time, it prompts to select a workspace on a window named Workspace Launcher. Click OK to proceed.

6.1.2

Creating a New Project in CCS


New CCS Project

Step1 : Run Code Composer Studio(CCS) Step2 : Select File

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

Figure 6.1: New CCS Project

46

Step4 : Select Empty Project from Project templates and examples and Finish main.c Main routine where the C coding for the application is specied. Path :Created automatically when a project is created and saved in the workspace

6.1.3

Customizing CCS

Frequently used terms of CCS are listed below: Project Explorer: Presents an one shot view of all the Projects that are currrenly under processing by CCS. Path :View Project Explorer Debug: Debugs the code and loads it onto the targrt device. Debug icon is directly available on the main toolbar of CCS. Path :View Debug Problems: Displays warnings and error messages in CCS. Path :View Problems Console: Displays current activity and status in CCS. Path :View Console

6.2
6.2.1

Port Programming - Basic I/O Operations


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 oneaddress instructions Each I/O has an individually programmable pullup/pulldown resistor

6.2.2

Port Conguration

The conguration of the port operations are dened in software using the following registers: Direction Registers (PxDIR): Read/write 8-bit registers, which selects the direction of the corresponding I/O pin, regardless of the selected function of the pin (general purpose I/O or as a special function I/O).

47

PxDIR conguration: 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 reects the input signal at the corresponding I/O pin (pin congured as general purpose I/O). PxIN conguration: Bit = 1: The input is high. Bit = 0: The input is low. Output Registers (PxOUT): The output registers are read-write. Each bit of these registers reects the value written to the corresponding output pin. PxOUT conguration: Bit = 1: The output is high. Bit = 0: The output is low. Pull-up/Pull-down Resistor Enable Registers (PxREN): Each bit of this register enables or disables the pullup/pulldown resistor of the corresponding I/O pin. PxREN conguration: Bit = 1: Pullup/pulldown resistor enabled. Bit = 0: Pullup/pulldown resistor disabled. Function Select Registers(PxSEL) and (PxSEL2): Selects alternate functions for the particular pin of a port. NB: The dierent functions are device dependent. Check datasheet for details. PxSEL 0 0 1 1 PxSEL2 0 1 0 1 Pin Function Selects general-purpose I/O function Selects the primary peripheral module function Reserved (See device-specic data sheet) Selects the secondary peripheral module function

Interruptible ports (P1 and P2): Each pin of ports P1 and P2 is able to generate an interrupt request (pin is interruptible) and is congured using the PxIFG, PxIE, and PxIES registers.

48

Interrupt Enable (PxIE) : Read-write register to enable interrupts on individual pins. Each PxIE bit enables the interrupt request associated with the corresponding PxIFG interrupt ag. Writing to PxOUT and/or PxDIR 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 register selects the transition on which an interrupt occurs for the corresponding I/O pin (if PxIE and GIE are set). Bit = 1: Interrupt ag is set on a high-to-low transition. Bit = 0: Interrupt ag is set on a low-to-high transition. Interrupt Flag Registers (PxIFG) :The bit of this read-write register is set automatically when the programmed signal transition (edge) occurs on the corresponding I/O pin, provided that the corresponding PxIE bit and the GIE bit are set. Bit = 1: An interrupt is pending. Bit = 0: No interrupt is pending.

6.3
6.3.1

Output Operations
Lighting an LED

Program #include <msp430G2231.h> void main(void) { WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer P1DIR = 0x01; // Set pin1 (P1.0)to output, 0b00000001 P1OUT = 0x01; // LED1 (P1.0) on while(1) { } }

49

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 0th bit 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 3 V voltage. A 270 resistor to reduce the drop across LED. This is done internally in the Launchpad. Here you can see unlike the usual C-Program which goes sequentially and terminated after certain number of steps, the programs for a C are generally written inside or are terminated by an innite loop so that it gets executed innitely.

6.4
6.4.1

Input Operations
Reading a switch

Program #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.3 P1OUT = SWITCH; //Enabling internal pull up resistor for P1.3

50

P1DIR = LED1; // Set pin1 (P1.0) with to output , 0b00000001 P1OUT |= LED1; // Set P1.0 high while(1) { if ((P1IN & SWITCH) == 0) // Is button down? { P1OUT |= LED1; // Yes: Turn LED1 on } else { P1OUT &= 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; ternal pull-up resistor for P1.0. These two statements enables an in-

An internal pullup resistor connects the PIN to the supply voltage(5V). P1IN& SWITCH compares the P1IN register and the current state of BIT3 of Port1. If the comparison yields to be true the LED is switched ON else it is switched OFF.

51

Figure 6.4: Interfacing an Switch

6.5

Introduction to Grace

Grace is a free, graphical user interface that generates source code and eliminates manual peripheral conguration. As an MSP430 developer allows Grace you to generate the peripherals setup code within minutes. This will save you much of the work of poring through user guides and copying code examples and allow you to focus on the more important aspects of your application.

Figure 6.5: Welcome to Grace

52

6.6

Customizing the Port - Lighting an LED


New CCS Project

Step1 : Run Code Composer Studio(CCS) Step2 : Select File

Step3 : Fill in the Projet Name and select the Device that is used. The Device inherently found in a new Launchpad is MSP430G2231. Step4 : Select Empty Grace(MSP430) project from Project templates and examples and Finish. Step5 : Grace Conguration Steps Click Device Overview Select VCC Basic Clock PortP1 Power User Set DCO,SMCLK & ACLK P1.0 GPIO Output Pinout TSSOP/PDIP

Inside the main function write while(1) { P1OUT = 0xFF; }

6.7

Implementation Using Grace - Reading the Switch


New CCS Project

Step1 : Run Code Composer Studio(CCS) Step2 : Select File

Step3 : Fill in the Projet Name and select the Device that is used. The Device inherently found in a new Launchpad is MSP430G2231. Step4 : Select Empty Grace(MSP430) project from Project templates and examples and Finish. Step5 : Grace Conguration Steps Click Device Overview Select VCC Basic Clock PortP1 P1/P2 Power User Set DCO,SMCLK & ACLK P1.0 GPIO Output Pinout TSSOP/PDIP Basic User

Resistor Enable Register - Set BIT3 53

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 on } else { P1OUT &= LED1; // No: Turn LED1 off } }

54

Chapter 7

Interrupts in MSP430
7.1 What is an Interrupt?

In a microcontroller or in any microprocessor, we could check the status of a device or input from a pin in two dierent ways: Polling Interrupt Method In polling the C periodically check for the input or status ags from the external peripheral to get the status of its working.The microcontroller will draw a lot of current since the CPU must act and use the hardware continuously to do the polling. In the case of interrupt method when the external (or even internal) peripheral needs the attention of the processor, it will trigger an interrupt and the processor will stop execution of the current statements and store the present program address in system stack, execute a set of codes called ISR (Interrupt Service Routine) associated with the particular interrupt and restores the lastly executed 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 the conditions that resets the microcontroller. Non-maskable Interrupts (NMI): Mask ability refers to the fact that these interrupts cannot be disabled collectively and must be disabled and enabled individually. These are interrupts in the category where the error can possible be handled without a reset. Maskable Interrupts

55

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
7.2.1

Toggling LED Using Interrupt


Using Interrupt Flag

Program #include "msp430G2231.h" volatile unsigned int i; // volatile to prevent optimization

void main(void) { WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer // Configure LED on P1.0 P1DIR = BIT0; // P1.0 output P1OUT &= BIT0; // P1.0 output LOW, LED Off // Configure Switch on P1.3 P1REN |= BIT3; // P1.3 Enable Pullup/Pulldown P1OUT = BIT3; // P1.3 pullup P1IES |= BIT3; // P1.3 Hi/lo edge P1IFG &= BIT3; // P1.3 IFG cleared just in case while(1) { if(P1IFG & BIT3) // P1.3 IFG cleared { P1IFG &= BIT3; // P1.3 IFG cleared P1OUT = BIT0; // Toggle LED at P1.0 } } }

Working In this case an interrupt handler that is called whenever the interrupt occurs ia absent. Rather, the CPU continuously polls for the ag to see if the interrupt occurred.

56

Advantages: Correctly toggles the LED only when the switch is pressed and dont have the continuous toggle issue since not until the next transition do we toggle the LED. Disadvantages: The CPU still works too hard on something trivial like polling and still wastes energy. LED is connected to 0th pin and SWITCH to 3rd pin internally in the Launchpad. The conguration of the LED pin is quite simple. It is the conguration of the switch that is important. First, we enable the pullup resistor by using 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 the interrupt should occur on the rising edge (0 to 1) or on the falling edge(1 to 0). Only transitions cause interrupts not just static levels. An important part of the code is clearing the interrupt ag for the pin. This ensures any previous ags set are cleared and prevents an immediate jump into the interrupt handler when we interrupts are activated. P1IFG &= BIT3; resets the interrupt ag.

7.2.2

Using General Interrupt Coding

Program #include "msp430G2231.h" volatile unsigned int i; // volatile to prevent optimization void main(void) { WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer // Configure LED on P1.0 P1DIR = BIT0; // P1.0 output P1OUT &= BIT0; // P1.0 output LOW, LED Off // Configure Switch on P1.2 P1REN |= BIT3; // P1.3 Enable Pullup/Pulldown P1OUT = BIT3; // P1.3 pullup P1IE |= BIT3; // P1.3 interrupt enabled P1IES |= BIT3; // P1.3 Hi/lo falling edge P1IFG &= BIT3; // P1.3 IFG cleared just in case

57

_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.0 P1IFG &= BIT3; // P1.3 IFG cleared }

Working -General Interrupt Coding Terms associated with an interrupt : Interrupt service routine(ISR):The code segment that is excecuted as soon as an interrupt is triggered. Interrupt Vector :The address of an ISR is its vector. Interrupt Vector Table :The dened memory address where ISR address is stored. The general interrupts are activated using _EINT() , by setting general interrupt enable (GIE) i.e. GIE = 1. Setting the line with P1IE alone cannot trigger an interrupt, besause these are maskable interrupts. Although these interrupts are controlled individually, a second layer exists which can enable or disable them together. Therefore, we must disable the masking to allow interrupts to run. _DINT(); GIE ag is cleared, disabling general interrupts. The MSP430 uses vectored interrupts, which means that it is stored in a vector table at a dened 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 interrupt vector. The second is the __interrupt keyword at the beginning of the line that names the function. Interrupt initialization of port1 is given by

58

#pragma vector=PORT1_VECTOR __interrupt void Port_1(void) Switch Debouncing : Switches are not perfect. It is possible that the mechanical system inside it will toggle several times when the user presses on it and this is causes unwanted triggering of interrupt enabled pins. This eect is appropriately called bouncing. A small delay of 50mS would probably suce to prevent and bouncing problems. Debouncing is not implemented here since the performance of the switch on the launchpad is not that bad. Implementation Using Grace Step1 : Run Code Composer Studio(CCS) Step2 : Select File New CCS Project

Step3 : Fill in the Projet Name and select the Device that is used. The Device inherently found in a new Launchpad is MSP430G2231. Step4 : Select Empty Grace(MSP430) project from Project templates and examples and Finish. Step5 : Grace Conguration Steps Click Device Overview Select VCC Basic Clock PortP1 P1/P2 Power User Set DCO,SMCLK & ACLK P1.0 GPIO Output Pinout TSSOP/PDIP 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. After the main function write as a seperate function. void button_pushed(void) { P1OUT = BIT0; // Toggle LED at P1.0 P1IFG &= BIT3; // P1.3 IFG cleared }

59

Chapter 8

Timers in MSP430
8.1 What is a Timer?

Timer is a specialized type of clock for measuring time intervals. A timer which counts upwards from zero for measuring elapsed time is often called a stopwatch. Eg. hourglass. Embedded Systems typically digital counters that either increment or decrement at a xed frequency, which is often congurable. Timers are the one of the most commonly used complex peripheral in a microcontroller. They are used for getting time periods, generating pulse signals and also for measuring time period of pulses.

8.2

Timers in MSP430
Included in all devices (newer ones have the enhanced watchdog timer+). It protects the system against malfunctions but it can instead be used as an interval timer if this protection is not needed.

Watchdog timer :

Real-time clock : In which the basic timer has been extended to provide a real-time clock in the most recent MSP430x4xx devices. Timer A: Provided in all devices and is much more versatile than the simpler timers just listed. Timer A can handle external inputs and outputs directly to measure frequency, time-stamp inputs, and drive outputs at precisely specied times, either once or periodically.

60

There are internal connections to other modules so that it can measure the duration of a signal from the comparator, for instance. It can also generate interrupts.We will use a few of its capabilities and 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
8.3.1

Timer A
Salient Features

16-bit Counter Modes of operation Stop Up Continuous Up/Down

61

8.3.2

Timer A Registers

Figure 8.1: TACTL Register Timer A Control Register(TACTL)

62

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

Figure 8.5: TACCTLx Register Timer A Capture/Compare Control Register x(TACCTLx)

64

8.3.3

Timer A Modes

The timer has four modes of operation. The operating mode is selected with the MCx bits. MCx 00 01 10 11 Mode Stop Up Continuous Up/down Description The timer is halted The timer repeatedly counts from zero to the value of TACCR0 The timer repeatedly counts from zero to 0FFFFh The timer repeatedly counts from zero up to the value of TACCR0 and back down to zero

Figure 8.6: Up Mode

65

Figure 8.7: Continuous Mode

Figure 8.8: Up/Down Mode

66

8.3.4

Blinking an LED

Program #include <msp430g2231.h> void main(void) { WDTCTL = WDTPW + WDTHOLD; P1DIR |= 0x01; CCTL0 = CCIE; CCR0 = 50000; TACTL = TASSEL_2 + MC_2; _EINT(); } // Timer A0 interrupt service routine #pragma vector=TIMERA0_VECTOR __interrupt void Timer_A (void) { P1OUT = BIT0; CCR0 += 50000; } Working CCTL0= CCIE; sets when the interrupt Timer A overows, i.e. when the count value crosses 0xFFFF. CCR0= 50000 sets an oset to the count value, forcing the counter to start from this count value. TACTL= TASSEL_2+ MC_2 presents the standard setting of the clock of the counter, for more details about the register refer g 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 New CCS Project

// // // // //

Stop WDT P1.0 output CCR0 interrupt enabled Setting count value SMCLK, contmode

// Toggle P1.0 // Add Offset to CCR0

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

67

Step4 : Select Empty Grace(MSP430) project from Project templates and examples and Finish. Step5 : Grace Conguration Steps Click Device Overview Select VCC Basic Clock PortP1 Timer0 A2 Power User Basic User Set DCO,SMCLK & ACLK P1.0 GPIO Output Pinout TSSOP/PDIP

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. After the main function write as a seperate function. void timed(void) { P1OUT = BIT0; }

// Toggle P1.0

68

Chapter 9

Analog to Digital Conversion(ADC)


An analog-to-digital converter (abbreviated ADC, A/D or A to D) is a device that uses sampling to convert a continuous quantity to a discrete time representation in digital form. The reverse operation is performed by a digitalto-analog converter (DAC) The world around us is analog in nature and the microcontroller usually understands only digital information i.e. Whether input is there or not. There is a built in Analog to Digital converter inside the microcontroller which could be used to read the input voltage given to the ADC pins of the C. ADC is a device which converts the analog waveform at the input to the equivalent representation in the digital domain.

9.1

ADCs in MSP430

The 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 in general. 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

Up to eight external input channels (twelve on MSP430F22xx devices) Conversion channels for internal temperature sensor, VCC, and external references Selectable conversion clock source Single-channel, repeated single-channel, sequence, and repeated sequence conversion 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 dene the upper and lower limits of the conversion. Conversion Clock Selection : The ADC10CLK is used both as the conversion clock and to generate the sampling period. The ADC10 source clock is selected using the ADC10SSELx bits and can be divided from 1 to 8 using the ADC10DIVx bits.

9.1.2

ADC Registers

Figure 9.1: ADC10 Registers

70

Figure 9.2: ADC10CTL0 Register ADC10 Control Register 0

9.1.3

Lighting an LED if input goes above 0.2V

Program #include "msp430g2231.h" void main(void) 71

{ WDTCTL = WDTPW + WDTHOLD; // Stop WDT ADC10CTL0 = SREF_1 + ADC10SHT_2 + REFON + ADC10ON + ADC10IE; __enable_interrupt(); // Enable interrupts. TACCR0 = 30; // Delay to allow Ref to settle TACCTL0 |= 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 A1 ADC10AE0 |= 0x02; // PA.1 ADC option select P1DIR |= 0x01; // Set P1.0 to output direction for (;;) { ADC10CTL0 |= ENC + ADC10SC; __bis_SR_register(CPUOFF + GIE); if (ADC10MEM < 0x88) P1OUT &= 0x01; else P1OUT |= 0x01; } } // ADC10 interrupt service routine #pragma vector=ADC10_VECTOR __interrupt void ADC10_ISR (void) { __bic_SR_register_on_exit(CPUOFF); } #pragma vector=TIMERA0_VECTOR __interrupt void ta0_isr(void) { TACTL = 0; LPM0_EXIT; } Working Timer A is used for ADC sampling and low power implementation. ADC10CTL0 is used to congure reference voltage to 1.5V. ADC input pin is continuously sampled and converted to digital form.

// // // //

Sampling and conversion start LPM0, ADC10_ISR will force exi ADC10MEM = A1 > 0.2V? Clear P1.0 LED off

// Set P1.0 LED on

// Clear CPUOFF bit from 0(SR)

// Exit LPM0 on return

72

ADC10MEM has the converted binary value, which is compared with the binary 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 end of ADC conversion.

73

Chapter 10

Communication Modules in MSP430


10.1 Universal Serial Interface

The universal serial interface (USI) is a lightweight module, which is included in the small F20x2 and F20x3 devices. It is much less grand than its name might imply.

10.2

Universal Serial Communication Interface

Recent, larger devices in the MSP430F2xx and MSP430F4xx families contain one 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 the usual 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

10.2.2
Program

A Software UART Using Timer A

void main(void) { WDTCTL = WDTPW + WDTHOLD; DCOCTL = 0x00; BCSCTL1 = CALBC1_1MHZ; DCOCTL = CALDCO_1MHZ; P1OUT P1SEL P1DIR P2OUT P2SEL P2DIR = = = = = = 0x00; UART_TXD + UART_RXD; 0xFF & UART_RXD; 0x00; 0x00; 0xFF;

// Stop watchdog timer // Set DCOCLK to 1MHz

// Initialize all GPIO // Timer function for TXD/RXD pins // Set all pins but RXD to output

__enable_interrupt(); TimerA_UART_init(); // Start Timer_A UART TimerA_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, Int TACTL = 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

while (TACCTL0 & CCIE); TACCR0 = TAR; TACCR0 += UART_TBIT; TACCTL0 = OUTMOD0 + CCIE; txData = byte; txData |= 0x100; txData <<= 1; }

// // // // // // //

Ensure last char got TXd Current state of TA counter One bit time till first bit Set TXD on EQU0, Int Load global variable Add mark stop bit to TXData 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; if (txBitCnt == 0) { TACCTL0 &= CCIE; txBitCnt = 10; } else { if (txData & 0x01) { TACCTL0 &= OUTMOD2; } else { TACCTL0 |= OUTMOD2; } txData >>= 1; txBitCnt--; } } // // // // Add Offset to CCRx All bits TXed? All bits TXed, disable interrupt Re-load bit counter

// TX Mark 1

// TX Space 0

76

NOTES

77

NOTES

78

NOTES

79

NOTES

80

NOTES

81

You might also like