Microcontrollerprogramming Msp430fr2433andmsp430fr5994 Part1 Secondedition
Microcontrollerprogramming Msp430fr2433andmsp430fr5994 Part1 Secondedition
Bad to the Bone: Crafting Electronic Systems with BeagleBone and BeagleBone Black
Steven F. Barrett and Jason Kridner
2013
Embedded Systems Interfacing for Engineers using the Freescale HCS08 Microcontroller
II: Digital and Analog Hardware Interfacing
Douglas H. Summerville
2009
Embedded Systems Interfacing for Engineers using the Freescale HCS08 Microcontroller
I: Assembly Language Programming
Douglas H.Summerville
2009
Pragmatic Power
William J. Eccles
2008
Pragmatic Logic
William J. Eccles
2007
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in
any form or by any means—electronic, mechanical, photocopy, recording, or any other except for brief quotations
in printed reviews, without the prior permission of the publisher.
Lecture #55
Series Editor: Mitchell A. Thornton, Southern Methodist University
Series ISSN
Print 1932-3166 Electronic 1932-3174
Microcontroller Programming
and Interfacing with
Texas Instruments
MSP430FR2433 and
MSP430FR5994 – Part I
Second Edition
Steven F. Barrett
University of Wyoming, Laramie, WY
Daniel J. Pack
University of Tennessee Chattanooga, TN
M
&C Morgan & cLaypool publishers
ABSTRACT
This book provides a thorough introduction to the Texas Instruments MSP430TM microcon-
troller. The MSP430 is a 16-bit reduced instruction set (RISC) processor that features ultra-low
power consumption and integrated digital and analog hardware. Variants of the MSP430 mi-
crocontroller have been in production since 1993. This provides for a host of MSP430 products
including evaluation boards, compilers, software examples, and documentation. A thorough in-
troduction to the MSP430 line of microcontrollers, programming techniques, and interface con-
cepts are provided along with considerable tutorial information with many illustrated examples.
Each chapter provides laboratory exercises to apply what has been presented in the chapter. The
book is intended for an upper level undergraduate course in microcontrollers or mechatronics
but may also be used as a reference for capstone design projects. Also, practicing engineers al-
ready familiar with another microcontroller, who require a quick tutorial on the microcontroller,
will find this book very useful. This second edition introduces the MSP–EXP430FR5994 and
the MSP430–EXP430FR2433 LaunchPads. Both LaunchPads are equipped with a variety of
peripherals and Ferroelectric Random Access Memory (FRAM). FRAM is a nonvolatile, low-
power memory with functionality similar to flash memory.
KEYWORDS
MSP430 microcontroller, microcontroller interfacing, embedded systems design,
Texas Instruments
xi
To our families
xiii
Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
xix
Preface
Texas Instruments is well known for its analog and digital devices, in particular, Digital Signal
Processing (DSP) chips. Unknown to many, the company quietly developed its microcontroller
division in the early 1990s and started producing a family of controllers aimed mainly for em-
bedded meter applications, which require an extended operating time without intervention for
power companies. It was not until the mid 2000s that the company began serious effort to
present the MSP430 microcontroller family, its flagship microcontroller, to the academic com-
munity and future engineers. Their efforts have been quietly attracting many educators and stu-
dents due to the MSP430’s cost and the suitability of the controller for capstone design projects
requiring microcontrollers. In addition, Texas Instruments offers many compatible analog and
digital devices that can expand the range of the possible embedded applications of the microcon-
troller. Texas Instruments has continually added new innovation to the MSP430 microcontroller
line. The second edition introduces the MSP–EXP430FR5994 and the MSP–EXP430FR2433
LaunchPads. Both LaunchPads are equipped with a variety of peripherals and Ferroelectric Ran-
dom Access Memory (FRAM). FRAM is a nonvolatile, low-power memory with functionality
similar to flash memory.
This book is about the MSP430 microcontroller family. We have three goals in writing
this book. The first is to introduce readers to microcontroller programming. The MSP430 mi-
crocontrollers can be programmed either using assembly language or a high–level programming
language such as C. The second goal of the book is to teach students how computers work. After
all, a microcontroller is a computer within a single integrated circuit (chip). Finally, we present
the microcontroller’s input/output interface capabilities, one of the main reasons for developing
embedded systems with microcontrollers.
Background
This book provides a thorough introduction to the Texas Instruments MSP430 microcontroller.
The MSP430 is a 16-bit reduced instruction set (RISC) processor that features ultra-low power
consumption and integrated digital and analog hardware. Variants of the MSP430 microcon-
troller have been in production since 1993 with a host of MSP430-related products including
evaluation boards, compilers, software examples, and documentation.
This book is intentionally tutorial in nature with many worked examples, illustrations,
and laboratory exercises. An emphasis is placed on real-world applications such as smart home
concepts, mobile robots, an unmanned underwater vehicle, and a DC motor controller to name
a few.
xx PREFACE
Intended Readers
The book is intended for an upper level undergraduate course in microcontrollers or mechatron-
ics but may also be used as a reference for capstone design projects. Also, practicing engineers
who are already familiar with another line of microcontrollers, but require a quick tutorial on
the MSP430 microcontroller, will find this book beneficial.
Approach and Organization
This book provides a thorough introduction to the MSP430 line of microcontrollers, program-
ming techniques, and interface concepts. Each chapter contains a list of objectives, background
tutorial information, and detailed information on the operation of the MSP430 system under
study. Furthermore, each chapter provides laboratory exercises to apply what has been presented
in the chapter and how the concepts are employed in real applications. Each chapter concludes
with a series of homework exercises divided into Fundamental, Advanced, and Challenging
categories. The reader will get the most out of the book by also having the following references
readily available:
• MSP430FR2433 Mixed–Signal Microcontroller, SLASE59B;
• MSP430FR4xx and MSP430FR2xx Family User’s Guide, SLAU445G;
• MSP430FR599x, MSP430FR596x Mixed–Signal Microcontrollers, SLASE54B; and
• MSP430FR58xx, MSP430FR59xx, and MSP430FR6xx Family User’s Guide,
SLAU367O.
This documentation is available for download from the Texas Instruments website [www.
ti.com].
Chapter 1 provides a brief review of microcontroller terminology and a short history fol-
lowed by an overview of the MSP430 microcontroller. The overview surveys systems onboard
the microcontroller and also various MSP430 families. The chapter concludes with an introduc-
tion to the hardware and software development tools that will be used for the remainder of the
book. Our examples employ the MSP–EXP430FR5994 and the MSP430FR2433 LaunchPads,
the Energia rapid prototyping platform, and the Texas Instruments’ Code Composer Studio In-
tegrated Development Environment (IDE). The information provided can be readily adapted
to other MSP430 based experimenter boards.
Chapter 2 provides a brief introduction to programming in C. The chapter contains mul-
tiple examples for a new programmer. It also serves as a good review for seasoned programmers.
Also, software programming tools including Energia, Code Composer Studio IDE, and debug-
ging tools are explored. This chapter was adapted from material originally written for the Texas
Instruments MSP432, a 32-bit processor that has close ties to the 16-bit MSP430.1 Embed-
1 This chapter was adapted with permission from Arduino Microcontroller Processing for Everyone, S. Barrett, 3rd ed., Mor-
gan & Claypool Publishers, San Rafael, CA, 2013.
PREFACE xxi
ded system developers will find a seamless transition between the MSP430 and MSP432 line
of processors.
Chapter 3 introduces the MSP430 hardware architecture, software organization, and pro-
gramming model. The chapter also presents an introduction to the MSP430 orthogonal instruc-
tion set, including its 27 instructions and 9 emulated instructions.
Chapter 4 describes a wide variety of input and output devices and how to properly inter-
face them to the MSP430 microcontroller. We believe it is essential for the embedded system
designer to understand the electrical characteristics of the processor so a proper interface to pe-
ripheral components may be designed. We have included a chapter on these concepts for the
books we have written for the Synthesis Lecture Series. We continue to add material as new
microcontroller peripherals are developed. The chapter begins with a review of the MSP430
electrical operating parameters followed by a discussion of the port system. The chapter in-
cludes a description of a wide variety of input device concepts including switches, interfacing,
debouncing, and sensors. Output device concepts are then discussed including light-emitting
diodes (LEDs), tri–state LED indicators, liquid crystal displays (LCDs), high-power DC and
AC devices, motors, and annunciator devices.
Chapter 5 provides an in–depth discussion of the MSP430 power management system.
The power management system provides for ultra-low power operation and practices.
Chapter 6 is dedicated to the different memory components onboard the MSP430 in-
cluding the new FRAM nonvolatile memory, RAM, EEPROM and the associated memory
controllers. The Direct Memory Access (DMA) controller is also discussed.
Chapter 6.11 discusses the clock and timer systems aboard the MSP430. The chapter be-
gins with a detailed discussion of the flexible clock system, followed by a discussion of the timer
system architecture. The timer architecture discussion includes the Watchdog timers, timers A
and B, real-time clocks, and pulse width modulation (PWM).
Chapter 6.11 provides an introduction to the concepts of resets and interrupts. The various
interrupt systems associated with the MSP430 are discussed, followed by detailed instructions
on how to properly configure and program them.
Chapter 6.11 discusses the analog systems aboard the MSP430. The chapter discusses
the analog–to–digital converters (ADCs), the digital–to–analog converters (DACs), and the
comparators.
Chapter 6.11 is designed for a detailed review of the complement of serial communication
systems resident onboard the MSP430, including the universal asynchronous receiver transmit-
ter (UART), the serial peripheral interface (SPI), the I2C system, the radio frequency (RF) link,
USB, and the IrDA infrared link. The systems are contained within the MSP430 universal serial
communication interfaces eUSCI_A and eUSCI_B subsystems.
Chapter 6.11 provides a detailed introduction to the data integrity features aboard the
MSP430 including a discussion of noise and its sources and suppression, an Advanced En-
cryption Standard (AES) 256 accelerator module, and a 16- or 32-bit cyclic redundancy check
xxii PREFACE
(CRC) engine. This chapter was adapted from material originally written for the Texas Instru-
ments MSP432, a 32-bit processor that has close ties to the 16-bit MSP430.2 Embedded system
developers will find a seamless transition between the MSP430 and MSP432 line of processors.
Chapter 6.11 discusses the system design process followed by system level examples. We
view the microcontroller as the key component within the larger host system. It is essential the
embedded system designer has development, design, and project management skills to success-
fully complete a project. This chapter provides an introduction some of the skills used for project
development. We have included a chapter on these concepts for the books we have written for
the Synthesis Lecture Series. The examples have been carefully chosen to employ a wide variety
of MSP430 systems discussed throughout the book.
Table 1 provides a summary of chapter contents and related MSP430 subsystems.
2 Embedded Systems Design with the Texas Instruments MSP432 32-bit Processor, Dung Dang, Daniel J. Pack, and Steven
F. Barrett, Morgan & Claypool Publishers, San Rafael, CA, 2017.
PREFACE xxiii
Acknowledgments
There have been many people involved in the conception and production of this book. We es-
pecially want to thank Doug Phillips, Mark Easley, and Franklin Cooper of Texas Instruments.
The future of Texas Instruments is bright with such helpful, dedicated engineering and staff
members. In 2005, Joel Claypool of Morgan & Claypool Publishers, invited us to write a book
on microcontrollers for his new series titled “Synthesis Lectures on Digital Circuits and Sys-
tems.” The result was the book Microcontrollers Fundamentals for Engineers and Scientists. Since
then we have been regular contributors to the series. Our goal has been to provide the fun-
damental concepts common to all microcontrollers and then apply the concepts to the specific
microcontroller under discussion. We believe that once you have mastered these fundamental
concepts, they are easily transportable to different processors. As with many other projects, he
has provided his publishing expertise to convert our final draft into a finished product. We thank
him for his support on this project and many others. He has provided many novice writers the
opportunity to become published authors. His vision and expertise in the publishing world made
this book possible. We thank Sara Kreisman of Rambling Rose Press, Inc. for her editorial ex-
pertise. We also thank Dr. C.L. Tondo of T&T TechWorks, Inc. and his staff for working their
magic to convert our final draft into a beautiful book. Finally, we thank our families who have
provided their ongoing support and understanding while we worked on books over the past
fifteen plus years.
CHAPTER 1
Introduction to
Microcontroller Technology
Objectives: After reading this chapter, the reader should be able to:
• describe the key technological accomplishments leading to the development of the micro-
controller;
• define microprocessor, microcontroller, and microcomputer;
• identify examples of microcontroller applications in daily life;
• list key attributes of the MSP430 microcontroller;
• describe different features that differentiate MSP430 microcontroller family members;
• list the subsystems onboard the MSP430FR2433 and the MSP430FR5994 microcon-
trollers;
• provide an example application for each subsystem onboard the MSP430 microcontrollers;
• describe the hardware, software, and emulation tools available for the MSP430 microcon-
trollers; and
• employ the development tools to load and execute simple programs on the MSP-
EXP430FR2433 and the MSP-EXP430FR5994 evaluation boards.
In every chapter, we start with a motivation and background followed by a section on the-
ory. After the theory section, an example application is used to demonstrate the operational use
of chapter concepts. Each chapter includes a hands-on laboratory exercise and a list of chapter
references, which you can use to explore further areas of interest. Each chapter concludes with
a series of practice exercises, divided into Fundamental, Advanced, and Challenging levels.
1.1 MOTIVATION
This book is about microcontrollers! A microcontroller is a self-contained processor system in a
single integrated circuit (IC or chip) that contains essential functional units of a general-purpose
computer such as a central processing unit (CPU), a memory, and input/output (I/O) units.
2 1. INTRODUCTION TO MICROCONTROLLER TECHNOLOGY
Microcontrollers provide local computational resources to many products, requiring a limited
amount of processing power to perform their functions. They are everywhere! In the routine of
daily life, we use multiple microcontrollers. Take a few minutes and jot down a list of microcon-
troller equipped products, sometimes called embedded systems, you have used today.
This chapter introduces the Texas Instruments MSP430 line of microcontrollers. We
begin with a brief history of computer technology followed by an introduction to the
MSP430FR2433 and the MSP430FR5994 microcontrollers. After a review of these MSP430
microcontrollers, we introduce you to the powerful and user-friendly development tools.
Processor
Input
Control
Memory
System
Datapath Output
Computer
Figure 1.1: Basic computer architecture. (Adapted from Patterson and Hennessy [1994].)
4 1. INTRODUCTION TO MICROCONTROLLER TECHNOLOGY
The memory system contains a variety of memory components to support the operation of
the computer. Typical memory systems aboard microcontrollers contain RAM, ROM, and elec-
trically erasable programmable read only memory (EEPROM) components. RAM is volatile.
When power is unavailable, the contents of RAM memory is lost. RAM is typically used in mi-
crocontroller operations for storing global variables, local variables, which are required during
execution of a function, and to support heap operations during dynamic allocation activities. In
contrast, ROM memory is nonvolatile. That is, it retains its contents even when power is not
available. ROM memory is used to store system constants and parameters. If a microcontroller
application is going to be mass produced, the resident application program may also be written
into ROM memory at the manufacturer.
EEPROM is available in two variants: byte-addressable and flash programmable. Byte-
addressable memory EEPROM, as its name implies, allows variables to be stored, read, and
written during program execution. The access time for byte-addressable EEPROM is much
slower than RAM memory; however, when power is lost, the EEPROM memory retains its
contents. Byte-addressable EEPROM may be used to store system passwords and constants.
For example, if a microcontroller-based algorithm has been developed to control the operation
of a wide range of industrial doors, system constants for a specific door type can be programmed
into the microcontroller onsite when the door is installed. Flash EEPROM can be erased or
programmed in bulk. It is typically used to store an entire program.
Ferroelectric Random Access Memory (FRAM) is a nonvolatile, ultra-low power (ULP)
with access speeds similar to RAM. It has been termed a universal memory because it can be used
for storing program code, variables, constants, and for stack operations. Note these functions
are typically performed by nonvolatile ROM and volatile RAM. FRAM also has a high level of
write endurance on the order of 1015 cycles [SLAA526A, 2014, SLAA628, 2014].
The input and output system of a microcontroller usually consists of a complement of
ports. Ports are fixed sized hardware registers that allow for the orderly transfer of data in and
out of the microcontroller. In most microcontroller systems, ports are equipped for dual use. That
is, they may be used for general-purpose digital I/O operations or may have alternate functions
such as input access for the analog-to-digital (ADC) system.
Our discussion thus far has been about microcontrollers in general. For the remainder
of this chapter and the rest of the book, we concentrate on the Texas Instruments MSP430
microcontroller, specifically the MSP430FR2433 and the MSP430FR5994.
MSP-EXP430FR2433 MSP-EXP430FR5994
Evaluation Module (EVM) Evaluation Module (EVM)
FR2xx/FR4xx family FRxx FRAM Family
Figure 1.2: MSP430 features [SLAB034AD, 2017, SLASE59D, 2018, SLASE54C, 2018].
1.5. TARGET MICROCONTROLLER FEATURES 7
• power management features,
• flexible clock system (CS),
• cyclic redundancy check (CRC),
• embedded emulation module (EEM),
• watch dog timer (WDT),
• real-time clock (RTC),
• joint test action group ( JTAG) interface,
• spy-bi-wire (SBW) JTAG interface,
• onboard light crystal display (LCD) controller (FR5994), and
• low-energy accelerator (LEA) (FR5994).
In addition, the MSP-EXP430FR5994 EVM has the following features:
• analog comparators,
• six channels of internal direct memory access (DMA),
• onboard LCD controller,
• capacitive touch features, and
• hardware AES encryption.
Provided below is a brief summary of these features. More details are found throughout
the remainder of the book [SLAB034AD, 2017, SLASE59D, 2018, SLASE54C, 2018]:
Maximum operating frequency: 16 MHz. Both the FR2433 and the FR5994 EVMs
have a maximum operating frequency of 16 MHz. Generally speaking, a microcontroller’s power
consumption is linearly related to its operating frequency. Microcontrollers are typically used in
remote applications sourced by battery power. To conserve energy the microcontroller is placed
in low-power, low-frequency sleep mode when inactive. The microcontroller is awoken when
needed. Therefore, a microcontroller needs a combination of both high- and low-frequency clock
sources, different operating modes, and the ability to quickly transition between the modes. The
MSP430 is equipped with a flexible and stable clock and distribution system to satisfy these
requirements.
16-bit RISC architecture. Reduced instruction set computer (RISC) architecture is based
on the premise of designing a processor that is very efficient in executing a basic set of building
8 1. INTRODUCTION TO MICROCONTROLLER TECHNOLOGY
block instructions. From this set of basic instructions more complex instructions may be con-
structed. The 16-bit data width establishes the range of numerical arguments that may be used
within the processor. For example, a 16-bit processor can easily handle 16-bit unsigned inte-
gers. This provides a range of unsigned integer arguments from 0 to .216 1/ or approximately
65,535. Larger arguments may be handled, but additional software manipulation is required for
processing, which consumes precious execution time.
Low supply voltage range: 1.8–3.6 VDC. The MSP430 operates at very low voltages.
Some operating voltage of interest include:
• 1.8 V: many modern sensors/consumer electronics operate at 1.8 V. Being able to run the
microcontroller at this range means the whole system can operate at VCC D 1.8 V.
Ultra-low power consumption. The MSP430 has a variety of operating modes including
an active mode (AM) and multiple low-power modes (LPM). In the active mode, the MSP430
draws 126 (FR2433)/118 (FR5994) microamps of current per MHz of clock speed. In the
standby mode the MSP430 draws less than one microamp of current. In LPM 3.5 and operat-
ing from a RTC frequency of 32,768 Hz, the MSP430 draws 73 nA (FR2433) and 350 nA
(FR5994). In LPM 4.5 shutdown mode, the MSP430 draws 16 nA (FR2433) and 45 nA
(FR5994) of current [SLASE59D, 2018, SLASE54C, 2018].
Large complement of I/O ports. The FR2433 is equipped with a single 16-bit digital
I/O port, designated as PA. This port may also be subdivided into two 8-bit ports, designated as
P1 and P2. The FR2433 also has a 3-bit, port designated as PB. The FR5994 is equipped with a
four 16-bit digital I/O ports, designated as PA through PD. These ports may also be subdivided
into two 8-bit ports. For example, port PA may be as designated P1 and P2. The FR5994 also
has an 8-bit port, designated as PJ.
Multi-channel, high-resolution analog-to-digital converter. The FR2433 is equipped
with an 8-channel, 10-bit analog-to-digital converter. The FR5994 is equipped with 16 channels
of 12-bit ADC. This feature provides for a large number of converters and very good resolution
of analog signals converted.
Hardware multiplier. Many microcontrollers can perform mathematical multiplication
operations. However, most perform these calculations using a long sequence of instructions that
consume multiple clock cycles. That is, it takes a relatively long period of time to perform a mul-
tiplication operation. The MSP430 is equipped with a dedicated hardware multiplier that can
1.5. TARGET MICROCONTROLLER FEATURES 9
multiply 32-, 24-, 16-, and 8-bit signed and unsigned multiplication operations. The hardware
multiplier can also perform the signed and unsigned multiply and accumulate operation. This
operation is used extensively in digital signal processing (DSP) operations.
Multiple enhanced universal serial communication interfaces (eUSCI). The MSP430
microcontroller is equipped with the enhanced Universal Serial Communication Interface (eU-
SCI). The system is equipped with many different serial communication subsystems. The eU-
SCI consists of two different communication subsystems: eUSCI A type modules and eUSCI B
modules. The FR2433 EVM is equipped with two A modules (A0, A1) and a single B module
(B0). The FR5994 EVM is equipped with four A modules (A0 to A3) and four B modules (B0
to B3).
The eUSCI A modules provide support for the following.
• Universal asynchronous serial receiver and transmitter (UART). The UART supports a
serial data link between a transmitter and a receiver. The transmitter and receiver pair
maintains synchronization using start and stop bits that are embedded in the data stream.
• Infrared data association (IrDA). The IrDA protocol provides for a short-range data link
using an infrared (IR) link. It is a standardized protocol for IR linked devices. It is used
in various communication devices, personal area networks, and instrumentation.
• The serial peripheral interface (SPI) provides synchronous communications between a re-
ceiver and a transmitter. The SPI system maintains synchronization between the trans-
mitter and receiver pair using a common clock provided by the master designated micro-
controller. An SPI serial link has a much faster data rate than UART.
The eUSCI B modules also provide support for SPI communications and inter-integrated
communication (I2 C) communications. The I2 C is one of prominent communication modes,
used when multiple serial devices are interconnected through a serial bus. The I2 C bus is a two-
wire bus with the serial data line (SDL) and the serial clock line (SCL). By configuring devices
connected to the common I2 C line as either a master device or a slave device, multiple devices
can share information using a common bus. The I2 C system is used to link multiple peripheral
devices to a microcontroller or several microcontrollers together in a system that are in close
proximity to one another [SLAU356A].
Multiple basic timers. The MSP430 employs timers for capturing the parameters of
an incoming signal (period, frequency, duty cycle, pulse length), generating a precision out-
put digital signal, or generating a pulse width modulated (PWM) signal. The FR2433 is
equipped with four 16-bit timers designated as type Timer_A3 and Timer_A2. Each of the
two Timer_A3 timers are equipped with three capture/compare registers. The two Timer_A2
timers are equipped with two capture/compare registers. The FR5994 is equipped with 6 dif-
ferent 16-bit registers with the number of capture/compare registers shown: Timer_TA0(3),
Timer_TA1(3), Timer_TA2(3), Timer_TA3(2), Timer_TA4(2), and Timer_TB0(7).
10 1. INTRODUCTION TO MICROCONTROLLER TECHNOLOGY
Memory system. FRAM is a nonvolatile and operates on ULP with access speeds similar
to RAM. It has been termed a universal memory because it can be used for storing program code,
variables, constants, and for stack operations. The FR2433 is equipped with 15 KB (kilobytes)
of FRAM for program storage and 512 bytes for data storage. The FR5994 is equipped with
256 KB of flexibly configurable FRAM for program and information storage.
Onboard RAM memory. The FR2433 hosts a 4 KB static RAM (SRAM) memory;
whereas, the FR5994 is equipped with 8 KB of SRAM memory. The SRAM memory is used
for global variables, local variables, and the dynamic allocation of user-defined data types during
program execution.
Power management system. The power management module (PMM) supplies the core
voltage for the microcontroller. It consists of an integrated voltage regulator to maintain a stable
core voltage. It is also equipped with a supply voltage supervisor and monitoring system, which
may be configured to reset the microcontroller when the core voltage falls below a preset value.
Flexible clock system. Microcontrollers are synchronous circuits. That is, all microcon-
troller operations are synchronized with a clock circuit. There are several clock source options
available for the MSP430 including a 32 kHz crystal (XT1), an internal very low-frequency
oscillator (VLO), an internal trimmed low-frequency oscillator (REFO), an integrated digitally
controlled oscillator (DCO) employing a frequency logic loop (FLL) with a digital modulator,
and a high-frequency crystal oscillator (XT1 or XT2).
Cyclic redundancy check (CRC) generator. Data stored aboard a microcontroller may
be corrupted by noise sources flipping 1s to 0s and vice versa. The MSP430 is equipped with
the CRC16 subsystem, which employs the CRC-CCITT standard to calculate a checksum for
a block of data. The checksum is also stored with the data. When the data is used, a checksum
is calculated again and compared to the stored value. If the values agree, the data is considered
good for use. Alternately, if the checksums do not agree, the data is considered corrupted and
not available for use. The CRC system onboard the FR5994 EVM may also be used in a 32-bit
mode.
Embedded emulation module (EEM). The EEM is used to troubleshoot system oper-
ation of an embedded system. It allows events to be triggered based on memory access, CPU
access, or hardware triggers.
Watch dog timer (WDT). The WDT is a timer that, if expired, results in a processor
reset. It is used to reset the processor when a software malfunction has occurred. During normal
program processing the WDT is reset by specific program steps. Should a software malfunction
occur and the WDT timer is not reset, the WDT will timeout and result in a processor reset.
In response to the processor reset, the software malfunction may clear.
1.6. INTRODUCTION TO THE EVALUATION MODULES (EVM) 11
Real-time clock (RTC). Microcontrollers keep time based on elapsed clock ticks. They
do not “understand” the concepts of elapsed time in seconds, hours, etc. The RTC provides a
general-purpose 16-bit counter while in the Counter Mode or an RTC in the Calendar Mode.
Both timer modes can be used to read or write counters using software.
Joint test action group ( JTAG) interface. JTAG is a four-wire standard interface to send
and receive data from the microcontroller. It is defined within IEEE Standard 1149.1. The
JTAG interface allows for programming and debugging programs.
Spy-bi-wire (SBW) JTAG interface. The SBW is a two-wire JTAG compatible interface.
In addition to the features common between the FR2433 and the FR5994 EVMs, the
FR5994 is also equipped with the following subsystems.
Analog comparator. The FR5994 is equipped with a 16-channel analog comparator to
monitor analog signals of interest. The comparator, as its name implies, compares an analog
input signal with a pre-defined threshold.
Direct memory access (DMA). Memory transfer operations from one location to another
typically requires many clock cycles involving the CPU. The FR5994 is equipped with six DMA
channels that allow memory-to-memory location transfers without involving the CPU, freeing
the CPU to perform other instructions.
Capacitive touch. The FR5994 is equipped with capacitive touch I/O features that sup-
port simple touch screen applications.
Hardware encryption. The FR5994 is also equipped with a hardware-based advanced
encryption standard (AES) accelerator. The accelerator speeds up the encryption and decryption
of data by one to two orders of magnitude over a software-based implementation. It can be used
for 128- or 256-bit encryption.
Low-energy accelerator. The FR5994 is equipped with a 32-bit, fixed-point processor,
the low energy accelerator (LEA) for vector-based operations. Vector-based operations are com-
monly used is signal processing applications. Operations include finite impulse response (FIR)
filtering, infinite impulse response (IIR) filtering, fast fourier transforms (FFT), inverse fast
fourier transforms (IFFT), and others. The LEA, once configured for operation, executes com-
mands independent of the MSP430 CPU SLAU367O [2017].
Throughout the rest of the book we use the MSP-EXP430FR2433 and the MSP-
EXP430FR5994 EVMs to illustrate operation of different systems aboard the MSP430.
12 1. INTRODUCTION TO MICROCONTROLLER TECHNOLOGY
MSP430FR2433 EVM. The MSP-EXP430FR2433 EVM layout is provided in Fig-
ure 1.3 and the pinout diagram in Figure 1.4. The FR2433 is programmed via a host PC or
laptop via a USB cable. The upper portion of the EVM is equipped with the eZ-FET Debug
Probe. This provides for EVM programming and also communication back to the host com-
puter. Also, the EVM is equipped with EnergyTrace Technology that allows power consump-
tion readings. The link from the upper to the lower board is provided by the Jumper Isolation
Block. The lower board is equipped with two switches, two light-emitting diodes (LEDs), and
breakout pins for a 20-pin BoosterPack. BoosterPacks allow the features of the MSP430 to be
extended [SLAU739, 2017].
MSP-EXP430FR5994 EVM. The MSP-EXP430FR5994 EVM layout is provided in
Figure 1.5 and the pinout diagram Figure 1.4. The FR5994 is programmed via a host PC or lap-
top via a USB cable. The upper portion of the EVM is equipped with the eZ-FET Debug Probe.
This provides for EVM programming and also communication back to the host computer. Also,
the EVM is equipped with EnergyTrace Technology that allows power consumption readings.
The link from the upper to the lower board is provided by the Jumper Isolation Block. The lower
board is equipped with two switches, two LEDs, and breakout pins for a 40-pin BoosterPack.
BoosterPacks allow the features of the MSP430 to be extended. The FR5994 is also equipped
with a Micro SD card [SLAU678A, 2016].
USB
to
Host Reset
eZ-FET
Debug Energy Trace
Probe Technology
Jumper Isolation
Block
Switch 1 Switch 2
MSP430FR2433
LED1 LED2
20-pin BoosterPack
Figure 1.3: FR2433 EVM [SLAU739, 2017]. (Illustration used with permission of Texas In-
struments (www.ti.com).)
14 1. INTRODUCTION TO MICROCONTROLLER TECHNOLOGY
Figure 1.4: FR2433 EVM pinmap [SLAU739, 2017]. (Illustration used with permission of
Texas Instruments (www.ti.com).)
1.7. DEVELOPMENT SOFTWARE 15
USB
to
Host
Jumper Isolation
Block
Reset
MSP430FR5944
Switch 1 Switch 2
LED1 LED2
20-pin BoosterPAck
LED1 Micro LED2
SD card
40-pin BoosterPack
Figure 1.5: FR5994 EVM [SLAU678A, 2016]. (Illustration used with permission of Texas
Instruments (www.ti.com).)
16 1. INTRODUCTION TO MICROCONTROLLER TECHNOLOGY
Figure 1.6: FR5994 EVM pinmap [SLAU678A, 2016]. (Illustration used with permission of
Texas Instruments (www.ti.com).)
• To compile, upload, and run the program, use the Upload icon (right facing arrow).
1.9 SUMMARY
In this chapter, we introduced microcontrollers and an overview of related technologies. We be-
gan with a brief review of computer development leading up to the release of microcontrollers,
reviewed microcontroller related terminology and provided an overview of systems associated
with the MSP-EXP430FR2433 and the MSP-EXP430FR5994 evaluation modules. The re-
mainder of the chapter was spent getting better acquainted with the EVMs and the Energia
IDE.
Boone, G. Computing System CPU, United States Patent 3,757,306 filed August 31, 1971, and
issued September 4, 1973. 3
Boone, G. Variable Function Programmable Calculator, United States Patent 4,074,351 filed
February 24, 1977 and issued February 15, 1978. 3
CHAPTER 2
A Brief Introduction to
Programming
Objectives: After reading this chapter, the reader should be able to:
• use the Energia Integrated Development Environment to interface with the MSP-
EXP430FR2433 and the MSP-EXP430FR5994 LaunchPads;
• describe key components of a C program;
• specify the size of different variables within the C programming language;
• define the purpose of the main program;
• explain the importance of using functions within a program;
• write functions that pass parameters and return variables;
• describe the function of a header file;
• discuss different programming constructs used for program control and decision process-
ing; and
• write programs in C for execution on the MSP-EXP430FR2433 and the MSP-
EXP430FR5994 LaunchPads.
2.1 OVERVIEW
The goal of this chapter is to provide a tutorial on how to begin programming on the MSP430
microcontroller.1 We begin with an introduction to programming using the Energia integrated
development environment (IDE), followed by an introduction to programming in C. Through-
out the chapter, we provide examples and pointers to several excellent references.
• Download and install the latest version of Energia from the energia.nu website to the
host computer. It is available for different operating systems including: Windows, Mac
OS X, and Linux.
• Launch Energia on the host computer by going to the Energia folder and clicking on the
Energia icon. The icon is a red ball with a rocket silhouette.
• Connect the LaunchPad to the host computer via the USB cable provided with the EVM.
• To compile, upload, and run the program, use the Upload icon (right facing arrow).
With the first program launched, let’s take a closer look at the Energia IDE.
A close-up of the Energia toolbar is provided in Figure 2.2. The toolbar provides sin-
gle button access to the more commonly used menu features. Most of the features are self-
explanatory. The “Upload” button compiles the program and uploads it to the LaunchPad. The
“Serial Monitor” button opens a serial monitor to allow text data to be sent to and received from
the LaunchPad.
Upload Save
Tab features
sketchbook. Similarly, we maintain our programs within a sketchbook in the Energia environ-
ment. Furthermore, we refer to individual programs as sketches. An individual sketch within
the sketchbook may be accessed via the Sketchbook entry under the file tab.
Menu
Energia Environment
Built-in Functions
//**********************************************************
void setup()
{
//place setup code here
}
void loop()
{
//main code steps are provided here
:
:
//**********************************************************
Example: Blink. Let’s examine the sketch used to blink the LED (energia.nu).
//**********************************************************
//Blink---The basic Energia example.
//Turns on an LED on for one second, then off for one second,
//repeatedly. Change the LED define to blink other LEDs.
//Hardware Required: LaunchPad with an LED
//This example code is in the public domain.
//**********************************************************
//**********************************************************
In the first line, the #define statement links the designator “LED” to the pin connected
to the red LED on the LaunchPad. In the setup function, LED is designated as an output pin.
Recall the setup function is only executed once. The program then enters the loop function that is
executed sequentially step-by-step and continuously repeated. In this example, the LED is first
set to logic high to illuminate the LED onboard the LaunchPad. Another 1000 ms delay then
occurs. The LED is then set low. A 1000 ms delay then occurs. The sequence then repeats. As a
second example, comment out the #define statement and remove the comment symbol from in
front of the second #define statement. When the modified code is verified and uploaded to the
EVM, the onboard green LED will blink.
Aside from the Blink example, there are also many program examples available to allow
a user to quickly construct a sketch. They are useful to understand the interaction between the
Energia IDE and the LaunchPad. They may also be used as a starting point to write new ap-
plications. The program examples are available via the File->Examples tab within Energia. The
examples fall within these categories:
1. Basics
2. Digital
3. Analog
4. Communication
5. Control
6. Strings
7. Sensors
28 2. A BRIEF INTRODUCTION TO PROGRAMMING
8. Display
We now examine several more Energia based examples. We use the MSP-
-EXP430FR2433 LaunchPad in the examples. The MSP-EXP430FR5994 LaunchPad may
also be used; however, pin numbers within the examples must be changed from FR2433 pins to
FR5994 pins.
Example: External LED. In this example we connect an external LED to the FR2433 Launch-
Pad pin 18. The onboard green LED will blink alternately with the external LED. The external
LED is connected to the LaunchPad as shown in Figure 2.5 using a prototype board. The board
is useful for implementing the first prototype of a circuit. Holes within a given column of the
board have a common conductor connecting them together. Holes in a row of five are con-
nected via a common conductor. Jumper wires (insulated AWG 22, solid) are used between the
MSP430 female pin connectors and the prototype board.
//**********************************************************
#define int_LED GREEN_LED
#define ext_LED 18
void setup()
{
pinMode(int_LED, OUTPUT);
pinMode(ext_LED, OUTPUT);
}
void loop()
{
digitalWrite(int_LED, HIGH);
digitalWrite(ext_LED, LOW);
delay(500); //delay specified in ms
digitalWrite(int_LED, LOW);
digitalWrite(ext_LED, HIGH);
delay(500);
}
//**********************************************************
2.6. WRITING AN ENERGIA SKETCH 29
(pin 18)
220
external
red LED
(ground: pin 20)
(a) schematic
220
(b) circuit layout
Figure 2.5: LaunchPad with an external LED. (Illustration used with permission of Texas In-
struments (www.ti.com).)
30 2. A BRIEF INTRODUCTION TO PROGRAMMING
Example: External LED and switch. In this example we connect an external LED to LaunchPad
pin 18 and an external switch attached to pin 17. The onboard green LED will blink alternately
with the external LED when the switch is depressed. The external LED and switch are connected
to the LaunchPad, as shown in Figure 2.6.
//**********************************************************
int switch_value;
void setup()
{
pinMode(int_LED, OUTPUT);
pinMode(ext_LED, OUTPUT);
pinMode(ext_sw, INPUT);
}
void loop()
{
switch_value = digitalRead(ext_sw);
if(switch_value == LOW)
{
digitalWrite(int_LED, HIGH);
digitalWrite(ext_LED, LOW);
delay(250);
digitalWrite(int_LED, LOW);
digitalWrite(ext_LED, HIGH);
delay(250);
}
else
{
digitalWrite(int_LED, LOW);
digitalWrite(ext_LED, LOW);
}
}
//**********************************************************
2.6. WRITING AN ENERGIA SKETCH 31
(pin 18)
(pin 17) 220
external
red LED
(ground: pin 20)
3.3 VDC
4.7 K
220
18 20
4.7K
17
Figure 2.6: LaunchPad with an external LED and switch. (Illustration used with permission of
Texas Instruments (www.ti.com).)
32 2. A BRIEF INTRODUCTION TO PROGRAMMING
Example: LED strip. LED strips may be used for motivational (fun) optical displays, games, or
for instrumentation-based applications. In this example we control an LPD8806-based LED
strip using Energia. We use a one meter, 32 RGB LED strip available from Adafruit (#306) for
approximately $30 USD (www.adafruit.com).
The red, blue, and green component of each RGB LED is independently set using
an eight-bit code. The most significant bit (MSB) is logic one followed by seven bits to set
the LED intensity (0–127). The component values are sequentially shifted out of the MSP-
EXP430FR2433 LaunchPad using the serial peripheral interface (SPI) features. The first com-
ponent value shifted out corresponds to the LED nearest the microcontroller. Each shifted
component value is latched to the corresponding R, G, and B component of the LED. As a
new component value is received, the previous value is latched and held constant. An extra byte
is required to latch the final parameter value. A zero byte .00/16 is used to complete the data
sequence and reset back to the first LED (www.adafruit.com).
Only four connections are required between the MSP-EXP430FR2433 LaunchPad and
the LED strip as shown in Figure 2.7. The connections are color coded: red-power, black-
-ground, yellow-data, and green-clock. It is important to note the LED strip requires a supply
of 5 VDC and a current rating of 2 amps per meter of LED strip. In this example we use the
Adafruit #276 5 V 2A (2000 mA) switching power supply (www.adafruit.com).
In this example each RGB component is sent separately to the strip. The example illus-
trates how each variable in the program controls a specific aspect of the LED strip. Here are
some important implementation notes.
• Each LED requires a separate R-G-B intensity component. The order of data is G-R-B.
• After sending data for all LEDs. A byte of (0x00) must be sent to return strip to first LED.
//***********************************************************************
//RGB_led_strip_tutorial: illustrates different variables within
//RGB LED strip
//
//LED strip LDP8806 - available from www.adafruit.com (#306)
//
//Connections:
// - External 5 VDC supply - Adafruit 5 VDC, 2A (#276) - red
// - Ground - black
2.6. WRITING AN ENERGIA SKETCH 33
Ground
to 5 VDC, 2A
power (b) MSP-EXP430FR2433 to LED strip connection [www.adafruit.com].
supply
Figure 2.7: LaunchPad controlling LED strip (www.adafruit.com). (Illustration used with per-
mission of Adafruit (www.adafruit.com).)
34 2. A BRIEF INTRODUCTION TO PROGRAMMING
// - Serial Data In - LaunchPad pin 15 (MOSI pin) P2.6 - yellow
// - CLK - LaunchPad pin 7 (SCK pin) P2.4 - green
//
//Variables:
// - LED_brightness - set intensity from 0 to 127
// - segment_delay - delay between LED RGB segments
// - strip_delay - delay between LED strip update
//
//Notes:
// - SPI must be configured for Most significant bit (MSB) first
// - LED brightness is seven bits. Most significant bit (MSB)
// must be set to logic one
// - Each LED requires a seperate R-G-B intensity component. The order
// of data is G-R-B.
// - After sending data for all strip LEDs. A byte of (0x00) must
// be sent to reutrn strip to first LED.
// - Data stream for each LED is:
//1-G6-G5-G4-G3-G2-G1-G0-1-R6-R5-R4-R3-R2-R1-R0-1-B6-B5-B4-B3-B2-B1-B0
//
//This example code is in the public domain.
//********************************************************************
#include <SPI.h>
void setup()
{
SPI.begin(); //SPI support functions
SPI.setBitOrder(MSBFIRST); //SPI bit order
SPI.setDataMode(SPI_MODE3); //SPI mode
2.6. WRITING AN ENERGIA SKETCH 35
SPI.setClockDivider(SPI_CLOCK_DIV32);//SPI data clock rate
Serial.begin(9600); //serial comm at 9600 bps
}
void loop()
{
SPI.transfer(LED_strip_latch); //reset to first segment
clear_strip(); //all strip LEDs to black
delay(500);
if(troubleshooting)
{
Serial.println(LED_brightness, DEC);
Serial.println(position, DEC);
}
delay(segment_delay);
}
SPI.transfer(LED_strip_latch); //reset to first segment
delay(strip_delay);
if(troubleshooting)
{
Serial.println(" ");
}
}
if(troubleshooting)
{
Serial.println(LED_brightness, DEC);
Serial.println(position, DEC);
}
delay(segment_delay);
}
SPI.transfer(LED_strip_latch); //reset to first segment
delay(strip_delay);
if(troubleshooting)
{
Serial.println(" ");
}
}
if(troubleshooting)
{
2.6. WRITING AN ENERGIA SKETCH 37
Serial.println(LED_brightness, DEC);
Serial.println(position, DEC);
}
delay(segment_delay);
}
SPI.transfer(LED_strip_latch); //reset to first segment
delay(strip_delay);
if(troubleshooting)
{
Serial.println(" ");
}
}
//****************************************************************
void clear_strip(void)
{
//clear strip
for(position = 0; position<strip_length; position = position+1)
{
SPI.transfer(0x80 | 0x00); //Green - none
SPI.transfer(0x80 | 0x00); //Red - none
SPI.transfer(0x80 | 0x00); //Blue - none
if(troubleshooting)
{
Serial.println(LED_brightness, DEC);
Serial.println(position, DEC);
}
}
SPI.transfer(LED_strip_latch); //Latch with zero
if(troubleshooting)
{
Serial.println(" ");
}
38 2. A BRIEF INTRODUCTION TO PROGRAMMING
delay(2000); //clear delay
}
//****************************************************************
Example: Analog In-Analog Out-Serial Out. This example is modified from the example Ana-
log In-Analog Out-Serial Out provided with Energia. It illustrates several Energia built-in
functions.
• Serial.begin(baud_rate): Sets baud rate in bits per second to communicate with the host
computer.
• Serial.print(text): Prints text to Energia serial monitor.
• AnalogRead(analog_channel): Reads the analog value at the designated analog channel
and returns a value from 0 (0 VDC) to 1023 (3.3 VDC).
• map(test_value, input_low, input_high, output_low, output_high): Remaps test_value
from a value between input_low and input_high to a corresponding value between out-
put_low and output_high.
• analogWrite(analogOutPin, outputValue): Sends an output value from 0–255 to desig-
nated analogOutPin.
//****************************************************************
//Analog input, analog output, serial output - Reads an analog input pin,
//maps the result to a range from 0 to 255 and uses the result to set the
//pulsewidth modulation (PWM) of an output pin. The PWM value is sent to
//the red LED pin to modulate its intensity. Also prints the results to
//the serial monitor. Open a serial monitor using the serial monitor
//button in Energia to view the results.
//
//
//The circuit:
// - Potentiometer connected to analog pin 0 (2). The center wiper
// pin of the potentiometer goes to the analog pin. The side pins of
// the potentiometer go to +3.3 VDC and ground. Place a small value
// resistor is series with the potentiometer
// - The analog output is designated as the onboard red LED.
//
//Created: Dec 29, 2008
//Modified: Aug 30, 2011
//Author: Tom Igoe
2.6. WRITING AN ENERGIA SKETCH 39
//This example code is in the public domain.
//****************************************************************
void setup()
{
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop()
{
//read the analog in value:
sensorValue = analogRead(analogInPin);
//****************************************************************
40 2. A BRIEF INTRODUCTION TO PROGRAMMING
Example: Mini round autonomous maze navigating robot. In this example, an autonomous,
maze navigating robot is equipped with infrared (IR) sensors to detect the presence of maze walls
and navigate about the maze. The robot has no prior knowledge about the maze configuration.
It uses the IR sensors and an onboard algorithm to determine the robot’s next move. The overall
goal is to navigate from the starting point of the maze to the end point as quickly as possible
without bumping into maze walls as shown in Figure 2.8. Maze walls are usually painted white
to provide a good, light reflective surface, whereas the maze floor is painted matte black to
minimize light reflections. Alternatively, a low-cost, table-top maze may be assembled from
white foam board.
Finish
Start
Before delving into the robot design, it would be helpful to review the fundamentals of
robot steering and motor control. Figure 2.9 illustrates the fundamental concepts. Robot steering
is dependent upon the number of powered wheels and whether the wheels are equipped with
unidirectional or bidirectional control. Additional robot steering configurations are possible. An
H-bridge is typically required for bidirectional control of a DC motor. We discuss the H-bridge
in greater detail in an upcoming chapter.
In this application project, we equip the Adafruit mini round robot (#3216) for control
by the LaunchPad as a maze navigating robot. Reference Figure 2.11. The robot is controlled by
two 6.0 VDC motors which independently drive a left and right wheel. A third non-powered
drag ball provides tripod stability for the robot.
We equip the mini round robot platform with three Sharp GP2Y0A21YKOF IR sensors
as shown in Figure 2.12. The sensors are available from SparkFun Electronics (www.sparkfun
.com). We mount the sensors on a bracket constructed from thin aluminum. Dimensions for
the bracket are provided in the figure. Alternatively, the IR sensors may be mounted to the
2.6. WRITING AN ENERGIA SKETCH 41
Pivot
Point Pivot
Point
(a) two-wheel, forward motor control (b) two-wheel, bi-directional motor control
Pivot
Point
Pivot
Point
(c) two-wheel, forward motor control, (d) two-wheel, forward motor control,
front-wheel drive rear-wheel drive
Pivot
Point
robot platform using “L” brackets available from a local hardware store. The characteristics of
the sensor are provided in Figure 2.10.
The circuit diagram for the robot is provided in Figure 2.13. The three IR sensors (left,
middle, and right) are mounted on the leading edge of the robot to detect maze walls. The output
from the sensors is fed to three ADC channels (analog in 0-2). The robot motors will be driven
by PWM channels (PWM: digital I/O 3 and PWM: digital I/O 4).
2.6. WRITING AN ENERGIA SKETCH 43
Sharp
IR Sensor
Bottom Platform
Mini Round Robot
6”
1-7/16”
Figure 2.12: Mini round robot platform modified with three IR sensors.
44 2. A BRIEF INTRODUCTION TO PROGRAMMING
To save on battery expense, a 9 VDC, 2A rated inexpensive, wall-mount power supply is
used to provide power to the robot. A power umbilical of flexible, braided wire may be used to
link the power supply to the robot while navigating about the maze. The robot motors are rated
at 6.0 VDC. Therefore, four 1N4001 diodes are placed in series with the motor to reduce the
supply voltage to be approximately 6.2 VDC. The LaunchPad is interfaced to the motors via
a Darlington NPN transistor (TIP120) with enough drive capability to handle the maximum
current requirements of the motor. A 3.3 VDC voltage regulator is used to supply power to the
LaunchPad.
Warning: It is important not to have the LaunchPad connected to the host computer
via the USB cable and an external 3.3 VDC supply at the same time. It is recommended to
download the program to the LaunchPad, disconnect the USB cable, remove the 3.3 VDC
header jumper on the Jumper Isolation Block, and then connect the 3.3 VDC external supply
to the J6 connector. Alternatively, a double-throw double-pole (DPDT) switch may be used, as
shown in Figure 2.13.
Sensor connection:
- Red: 5 VDC
- Yellow: Signal output
- Black: Ground IR sensor IR sensor IR sensor
left middle right
5 VDC 5 VDC 5 VDC 9 VDC
9 VDC
voltage 1N4001
1N4001 dropping 1N4001
diodes
1N4001
Note: 3.3 VDC +
1N4001 + 1N4001
jumper removed
protection
M 6.0 VDC from MSP430 M 6.0 VDC
diode
Program
- -
DPDT
switch
TIP120 330 330 TIP120 motor
NPN Run NPN
(4) current
Darlington Darlington
left motor/wheel right motor/wheel
interface interface
7805
9 VDC power umbilical
3.3VDC
reg
5.0 VDC
5 VDC 5 VDC 5 VDC 5 VDC 5 VDC
LM1084-3.3
3.3VDC
reg 3.3 VDC 220 220 220 220 220
left turn wall wall wall right turn
9VDC signal left center right signal
2A
(#276) 10 K 10 K 10 K 10 K 10 K
2N2222 2N2222 2N2222 2N2222 2N2222
(5) (6) (7) (8) (9)
Figure 2.13: Robot circuit diagram. (Illustration used with permission of Texas Instruments
(www.ti.com).)
Left Middle Right Wall Wall Wall Left Right Left Right
Comments
Sensor Sensor Sensor Left Middle Right Motor Motor Signal Signal
0 0 0 0 0 0 0 1 1 0 0 Forward
1 0 0 1 0 0 1 1 1 0 0 Forward
2 0 1 0 0 1 0 1 0 0 1 Right
3 0 1 1 0 1 1 0 1 1 0 Left
4 1 0 0 1 0 0 1 1 0 0 Forward
5 1 0 1 1 0 1 1 1 0 0 Forward
6 1 1 0 1 1 0 1 0 0 1 Right
7 1 1 1 1 1 1 1 0 0 1 Right
//***********************************************************************
//robot
//
////This example code is in the public domain.
//***********************************************************************
//analog input pins
#define left_IR_sensor 2 //analog pin - left IR sensor
#define center_IR_sensor 19 //analog pin - center IR sensor
#define right_IR_sensor 10 //analog pin - right IR sensor
//motor outputs
#define left_motor 3 //digital pin - left_motor
#define right_motor 4 //digital pin - right_motor
void loop()
{
//read analog output from IR sensors
left_IR_sensor_value = analogRead(left_IR_sensor);
center_IR_sensor_value = analogRead(center_IR_sensor);
right_IR_sensor_value = analogRead(right_IR_sensor);
Testing the control algorithm: It is recommended that the algorithm be first tested without the
entire robot platform. This may be accomplished by connecting the three IR sensors and LEDS
to the appropriate pins on the LaunchPad as specified in Figure 2.13. In place of the two motors
and their interface circuits, two LEDs with the required interface circuitry may be used. The
LEDs illuminate to indicate motor assertion. Once the algorithm is fully tested in this fashion,
the LaunchPad may be mounted to the robot platform and connected to the motors. Full up
testing in the maze may commence. Enjoy!
2.8 PROGRAMMING IN C
Most microcontrollers are programmed with some variant of the C programming language.
The C programming language provides a nice balance between the programmer’s control of the
microcontroller hardware and time efficiency in programming writing.
As you can see in Figure 2.15, the compiler software is hosted on a computer separate from
the LaunchPad. The job of the compiler is to transform the program provided by the program
writer (filename.c and filename.h) into machine code suitable for loading into the processor.
Once the source files (filename.c and filename.h) are provided to the compiler, the com-
piler executes two steps to render the machine code. The first step is the compilation process.
Here the program source files are transformed into assembly code (filename.asm). If the pro-
gram source files contain syntax errors, the compiler reports these to the user. Syntax errors are
reported for incorrect use of the C programming language. An assembly language program is
not generated until the syntax errors have been corrected. The assembly language source file is
then passed to the assembler. The assembler transforms the assembly language source file to
machine code suitable for loading to the LaunchPad.
54 2. A BRIEF INTRODUCTION TO PROGRAMMING
C compiler
filename.c compiler
filename.h
computer filename.asm
assembler
Arduino Development
Environment filename.hex
or filename.eep
C compiler
USB
Figure 2.15: Programming the LaunchPad. (Illustration used with permission of Texas Instru-
ments (www.ti.com).)
2.9. ANATOMY OF A PROGRAM 55
During the compilation process, warnings may also be generated. Warnings do not pre-
vent the creation of an assembly language version of the C program. However, they should be
resolved since flagged incorrect usage of the C language may result in unexpected program run
time errors.
As seen earlier in the chapter, the Energia Integrated Development Environment pro-
vides a user-friendly interface to aid in program development, transformation to machine code,
and loading into the LaunchPad. As described in Chapter 1, the LaunchPad may also be pro-
grammed using Code Composer Studio, Keil and IAR Systems software. We use Code Com-
poser Studio throughout the book.
For the remaining portion of the chapter we present a brief introduction to C. Many
examples are provided. We encourage the reader to modify, load, and run the examples on the
LaunchPad.
In the next section, we will discuss the components of a C program.
//include file(s)
#include<file_name.h>
//function prototypes
A list of functions and their format used within the program
//program constants
#define TRUE 1
#define FALSE 0
#define ON 1
#define OFF 0
56 2. A BRIEF INTRODUCTION TO PROGRAMMING
//interrupt handler definitions
Used to link the software to hardware interrupt features
//global variables
Listing of variables used throughout the program
//main program
void main(void)
{
//*************************************************************
//function definitions: A detailed function body and definition
//for each function used within the program. For larger
//programs, function definitions may be placed in accompanying
//header files.
//*************************************************************
2.9.1 COMMENTS
Comments are used throughout the program to document what and how things were accom-
plished within a program. The comments help you and others to reconstruct your work at a
later time. Imagine that you wrote a program a year ago for a project. You now want to modify
that program for a new project. The comments will help you remember the key details of the
program.
Comments are not compiled into machine code for loading into the microcontroller.
Therefore, the comments will not fill up the memory of your microcontroller. Comments are
indicated using double slashes (==). Anything from the double slashes to the end of a line is
then considered a comment. A multi-line comment is constructed using a = at the beginning
of the comment and a = at the end of the comment. These are handy to block out portions of
code during troubleshooting or providing multi-line comments.
At the beginning of the program, comments may be extensive. Comments may include
some of the following information:
• file name,
2.9. ANATOMY OF A PROGRAM 57
• program author and dates of creation,
• revision history or a listing of the key changes made to the program,
• compiler setting information,
• hardware connection description to microcontroller pins, and
• program description.
2.9.3 FUNCTIONS
Later in the book we discuss in detail the top-down design, bottom-up implementation approach
to designing microcontroller-based systems. In this approach, a project including both hardware
and software is partitioned into systems, subsystems, etc. The idea is to take a complex project
and break it into smaller, doable pieces with a defined action.
We use the same approach when writing computer programs. At the highest level is the
main program which calls functions that have a defined action. When a function is called, pro-
gram control is released from the main program to the function. Once the function is complete,
program control returns to the main program.
Functions may in turn call other functions as shown in Figure 2.16. This approach results in
a collection of functions that may be reused in various projects. Most importantly, the program is
now subdivided into doable pieces, each with a defined action. This makes writing the program
easier but also makes it convenient to modify the program since every action is in a known
location.
There are three different pieces of code required to properly configure and call a function:
58 2. A BRIEF INTRODUCTION TO PROGRAMMING
void main(void)
{
• function prototype,
• function call, and
• function body.
Function prototypes are provided early in the program as previously shown in the pro-
gram template. The function prototype provides the name of the function and any variables
required and returned by the function.
The function prototype follows this format:
return_variable function_name(required_variable1, required_variable2);
If the function does not require variables or sends back a variable the word “void” is placed
in the variable’s position.
The function call is the code statement used within a program to execute the function. The
function call consists of the function name and the actual arguments required by the function.
If the function does not require arguments to be delivered to it for processing, the parenthesis
containing the variable list is left empty.
The function call follows this format:
function_name(required_variable1, required_variable2);
//return variable
return return_variable;
}
– 00x: input
– 010: input with pull-down resistor
– 011: input with pull-up resistor
– 1xx: output
• Output Drive Strength Selection Registers (PxDS): The value of the register determines
the drive strength for specific pins (1: high drive strength, 0: regular drive strength).
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop watchdog timer
//***********************************************************************
2.9. ANATOMY OF A PROGRAM 63
The code example begins with the inclusion of the msp430.h header file. The Watchdog
timer that is normally on is then turned off. This is typically done during code development. The
next three statements are a shorthand method of accomplishing the following:
P1OUT = P1OUT & ~BIT0; //Clear P1.0 output latch for a
//defined power-on state
P1DIR = P1DIR | BIT0; //Set P1.0 to output direction
BIT0 is defined in the MSP430.h header files as 0x0001. The P1OUT register is used to set
PORT P1, pin 0 initially to logic 0. The P1DIR register is used to configure PORT P1, pin 0 to
output. The Power Mode 5 Control Register 0 is then used to disable the general-purpose I/O
power-on default configuration. LOCKLPM5 is defined as 0x0001 in the MSP430.h header
file. The program then enters an infinite loop where PORT 1, pin 0 is toggled every 0.1 s.
2.9.7 VARIABLES
There are two types of variables used within a program: global variables and local variables. A
global variable is available and accessible to all portions of the program, whereas a local variable
is only known and accessible within the function where it is declared.
64 2. A BRIEF INTRODUCTION TO PROGRAMMING
When declaring a variable in C, the number of bits used to store the variable is also
specified. Variable specifications may vary by compiler. For code portability among different
platforms fixed formats may be used.
Fixed format variables are defined within the “stdint.h” header file [stdint.h]. Provided
below is a small extract from this header file.
//*****************************************************************
//*****************************************************************
When programming microcontrollers, it is important to know the number of bits and the
memory location used to store the variable. For example, assigning the contents of an unsigned
char variable, which is stored in 8-bits, to an 8-bit output port will have a predictable result.
2.9. ANATOMY OF A PROGRAM 65
However, assigning an unsigned int variable, which is stored in 16-bits, to an 8-bit output port
does not provide predictable results. It is wise to ensure your assignment statements are balanced
for accurate and predictable results. The modifier “unsigned” indicates all bits will be used to
specify the magnitude of the argument. Signed variables will use the left most bit to indicate the
polarity (˙) of the argument.
Variables may be read (scanned) into a program using the “scanf ” statement. The general
format of the scanf statement is provided below. The format of the variable and the variable
name are specified. Similarly, the variables may be printed using the “printf ” statement. The
backslash n specifies start a new line.
//*******************************************************************
#include<stdio.h>
int main( )
{
int input_variable;
scanf("
printf("
//*******************************************************************
A global variable is declared using the following format provided below. The type of the
variable is specified, followed by its name, and an initial value if desired.
//*******************************************************************
//global variables
unsigned int loop_iterations = 6;
//*******************************************************************
2.10.1 OPERATORS
There are a wide variety of operators provided in the C language. An abbreviated list of common
operators is provided in Figures 2.18 and 2.19. The operators have been grouped by general cat-
egory. The symbol, precedence, and brief description of each operator are provided. The prece-
dence column indicates the priority of the operator in a program statement containing multiple
operators. Only the fundamental operators are provided.
General Operations
Within the general operations category are brackets, parenthesis, and the assignment operator.
We have seen in an earlier example how bracket pairs are used to indicate the beginning and
end of the main program or a function. They are also used to group statements in programming
constructs and decision processing constructs. This is discussed in the next several sections.
The parenthesis is used to boost the priority of an operator. For example, in the mathemat-
ical expression 7 3 C 10, the multiplication operation is performed before the addition since
it has a higher precedence. Parenthesis may be used to boost the precedence of the addition op-
eration. If we contain the addition operation within parenthesis 7 .3 C 10/, the addition will
be performed before the multiplication operation and yield a different result from the earlier
expression.
The assignment operator (D) is used to assign the argument(s) on the right-hand side of
an equation to the left-hand side variable. It is important to insure that the left- and the right-
-hand side of the equation have the same type of arguments. If not, unpredictable results may
occur.
Arithmetic Operations
The arithmetic operations provide for basic math operations using the various variables described
in the previous section. As described in the previous section, the assignment operator (D) is used
to assign the argument(s) on the right-hand side of an equation to the left-hand side variable.
In this example, a function returns the sum of two unsigned int variables passed to the
function.
2.10. FUNDAMENTAL PROGRAMMING CONCEPTS 67
General
Symbol Precedence Description
{} 1 Brackets, used to group program statements
() 1 Parenthesis, used to establish precedence
= 12 Assignment
Arithmetic Operations
Symbol Precedence Description
* 3 Multiplication
/ 3 Division
+ 4 Addition
- 4 Subtraction
Logical Operations
Symbol Precedence Description
< 6 Less than
<= 6 Less than or equal to
> 6 Greater
>= 6 Greater than or equal to
== 7 Equal to
!= 7 Not equal to
&& 9 Logical AND
|| 10 Logical OR
Unary Operations
Symbol Precedence Description
! 2 Unary negative
~ 2 One’s complement (bit-by-bit inversion)
++ 2 Increment
__ 2 Decrement
Type(argument) 2 Casting operator (data type conversion)
Figure 2.19: C operators (continued) (adapted from Barrett and Pack [2005]).
//*******************************************************************
return sum;
}
//*******************************************************************
Logical Operations
The logical operators provide Boolean logic operations. They can be viewed as comparison oper-
ators. One argument is compared against another using the logical operator provided. The result
is returned as a logic value of one (1, true, high) or zero (0 false, low). The logical operators are
2.10. FUNDAMENTAL PROGRAMMING CONCEPTS 69
used extensively in program constructs and decision processing operations to be discussed in the
next several sections.
//*******************************************************************
Answer: Variable “variable1” is declared as an 8-bit unsigned char and assigned the hex-
adecimal value of .73/16 . In binary, this is .0111_0011/2 . The << 2 operator provides a left
shift of the argument by two places. After two left shifts of .73/16 , the result is .cc/16 and will
be assigned to the variable “variable2.” Note that the left and right shift operation is equivalent
to multiplying and dividing the variable by a power of two.
The bitwise operators perform the desired operation on a bit-by-bit basis. That is, the
least significant bit (LSB) of the first argument is bit-wise operated with the LSB of the second
argument and so on.
Given the following code segment, what will the value of variable3 be after execution?
//*******************************************************************
//*******************************************************************
Answer: Variable “variable1” is declared as an eight bit unsigned char and assigned the
hexadecimal value of .73/16 . In binary, this is .0111_0011/2 . Variable “variable2” is declared
as an 8-bit unsigned char and assigned the hexadecimal value of .f a/16 . In binary, this is
.1111_1010/2 . The bitwise AND operator is specified. After execution variable “variable3,” de-
clared as an 8-bit unsigned char, contains the hexadecimal value of .72/16 .
70 2. A BRIEF INTRODUCTION TO PROGRAMMING
Unary Operations
The unary operators, as their name implies, require only a single argument. For example, in the
following code segment, the value of the variable “i” is incremented. This is a shorthand method
of executing the operation “i D i C 1;”
//*******************************************************************
unsigned int i;
i++;
//*******************************************************************
Bit Twiddling
It is not uncommon in embedded system design projects to have every pin on a microcontroller
employed. Furthermore, it is not uncommon to have multiple inputs and outputs assigned to
the same port but on different port I/O pins. Some compilers support specific pin reference.
Another technique that is not compiler specific is bit twiddling. Figure 2.20 provides bit twid-
dling examples on how individual bits may be manipulated without affecting other bits using
bitwise and unary operators. The information provided here was extracted from the ImageCraft
ICC AVR compiler documentation [ImageCraft].
a&b bitwise and if ((P2IN & 0x81) == 0) // check bit 7 and bit 0
//*******************************************************************
The for loop begins with the variable “loop_ctr” equal to 0. During the first pass through
the loop, the variable retains this value. During the next pass through the loop, the variable
“loop_ctr” is incremented by one. This action continues until the “loop_ctr” variable reaches
the value of ten. Since the argument to continue the loop is no longer true, program execution
continues with the next instruction after the close bracket of the for loop.
In the previous example, the for loop counter was incremented by one. The “loop_ctr” vari-
able can be updated by any amount. For example, in the following code fragment the “loop_ctr”
variable is increased by three for every pass of the loop.
//*******************************************************************
//*******************************************************************
72 2. A BRIEF INTRODUCTION TO PROGRAMMING
The “loop_ctr” variable may also be initialized at a high value and then decremented at
the beginning of each pass of the loop as shown below.
//*******************************************************************
//*******************************************************************
As before, the “loop_ctr” variable may be decreased by any numerical value as appropriate
for the application at hand.
The while loop is another programming construct that allows multiple passes through a
portion of code. The while loop will continue to execute the statements within the open and
close brackets while the condition at the beginning of the loop remains logically true. The code
snapshot below will implement a ten iteration loop. Note how the “loop_ctr” variable is initial-
ized outside of the loop and incremented within the body of the loop. As before, the variable
may be initialized to a greater value and then decremented within the loop body.
//*******************************************************************
loop_ctr = 0;
while(loop_ctr < 10)
{
//loop body
loop_ctr++;
}
//*******************************************************************
Frequently, within a microcontroller application, the program begins with system initial-
ization actions. Once initialization activities are completed, the processor enters a continuous
loop. This may be accomplished using the following code fragment.
2.10. FUNDAMENTAL PROGRAMMING CONCEPTS 73
//*******************************************************************
while(1)
{
//*******************************************************************
#include <msp430.h>
void main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop watchdog timer
//***********************************************************************
The switch statement is used when multiple if-else conditions exist. Each possible condi-
tion is specified by a case statement. When a match is found between the switch variable and a
specific case entry, the statements associated with the case are executed until a break statement
is encountered. When a case match is not found, the default case is executed. Provided below is
a template for the switch statement.
//***********************************************************************
switch (switch_variable)
{
case 1: code steps associated with case 1;
:
:
break;
:
:
:
//***********************************************************************
An example using the switch statement is provided later in the text. That completes our
brief overview of Energia and the C programming language.
• Create a new project by clicking File->New->CCS Project and entering a project name.
• Set the Device Family to MSP430 and select the device variant to use (for example,
MSP430FR2433).
• Select “Blink The LED” in the “Project templates and example” section and then click
Finish.
• Compile the code and download the application to the target device by clicking Run-
>Debug (F11).
• To run the application, click Run->Resume (F8) or click the Play button on the toolbar.
Procedure 1: Energia.
1. Create a counter that counts continuously from 1–100 and repeats with a 50 ms delay
between counts. The onboard red LED should illuminate for odd numbers and the onboard
green LED for even numbers.
2. Modify the code produced for the previous step to illuminate the green LED when the
number is evenly divisible by three and the red LED for the other numbers.
2.12. SUMMARY 77
Procedure 2: C.
1. Develop a program that prompts the user for two integer numbers. If the first number is
less than the second, the program should count-up continuously from the lower to the
higher number with a 50 ms delay between counts. The onboard red LED should illumi-
nate for odd numbers and the onboard green LED for even numbers. If the first number
is higher than the second, the program should count down continuously from the lower
to the higher number with a 50 ms delay between counts. The onboard red LED should
illuminate for odd numbers and the onboard green LED for even numbers.
2. Develop a program that prompts the user for an integer number. If the number is evenly
divisible by 2 the red LED illuminates, evenly divisible by three the green LED, and for
other numbers no LEDs illuminate. Note: More than one LED may illuminate depending
on the number provided.
2.12 SUMMARY
The goal of this chapter was to provide a tutorial on how to begin programming. We began with
a discussion on the Energia Development Environment and how it may be used to develop a
program for the MSP430 LaunchPads. For C, we used a top-down design approach. We began
with the “big picture” of the program of interest followed by an overview of the major pieces
of the program. We then discussed the basics of the C programming language. Only the most
fundamental concepts were covered. Throughout the chapter, we provided examples and several
excellent references.
Barrett, S. F. Embedded Systems Design with the Atmel AVR Microcontroller, Morgan & Claypool
Publishers, San Rafael, CA, 2010. DOI: 10.2200/s00225ed1v01y200910dcs025.
Barrett, S. F. and Pack, D. J. Embedded Systems Design and Applications with the 68HC12 and
HCS12, Pearson Prentice Hall, 2005. 67, 68
Barrett, S. F. and Pack, D. J. Microcontrollers Fundamentals for Engineers and Scientists, Morgan
& Claypool Publishers, San Rafael, CA, 2006. DOI: 10.2200/s00025ed1v01y200605dcs001.
78 2. A BRIEF INTRODUCTION TO PROGRAMMING
Code Composer Studio v7.x for MSP430 User’s Guide, (SLAU157AP), Texas Instruments, 2017.
76
Energia. www.energia.nu
ImageCraft Embedded Systems C Development Tools, Palo Alto, CA. www.imagecraft.com
70
Advanced
1. Provide the C program statement to set PORT 1 pins 1 and 7 to logic one. Use bit-
twiddling techniques.
2. Provide the C program statement to reset PORT 1 pins 1 and 7 to logic zero. Use bit-
twiddling techniques.
3. Using a MSP430 LaunchPad, write a program in Energia that takes an integer input from
the user. If negative, the red LED is illuminated. If positive, the green LED is illuminated.
4. Repeat the program above using C.
2.14. CHAPTER PROBLEMS 79
Challenging
1. Create a counter that counts continuously from 1–100 an repeats with a 50 ms delay be-
tween counts. The onboard red LED should illuminate for odd numbers and the onboard
green LED for even numbers.
2. Develop a program that prompts the user for two integer numbers. If the first number is
less than the second, the program should count-up continuously from the lower to the
higher number with a 50 ms delay between counts. The onboard red LED should illumi-
nate for odd numbers and the onboard green LED for even numbers. If the first number
is greater than the second, the program should count down continuously from the lower
to the higher number with a 50 ms delay between counts. The onboard red LED should
illuminate for odd numbers and the onboard green LED for even numbers.
81
CHAPTER 3
• explain advantages and disadvantages of using a high-level programming language and the
MSP430 assembly programming language;
• program the MSP430 controller for simple applications using both C and assembly lan-
guage programs; and
In this chapter, we present fundamental materials to understand the software and hard-
ware systems of the MSP430 microcontroller. Mastering the contents of this chapter is critical in
proceeding with the contents in the rest of this book, as they will serve as foundational MSP430
knowledge. Before getting into the specific hardware and software environments of the MSP430
microcontroller, the overall hardware and software organizations of a typical RISC (Reduced
Instruction Set Computer) based microcontroller is presented, followed by the MSP430 specific
hardware and software environments. The objectives of this chapter are to provide readers with
a solid understanding of basic hardware and software concepts required to design, develop, and
evaluate embedded systems using the MSP430 microcontroller.
3.1 MOTIVATION
The MSP430 microcontroller was designed for applications requiring ULP consumption, typi-
cally found in portable, battery-operated embedded systems applications. The MSP430 is cur-
rently used in a wide range of products, including medical diagnostic equipment, smart power
82 3. HARDWARE ORGANIZATION AND SOFTWARE PROGRAMMING
systems, security and fire monitoring sensors, alarm systems, power tools, and a host of con-
sumer products. It is expected that the MSP430 will continue to grow its market share in smart
homes and personal health monitoring applications.
Figure 3.1: MSP430FR2433 and the MSP430FR5994 block diagrams [SLASE59D, 2018,
SLASE54C, 2018]. Illustrations used with permission of Texas Instruments (www.ti.com).
84 3. HARDWARE ORGANIZATION AND SOFTWARE PROGRAMMING
most basic multiplication operations, requiring excessive execution time. The MSP430 provides
the MPY32 hardware-based multiplier to reduce the multiplication operation time. Typically,
hardware-based solutions are much faster than their software-based counterparts.
Moving to the right in the figure, the two remaining modules on the first row, show
general-purpose I/O port subsystems of the controller. The ports provide the controller access
and interface to a wide variety of peripheral components.
On the second row, the purpose of embedded emulator module (EEM) is to assist system
developers in providing access to program execution during a debugging process. This is espe-
cially helpful during program development and troubleshooting. The built-in emulator allows
us to view memory contents and insert break points. The JTAG module is used to interface the
controller with a desktop or laptop computer for loading programs and debugging programs
using the EEM during program execution. Finally, the CPU in the center of the figure contains
the arithmetic and logical unit (ALU), the CPU registers, and a Control subunit responsible for
performing program branching and data transfer.
The system Watchdog module (WDT) is responsible for keeping the microcontroller
operating properly and taking appropriate actions when abnormal activities are detected. The
WDT is a timer that, if expired, results in a processor reset. It is used to reset the processor
when a software malfunction has occurred. During normal program processing the WDT is
reset by specific program steps. Should a software malfunction occur and the WDT timer is not
reset, the WDT will timeout and result in a processor reset. In response to the processor reset,
the software malfunction may clear.
The CRC16 subsystem is responsible for the cyclical redundancy check (using 16 bits).
Cyclical redundancy checks are used to validate error-free communications among digital sys-
tems. Each time a transmitter sends a set of data to a receiver, it sends an additional value derived
from the original data called a “key.” The receiver, having received the data being sent, uses the
original data to perform the same computation to generate the key value. By comparing the
generated value with the one received, the receiver can quickly verify whether or not the original
data it received are valid.
The timer blocks represent timer-related I/O port systems. The timers are I/O systems
where external signals can be captured to measure time-related parameters such as signal fre-
quency, period, and duty cycle, and output signals intended for an external world with specific
time-related parameters are generated. In other microcontroller manufacturers, these ports are
referred to as input capture and output compare timer ports. The timer port module may also
contain channels to generate a variety of PWM output signals. A PWM signal may be used to
control the speed of a motor, the light intensity of an LED, or control various peripheral devices.
The next several modules contain the serial communication subsystem that allows the
MSP430 microcontroller to interface with external devices using the serial peripheral inter-
face (SPI), universal asynchronous receiver-transmitter (UART), and the inter-integrated circuit
(I2C) protocols.
3.3. HARDWARE SUBSYSTEMS 85
As shown in Figure 3.1b, the MSP430FR5994 has similar features and layout to the
MSP430FR2433. In addition, the MSP430FR5994 hosts the additional subsystems.
• The DMA controller shown on the left edge of the figure is responsible for accessing
memory by all subsystems of the controller. DMA provides the capability to move data
from memory location to memory location without involving the central processing unit.
This is especially useful for low power operation when moving data from peripherals to
specific memory locations [SLAU367O, 2017].
• The reference module (REF) is responsible for generating voltages required by all periph-
eral subsystems of the MSP430, including the analog-to-digital converter.
• Advanced encryption standard (AES) accelerator. The accelerator speeds up the encryp-
tion and decryption of data by one to two orders of magnitude over a software-based
implementation. It can be used for 128- or 256-bit encryption.
(3000)16
Random Access (01000)16
Memory (RAM) (2000)16 (2FFF)16 (4096)10 ~ 4K bytes
(2000)16
Information Memory (00200)16
(FRAM) (1800)16 (19FF)16 (512)10 bytes
(1800)16
Bootstrap Loader (0800)16
(1000)16 (17FF)16
Segment 1 (2048)10 ~ 2K bytes
(1000)16
(1000)16
Peripherals (0000)16 (0FFF)16 (4096)10 ~ 4K bytes
(0000)16
saving, and error correction coding. The RAM controller is used to power down in a power
saving mode, and the DMA controller is used to transfer contents of memory locations to other
memory locations without the intervention of a controller.
19 16 15 0
R0/PC Program Counter 0
R4 General Purpose
R5 General Purpose
R6 General Purpose
R7 General Purpose
R8 General Purpose
R9 General Purpose
Figure 3.5: MSP430 CPU block diagram [SLAU208Q, 2018]. Illustration used with permission
of Texas Instruments (www.ti.com).
3.4. CPU PROGRAMMING MODEL/REGISTER DESCRIPTIONS 95
of CPU registers which collectively contain pertinent information about the operational status of
the computer. For example, a programming model contains a status register that shows whether
the most recently executed instruction resulted in a negative number, a positive number, or a
zero. It shows which instruction is on queue to be executed next via the program counter (PC)
and the next available location on the stack via the stack pointer (SP).
A stack is a designated portion of RAM memory which is used to store data temporarily
during program execution. It is a first-in-last-out data structure, similar to the spring-loaded
plate holder one finds in a buffet restaurant. The first plate placed in the plate holder is the last
one used by customers. To keep track of the size of a stack, the top of the stack (either the next
available memory location to be used by the stack or the last memory location used by the stack
depending on the computer architecture) is always identified by a special register called the SP.
A programming model also includes the PC, which contains the address of the instruction to
be executed next.
The programming model for MSP430 is shown in Figure 3.6. As shown, the MSP430
microcontroller has four special and 12 general-purpose CPU registers that make up its pro-
gramming model. Registers are 16 or 20 bits wide. The first special register, R0, is the PC
register. This register contains the address of the next instruction to be executed by CPU. Since
all instructions are aligned and start at even addresses, the LSB of R0 is hardwired to zero. The
value of PC is incremented by two each time an instruction is executed to update the address of
the instruction to be executed next.
The second special register, R1, is the SP register, which contains the address of the top
of the stack. Since data is “pushed” onto the stack and “pulled” off the stack using only one end
of the stack, the top of the stack must be monitored always. The top of the stack contains the
address of the most recently added word to the stack. Again, the MSP430 always puts (pushes)
and pulls data onto and from the stack one word (16 bits) at a time, which allows the designer
of the MSP430 to hardwire the LSB of SP to zero.
The R2 register contains the current status of the computer operation. Figure 3.7 shows
the contents of the Status Register R2. The MSP430 status is shown as a series of status bits.
Most of the flag definitions are quite straightforward. The definition of the V bit is a bit more
involved.
The V bit represents overflow from the execution of the previous instruction. An overflow
occurs when the result of a signed number operation is incorrect due to the available, limited
space of a register to correctly hold the result. When this bit is set, an overflow occurred, and
when it is cleared, no overflow occurred. There are several different situations that result in an
overflow condition (adapted from Hamann [2017], Miller [1995], Mano [2002], and CPU12
[1997]).
• In an unsigned addition operation, an overflow occurs when there is a carry out of the
MSB after an addition operation.
• In an unsigned subtraction operation, an overflow occurs if the MSB requires a borrow.
96 3. HARDWARE ORGANIZATION AND SOFTWARE PROGRAMMING
R0 15 0 Program Counter
R1 15 0 Stack Pointer
R2 15 0 Status Register
R3 15 0 Constant Generator
R4 15 0
R15 15 0
Instruction Register
Programming Model
OSC CPU
Reserved V SCG1 SCG0 GIE N Z C
OFF OFF
15 ....... 9 8 7 6 5 4 3 2 1 0
Status Register R2
• Active mode. During normal operation in the active mode, all four bits should be cleared
(CPUOFF = 0, OSCOff = 0, SCG0 = 0, and SCG1 = 0), which allows all CPU clocks to
become active.
• LPM0. When only the CPUOFF bit is set, called low-power mode 0 (LPM0), the CPU
and the master clock (MCLK) are turned off and only the subsystem clock (SMCLK) and
auxiliary clock (ACLK) operate. The controller can be awakened by enabled interrupts,
special requests generated internally or externally (to be studied in Chapter 6.11).
• LPM1. Low-power mode 1 (LPM1) is similar to LPM0 with CPUOFF and SCG0 bits
set while the other two bits are cleared. In this mode, the CPU, MCLK, SMCLK, and
ACLK are configured the same as in LPM0. The digitally controlled oscillator (DCO) is
turned on/off based on the use of the DCO by the SMCLK.
• LPM 2. The MSP430 operates in the low-power mode 2 (LPM2) when both SCG0 and
OSCOFF bits are cleared and the SCG1 and CPUOFF bits are set. In this mode, the
CPU, MCLK, and SMCLK are turned off as well as the DCO. The dc-generator of the
DCO remains active along with the ACLK.
• LPM 3. When the CPUOFF, SCG0, and SCG1 bits are set and the OSCOFF bit is
cleared, the MSP430 is operating in the LPM3 operating mode; all clocks and the DCO
and CPU are turned off. Only the ACLK is enabled.
3.5. OPERATING MODES 99
• LPM 3.5. When all of bits are set (CPUOFF, OSCOff, SCG0, and SCG1) and the
PMMREGOFF is set (Regulator off bit in the Power Management Module Control Reg-
ister 0), the MSP430 is operating in LPM3.5. In this LPM the voltage regulator in the
Power Management Module is disabled. The RAM and register contents are lost but RTC
operation is possible.
• LPM 4. When all of bits are set (CPUOFF, OSCOff, SCG0, and SCG1), the MSP430
is operating in LPM4; the CPU, all clocks, the DCO, and the crystal oscillator are turned
off. The controller is wakened up by an enabled interrupt.
• LPM 4.5. In low-power mode 4.5 (LPM4.5), the MSP430 achieves the lowest power
consumption. In this mode, in addition to the CPU, MCLK, SMCLK, and the DCO
being turned off, the regulator for the PMM is also turned off. This results in turning off
the JTAG and EEM logic devices. These operating modes will be discussed in depth in
Chapter 5 when we discuss the CS onboard the MSP430 microcontroller. The different
processor operating modes are summarized in Figure 3.8.
to LPM4.5
PMMREGOFF=1
CPUOFF=1 CPUOFF=1
OSCOFF=0 OSCOFF=1
LPM0: SCG0=0 SCG0=1 LPM4:
CPU/MCLK = off SCG1=0 Active Modes: SCG1=1 CPU/MCLK = off
FLL = on - CPU is active FLL = off
ACLK = on - Various modules ACLK = off
Int/NMI are active Int/NMI
Vcore = on Vcore = on
CPUOFF=1 CPUOFF=1
OSCOFF=0 OSCOFF=0
SCG0=1 SCG0=1
SCG1=0 SCG1=1
Int/NMI Int/NMI
LPM1: LPM3:
CPU/MCLK = off CPUOFF=1
Int/NMI CPU/MCLK = off
FLL = off OSCOFF=0
FLL = off
ACLK = on SCG0=0 ACLK = on
Vcore = on SCG1=1 Vcore = on
LPM2:
CPU/MCLK = off
FLL = off
ACLK = on
Vcore = on
Figure 3.8: MSP430 operating modes (adapted from Texas Instruments SLAU208Q [2018]).
100 3. HARDWARE ORGANIZATION AND SOFTWARE PROGRAMMING
3.6 SOFTWARE PROGRAMMING
In this section, we describe tools and constructs of software programming for MSP430 con-
trollers, including what is known as the instruction set architecture of the microcontroller. An
instruction set architecture of a CPU determines the complexity of computer hardware and re-
quired compiler technologies. The MSP430 controller architects chose to design a RISC-based
microcontroller by limiting the type of instructions that are interpreted by the controller. The
designers of the MSP430 sought to increase the CPU performance by making all instructions
have a fixed length (1–4 words) and a fixed execution time. Such simplification of the instruction
set decreases hardware complexity and allows easier implementation of hardware modules such
as pipelining and scoreboarding.1
Each instruction consists of an opcode and an optional operand. The opcode is the portion
of the instruction that instructs hardware the nature of the instruction to be performed, and the
operand specifies either the location of or the data itself necessary for the instruction. As we will
see in this section, a method used to identify the necessary data for an instruction is called an
addressing mode.
When an editor is used to write assembly instructions for the MSP430, each instruction
should comply with the format shown below. If the C language is used to write your program,
each C instruction is converted to one or more assembly language instructions with the same
format shown below. Each instruction can have up to four separate fields, each field separated
by one or more blank spaces.
The Label field should start at column one of your editor and should be made of alphanu-
meric characters. Labels are used to name particular locations within a program, such as a loca-
tion where a loop should return to or a location of an instruction set that needs to be executed as
a result of a conditional decision (if-then-else). The mnemonic field contains assembly language
instructions while the operand field contains an expression, symbols, and/or constants identi-
fying data required for the instruction specified in the mnemonic field. For TI’s presentation
of the MSP430 instruction set, reference the MSP430x4xx Family User’s Guide [SLAU056L,
2013]. It is not mandatory that each instruction have all four fields filled. As you will see, some
instructions do not require operands. For some instructions, providing comments may not be
appropriate. Furthermore, it would be excessive to put a label on every instruction.
1 The principle of pipelining is to utilize all computer resources at all times to minimize the overall clock cycles to execute
a set of instructions. RISC-based instructions support such design better than CISC (Complex Instruction Set Computer)-
-based instructions since each instruction goes through the same process for execution, making it easy for a CPU to issue
one instruction and to complete an instruction at each clock cycle. The scoreboarding module’s goal is the same as the one
for pipelining: minimize clock cycles required to execute instructions. By keeping track of the progress of instructions and
allowing instructions that are ready to be executed to proceed to completion without waiting for other instructions to complete
their tasks, the module supports the goal of executing instructions within a minimal time.
3.6. SOFTWARE PROGRAMMING 101
3.6.1 MSP430 ASSEMBLY LANGUAGE
The MSP430 assembly language is designed to support the hardware functional units of the
controller. It is made of an instruction set, discussed in the next section. There is also a set of
instructions, directives used by an assembler, which we discuss next.
3.6.2 DIRECTIVES
Simply put, directives are instructions to assemblers. Directives are part of an assembly program,
but they do not get converted to machine code. Instead, directives are interpreted and executed
by assemblers. Since directives are executed by assemblers, available directives vary from an as-
sembler to an assembler. In this section, we describe the directives available for most of MSP430
assemblers: the IAR assembler and Code Composer.
There are two types of directives: macro directives and assembler directives. We explain
assembler directives first. Assembler directives are used by programmers to specify locations
for different segments of your program, initialize defined variables, reserve memory locations
for variables used in your program, and define constants, to name some of the common uses
of assembler directives. Some assembler directives are used to control the assembly process,
examine symbols, and specify libraries for macros. All MSP430 microcontroller directives start
with a period (.). For a complete presentation of directives, see the MSP430 Assembly Language
Tools User’s Guide [SLAU131R, 2018].
One can group these assembler directives into one of the following categories.
1. Define sections.
6. Others
Others
There are other directives that do not fall under the categories we defined. We explain the re-
maining assembler directives here. The .asmfunc directive is used to locate the beginning of a
code section that contains a designated function. The .cdecls directive allows an assembly pro-
104 3. HARDWARE ORGANIZATION AND SOFTWARE PROGRAMMING
gram and a C program to share a header file. The .clink directive is used to conditionally link
current code segment. The .emsg directive can be used to send pre-defined error messages to an
output device. The .end directive informs an assembler to ignore instructions that follow this
directive, while the .endasmfunc directive identifies the end of a block that contains a function.
The .mmsg directive is used to send user messages to output device while the .wmsg directive is
used to send warning messages to output device.
Finally, the .newblock directive is used to indicate a new section of code which undefines
any previous local labels. Table 3.4 contains a summary of all assembler directives presented in
this section.
As you just saw, there are many, many directives you can use. We suggest you start with
a small set of directives in your arsenal and expand your use of other directives as you acquire
the MSP430 controller programming skills. Before leaving this section, we present a type of
directives called “macro” directives. Macro directives are also instructions to an assembler. There
are two reasons why you may want to learn to use macro directives.
The first reason is macro directives allow a programmer to combine a number of assembly
instructions and assembly directives and define them as a single macro instruction. Such capa-
bility becomes very useful if you want to repeat executing a set of instructions over and over.
For example, suppose your application requires you to read from an input port (16 bits), swap
the high byte with the low byte, invert each bit of the resulting value, and write to an output
port (16 bits). Instead of writing the required instructions each time you need the task to be
performed, you can write the following macro directive and call it when it is required. Suppose,
for our discussion, the input port is at address 0000h and the output port is at 0002h.
Invert .macro input, output
SWAP input, R15
BIT.W R15, output
.endm
.mlib filename
where filename must be xx.asm and xx.asm contains macro definitions, such as the In-
vert macro we saw earlier.
Assembler
is used by a linker program to generate an overall machine code when more than one assembly
program is used to generate an overall code. In an object file, there are three separate sections.
The first section is executable code designated by the .text directive. The second section contains
initialized variables which is designated by the .data directive, and, finally, the third and last
section contains uninitialized variables which are reserved by the .bss directive.
The assembly process involves, typically, two phases. During the first phase, an assembler
scans through an assembly language program to identify all symbols used, including labels, and
computes their values (memory locations, offsets) and stores them to a symbol table in prepara-
tion of the second phase where actual machine code is generated using the symbol table obtained
during the first phase.
C
b15/b7- - - - - - - - -b0 b15/b7- - - - - - - - -b0
Rotate Right Rotate Left
the left, we get 15,270, or the value obtained by multiplying the original number by base 10. The
shift instructions of the MSP430 perform the same task except in the binary number system.
Example: Suppose you start with a signed decimal number 4 represented as an 8-bit number
(0000_ 0100 binary). When we perform an arithmetic right shift, the resulting value is decimal
number 2 (0000_ 0010 binary). Shift it right again, we have decimal number 1 (0000_ 0001
binary). Thus, each shift operation is equivalent to dividing the original value by 2, and repeating
the shift operation n times results in dividing the original number by 2n .
Example: Suppose now we are working with decimal number -2 (1111_ 1110 binary 2’s com-
plement representation). An arithmetic shift left produces decimal number -4 (1111_ 1100).
Two more left shifts result in decimal number -16 (1111_0000). Thus, the arithmetic left shift
is equivalent to performing multiplication by 2n where n is the number of left shifts.
As can be seen by the simple examples above, arithmetic shift operations of the MSP430
microcontroller are used to perform multiplications and divisions by a factor of 2n .
Logical shift instructions are used to test each bit of a byte one at a time. Note from
Figure 3.10 that, for logical shift operations, a zero is introduced from the left for a right shift
and from the right for a left shift each time a shift operation is performed. We can test each bit
of a byte, say by testing the LSB, as we repeat a logical shift right operation eight times. Also,
note that once we have tested all eight bits of the byte, we replace them with zeros.
3.6. SOFTWARE PROGRAMMING 113
You might ask, where would such operations be useful? It is fairly common to use such
operations in multiple applications. One such application is managing appliances in a smart
home. As we discussed, one of the main reasons for using a microcontroller over a general-
purpose computer is its ability to interface with multiple external systems using built-in I/O
interface capabilities via the physical ports. Suppose for our discussion, that one of the MSP430
input ports (eight pins) is connected to eight different appliances in your home, where each
input pin is used by the appliances to let the MSP430 know the on/off status of the appliances.
Assuming you have the remote access capability of the MSP430, you can login to your controller,
read the input port value, perform logical shift operations to check the on/off status of your
appliances, and take appropriate actions, if necessary.
Logical shift instructions can also be used to perform multiplication and division opera-
tions. In fact, both the arithmetic shift left and the logical shift left operations perform the exact
same task and can be interchangeably used to multiply unsigned and signed numbers by a factor
of 2. The logical shift right instruction, however, should be used to divide unsigned numbers by
a factor of 2, while for signed numbers, the arithmetic shift right instruction should be used.
The rotate instruction should be used to retain the original bit order of your data, but
requires shifting bits of the data. For example, suppose you want to swap the high order four
bits with the low-order four bits of a byte, say 3Eh.3 We obtain E3h by rotating the original
value four times to either left or right. Designers of the MSP430 have combined the rotate and
shift instructions as much as possible.
The available rotate and shift instructions of the MSP430 are
• RLA – rotate left arithmetically, arithmetic shift left
• RRA – rotate right arithmetically, arithmetic shift right
• RLC – rotate left through carry
• RRC – rotate right through carry
The last category of the data manipulation instructions contain two instructions that are
used to sign extend a byte and swap bytes. The instructions format are:
• SWPB src – swaps the upper and lower bytes of a word
• SXT src – sign extends the lower byte to the upper byte of a word
The SXT instruction replaces the upper byte of a word either with 1’s (lower byte contains a
2’s complement negative number) or 0’s (lower byte contains a 2’s complement positive number).
4 The BCD format uses four bits to represent decimal numbers 0–9 instead of all possible numbers four bits can represent:
0–15 decimal or 0–F in hexadecimal. Thus, decimal 37 is represented as 0011_0111 binary ($37).
3.6. SOFTWARE PROGRAMMING 115
We discuss the multiplication operation, next. Suppose you want to multiply the following
two 8-bit numbers: 78h and 03h. Again, the letter h at the end of each number represents
hexadecimal numbers. The hexadecimal number system uses 16 numbers instead of 10, as in
the decimal system, to represent each number. The numerical numbers used in the hexadecimal
number system are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. The corresponding numbers in
the decimal system are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15. Thus, 78h represents
.7 161 / C .8 160 / or decimal value 280.
The following instructions perform the multiplication operation in the MSP430.
Once the second number is loaded into the second operand register, the multiplication
starts. Note that both operands are bytes, hence the use of MPY_B and OP2_B registers. A
set of 8 bits makes up a byte. The two numbers used in the example are 0111_1000 (78h) and
0000_0011 (03h). The result is stored in the RESLO register.
As another example, suppose now you want to multiply the following two 32-bit signed
numbers: 24184219h and F249E201h. One must write the following code segment using the
appropriate 32-bit registers.
Pay special attention to the order of loading numbers in the example above. You must first
load the operand one register then the operand two register. For each register, you must also
remember to load the low byte first followed by the high byte. If one of the operand is only 16
bits long, you must write to the high byte of the target register followed by the low byte register,
which will indicate to the controller to ignore the high byte and that the operand should be
considered as a 16-bit (low byte) long number. The result of the above code will be in RES0-
RES3 registers where RES3 contains the most significant word (two bytes) and RES0 contains
the least significant word of the result.
Branch Instructions
Branch instructions are used to implement IF-THEN-ELSE programming constructs. There
are 11 such instructions in the MSP430 microcontroller instruction set. Typically, these instruc-
tions can be further divided into branch instructions designed to deal with signed numbers and
ones for unsigned numbers. Branch instructions for signed numbers are as follows.
• JN label – jumps to a location specified by the label if the Negative bit in the Status Register
(SR) is set
• JGE label – jumps to a location specified by the label if the test/comparison/operation
made immediately before the current instruction execution results in a signed number
greater than or equal to zero
• JL(t) label – jumps to a location specified by the label if the test/comparison/operation
made previously results in a signed number less than zero
Branch instructions for unsigned numbers are as follows.
• JHS label – jumps to a location specified by the label if the test/comparison/operation
made previously results in an unsigned number higher than or same as zero
• JLO label – jumps to a location specified by the label if the test/comparison/operation
made previously results in an unsigned number lower than zero
Other available branch instructions are as follows.
• JZ label – jumps to a location specified by the label if the zero bit in SR is set
118 3. HARDWARE ORGANIZATION AND SOFTWARE PROGRAMMING
• JNZ label – jumps to a location specified by the label if the zero bit in SR is not set
• JC label – jumps to a location specified by the label if the carry bit in SR is set
• JNC label – jumps to a location specified by the label if the carry bit in SR is clear
• JEQ label – jumps to a location specified by the label if the test/comparison/operation
preceding the instruction results in zero
• JNE label – jumps to a location specified by the label if the test/comparison/operation
preceding the instruction results in non-zero value
subroutine1: :
:
:
RET
Provided in Figure 3.11 is a summary of the MSP430 assembly language instruction set.
MOV.W R5,R7
AND.B R5,R7
to execute the AND operation, the MSP430 takes the contents of R5 and R7 and performs bit
wise AND operation and stores the result in R7.
ADD.W 5(R4), R5
The instruction takes the data located at the address specified by 5 plus the contents of
R4, adds the value to the value in R5 and stores the result to R5.
120 3. HARDWARE ORGANIZATION AND SOFTWARE PROGRAMMING
Figure 3.11: Texas Instruments MSP430 assembly language instruction set [SLAU056L, 2013].
Used with permission of Texas Instruments.
3.7. ADDRESSING MODES 121
3.7.3 SYMBOLIC ADDRESSING MODE
To those who are familiar with other microcontrollers’ addressing modes, this addressing mode is
similar to a program counter (PC) relative addressing mode. The data necessary for an instruction
is found by finding the relative offset from the current instruction to a destination location.
The contents of the source address (contents of PC C X) are moved to the destination address
(contents of PC C Y).
moves the contents of address location, whose address value was determined by the contents of
R5, are moved to register R10.
MOV.B @R4+,R5
The above instruction takes the contents of R4, uses it as the address location to find the
data, moves the data to R5, then increments the contents of R4 by one.
mov.w #78F2h, R4
122 3. HARDWARE ORGANIZATION AND SOFTWARE PROGRAMMING
This instruction moves 78F2h to R4 where h represents a hexadecimal number.
Examples: Assume that the following instructions are not sequential. Given that the contents
of R5 is .128/10 and R6 is CAFEh, describe the results of each instruction.
1. ADD #10, R5
Answer: Add 10 to the contents of register R5.
2. ADD.B #10, R5
Answer: Add 10 to the low byte of R5.
3. MOV #AA55h, R4
Answer: Places AA55h into register R4.
5. BIC #FC00h, R6
Answer: Clears the 6 MSBs of R6 resulting in 02FEh.
6. BIS #FC00h, R6
Answer: Sets the 6 MSBs of R6 resulting in FEFEh.
7. CLR R5
Answer: Set R5 to zero.
8. CLR.B R6
Answer: Clears the low byte of R6 resulting in a value of CA00h.
Programming Constructs
Instruction n Instruction n
No
<argument>
true?
Instruction n + 1 Instruction n + 1
Yes
Instruction n
Loop1: :
:
:
JMP Loop1
Example: Provided below is the basic assembly language construct for the if-then statement.
:
:
CMP R6, R7 ;R6 = R7:
JEQ EQUAL1
:
EQUAL1: :
:
3. For each subtask, repeat step one if the subtask is too big. Stop when the subtasks cannot
be further subdivided.
4. Place each subtask on the structure chart in proper hierarchy relative to the other sub tasks.
5. Draw the UML activity diagram for each subtask showing enough detail to write instruc-
tions to accomplish the task.
6. Write a program segment to fulfill the subtask, proceeding to the next one only after you
have thoroughly tested the functionality of the subtask program segment.
7. Integrate subtask segments one at a time, testing their combined functionality (this may
require a test plan).
8. Continue this process until all subtask solution segments are integrated and the overall
task is completed.
determine_robot
_action
robot sensor
action data
analog-to-digital digital
motor_control
converter (ADC) input/output
desired
motor
action ch for conv
conv data
left right
PWM_left PWM_right ADC
ReadADC turn running turn
Initialize signal lights signal
language offers, discussed in the next section, the compiler technologies continued to improve.
Today, the difference between a converted assembly program initially written in C and an as-
sembly program written directly is very small.
Advantages/Disadvantages
So why should anyone learn to write assembly language programs? After all, high-level lan-
guages, in particular, the C language, are programmer friendly, portable, and compact. Fur-
thermore, most programmers are already familiar with high-level languages, removing the time
required to learn a new assembly language. A C program can be machine independent (portabil-
ity).6 Although programs usually become more compact when written in an assembly language,
the primary reason for most microcontroller programmers who choose to use a high-level lan-
guage is that a programmer does not need to understand the Instruction Set Architecture (ISA)
to write programs for a particular platform, while having access to bit-by-bit level instructions,
if necessary.
The proponents of assembly language programs point out the advantage of writing pro-
grams with instructions that can directly map to designed functions of a hardware platform. That
is, each instruction is written as a specific machine level instruction, allowing a programmer to
have full control of the execution of those instructions in the use of time (clock cycle by clock
6 This statement is marginally true if specific ports and registers for a platform are not used in a program.
3.9. ASSEMBLY VS. C 127
include files
global variables
function prototypes
initialize ports
initialize ADC
initialize PWM
while(1)
determine robot
action
issue motor
control signals
cycle) and hardware resources. This leads to writing an efficient program compared to the one
written with a high-level language and later converted to assembly code.
Writing programs at the level of machine language also allows programmers control over
where his/her programs will reside in memory, optimizing the use of available memory of a mi-
crocontroller. Writing assembly language programs also allow programmers to embed pertinent
error messages in their programs at the machine level, while high-level language programmers
do not have the same option. Finally, programming at the machine specific ISA level allows as-
sembly language programmers to better understand related computer architecture issues, which
enables them to take full advantages of the particular hardware and software features of each
microcontroller.
128 3. HARDWARE ORGANIZATION AND SOFTWARE PROGRAMMING
3.9.1 OUR APPROACH
Acknowledging the advantages offered by both high-level languages and assembly languages, we
use the C language in this book. Once we establish the necessary foundation of the hardware and
software systems, we use the C programming language to concentrate on functional capabilities
of the MSP430 microcontrollers. Many of the examples provided in the book, written in C, are
also available in assembly language within MSPWare (www.ti.com).
• perform some mathematical operations and observe the flag values generated.
• PxIN, Port x input. This register is read only and is used to determine the current value of
the specified port. For example, to read Port 2, you would read register P2IN.
• PxOUT, Port x output. This is the output register for the specified port. When a value is
written to this register, the value written appears at the specified port pins.
• PxDIR, Port x direction register. This is the pin direction register for the specified port.
Each port pin has internal interface hardware which is used to configure each pin as an
input pin or an output pin. Setting the PxDIR register for a specific port pin to a logic 1
configures the pin as an output pin. A logic 0 configures the pin as an input pin.
• PxSEL, Port x function select. Many pins on the MSP430 microcontroller have alternate
functions besides their general purpose I/O function. A logic 0 configures the pin for
general purpose I/O, whereas a logic 1 connects the pin to its alternate function.
• PxREN, Port x Pull-up/Pull-down resistor enable register. A logic 0 disables the pull-
up/pull-down resistor for the corresponding pin; whereas, a logic 1 connects the pin to a
pull-up/pull-down resistor as shown in Figure 3.15.
Provided below is an assembly language program to flash an LED. Execute the code on
the MSP-EXP430FR2433 evaluation board. To assemble the code, use the same procedure as
that used for the C program. An abbreviated version of the steps is provided here for convenience
(adapted from SLAU157AP [2017]).
1. Plug the MSP-EXP430FR2433 LaunchPad into the host PC via the USB cable.
15. Important step: Select Run > Terminate to properly stop the program.
; ******************************************************************
; MSP430 CODE EXAMPLE DISCLAIMER
;MSP430 code examples are self-contained low-level programs that
;typically demonstrate a single peripheral function or device feature
;in a highly concise manner. For this the code may rely on the
;device's power-on default register values and settings such as the
;clock configuration and care must be taken when combining code from
;several examples to avoid potential side effects. Also see
;www.ti.com/grace for a GUI- and www.ti.com/msp430ware for an API
;functional library-approach to peripheral configuration.
;
; --/COPYRIGHT--
;********************************************************************
;MSP430FR243x Demo - Toggle P1.0 using software
;
;Description: Toggle P1.0 every 0.1s using software.
;By default, FR413x select XT1 as FLL reference.
;If XT1 is present, the XIN and XOUT pin needs to configure.
;If XT1 is absent, switch to select REFO as FLL reference
;automatically.
; XT1 is considered to be absent in this examples.
3.11. LABORATORY EXERCISE: PROGRAMMING MSP430 IN ASSEMBLY LANGUAGE 131
; ACLK = default REFO ~32768Hz, MCLK = SMCLK = default DCODIV ~1MHz.
;
; MSP430FR2433
; ---------------
; /|\| |
; | | |
; --|RST |
; | P1.0|-->LED
;
;Cen Fang
;Texas Instruments Inc.
;June 2013
;Built with Code Composer Studio v6.0
;********************************************************************
.cdecls C,LIST,"msp430.h" ;Include device header file
;--------------------------------------------------------------------
.def RESET ;Export program entry-point to
;make it known to linker.
;--------------------------------------------------------------------
.global __STACK_END
.sect .stack ;Make stack linker segment known
;---------------------------------------------------------------------
132 3. HARDWARE ORGANIZATION AND SOFTWARE PROGRAMMING
; Interrupt Vectors
;---------------------------------------------------------------------
.sect RESET_VECTOR ;MSP430 RESET Vector
.short RESET ;
.end
;*********************************************************************
Include C header
file for MSP430
;********************************************************************
; MSP430 CODE EXAMPLE DISCLAIMER
; --/COPYRIGHT--
;********************************************************************
3.11. LABORATORY EXERCISE: PROGRAMMING MSP430 IN ASSEMBLY LANGUAGE 133
;MSP430FR243x Demo - Software Poll P1.3, Set P1.0 if P1.3 = 1
;
;Description: Poll P1.3 in a loop. Set P1.0 if P1.3 = 1, or reset P1.0.
;By default, FR413x select XT1 as FLL reference.
;If XT1 is present, the XIN and XOUT pin needs to be configured.
;If XT1 is absent, REFO is automatically switched for FLL reference.
;XT1 is considered to be absent.
; ACLK = default REFO ~32768Hz, MCLK = SMCLK = default DCODIV ~1MHz
;
; MSP430FR2433
; ---------------
; /|\| |
; | | |
; --|RST |
; /|\ | |
; --o--|P1.3 P1.0|-->LED
; \|/ | |
; | |
;
;Cen Fang
;Texas Instruments Inc.
;June 2013
;Built with Code Composer Studio v6.0
;*******************************************************************
;-------------------------------------------------------------------
.cdecls C,LIST,"msp430.h" ;Include device header file
;-------------------------------------------------------------------
.def RESET ;Export program entry-point
;to make it known to linker
;-------------------------------------------------------------------
.global __STACK_END
.sect .stack ;Make stack linker segment
;
;-------------------------------------------------------------------
; Interrupt Vectors
;-------------------------------------------------------------------
.sect RESET_VECTOR ;MSP430 RESET Vector
.short RESET ;
.end
;********************************************************************
Execute the code on the MSP-EXP430FR2433 evaluation board. Then modify the pro-
gram to illuminate LED1 when switch S1 is depressed, illuminate LED2 when switch S2 is
depressed, and exit the program when switch S1 and S2 are depressed simultaneously. Provide
a UML activity diagram of the modified program in your lab notebook.
1. For each of the operations listed below, predict the final result and the value of flags V, N,
Z, and C.
3.12. SUMMARY 135
2. Perform the following operations in assembly language. At least three different addressing
modes must be employed.
(a) Place (CAFE)h into R12. Rotate R12 two bits to the right.
(b) Place (CAFE)h into R12. Rotate R12 two bits to the left.
(c) Perform (CAFE)h + (DABA)h.
(d) Perform (CAFE)h - (DABA)h.
(e) Perform (CA)h x (FE)h.
(f ) Place (CAFE)h into R12. Clear even bits.
(g) Place (CAFE)h into R12. Clear odd bits.
(h) Place (CAFE)h into R12. Set even bits.
(i) Place (CAFE)h into R12. Set odd bits.
(j) Place (CAFE)h into R12. Increment R12.
3. Compare predicted and actual results. There are several features with Code Composer
Studio (CCS) that will prove very helpful in this step.
• Register contents may be viewed by selecting View > Registers.
• You can single step through the program by selecting Target > Assembly Step
Into.
• The single step progress can be viewed in the Disassembly window within the CCS
main screen.
3.12 SUMMARY
In this chapter, we introduced a number of fundamental concepts and tools used to program
MSP430 microcontrollers. These include the programming model which allows programmers to
“see” the current operation status of the controller, a number of power-saving operating modes,
the hardware and software organizations of the controller, the instruction set architecture (and
available instructions), directives which are the instructions to assemblers, and the overall as-
sembly process. We also presented good software programming skills called top-down design
and bottom-up implementation and the use of high-level and assembly languages when pro-
gramming embedded controllers such as MSP430.
3. The registers onboard the MSP430 microcontroller are 16 bits wide. What is the largest
unsigned integer that can be stored in 16 bits? Signed integer?
4. What is the fundamental premise of the low-power operating modes of the MSP430 mi-
crocontroller?
5. Construct a summary chart of the MSP430 low-power operating modes. Include the status
register bit settings to enter a specific mode and the clock status for each mode.
7. For each of the operations listed below, predict the final result and the value of flags V, N,
Z, and C.
(a) Place (CAFE)h into R12. Rotate R12 three bits to the right.
(b) Place (CAFE)h into R12. Rotate R12 three bits to the left.
(c) Perform (CAFE)h + (DABA)h. Add the carry bit to the result. State any assumptions
made.
(d) Perform (CAFE)h - (DABA)h. Subtract the carry bit from the result. State any as-
sumptions made.
(e) Perform (CA)h x (FE)h.
(f ) Place (CAFE)h into R12. Clear even bits.
(g) Place (CAFE)h into R12. Clear odd bits.
(h) Place (CAFE)h into R12. Set even bits.
(i) Place (CAFE)h into R12. Set odd bits.
(j) Place (CAFE)h into R12. Increment R12.
(k) Place (CAFE)h into R12. Swap the high- and low-order bytes.
Challenging
1. Write an assembly language program which increments a variable. If the variable is even,
LED1 on the MSP-EXP430FR2433 evaluation board will illuminate, whereas LED2 will
illuminate for an even value. Note: You will need to single step through the program to
observe program operation.
138 3. HARDWARE ORGANIZATION AND SOFTWARE PROGRAMMING
2. Write an assembly language program which loads a variable and then performs a sequential
logical shift right. If the bit shifted out is even, LED1 on the MSP-EXP430FR2433
experimenter board will illuminate, whereas LED2 will illuminate for an even value. Note:
You will need to single step through the program to observe program operation.
139
CHAPTER 4
• describe the voltage and current parameters for the Texas Instruments MSP430 micro-
controller;
• apply the knowledge of voltage and current parameters toward properly interfacing input
and output devices to the MSP430 microcontroller;
• distinguish between low voltage 3.3 VDC and 5.0 VDC microcontroller operations;
• interface the MSP430 microcontroller operating at 3.3 VDC with a peripheral device
operating at 5.0 VDC;
• interface a wide variety of input and output devices to the MSP430 microcontroller;
• describe the special concerns that must be followed when the MSP430 microcontroller is
used to interface to a high-power DC or AC device;
In this chapter, we introduce the important concepts of the operating envelope for a micro-
controller. We begin by reviewing the voltage and current electrical parameters for the MSP430
microcontroller. We use this information to properly interface input and output devices to the
MSP430 microcontroller. The MSP430 operates at a low voltage (3.3 VDC and below). There
are many compatible low voltage peripheral devices. However, many peripheral devices still
operate at 5.0 VDC. We discuss how to interface a 3.3 VDC microcontroller to 5.0 VDC pe-
ripherals. We then discuss the special considerations for controlling a high-power DC or AC
load such as a motor. Throughout the chapter, we provide several detailed examples to illustrate
concepts.
140 4. MSP430 OPERATING PARAMETERS AND INTERFACING
4.1 OPERATING PARAMETERS
A microcontroller is an electronic device which has precisely defined operating conditions. If
the microcontroller is used within its defined operating parameter limits, it should continue to
operate correctly. However, if the allowable conditions are violated, spurious results or micro-
controller damage may result.
These drive parameters cannot be used at their face value. To properly interface a periph-
eral device to the microcontroller, the parameters provided in Figure 4.1 must be used. As shown
in the figure, operating parameter curves for the MSP430 microcontroller operating at 3.0 VDC
change under varying conditions.
It is important to realize that these are static values taken under specific operating con-
ditions. If external circuitry is connected such that the microcontroller acts as a current source
(current leaving microcontroller) or current sink (current entering microcontroller), the voltage
parameters listed above will also be affected.
In the current source case, an output voltage VOH is provided at the output pin of the
microcontroller when the load connected to this pin draws a current of IOH . If a load draws
more current from the output pin than the IOH specification, the value of VOH is reduced. If the
load current becomes too high, the value of VOH falls below the value of VIH for the subsequent
logic circuit stage, and it will not be recognized as an acceptable logic high signal. When this
situation occurs, erratic and unpredictable circuit behavior results.
4.1. OPERATING PARAMETERS 141
25
20
10
5
85°C
0 25°C
-40°C
-5
0 0.5 1 1.5 2 3.5 3
Low-Level Output Voltage (V)
DVCC = 3 V
Typical Low-Level Output Current vs. Low-Level
Output Voltage
5
85°C
0 25°C
High-Level Output Current (mA)
-5 -40°C
-10
-15
-20
-25
-30
0 0.5 1 1.5 2 3.5 3
High-Level Output Voltage (V)
DVCC = 3 V
Typical High-Level Output Current vs. High-Level
Output Voltage
Figure 4.1: MSP430 drive current parameters [SLASE59C, 2018]. Illustration used with per-
mission of Texas Instruments (www.ti.com).
142 4. MSP430 OPERATING PARAMETERS AND INTERFACING
In the sink case, an output voltage VOL is provided at the output pin of the microcontroller
when the load connected to this pin delivers a current of IOL to this logic pin. If a load delivers
more current to the output pin of the microcontroller than the IOL specification, the value of
VOL increases. If the load current becomes too high, the value of VOL rises above the value of VIL
for the subsequent logic circuit stage, and it will not be recognized as an acceptable logic low
signal. When this situation occurs, erratic and unpredictable circuit behavior results.
You must also ensure that total current limits for an entire microcontroller port and overall
bulk port specifications are observed. For planning purposes, the sum of current sourced or
sinked from a port should not exceed 48 mA. As before, if these guidelines are not complied
with, erratic microcontroller behavior may result. Several examples are provided in an upcoming
section.
• IIL = 10 microamps.
4.1. OPERATING PARAMETERS 143
loc 10 uA 20 uA 190 uA
(b) LV parameters
Example: Large LED displays. Large seven-segments displays with character heights of 6.5
inches are available from SparkFun Electronics (www.sparkfun.com). Multiple display char-
acters may be daisy chained together to form a display panel of desired character length. Only
four lines from the MSP430 are required to control the display panel (ground, latch, clock,
and serial data). Each character is controlled by a Large Digit Driver Board (#WIG-13279)
equipped with the Texas Instruments TPIC6C596 IC Program Logic 8-bit Shifter Register.
The shift register requires a 5 VDC supply and has a VIH value of 4.25 VDC. The MSP430,
when supplied at 3.3 VDC, has a maximum VOH value of 3.3 VDC. Since the output signal
levels from the MSP430 are not high enough to control the TPIC6C596, a level shifter (e.g.,
4.2. INPUT DEVICES 145
LSF010XEVM module) is required to up convert the MSP430 signals to be compatible to the
ones for the TPIC6C596 [SLIS093D, 2015].
4.2.1 SWITCHES
Switches come in a variety of types. As a system designer, it is up to you to choose the appropriate
switch for a specific application. Switch varieties commonly used in microcontroller applications
are illustrated in Figure 4.4a. Provided below is a brief summary of the different types.
• Slide switch: A slide switch has two different positions: on and off. The switch is manually
moved to one position or the other. For microcontroller applications, slide switches are
available that fit in the profile of a common integrated circuit size dual inline package
(DIP). A bank of four or eight DIP switches in a single package is commonly available.
• Momentary contact pushbutton switch: A momentary contact pushbutton switch comes
in two varieties: normally closed (NC) and normally open (NO). A normally open switch,
as its name implies, does not normally provide an electrical connection between its con-
tacts. When the pushbutton portion of the switch is depressed, the connection between
the two switch contacts is made. The connection is held as long as the switch is depressed.
When the switch is released, the connection is opened. The converse is true for a nor-
mally closed switch. For microcontroller applications, pushbutton switches are available
in a small Tactile (tact) type switch configuration. The MSP-EXP430FR2433 and the
MSP-EXP430FR5994 LaunchPads are each equipped with two pushbutton tactile (tact)
switches designated S1 and S2.
• Push on/push off switches: This switch type of is also available in a normally open or nor-
mally closed configuration. For the normally open configuration, the switch is depressed
to make connection between the two switch contacts. The pushbutton must be depressed
again to release the connection.
• Hexadecimal rotary switches: Small profile rotary switches are available for microcon-
troller applications. These switches commonly have sixteen rotary switch positions. As the
switch is rotated to each position, a unique four-bit binary code is provided at the switch
contacts.
A common switch interface is shown in Figure 4.4b. This interface allows a logic one or
zero to be properly introduced to a microcontroller input port pin. The basic interface consists
of the switch in series with a current limiting resistor. The node between the switch and the
146 4. MSP430 OPERATING PARAMETERS AND INTERFACING
VDD VDD
microcontroller
4.7 kOhm pullup resistor
To microcontroller input activated
- Logic one when switch open
- Logic zero when switch is closed
VDD
0.1 μF
4.2.3 KEYPADS
A keypad is an extension of the simple switch configuration. A typical keypad configuration and
interface are shown in Figure 4.5. As you can see, the keypad contains multiple switches in a
two-dimensional array configuration. The switches in the array share common row and column
connections. The common column connections are pulled up to Vcc by external 10 K resistors
or by pull-up resistors within the MSP430.
To determine if a switch has been depressed, a single row of keypad switches is first as-
serted by the microcontroller, followed by a reading of the host keypad column inputs. If a switch
has been depressed, the keypad pin corresponding to the column the switch is in will also be
asserted. The combination of a row and a column assertion can be decoded to determine which
key has been pressed. The keypad rows are sequentially asserted. Since the keypad is a collection
148 4. MSP430 OPERATING PARAMETERS AND INTERFACING
Ro w 3
1
Row 2
Row 4
C l1
C l2
C l3
Ro l 4
w
1
2
3
4
o
o
o
o
C
ol
ol
ol
ol
EFGH J KLM
C
C
C
C
0 1 2 3 Row 1
4 5 6 7 Row 2
8 9 A B Row 3
C D E F Row 4
0 1 2 3
M row 1 (31)
4 5 6 7
L row 2 (32)
8 9 A B
K row 3 (33)
C D E F
J row 4
(34)
Vcc
column 3 (37)
Vcc
column 2 (36)
Vcc
column 1 (35)
#define row1 31
#define row2 32
#define row3 33
#define row4 34
#define col1 35
#define col2 36
#define col3 37
#define col4 38
void setup()
{
//start serial connection to monitor
Serial.begin(9600);
void loop()
{
//Assert row1, deassert row 2,3,4
digitalWrite(row1, LOW); digitalWrite(row2, HIGH);
digitalWrite(row3, HIGH); digitalWrite(row4, HIGH);
//Read columns
if (digitalRead(col1) == LOW)
key_depressed = '0';
else if (digitalRead(col2) == LOW)
key_depressed = '1';
else if (digitalRead(col3) == LOW)
key_depressed = '2';
else if (digitalRead(col4) == LOW)
key_depressed = '3';
else
key_depressed = '*';
if (key_depressed == '*')
{
//Assert row2, deassert row 1,3,4
digitalWrite(row1, HIGH); digitalWrite(row2, LOW);
digitalWrite(row3, HIGH); digitalWrite(row4, HIGH);
//Read columns
if (digitalRead(col1) == LOW)
key_depressed = '4';
else if (digitalRead(col2) == LOW)
key_depressed = '5';
4.2. INPUT DEVICES 151
else if (digitalRead(col3) == LOW)
key_depressed = '6';
else if (digitalRead(col4) == LOW)
key_depressed = '7';
else
key_depressed = '*';
}
if (key_depressed == '*')
{
//Assert row3, deassert row 1,2,4
digitalWrite(row1, HIGH); digitalWrite(row2, HIGH);
digitalWrite(row3, LOW); digitalWrite(row4, HIGH);
//Read columns
if (digitalRead(col1) == LOW)
key_depressed = '8';
else if (digitalRead(col2) == LOW)
key_depressed = '9';
else if (digitalRead(col3) == LOW)
key_depressed = 'A';
else if (digitalRead(col4) == LOW)
key_depressed = 'B';
else
key_depressed = '*';
}
if (key_depressed == '*')
{
//Assert row4, deassert row 1,2,3
digitalWrite(row1, HIGH); digitalWrite(row2, HIGH);
digitalWrite(row3, HIGH); digitalWrite(row4, LOW);
//Read columns
if (digitalRead(col1) == LOW)
key_depressed = 'C';
else if (digitalRead(col2) == LOW)
key_depressed = 'D';
else if (digitalRead(col3) == LOW)
152 4. MSP430 OPERATING PARAMETERS AND INTERFACING
key_depressed = 'E';
else if (digitalRead(col4) == LOW)
key_depressed = 'F';
else
key_depressed = '*';
}
if(key_depressed != '*')
{
Serial.write(key_depressed);
Serial.write(' ');
switch(key_depressed)
{
case '0' : Serial.println("Do something associated with case 0");
break;
4.2.4 SENSORS
A microcontroller is typically used in control applications where data is collected. The data is
assimilated and processed by the host algorithm, and a control decision and accompanying sig-
nals are provided by the microcontroller. Input data for the microcontroller is collected by a
complement of input sensors. These sensors may be digital or analog in nature.
Digital Sensors
Digital sensors provide a series of digital logic pulses with sensor data encoded. The sensor data
may be encoded in any of the parameters associated with the digital pulse train such as duty cycle,
154 4. MSP430 OPERATING PARAMETERS AND INTERFACING
frequency, period, or pulse rate. The input portion of the timing system may be configured to
measure these parameters.
An example of a digital sensor is the optical encoder. An optical encoder consists of a
small plastic transparent disk with opaque lines etched into the disk surface. A stationary optical
emitter and detector pair are placed on either side of the disk. As the disk rotates, the opaque
lines break the continuity between the optical source and detector. The signal from the optical
detector is monitored to determine disk rotation, as shown in Figure 4.6.
Stationary Optical
Source and Detector
Rotating Pair
Disk D
Detector Output
Ch A
Ch B
There are two major types of optical encoders: incremental encoders and absolute en-
coders. An absolute encoder is used when it is required to retain position information when
power is lost. For example, if you were using an optical encoder in a security gate control
system, an absolute encoder would be used to monitor the gate position. The absolute en-
coder is equipped with multiple data tracks to determine the precise location of the encoder
disk [Stegmann].
4.2. INPUT DEVICES 155
An incremental encoder is used in applications where velocity and/or direction informa-
tion is required. The incremental encoder types may be further subdivided into tachometers and
quadrature encoders. An incremental tachometer encoder consists of a single track of etched
opaque lines as shown in Figure 4.6a. It is used when the velocity of a rotating device is re-
quired. To calculate velocity, the number of detector pulses is counted in a fixed amount of
time. Since the number of pulses per encoder revolution is known, velocity may be calculated.
The quadrature encoder contains two tracks shifted in relationship to one another by 90ı . This
allows the calculation of both velocity and direction. To determine direction, one would monitor
the phase relationship between Channel A and Channel B, as shown in Figure 4.6b [Stegmann].
Example: Optical encoder. An optical encoder provides 200 pulses per revolution. The encoder
is connected to a rotating motor shaft. If 80 pulses are counted in a 100 ms span, what is the
speed of the motor in revolutions per minute (RPM)?
VDD
10 K Fixed
Resistor
Flex Sensor:
-- 0° flex, 10 K
-- 90° flex , 30–40 K
(b) Flex action
Xmax
X1max X2max
X1min
K X2min
Xmin Screen
Input Transducer Multiplier ADC Input
B
(Bias)
Figure 4.8: A block diagram of the signal conditioning for an analog-to-digital converter. The
range of the sensor voltage output is mapped to the analog-to-digital converter input voltage
range. The scalar multiplier maps the magnitudes of the two ranges and the bias voltage is used
to align two limits.
4.2. INPUT DEVICES 157
Y-Vertical
(analog)
0 VDC
Y-Vertical
(analog)
3.3 VDC (b) Sparkfun joystick (COM-09032) and
(a) Joystick operation breakout board (BOB-09110)
3.3 VDC
VERT 10 K
Vcc to MSP430
sel to MSP430
3.3 VDC
SEL
HORZ
to MSP430 GND
Figure 4.9: Thumb joystick. Images used with permission of Sparkfun (www.sparkfun.com).
Example: IR sensor. In Chapter 2, a Sharp IR sensor is used to sense the presence of maze
walls. In this example, we use the Sharp GP2Y0A21YKOF IR sensor to control the intensity
of an LED. The profile of the Sharp IR sensor is provided in Figure 4.10.
//****************************************************************
//IR_sensor
//
//The circuit:
//- For the MSP-EXP430FR2433 LaunchPad, the IR sensor signal pin is
// connected to analog pin 0 (2).
//- The sensor power and ground pins are connected to 5 VDC and
// ground respectively.
//- The analog output is designated as the onboard red LED.
//
158 4. MSP430 OPERATING PARAMETERS AND INTERFACING
3V
void setup()
{
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop()
{
//read the analog in value:
sensorValue = analogRead(analogInPin);
4.2. INPUT DEVICES 159
//****************************************************************
Example: Ultrasonic sensor. The ultrasonic sensor pictured in Figure 4.11 is an example of an
analog-based sensor. The sensor is based on the concept of ultrasound or sound waves that are at
a frequency above the human range of hearing (20 Hz to 20 kHz). The ultrasonic sensor pictured
in Figure 4.11c emits a sound wave at 42 kHz. The sound wave reflects from a solid surface and
returns to the sensor. The amount of time for the sound wave to transit from the surface and back
to the sensor may be used to determine the range from the sensor to the wall. Figure 4.11c,d
show an ultrasonic sensor manufactured by Maxbotix (LV-EZ3). The sensor provides an output
that is linearly related to range in three different formats: (a) a serial RS-232 compatible output
at 9600 bits per second, (b) a pulse output which corresponds to 147 us/in width, and (c) an
analog output at a resolution of 10 mV/in. The sensor is powered from a 2.5–5.5 VDC source
(www.sparkfun.com).
Example: Inertial measurement unit. Pictured in Figure 4.12 is an inertial measurement unit
(IMU) which consists of an IDG5000 dual-axis gyroscope and an ADXL335 triple axis ac-
celerometer. This sensor may be used in unmanned aerial vehicles (UAVs), autonomous heli-
copters and robots. For robotic applications the robot tilt may be measured in the X and Y
directions as shown in Figure 4.12c,d (www.sparkfun.com).
Example: Level sensor. Milone Technologies manufacture a line of continuous fluid level sen-
sors. The sensor resembles a ruler and provides a near liner response, as shown in Figure 4.13.
160 4. MSP430 OPERATING PARAMETERS AND INTERFACING
Ultrasonic
Transducer
Figure 4.11: Ultrasonic sensor. (Sensor image used courtesy of SparkFun, Electronics (www.sp
arkfun.com).)
4.2. INPUT DEVICES 161
IMU
IDG500/ADXL335
VDD raw
grnd
xrate
yrate x4.5out
vref y4.5out
st ptats
zout az
yout
xout
IR Sensor IR Sensor
Array Array
Starboard Port Stern Bow
drive drive
motor motor
battery
compartment
sor
Sen y S te
IR Arra t rn
Por
ve
driotor
m IR
com bat Bo S
w Ar enso
d par ter y ray r
rb oar ve
driotor
tm
ent
Sta m
Figure 4.12: Inertial measurement unit. (IMU image used courtesy of SparkFun, Electronics
(www.sparkfun.com).)
162 4. MSP430 OPERATING PARAMETERS AND INTERFACING
The sensor reports a change in resistance to indicate the distance from sensor top to the fluid
surface. A wide resistance change occurs from 700 ohms at a 1-in fluid level to 50 ohms at a
12.5-in fluid level (www.milonetech.com). To covert the resistance change to a voltage change
measurable by the MSP430, a voltage divider circuit as shown in Figure 4.13 may be used. With
a supply voltage (VDD ) of 3.3 VDC, a VTAPE voltage of 0.855 VDC results for a one inch fluid
level. Whereas, a fluid of 12.5 in provides a VTAPE voltage level of 0.080 VDC.
V2max D .V1max K/ C B
V2min D .V1min K/ C B:
The variable V1max represents the maximum output voltage from the input transducer. This
voltage occurs when the maximum physical variable (Xmax ) is presented to the input transducer.
This voltage must be scaled by the scalar multiplier (K) and then have a DC offset bias voltage
(B) added to provide the voltage V2max to the input of the ADC converter [USAFA].
Similarly, the variable V1min represents the minimum output voltage from the input trans-
ducer. This voltage occurs when the minimum physical variable (Xmin ) is presented to the input
transducer. This voltage must be scaled by the scalar multiplier (K) and then have a DC offset
bias voltage (B) added to produce voltage V2min , the input of the ADC converter.
Usually the values of V1max and V1min are provided with the documentation for the trans-
ducer. Also, the values of V2max and V2min are known. They are the high and low reference voltages
for the ADC system (usually 3.3 VDC and 0 VDC for the MSP430 microcontroller). We thus
have two equations and two unknowns to solve for K and B. The circuits to scale by K and add
the offset B are usually implemented with operational amplifiers.
Example: A photodiode is a semiconductor device that provides an output current, correspond-
ing to the light impinging on its active surface. The photodiode is used with a transimpedance
amplifier to convert the output current to an output voltage. A photodiode/transimpedance am-
plifier provides an output voltage of 0 volt for maximum rated light intensity and -2.50 VDC
4.2. INPUT DEVICES 163
700
600
500
Resistance [ohms]
400
300
200
100
0
0 1 2 3 4 5 6 7 8 9 10 11 12
Distance from Sensor Top to Fluid Level (inches)
(a) Characteristics for Milone Technologies eTape TM fluid level sensor
Sensor Lead
Connections
Connection
Area
VDD = 3.3 VDC
Max
2 kOhm fixed
resistor
12
eTape sensor
-- 700 ohms at 1” fluid
--50 ohms at 12.5” fluid
V2max D .V1max K/ C B
V2min D .V1min K/ C B
3:3V D .0V K/ C B
0V D . 2:50V K/ C B:
The values of K and B may then be determined to be 1.3 and 3.3 VDC, respectively.
Vcc
In Vo
Vn - Vcc saturation
Ideal conditions:
--In = Ip = 0
saturation -Vcc
-- Vp = Vn
-- Avol >> 50,000
-- Vo = Avol (Vp - Vn)
Rf
+Vcc
Ri +Vcc -
- Vout = Vin
+
Vin Vout = - (Rf / Ri )(Vin )
+ Vin -Vcc
-Vcc
+Vcc V1 +Vcc
Ri
- -
Vout = ((Rf + Ri )/Ri)(Vin ) Vout = (Rf /Ri)(V2 -V1 )
+ +
Vin -Vcc V2 -Vcc
Ri Rf
(c) Non-inverting amplifier (d) Differential input amplifier
R1
Rf Rf
V1
R2
V2 +Vcc +Vcc
R3
V3 - -
Vout = - (Rf / R1 )(V1 ) Vout = - (I Rf )
+ +
- (Rf / R2 )(V2 ) I
-Vcc -Vcc
- (Rf / R3 )(V3 )
(e) Scaling adder amplifier (f) Transimpedance amplifier
(current-to-voltage converter)
Rf C
+Vcc Rf +Vcc
C
- -
Vin Vout = - Rf C (dVin /dt) Vin Vout = - 1/(Rf C) (Vin dt)
+ +
-Vcc -Vcc
Figure 4.15: Classic operational amplifier configurations. (Adapted from Faulkenberry [1977].)
4.3. OUTPUT DEVICES 167
Rf Node equation at Vn :
Vn +Vcc
Ri Apply ideal conditions:
-
In In = Ip = 0
Vin Vout
Ip
+ Vn = Vp = 0 (since Vp is grounded)
Vp -Vcc
Solve node equation for Vout :
Figure 4.16: Operational amplifier analysis for the non-inverting amplifier. (Adapted
from Faulkenberry [1982].)
Rf = 13 K
Rf = 10 K
+Vcc
Ri = 10 K +Vcc
- Ri = 10 K
Vin -
+ -Vcc Vout
Ri = 10 K +
-Vcc
10 K bias = 3.3 VDC -Vcc
I I R
R
+ +
from
micro
(a) LED illuminates (b) LED illuminates
for a logic high for a logic high
I R RC
+ +
Vf
C
If
from from B
micro micro
74LVC04 RB E
Common Cathode
VOH : 5.0 VDC 7-segment Display
DIP
IOH : 24 mA (Vf 1.85 VDC @ If 12 mA)
Resistor
a a
Microcontroller Port
b
c 74LVC4245A f b
d Octal Bus
e Transceiver
f g
g
e c
R = (VOH - Vf ) / If
d
R = (5.0 - 1.85)/ 12 mA
R = 262 ohms ~ 270 ohms
1.2K (13)
PORTy[0]
(3) (5) (10) (12)
a PORTx[6]
b PORTx[5]
d PORTx[3]
g PORTx[0]
c PORTx[4]
e PORTx[2]
f PORTx[1]
Numeral
12 7
hex rep
a a a a
f b f b f b f b
0 1 1 1 1 1 1 0 0x7E g g g g
e c e c e c e c
1 0 1 1 0 0 0 0 0x30 d d d d
2 1 1 0 1 1 0 1 0x6D
1 6
3 1 1 1 1 0 0 1 0x79
4 0 1 1 0 0 1 1 0x33
(d) Quad seven segment display pinout
5 1 0 1 1 0 1 1 0x5D UN(M)5624-11 EWRS
6 0 0 1 1 1 1 1 0x1F
7 1 1 1 0 0 0 0 0x70
8 1 1 1 1 1 1 1 0x7F
9 1 1 1 0 0 1 1 0x73
47 G
47 G
Microcontroller Port
47 G
74LVC4245A R
Octal Bus
Transceiver 47 G
47 G
47 G
47 G
5 VDC
5 VDC
5 VDC
3.0 K 2N2222
-
LM324
+
2N2907
3.0 K
C2
Column
Select
Interface
C1
Circuitry
C0
Microcontroller
R6
R5
Row Select
Circuitry
R4
Interface
R3
R2
R1
R0
5 x 7 Dot
Matrix Display
ta
d/da
n
a e
mm abl ata ata
V cc co en d ald
V cc i
ser
10K
DB3-10
DB5-12
DB6-13
DB7-14
RS-4
Vo-3
GND-1
VDD-2
R/W-5
E-6
DB0-7
DB1-8
DB2-9
DB4-11
line1 line1
line2 line2
Figure 4.22: LCD display with (a) parallel interface and (b) serial interface.
4.3. OUTPUT DEVICES 175
precious microcontroller pins. A small microcontroller mounted to the back panel of the LCD
translates the ASCII data characters and control signals to properly display the characters. Sev-
eral manufacturers provide 3.3 VDC compatible displays.
To conserve precious, limited microcontroller I/O pins, a serial configured LCD may be
used. A serial LCD reduces the number of required microcontroller pins for interface, from ten
down to one, as shown in Figure 4.22b. Display data and control information is sent to the LCD
via an asynchronous UART serial communication link (8 data bits, 1 stop bit, no parity, 9600
Baud). A serial configured LCD costs slightly more than a similarly configured parallel LCD.
Example: LCD. In this example a Sparkfun LCD-09067, 3.3 VDC, serial, 16 by 2 charac-
ter, black on white LCD display is connected to the MSP430. Communication between the
MSP430 and the LCD is accomplished by a single 9600 bits per second (baud) connection us-
ing the onboard universal asynchronous receiver transmitter (UART). The UART is configured
for 8 data bits, no parity, and one stop bit (8-N-1). The MSP-EXP430FR5994 LaunchPad is
equipped with two UART channels. One is the back channel UART connection to the PC.
The other is accessible by pin 3 (RX, P6.1) and pin 4 (TX, P6.0). Provided below is the sample
Energia code to print a test message to the LCD. Note the UART is designated “Serial1” in the
program. The back channel UART for the Energia serial monitor display is designated “Serial.”
//*******************************************************************
//Serial_LCD_energia
//Serial 1 accessible at:
// - RX: P6.1, pin 3
// - TX: P6.0, pin 4
//
//This example code is in the public domain.
//*******************************************************************
void setup()
{
//Initialize serial channel 1 to 9600 baud and wait for port to open
Serial1.begin(9600);
}
void loop()
{
Serial1.print("Hello World");
delay(500);
Serial1.println("...Hello World");
delay(500);
}
176 4. MSP430 OPERATING PARAMETERS AND INTERFACING
//*******************************************************************
• DC motor: A DC motor has a positive and a negative terminal. When a DC power supply
of suitable current rating is applied to the motor, it will rotate. If the polarity of the supply
is switched with reference to the motor terminals, the motor will rotate in the opposite
direction. The speed of the motor is roughly proportional to the applied voltage up to the
rated voltage of the motor.
• Servo motor: A servo motor provides a precision angular rotation for an applied pulse
width modulation duty cycle. As the duty cycle of the applied signal is varied, the angular
displacement of the motor also varies. This type of motor is used to change mechanical
positions such as the steering angle of a wheel.
• Stepper motor: A stepper motor, as its name implies, provides an incremental step change
in rotation (typically 2.5ı per step) for a step change in control signal sequence. The motor
is typically controlled by a two or four wire interface. For the four wire stepper motor,
the microcontroller provides a 4-bit control sequence to rotate the motor clockwise. To
turn the motor counterclockwise, the control sequence is reversed. The low-power control
signals are interfaced to the motor via metal oxide semiconductor field effect transistors
(MOSFETs) or power transistors to provide for the proper voltage and current require-
ments of the pulse sequence.
• Linear actuator: A linear actuator translates the rotation motion of a motor to linear for-
ward and reverse movement. The actuators are used in a number of different applications
where precisely controlled linear motion is required. The control software and interface for
linear actuators are very similar to DC motors.
Vmotor
Veff
(a) DC motor
9.0 VDC
1N4001
1N4001
Diodes
protection
+ diode
7.2 VDC M
at 300 mA
-
330
From Motor
TIP 120
MSP430 Current
Vcc = 5 VDC
y_ch_pin (3) (4)
(1) x
(pin 39, P2.6) (2) LM324
(11)
5 VDC
White
mirror
10 K 2.5 VDC
Threshold Parallax 900-00005
Setting servo motor
10 K
Red
Black
Vcc = 5 VDC
Vcc = 5 VDC
x_ch_pin (5) (4)
(7) White
(pin 40, P2.7) (6) LM324
(11) laser source
mirror
//*************************************************************
//X-Y ramp
//
//This example code is in the public domain.
//*************************************************************
void setup()
{
myServo_x.attach(40); //Servo is connected to PWM pin 40
myServo_y.attach(39); //Servo is connected to PWM pin 39
}
void loop()
{
int i = 0;
for(i=0; i<=180; i++) //Rotates servo 0 to 180 degrees
{
myServo_x.write(i); //Rotate servo counter clockwise
myServo_y.write(i); //Rotate servo counter clockwise
delay(20); //Wait 20 milliseconds
if(i==180)
delay(5000);
}
180 4. MSP430 OPERATING PARAMETERS AND INTERFACING
}
//*************************************************************
3.3 VDC
10 uF
Speed. As previously mentioned, DC motor speed may be varied by changing the applied
voltage. This is difficult to do with a digital control signal. However, PWM techniques combined
with a MOSFET interface circuit may be used to precisely control motor speed. The duty cycle
of the PWM signal governs the percentage of the motor supply voltage applied to the motor
and hence the percentage of rated full speed at which the motor will rotate. The interface circuit
4.4. HIGH-POWER DC INTERFACES 181
to accomplish this type of control is shown in Figure 4.27. It is a slight variation of the control
circuit provided in Figure 4.26. In this configuration, the motor supply voltage may be different
than the microcontroller’s 3.3 VDC supply. For an inductive load, a reverse biased protection
diode should be connected across the load. The interface circuit allows the motor to rotate in a
given direction.
DC Motor
3.3 VDC Supply Voltage
10 uF Protection
M Diode
30 K MTD3055EL
IN1 G1 Power FET
MSP430 LTC1157
Microcontroller MOSFET
Driver
IN2 G2
Direction. For a DC motor to operate in both the clockwise and counterclockwise di-
rections, the polarity of the DC motor supplied must be changed. To operate the motor in the
forward direction, the positive battery terminal must be connected to the positive motor ter-
minal while the negative battery terminal must be attached to the negative motor terminal. To
reverse the motor direction, the motor supply polarity must be reversed. An H-bridge is a cir-
cuit employed to perform this polarity switch. An H-bridge may be constructed from discrete
components as shown in Figure 4.28. If PWM signals are used to drive the base of the transis-
tors, both motor speed and direction may be controlled by the circuit. The transistors used in
the circuit must have a current rating sufficient to handle the current requirements of the motor
during start and stall conditions.
Texas Instruments provides a self-contained H-bridge motor controller integrated circuit,
the DRV8829. Within the DRV8829 package is a single H-bridge driver. The driver may control
DC loads with supply voltages from 8–45 VDC with a peak current rating of 5 amps. The
182 4. MSP430 OPERATING PARAMETERS AND INTERFACING
12 VDC
1000 uF
200 200
ZTX451 11DQ06 ZTX451
M
+
-
11DQ06 to PD5
to PD4
470 ZTX551 ZTX551 470
single H-bridge driver may be used to control a DC motor or one winding of a bipolar stepper
motor [DRV8829].
Example: MIKROE-1526 DC MOTOR click. MikroElectronica (www.mikroe.com) man-
ufactures a number of motor interface products including the MIKROE-1526 DC MOTOR
click motor driver board. The board features the T.I. DRV8833RTY H-bridge motor driver. A
test circuit to control a DC motor’s speed and direction is provided in Figure 4.29. We use one
of the motors from the Mini Round Autonomous Maze Navigating Robot (Chapter 2).
In the test circuit, a tach switch is used to determine motor direction and a potentiometer
for motor speed control. These two inputs are read by the Energia program and proper control
signals are issued to the MIKROE-1526 (SL1, SL2, and PWM) for motor speed and direction.
The nSLP pin on the MIKROE-1526 must be logic high to enable the devive. For the test
circuit, the pin is tied to Vcc (3.3 VDC) (www.mikroe.com).
//****************************************************************
//MIKROE-1526 DC Motor click
//Sketch demonstrates operation of the MIKROE-1526 DC Motor click
//
//The circuit:
// - Motor speed control potentiometer.
// Potentiometer connected to analog pin 0 (2). The center wiper
// pin of the potentiometer goes to the analog pin. The side
4.4. HIGH-POWER DC INTERFACES 183
3.3 VDC
Mini round
robot motor M
3.3 VDC
3.3 VDC
(MSP430:19)
3.3 VDC PWM
(MSP430:6) SL1
to MSP430:2 (MSP430: 7) SL2
3.3VDC
Figure 4.29: MIKROE-1526 DC MOTOR click. (Illustration used with permission (www.mi
kroe.com).)
184 4. MSP430 OPERATING PARAMETERS AND INTERFACING
// pins of the potentiometer go to +3.3 VDC and ground.
// - Motor forward/reverse control.
// Tact switch connected to pin 5 of MSP430.
// - MIKROE-1526 connections:
// -- Select 1 (SL1) to MSP430 pin 6
// -- Select 2 (SL2) to MSP430 pin 7
// -- PWM to MSP430 pin 19
// -- nSLEEP to Vcc (3.3 VDC) to enable device
//
//This example code is in the public domain.
//****************************************************************
void setup()
{
pinMode(forward_reverse, INPUT);
pinMode(select1, OUTPUT);
pinMode(select2, OUTPUT);
}
void loop()
{
//Deteremine motor direction
switch_value = digitalRead(forward_reverse);
if(switch_value == HIGH) //forward direction
{
digitalWrite(select1, LOW);
digitalWrite(select2, LOW);
}
else //reverse direction
{
4.4. HIGH-POWER DC INTERFACES 185
digitalWrite(select1, LOW);
digitalWrite(select2, HIGH);
}
delay(50);
}
//****************************************************************
10 uF Protection
Diode
30 K
MTD3055EL
IN1 G1 Power FET
MSP430 LTC1157
Microcontroller MOSFET
Driver
IN2 G2
or counterclockwise, a specific step sequence must be sent to the motor control wires as shown
in Figure 4.31b.
The microcontroller does not have sufficient capability to drive the motor directly. There-
fore, an interface circuit is required as shown in Figure 4.32. The speed of motor rotation is
determined by how fast the control sequence is completed.
//**********************************************************
//stepper
//
//This example code is in the public domain.
//**********************************************************
//external switches
#define ext_sw1 36
#define ext_sw2 35
//stepper channels
#define stepper_ch1 31
#define stepper_ch2 32
#define stepper_ch3 33
#define stepper_ch4 34
4.4. HIGH-POWER DC INTERFACES 187
step
Figure 4.31: Unipolar stepper motor. (Illustration used with permission of Texas Instruments
(www.ti.com).)
188 4. MSP430 OPERATING PARAMETERS AND INTERFACING
3.3 VDC
4.7 K
External Switch 1
(clockwise)
36
3.3 VDC
35
4.7 K
External Switch 2
(clockwise)
12 VDC
orange
1N4001
BCE
42BYG016, 4 phase unipolar, 1.8o/step, 12 VDC, 160 mA
void setup()
{
//Screen
Serial.begin(9600);
//external switches
pinMode(ext_sw1, INPUT);
pinMode(ext_sw2, INPUT);
//stepper channel
pinMode(stepper_ch1, OUTPUT);
pinMode(stepper_ch2, OUTPUT);
pinMode(stepper_ch3, OUTPUT);
pinMode(stepper_ch4, OUTPUT);
void loop()
{
switch_value1 = digitalRead(ext_sw1);
switch_value2 = digitalRead(ext_sw2);
else
{
digitalWrite(stepper_ch1, LOW);
digitalWrite(stepper_ch2, LOW);
digitalWrite(stepper_ch3, LOW);
digitalWrite(stepper_ch4, LOW);
}
}
//**********************************************************
//**********************************************************
//stepper2
//
//This example code is in the public domain.
//**********************************************************
//external switches
#define ext_sw1 2
#define ext_sw2 5
4.4. HIGH-POWER DC INTERFACES 193
3.3 VDC
4.7 K
2
external Switch 1
(clockwise)
5
3.3 VDC
4.7 K
external Switch 2
(counter clockwise)
C
VD
VD
3.3
3.3
6 7 8 9
+
10 VDC
Blu
Figure 4.33: Unipolar stepper motor with DRV8833 breakout board. (Illustration used with
permission of Texas Instruments (www.ti.com).)
194 4. MSP430 OPERATING PARAMETERS AND INTERFACING
//stepper channels
#define stepper_ch1 6
#define stepper_ch2 7
#define stepper_ch3 8
#define stepper_ch4 9
void setup()
{
//Screen
Serial.begin(9600);
//external switches
pinMode(ext_sw1, INPUT);
pinMode(ext_sw2, INPUT);
//stepper channel
pinMode(stepper_ch1, OUTPUT);
pinMode(stepper_ch2, OUTPUT);
pinMode(stepper_ch3, OUTPUT);
pinMode(stepper_ch4, OUTPUT);
void loop()
{
switch_value1 = digitalRead(ext_sw1);
switch_value2 = digitalRead(ext_sw2);
else
{
digitalWrite(stepper_ch1, LOW);
digitalWrite(stepper_ch2, LOW);
digitalWrite(stepper_ch3, LOW);
digitalWrite(stepper_ch4, LOW);
}
}
//**********************************************************
1 6 Vcc
RL
2 5
3 4
nc
220 220
from 10 K from 10 K
2N2222 2N2222
micro micro
4.5.3 DC FAN
The interface circuit shown in Figure 4.24 may also be used to control a DC fan. As before, a
reverse biased diode is placed across the DC fan motor.
12 VDC
Shoreline
Bilge Pump BP 1N4001
4.6 AC DEVICES
A high-power alternating current (AC) load may be switched on and off using a low power
control signal from the microcontroller. In this case, a Solid State Relay is used as the switching
200 4. MSP430 OPERATING PARAMETERS AND INTERFACING
device. Solid state relays are available to switch a high power DC or AC load [Crydom]. For
example, the Crydom 558-CX240D5R is a printed circuit board-mounted, air-cooled, single-
pole single-throw (SPST), normally open (NO) solid-state relay. It requires a DC control voltage
of 3-15 VDC at 15 mA. This microcontroller compatible DC control signal is used to switch
12-280 VAC loads rated from 0.06–5 amps [Crydom].
To vary the direction of an AC motor, you must use a bi-directional AC motor. A bi-
directional motor is equipped with three terminals: common, clockwise, and counterclockwise.
To turn the motor clockwise, an AC source is applied to the common and clockwise connections.
In like manner, to turn the motor counterclockwise, an AC source is applied to the common and
counterclockwise connections. This may be accomplished using two of the Crydom SSRs.
PowerSwitch manufacturers an easy-to-use AC interface the PowerSwitch Tail II. The
device consists of a control module with attached AC connections rated at 120 VAC, 15 A. The
device to be controlled is simply plugged inline with the PowerSwitch Tail II. A digital control
signal from MSP430 (3 VDC at 3 mA) serves as the on/off control signal for the controlled
AC device. The controlled signal is connected to the PowerSwitch Tail II via a terminal block
connection. The PowerSwitch II may be configured as either normally closed (NC) or normally
open (NO) (www.powerswitchtail.com).
Example: PowerSwitch Tail II. In this example, we use an IR sensor to detect someone’s pres-
ence. If the IR sensor’s output reaches a predetermined threshold level, an AC desk lamp is
illuminated, as shown in Figure 4.37.
//****************************************************************
//switch_tail
//
//The circuit:
// - The IR sensor signal pin is connected to analog pin 3 (6).
// The sensor power and ground pins are connected to 5 VDC and
// ground respectively.
// - The analog output is designated as the onboard red LED.
// - The switch tail control signal is connected to P6.2 (pin 5)
//
//Adapted for code originally written by Tom Igoe
//Created: Dec 29, 2008
//Modified: Aug 30, 2011
//Author: Tom Igoe
//
//This example code is in the public domain.
//****************************************************************
Desk Lamp
PowerSwitch Tail II
To AC
3: Gnd
1: +in
2: -in
Wall Outlet
5 VDC
5
6
GND
RYB
IR Sensor
Figure 4.37: PowerSwitch Tail II. (Illustration used with permission of Texas Instruments (ww
w.ti.com).)
202 4. MSP430 OPERATING PARAMETERS AND INTERFACING
const int analogOutPin = RED_LED; //Energia onboard red LED pin
const int switch_tail_control =5zz; //Switch Tail control signal
void setup()
{
//initialize serial communications at 9600 bps:
Serial.begin(9600);
void loop()
{
//read the analog in value:
sensorValue = analogRead(analogInPin);
//****************************************************************
Joystick Switches
Color 128 × 128 TFT LCD
RGB LED
Microphone
Buzzer
Figure 4.38: Educational Booster Pack MkII. (Illustration used with permission of Texas In-
struments (www.ti.com).)
204 4. MSP430 OPERATING PARAMETERS AND INTERFACING
In the list of features below, pin numbers provided refer to the MkII pin placement. The MkII
is equipped with a [SLAU599].
• Microphone. The MkII is equipped with the CUI CMA-4544PW-W electret micro-
phone. The microphone signal is amplified via an OPA344 operational amplifier. The mi-
crophone has a frequency response of 20 Hz to 20 kHz. The microphone is connected to
MSP430 pin J1.6.
• Light sensor. The light sensor aboard the MkII is the OPT3001 digital ambient light
sensor. The sensor measures ambient light intensity and it is tuned to the light response
of the human eye. It also has filters to reject infrared (IR) light. It detects light intensity
in the range from 0.01–83 lux. The I2C compatible output of the sensor is provided to
MSP430 via pins J1.9 (I2C SCL), J1.10 (I2C SDA), and J1.8 (sensor interrupt).
• Temperature sensor. The temperature sensor is also I2C compatible. The TMP006 is a
noncontact sensor that passively absorbs IR wavelengths from 4–16 m. The I2C com-
patible output is provided to the MSP430 via pins J1.9 (I2C SCL), J1.10 (I2C SDA), and
J2.11 (sensor interrupt).
• Servo motor controller. The MkII is equipped with a convenient connector for a servo
motor. The servo motor control signal is provided by MSP430 signal pin J2.19.
• Pushbuttons. The MkII is equipped with two pushbuttons designated S1 and S2. They
are connected to the MSP430 via pins J4.33 (S1) and J4.32 (S2).
• Red-Green-Blue (RGB) LED. The RGB LED aboard the MkII is the Cree CLV1A-
-FKB RGB multicolor LED. The three-color components are accessible via pins J4.39
(red), J4.38 (green), and J4.37 (blue). The intensity of each component may be adjusted
using PWM techniques.
• Buzzer. The piezo buzzer aboard the MkII is the CUI CEM-1230. The buzzer will operate
at various frequencies using PWM techniques. The buzzer is accessible via pin J4.40.
4.8. GROVE STARTER KIT FOR LAUNCHPAD 205
• Color TFT LCD. The color 2D LCD aboard the MkII is controlled via the serial pe-
ripheral interface (SPI) system. The Crystalfontz CFAF 128128B-0145T is a color 128
by 128 pixel display.
Provided in Energia is considerable software support for the MkII. This software will
be explored in the Laboratory Exercise, Section 4.10. It is important to note that not all of
the Educational Booster Pack MkII examples included within Energia are compatible with the
MSP430FR5994.
Figure 4.39: Grove starter kit for LaunchPad (www.seeedstudio.com). (Illustrations used with
permission of Texas Instruments (www.TI.com).)
1. Interface the 3.3 VDC MSP430 to an LED cube designed for 5 VDC operation via a
3.3–5.0 VDC level shifter.
LED0
Idiode LED
0 1 2
_
_
_
3
- +
+
+
+
Cocktail
Straw
Spacer
4 5 6
_
_
_
7
- +
+
+
+
_ 8 9 10
_
_
_
11
- + +
+
+
+
LED horizontal layer 3
LED horizontal layer 2
LED horizontal layer 1
Idiode
12 13 14
_
_
Side _ 15
+_
Vcc = 5 VDC
View - +
+
+
+
+
220 18 16 14 12 9 7 5 3
LED horizontal layer 0 20
Idiode = top view 74HC244
/OEa-1
/OEb-19
IOL = +/- 25 mA 10
Vcc = 5 VDC 2 4 6 8 11 13 15 17
1 2 3 4 5 6 7 8 9 10 11 13 14 1516 17 24
74HC154
/E0-18 4-to-16 decoder
/E1-19
20 21 22 23 12
D C B A
LED select
31 led_sel0
32 led_sel1
33 led_sel2
34 led_sel3
MSP430
Adafruit
TXB0108
Level
layer select
35 layer_sel0
Shifter
36 layer_sel1
37 layer_sel2
38 layer_sel3
Notes:
1. LED cube consists of 4 layers of 16 LEDs each.
2. Each LED is individually addressed by asserting the appropriate cathode signal (0‒15)
and asserting a specific LED layer.
3. All LEDs in a given layer share a common anode connection.
4. All LEDs in a given position (0‒15) share a common cathode connection.
LED0
Idiode
- +
Cocktail LED
Straw 0 1 2
_
_
_
3
+
Spacer
+
- +
4 5 6
_
_
_
7
+
+
+
- +
8 10
_
_
9
_
11
+
+
+
+
LED horizontal layer 3
Side LED horizontal layer 2
View - +
LED horizontal layer 1
Idiode
Idiode = 12 13
_
_
14
_
15
+
_
Vcc = 5 VDC
+
+
+
+
220 18 16 14 12 9 7 5 3
IOL = +/- 25 mA 74LVX244 20
/OE1-1
/OE2-19
10
2 4 6 8 11 13 15 17
LE C
C
D 0
D 1
D 2
LE 13
D 4
15
VD
VD
LE 0
LE 1
LE 2
LE 3
LE 4
LE 5
LE 6
7
LE 8
LE 9
LE 1
LE 1
LE 1
LE 1
D
D
D
D
D
D
D
D
D
D
D
D
5
5
LE
cc =
cc =
V
O0 O1 O2 O3 O4 O5 O6 O7 (16) O0 O1 O2 O3 O4 O5 O6 O7 (16)V
(15) (14) (13)(12) (11) (10) ( 9) ( 7) (15) (14) (13)(12) (11) (10) ( 9) ( 7)
74LVX138 74LVX138
(4) (5) (6) (1) (2) (3) (4) (5) (6) (1) (2) (3)
/E1 /E2 E3 A0 A1 A2 (8) /E1 /E2 E3 A0 A1 A2 (8)
5 VDC
LED select
31 led_sel0
32 led_sel1
33 led_sel2
34 led_sel3
MSP430
Layer Select
35 layer_sel0
36 layer_sel1
37 layer_sel2
38 layer_sel3
_
_
_
+
+
+
+
LED anodes are connected together
to form a common anode crossbar
between LED rows and columns
4 5 6 7
_
_
_
+
+
+
+
8 10 11
_
_
9
_
+
+
+
+
12 13 15
_
_
14
_
_
+
+
+
+
(a) LED soldering diagram
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
-+ -+ -+ -+
void setup()
{
pinMode(led_sel0, OUTPUT);
pinMode(led_sel1, OUTPUT);
pinMode(led_sel2, OUTPUT);
pinMode(led_sel3, OUTPUT);
pinMode(layer_sel0, OUTPUT);
pinMode(layer_sel1, OUTPUT);
pinMode(layer_sel2, OUTPUT);
pinMode(layer_sel3, OUTPUT);
}
void loop()
{
//illuminate LED 0, layer 0
//led select
digitalWrite(led_sel0, LOW);
digitalWrite(led_sel1, LOW);
digitalWrite(led_sel2, LOW);
digitalWrite(led_sel3, LOW);
//layer select
digitalWrite(layer_sel0, HIGH);
digitalWrite(layer_sel1, LOW);
digitalWrite(layer_sel2, LOW);
digitalWrite(layer_sel3, LOW);
//*********************************************
In the next example, a function “illuminate_LED” has been added. To illuminate a specific
LED, the LED position (0–15), the LED layer (0–3), and the length of time to illuminate the
LED in milliseconds are specified. In this short example, LED 0 is sequentially illuminated in
each layer. An LED grid map is shown in Figure 4.44. It is useful for planning special effects.
//************************************************
//led_cube2
//
//This example code is in the public domain.
//************************************************
void setup()
{
pinMode(led_sel0, OUTPUT);
pinMode(led_sel1, OUTPUT);
pinMode(led_sel2, OUTPUT);
pinMode(led_sel3, OUTPUT);
pinMode(layer_sel0, OUTPUT);
pinMode(layer_sel1, OUTPUT);
pinMode(layer_sel2, OUTPUT);
pinMode(layer_sel3, OUTPUT);
}
void loop()
{
214 4. MSP430 OPERATING PARAMETERS AND INTERFACING
0 1 2 3
layer 3
4 5 6 7
8 9 10 11
12 13 14 15
0 1 2 3
layer 2
4 5 6 7
8 9 10 11
12 13 14 15
0 1 2 3
layer 1
4 5 6 7
8 9 10 11
12 13 14 15
0 1 2 3
layer 0
4 5 6 7
8 9 10 11
12 13 14 15
//*********************************************
if(layer==0)
{
digitalWrite(layer_sel0, HIGH);
digitalWrite(layer_sel1, LOW);
digitalWrite(layer_sel2, LOW);
digitalWrite(layer_sel3, LOW);
}
else if(layer==1)
{
digitalWrite(layer_sel0, LOW);
digitalWrite(layer_sel1, HIGH);
digitalWrite(layer_sel2, LOW);
digitalWrite(layer_sel3, LOW);
}
else if(layer==2)
{
digitalWrite(layer_sel0, LOW);
digitalWrite(layer_sel1, LOW);
digitalWrite(layer_sel2, HIGH);
digitalWrite(layer_sel3, LOW);
}
else if(layer==3)
{
digitalWrite(layer_sel0, LOW);
digitalWrite(layer_sel1, LOW);
digitalWrite(layer_sel2, LOW);
digitalWrite(layer_sel3, HIGH);
}
delay(delay_time);
}
//*********************************************
4.9. APPLICATION: SPECIAL EFFECTS LED CUBE 219
In the next example, a “fireworks” special effect is produced. The firework goes up, splits
into four pieces, and then falls back down as shown in Figure 4.45. It is useful for planning
special effects.
//************************************************
//fireworks
//
//This example code is in the public domain.
//************************************************
void setup()
{
pinMode(led_sel0, OUTPUT);
pinMode(led_sel1, OUTPUT);
pinMode(led_sel2, OUTPUT);
pinMode(led_sel3, OUTPUT);
pinMode(layer_sel0, OUTPUT);
pinMode(layer_sel1, OUTPUT);
pinMode(layer_sel2, OUTPUT);
pinMode(layer_sel3, OUTPUT);
}
void loop()
{
int i;
220 4. MSP430 OPERATING PARAMETERS AND INTERFACING
0 1 2 3
layer 3
4 5 6 7
8 9 10 11
12 13 14 15
0 1 2 3
layer 2
4 5 6 7
8 9 10 11
12 13 14 15
0 1 2 3
layer 1
4 5 6 7
8 9 10 11
12 13 14 15
0 1 2 3
layer 0
4 5 6 7
8 9 10 11
12 13 14 15
delay(200);
delay(200);
delay(200);
delay(10);
}
//*********************************************
if(layer==0)
{
digitalWrite(layer_sel0, HIGH);
digitalWrite(layer_sel1, LOW);
digitalWrite(layer_sel2, LOW);
digitalWrite(layer_sel3, LOW);
}
else if(layer==1)
{
digitalWrite(layer_sel0, LOW);
digitalWrite(layer_sel1, HIGH);
digitalWrite(layer_sel2, LOW);
digitalWrite(layer_sel3, LOW);
}
else if(layer==2)
{
digitalWrite(layer_sel0, LOW);
digitalWrite(layer_sel1, LOW);
digitalWrite(layer_sel2, HIGH);
digitalWrite(layer_sel3, LOW);
}
else if(layer==3)
226 4. MSP430 OPERATING PARAMETERS AND INTERFACING
{
digitalWrite(layer_sel0, LOW);
digitalWrite(layer_sel1, LOW);
digitalWrite(layer_sel2, LOW);
digitalWrite(layer_sel3, HIGH);
}
delay(delay_time);
}
//*********************************************
• MkII feature,
Procedure 2: Access the Grove Starter Kit support software. Execute the software and interact
with the peripherals aboard the Grove. Develop a table of features for the Grove. The table
should have column headings for:
• grove feature,
4.12 SUMMARY
In this chapter, we presented the voltage and current operating parameters for the MSP430 mi-
crocontroller. We discussed how this information may be applied to properly design an interface
for common input and output circuits. It must be emphasized a carefully and properly designed
interface allows the microcontroller to operate properly within its parameter envelope. If due
to a poor interface design, a microcontroller is used outside its prescribed operating parameter
values, spurious and incorrect logic values will result. We provided interface information for a
wide range of input and output devices. We also discussed the concept of interfacing a motor to a
microcontroller using PWM techniques coupled with high power MOSFET or SSR switching
devices.
Linear Technology, LTC1157 3.3 Dual Micropower High-Side/Low-Side MOSFET Driver. 180
MikroElektronika. www.mikroe.com
Sedra, A. and Smith, K. Microelectronic Circuits, 5th ed., Oxford, Oxford University Press, 2004.
170
Sparkfun. www.sparkfun.com
Texas Instruments Logic Guide, (SDYU001AB), Texas Instruments, 2017. 142, 143
Texas Instruments LSF010XEVM-001 User’s Guide, (SDLU003A), Texas Instruments, 2015. 144
Texas Instruments TPIC6C596 Power Logic 8-Bit Shift Register, (SLIS093D), 2015. 145
4.14. CHAPTER PROBLEMS 229
4.14 CHAPTER PROBLEMS
Fundamental
1. What will happen if a microcontroller is used outside of its prescribed operating envelope?
2. Discuss the difference between the terms “sink” and “source” as related to current loading
of a microcontroller.
3. Can an LED with a series-limiting resistor be directly driven by the MSP430 microcon-
troller? Explain.
4. In your own words, provide a brief description of each of the microcontroller electrical
parameters.
5. What is switch bounce? Describe two techniques to minimize switch bounce.
6. Describe a method of debouncing a keypad.
Advanced
1. What is the difference between an incremental encoder and an absolute encoder? Describe
applications for each type.
2. What must be the current rating of the 2N2222 and 2N2907 transistors used in the tri-
state LED circuit? Support your answer.
Challenging
1. Draw the circuit for a six-character seven segment display. Fully specify all components.
Write a program to display “MSP430.”
2. Repeat the question above for a dot matrix display.
3. Repeat the question above for a LCD display.
4. An MSP430 has been connected to a JRP 42BYG016 unipolar, 1.8ı per step, 12 VDC
at 160 mA stepper motor. A 1-s delay is used between the steps to control motor speed.
Pushbutton switches SW1 and SW2 are used to assert CW and CCW stepper motion.
Write the code to support this application.
231
CHAPTER 5
5.1 OVERVIEW
In a basic circuits course, we learn energy consumption is the product of power and time. We
also learn that power is the product of voltage and current. This chapter discusses techniques
to minimize the energy consumption in an MSP430 microcontroller-based application. The
overriding chapter theme is to strategically use different techniques to minimize the time the
microcontroller is operated in high voltage and current modes.
232 5. POWER MANAGEMENT AND CLOCK SYSTEMS
We begin the chapter with a discussion on the balancing act microcontroller-based sys-
tem designers perform between the energy requirements of a given application and available
power sources. We also provide an overview of the ultra-low power strategies and features of
the MSP430 microcontroller that support such strategies. We then discuss the LPMs of the
MSP430 and how they help to reduce power consumption. We investigate the MSP430 subsys-
tems which contribute to ULP operation, including the Power Management Module, the Supply
Voltage Supervisor, and the CS. The MSP430 CS provides for a variety of clock sources and
operating frequencies for the MSP430. Since operating frequency is directly related to power
consumption, the goal is to choose the lowest operating frequency and still accomplish the mi-
crocontroller’s task. We then consider the battery supply. We begin with a discussion of battery
capacity and its key parameters. We also describe the important concept of voltage regulation
and different methods of achieving a stable voltage source within a circuit. The chapter concludes
with a laboratory exercise to investigate current drain in different MSP430 operating modes and
methods to operate an MSP430 using various power sources including a single 1.5 VDC battery
by employing a high-efficiency charge pump integrated circuit.
• operating temperature,
PMMREGOFF=1
CPUOFF=1 CPUOFF=1
OSCOFF=0 OSCOFF=1
LPM0: SCG0=0 SCG0=1 LPM4:
CPU/MCLK = off SCG1=0 Active Mode: SCG1=1 CPU/MCLK = off
FLL = on - CPU is active FLL = off
ACLK = on - Various modules ACLK = off
Int/NMI are active Int/NMI
Vcore = on Vcore = on
CPUOFF=1 CPUOFF=1
OSCOFF=0 OSCOFF=0
SCG0=1 SCG0=1
SCG1=0 SCG1=1
Int/NMI Int/NMI
LPM1: LPM3:
CPU/MCLK = off CPUOFF=1
Int/NMI CPU/MCLK = off
FLL = off OSCOFF=0
FLL = off
ACLK = on SCG0=0 ACLK = on
Vcore = on SCG1=1 Vcore = on
LPM2:
CPU/MCLK = off
FLL = off
ACLK = on
Vcore = on
Figure 5.1: MSP430 operating modes. Adapted from Texas Instruments SLAU208Q [2018].
(Illustration used with permission of Texas Instruments (www.ti.com).)
• Insert filename.c into the white box at the bottom right corner of the Energia screen and
click “OK.” A new tab will now open with the designation filename.c.
• The C program may now be written in the new tab.
• Compile and load the program to the LaunchPad using the check and right arrow icons.
Note: The MSP-EXP430FR2433 LaunchPad may also be used for this example; however,
the 32 kHz crystal is not connected. Procedures for connecting the crystal is provided in the
MSP430FR2433 LaunchPad Development Kit User’s Guide [SLAU739, 2017].
Use the following procedures to measure the current used by the LaunchPad [SLAU678A,
2016]:
• Remove the 3V3 jumper that links the eZ-FET Debug Probe from the MSP430FR5994
portion of the MSP-EXP430FR5994 LaunchPad, as shown in Figure 5.2.
• Connect an ammeter in place of the jumper. Insure the ammeter is capable of measuring
microamps.
5.3. OPERATING MODES 235
• Disconnect the UART channel back to the host computer by removing the TXD jumper.
• Declare all unused pins as output.
• Once the current measurement is complete, restore the 3V3 and TXD jumpers.
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2014, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
//MSP430FR5x9x Demo - Entering and waking up from LPM4.5 via P1.3
//interrupt with SVS disabled.
//
//Description:
//- Download and run the program.
//- When LPM4.5 entered, no LEDs should be on.
//- Use a multimeter to measure current on JP1 and compare to the
// datasheet.
//- When a positive voltage is applied to P1.3 the device should
// wake up from LPM4.5. This will enable the LFXT oscillator
// and blink the LED (on P1.0).
//
// MSP430FR5994
// ---------------
// /|\| XIN|-
// | | | 32KHz Crystal
// --|RST XOUT|- /|\
// | | |
// | P1.0|---> LED / switch
// | | |
// | P1.3|<------------------
// Pulled-down internally.
// Apply positive voltage.
//
//William Goh
//Texas Instruments Inc.
//October 2015
236 5. POWER MANAGEMENT AND CLOCK SYSTEMS
USB
to A
Host
Jumper Isolation
Block
LED1
Figure 5.2: Configuring the FR5994 for current measurements. (Illustration used with permis-
sion of Texas Instruments (www.ti.com).)
5.3. OPERATING MODES 237
//Built with IAR Embedded Workbench V6.30 & Code Composer Studio V6.1
//**********************************************************************
#include <msp430.h>
//Function prototypes
void configure_GPIO(void);
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //stop watchdog timer
configure_GPIO(); //configure I/O
//After wakeup from LPM4.5 state of I/Os are locked until the LOCKLPM5
//bit in the PM5CTL0 register is cleared.
//Disable the GPIO power-on default high-impedance mode to activate
//previously configured port settings. The oscillator should now
//start...
PM5CTL0 &= ~LOCKLPM5;
do{
CSCTL5 &= ~LFXTOFFG; //Clear XT1 fault flag
SFRIFG1 &= ~OFIFG;
238 5. POWER MANAGEMENT AND CLOCK SYSTEMS
}while (SFRIFG1 & OFIFG); //Test oscillator fault flag
}//end if
else
{
//Configure P1.3 Interrupt
P1OUT &= ~BIT3; //Pull-down resistor on P1.3
P1REN |= BIT3; //Select pull-down mode for P1.3
P1DIR = 0xFF ^ BIT3; //Set all but P1.1 to output
//direction
P1IES &= ~BIT3; //P1.3 Lo/Hi edge
P1IFG = 0; //Clear all P1 interrupt flags
P1IE |= BIT3; //P1.3 interrupt enabled
//Enter LPM4 Note that this operation does not return. The LPM4.5
//will exit through a RESET event, resulting in a re-start
//of the code.
__bis_SR_register(LPM4_bits); //SCG1+SCG0+OSCOFF+CPUOFF
//*********************************************************************
5.4. THE POWER MANAGEMENT MODULE AND SUPPLY VOLTAGE SUPERVISOR 239
void configure_GPIO(void)
{
P1OUT = 0; P1DIR = 0xFF; P2OUT = 0; P2DIR = 0xFF;
P3OUT = 0; P3DIR = 0xFF; P4OUT = 0; P4DIR = 0xFF;
P5OUT = 0; P5DIR = 0xFF; P6OUT = 0; P6DIR = 0xFF;
P7OUT = 0; P7DIR = 0xFF; P8OUT = 0; P8DIR = 0xFF;
//*********************************************************************
Supervisor-Supervised Supervisor-Supervised
High Side (SVSH) LowSide (SVSL) Brownout
Supervisor-Monitored Reference Supervisor-Monitored Reset
High Side (SVMH) Low Side (SVML) (BOR)
Figure 5.3: Power management module and supply voltage supervisor. (Adapted from
SLAU208Q [2018].)
f3
System Frequency (MHz)
3
f2
2 2,3
f1
1 1, 2 1, 2,3
f0
0 0, 1 0, 1, 2 0, 1, 2,3
1.8 2.0 2.2 2.4 3.6
Figure 5.4: Operating frequency vs. supply voltage profile for the MSP430 microcontroller.
(Adapted from SLAU208Q [2018].)
5.5. CLOCK SYSTEM 241
falls below a prescribed level. If monitoring options are selected, an interrupt is generated to
indicate which sensed voltage has fallen below prescribed levels [SLAU208Q, 2018].
The SVS also has brownout reset (BOR) circuitry which monitors the VCORE voltage.
During startup, the BOR keeps the microcontroller in the reset state until voltages have reached
minimum levels and stabilized. During normal operation, the BOR will generate a reset if VCORE
falls below prescribed levels [SLAU208Q, 2018].
#include <msp430.h>
244 5. POWER MANAGEMENT AND CLOCK SYSTEMS
FLLWARNEN, FLLULIE
FLLUNLOCKHIS, FLLUNLOCK
FLLULIFG, DCOFFG
DC OF TRIM
SELREF FLLREFDIV DCORSEL, DCO
DISMOD, MOD
REFOCLK
FD
LPF
REFO
DCOCLK
DCO
XT1 10
VLOAUTOOFF
XT1OUT
SMCLK
XT1 11
ENSTFCNT1 DIVS SMCLKOFF
XT10FFG VLO
VLOCLK
ACLK
SELA
MODCLK
DIVA MODO
XT1CLK
From Peripherals
MODCLK Request
MODCLKREQEN
From Peripherals
MCLK Request
MCLKREQEN
From Peripherals
ACLK Request
ACLKREQEN
Figure 5.6: MSP430FR2433 clock system (CS) overview [SLAU445G, 2016]. (Illustration used
with permission of Texas Instruments (www.ti.com).)
5.5. CLOCK SYSTEM 245
ACLK_REQEN
ACLK_REQ
SELA OSCOFF
1 LFXTCLK
LFXIN 000
0 001 DIVA
010
Divider
rsvd 011
LFXOUT /1/2/4/8/16/32 0 ACLK
rsvd 100
LFXTDRIVE LFXT rsvd 101 1
rsvd 110
rsvd 111
MCLK_REQEN
MCLK_REQ
SELM CPUOFF
EN
Faut
HFXTBYPASS Detection
000
001 DIVM
1 HFXTCLK
HFXIN 010
0 Divider
011
/1/2/4/8/16/32 0 MCLK
100
101 1
HFXOUT
rsvd 110
HFXTDRIVE HFXT rsvd 111
SMCLK_REQEN
SMCLK_REQ
VLOCLK
VLO SELS SMCLKOFF
EN
000
001 DIVS
2.7/3.3/4/5.3/6.7/8MHz 010
0 DCOCLK Divider
011 0 SMCLK
16/20/24 MHz 1 /1/2/4/8/16/32
100
101 1
DCO rsvd 110
rsvd 111
MODOSC_REQEN VLOCLK
MODOSC_REQ
LFXTCLK
SELA OSCOFF
Unconditional MODOSC
requests
MODOSC Enable
Logic
EN LFMODCLK
/128
MODCLK
MODOSC /1
Figure 5.7: MSP430FR5994 clock system (CS) overview [SLAU367O, 2017]. (Illustration used
with permission of Texas Instruments (www.ti.com).)
246 5. POWER MANAGEMENT AND CLOCK SYSTEMS
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop watchdog timer
P1DIR |= BIT0 | BIT3 | BIT7; //set MCLK SMCLK and LED pin as output
P1SEL1 |= BIT3 | BIT7; //set MCLK, SMCLK pin as second func
P2DIR |= BIT2; //set ACLK pin as output
P2SEL1 |= BIT2; //set ACLK pin as second function
PM5CTL0 &= ~LOCKLPM5; //disable the GPIO power-on default
//high-impedance mode
//to activate previously configured
//port settings
while(1)
{
P1OUT ^= BIT0; //Toggle P1.0 using exclusive-OR
__delay_cycles(8000000); //delay for 8000000*(1/MCLK)=0.5s
}
}
//*********************************************************************
5.5. CLOCK SYSTEM 247
Example: In this example the MSP-EXP430FR5994 LaunchPad is used to configure the
MCLK and SMCLK for 8 MHz operation. The ACLK is sourced by the VLOCLK and di-
vided for a 9.4 kHZ output. The clock signals are routed to external pins for observation on an
oscilloscope or logic analyzer.
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2014, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
//MSP430FR5x9x Demo - Configure MCLK for 8MHz operation
//
//Description: Configure SMCLK = MCLK = 8MHz, ACLK = VLOCLK.
//
// MSP430FR5994
// ---------------
// /|\| |
// | | |
// --|RST |
// | |
// | P1.0|---> LED
// | P2.0|---> ACLK = ~9.4kHz
// | P3.4|---> SMCLK = MCLK = 8MHz
//
//William Goh, Texas Instruments Inc., October 2015
//Built with IAR Embedded Workbench V6.30 & Code Composer Studio V6.1
//*********************************************************************
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop WDT
//Configure GPIO
P1OUT &= ~BIT0;
P2DIR |= BIT0;
P2SEL0 |= BIT0; //Output ACLK
P2SEL1 |= BIT0;
P3DIR |= BIT4;
P3SEL1 |= BIT4; //Output SMCLK
P3SEL0 |= BIT4;
while(1)
{
P1OUT ^= BIT0; //Toggle LED
__delay_cycles(8000000); //Wait 8,000,000 CPU Cycles
}
5.6. BATTERY OPERATION 249
}
//*********************************************************************
• What are the voltage and current required by the embedded system?
• How long must the embedded system operate before battery replacement or recharge?
• Will the embedded system be powered from primary, non-rechargeable batteries or sec-
ondary, rechargeable batteries?
Once these questions have been answered, a battery may be chosen for a specific applica-
tion. To choose an appropriate battery, the following items must be specified:
• battery voltage,
• battery capacity,
Battery capacity is typically specified as a mAH rating. The capacity is the product of the
current drain and the battery operational life at that current level. It provides an approximate
estimate of how long a battery will last under a given current drain. The capacity is reduced at
higher discharge rates. It is important to note that a battery’s voltage declines as the battery
discharges. Provided in Figure 5.8 are approximate capacity ratings for common battery sizes
and technologies (www.duracell.com).
Primary and secondary batteries are manufactured using a wide variety of processes.
In general, primary (non-rechargeable) batteries have a higher capacity than their secondary
(rechargeable) counterparts. Also, batteries with higher capacity are more expensive than those
using a lower-capacity technology. A thorough review of the manufacturers’ literature is recom-
mended to select a battery for a specific application.
250 5. POWER MANAGEMENT AND CLOCK SYSTEMS
Primary Secondary
Other Battery
(non-rechargeable) (rechargeable)
Technologies
Alkaline Battery Nickel-Cadmium (Ni-Cad)
Battery Rated Rated Rated
Designator Voltage Capacity Voltage Capacity Voltage Capacity
D 1.5 V 15,000 mAh 1.2 V 1,200 mAh ---
C 1.5 V 7,000 mAh 1.2 V 1,200 mAh ---
AA 1.5 V 2,250 mAh 1.2 V 500 mAh ---
AAA 1.5 V 1,000 mAh 1.2 V 180 mAh ---
3.7 V (18650) --- --- 3.7 V 6,000 mAh (Li-ion)
9V 9.0 V 550 mAh --- 9.0 V 250 mAh (NI-MH)
12 V --- --- 12.0 V 8.5 Ah (sealed Lead Acid)
I
LM1117-3.3 O +3.3 VDC
C
+ 10 uF +
Battery 10 uF
Tantalum Tantalum
Figure 5.9: Battery supply circuits employing a 3.3 VDC regulators [SNOS412N, 2016].
C1 C2
1 uF 1 uF
VIN OUT1 2X IN
40 mA maximum
0.9–1.8 CIN COUT1
VDC 1 uF TPS60310 1 uF
High-efficiency Charge Pump
5.10 SUMMARY
In this chapter, we presented the ultra-low power features of the MSP430 microcontroller. We
then reviewed the low-power operating modes to reduce power consumption. We then investi-
gated the MSP430 subsystems which contribute to ULP operation, including the power man-
agement system, the supply voltage supervisor, and the CS. By evaluating the required battery
capacity and the operating modes of the MSP430 controllers, one can choose appropriate bat-
teries to satisfy system requirements.
We then examined the other side of the coin, the battery supply. We began with a dis-
cussion of battery capacity and its key parameters. We also described the important concept of
voltage regulation and different methods of achieving a stable input voltage for the MSP430. The
chapter concluded with a laboratory exercise to investigate current drain in different MSP430
operating modes and how to operate an MSP430 using a single 1.5 VDC battery, by employing
a high-efficiency charge pump integrated circuit.
2. Draw a block diagram and describe the operation of the supply supervisor system (SVS).
3. Draw a block diagram and describe the operation of the clock system (CS).
4. Describe the differences of the three clocks on the MSP430: the MCLK, ACLK, and
SMCLK.
5. What is the difference between supply voltage supervision (SVS) and monitoring?
Challenging
1. Write a function in C to place the MSP430 in a specified low-power mode (LPM). The
desired LPM is passed into the function as a variable.
2. Compile a list of best practices to operate the MSP430 microcontroller in the most efficient
manner.
255
CHAPTER 6
• employ the binary and hexadecimal numbering systems to describe the contents or address
of a specific memory location;
• describe the function of the address, data, and control buses of a memory component;
• list the steps required for a memory component to be read from or written to;
• describe the difference between a Harvard and a von Neumann microcontroller architec-
ture;
• provide the distinguishing features of RAM, ROM, and EEPROM type memory com-
ponents;
• sketch the memory map for the MSP430FR2433 and the MSP430FR5994 microcon-
trollers;
• list the advantages of employing DMA techniques to transfer data using the
MSP430FR5994;
• program the MSP430 DMA controller to transfer data from different portions of memory;
and
6.1 OVERVIEW
In general, there are two purposes for a memory system in a microcontroller: the storage and
retrieval space for computer instructions and the storage and working space for data. For a
memory-mapped I/O system, memory locations are used to capture inputs, store outputs, and
256 6. MSP430 MEMORY SYSTEM
program subsystems of microcontrollers. As its name implies, the memory system allows a mi-
crocontroller to retain the program it is supposed to execute. Various memory components also
allow data to be stored and modified during program execution.
Memory is essential in all microcontroller-based applications. In a smart home applica-
tion, memory is used to store the algorithm to control the environmental factors serving the
entire home. Other memory components are used to store and allow the update of combina-
tions to secure areas of the home, control temperature, and to activate lawn irrigation systems.
Furthermore, external memory components can be used for data logging. For example, key smart
home parameters such as temperature and humidity may be measured and stored on a multi me-
dia card/secure digital (MMC/SD) card. The data may be logged over a long period of time. The
MMC/SD card may be removed from the microcontroller-based system and read by a personal
computer (PC) to examine and analyze the data. From this analysis, trends may be established
to optimize the operation of the smart home control algorithm.
The intent of this chapter is to allow the reader to become acquainted with memory con-
cepts, types of memory, and its operation. The chapter begins with a review of key memory
concepts and terminology. This is followed by detailed maps of the MSP430FR2433 and the
MSP430FR5994 microcontroller memory components. The different memory systems onboard
the MSP430 are then discussed. These include the FRAM, RAM, and the DMA memories.
We also provide examples on how to equip a LaunchPad with an MMC/SD card. The chapter
concludes with a laboratory exercise detailing the operation of the DMA memory controller.
Memory
System
Address
Bus m
Control
Bus c
Data
Bus n
(a) Memory system model
0000_0000_0000_0000_0000 Word 0
Word 1
Word 2
1111_1111_1111_1111_1111
Figure 6.1: (a) General model for a memory system and (b) memory length and width.
258 6. MSP430 MEMORY SYSTEM
address bus contains a number (m) of separate address lines. Using linear addressing techniques,
the expression 2address lines shows the number of uniquely addressable memory locations. For
example, some variants of the MSP430 microcontroller have 20 address lines and, therefore,
may separately address 220 or 1,048,576 different memory locations.
The data bus width (n) usually matches the width of memory or the number of bits stored
at each memory location. This allows the contents of a specific memory location to be read from
or written to simultaneously. The MSP430 microcontroller has a 16-bit data path. The width of
the data path also determines the maximum size of mathematical arguments that can be easily
processed by the microcontroller. For example, with a 16-bit data width, the maximum unsigned
integer that may be processed without overflow is 216 or 65,535.
The control bus consists of the signal lines required to perform memory operations such
as read and write. There are typically control signals to specify the memory operation (read or
write), a clock input, and an enable output for the memory system.
• The address of the memory location to be read is provided by the microcontroller on its
address bus to the memory system.
• The control signal to read the specified memory location is asserted by the microcontroller.
• The data at the specified memory location is fetched from memory and placed on the
memory system data lines.
• The control signal to enable the memory system output is asserted. This allows the fetched
memory data access to the data bus.
• The data to be written to the specified memory location is provided by the microcontroller
on its data bus.
32768
16834
8192
4096
2048
1024
512
256
128
64
32
16
8
4
2
1
215 214 213 212 211 210 29 28 27 26 25 24 23 22 21 20
(a) Binary number system
Binary Hex Binary Hex Binary Hex Binary Hex
0000 0 0100 4 1000 8 1100 c
0001 1 0101 5 1001 9 1101 d
0010 2 0110 6 1010 a 1110 e
0011 3 0111 7 1011 b 1111 f
(b) Hexadecimal number system
32768
16834
8192
4096
2048
1024
512
256
128
64
32
16
8
4
2
1
215 214 213 212 211 210 29 28 27 26 25 24 23 22 21 20
Figure 6.2: (a) The binary numbering system, (b) the hexadecimal numbering system, and
(c) conversion from binary to hexadecimal.
As previously mentioned, the address bus of some variants of the MSP430 is 20 bits
wide and the data bus is 16 bits. Rather than specify large binary numbers, the contents of
the address and data bus are often expressed in the hexadecimal numbering system to enhance
readability. A set of equivalent numbers of the binary system and the hexadecimal system is
shown in Figure 6.2b.
To convert from the binary numbering system to the hexadecimal system, binary bits are
grouped in fours from either side of the radix point. Each group of four binary bits is represented
by its hexadecimal equivalent. Various methods are used to indicate that a specific number is rep-
resented in the hexadecimal numbering system. In assembly language, the number is followed
by an “h”. In the C programming language the number is preceded by a 0x. Various documen-
260 6. MSP430 MEMORY SYSTEM
tation sources will place a dollar sign ($) before the numerical value or a subscripted 16 by the
number indicating the hexadecimal content.
Microcontroller memory capacity is commonly specified in kilobytes (kB). The prefix kilo
specifies .103 / or for a kilobyte, 1,000 bytes. However, in common computer usage a kilobyte is
used to specify 1,024 bytes or 210 bytes.
Examples:
1. Some variants of the MSP430 has 16 address lines, giving it the capability to separately ad-
dress 65,536 different memory locations. What is the address of the first and last memory
location expressed in hexadecimal?
Answer: The first and last addressable memory locations expressed in hexadecimal nota-
tion are .0000/16 and (FFFF)16 .
3. The MSP430 has the value of .0001_1010_1111_1100/2 present on the data base. Express
the value in hexadecimal.
Answer: Each group of four binary bits is expressed with its corresponding hexadecimal
equivalent resulting in (1AFC)16 .
RAM
RAM is volatile. That is, it only retains its memory contents while power is present. Within
a microcontroller system, RAM memory is used for storing global variables, local variables,
6.2. BASIC MEMORY CONCEPTS 261
stack implementation, and the dynamic allocation of user-defined data types during program
execution.
ROM
ROM is non-volatile. That is, a ROM memory retains its contents even when power is lost. A
ROM variant, EEPROM, is often referred to as flash memory. Flash memory is used to store
programs and system constants that must be retained when system power is lost (non-volatile
memory).
FRAM
Some variants of the MSP430, including the MSP430FR2433 and the MSP430FR5994, have
been equipped with FRAM memory. FRAM is a nonvolatile, ULP with access speeds similar to
RAM. It has been termed a universal memory because it can be used for storing program code,
variables, constants, and for stack operations. Note these functions are typically performed by
nonvolatile ROM and volatile RAM. FRAM also has a high level of write endurance on the
order of 1015 cycles [SLAA526A, 2014, SLAA628, 2014].
3. The data logging system will be dispersed at a number of locations on existing farms and
ranches. The plan is to collect the data over a six-month period and then have the property
owner transfer the data to a central facility for processing. What is the appropriate memory
technology to use in this situation?
4. How do you determine the required capacity for the MMC/SD card to log data over a
six-month period?
Answer: To determine the required memory capacity the following parameters must be
considered.
• How many data variables are collected (e.g., date, time, temperature, wind speed,
altitude) at a time?
• In what format will the data be stored (e.g., integers, floating point numbers, custom
abstract data type such as a record)?
• How often will data be collected (e.g., every 15 min, hourly, every 6 h, daily)?
• Over what time period will data be collected?
(3000)16
Random Access (01000)16
Memory (FRAM) (2000)16 (2FFF)16 (4096)10 ~ 4K bytes
(2000)16
Information Memory (00200)16
(FRAM) (1800)16 (19FF)16 (512)10 bytes
(1800)16
Bootstrap Loader (0800)16
(1000)16 (17FF)16
Segment 1 (2048)10 ~ 2K bytes
(1000)16
(1000)16
Peripherals (0000)16 (0FFF)16 (4096)10 ~ 4K bytes
(0000)16
Bootstrap Loader
The bootstrap loader (BSL) portion of flash memory allows the user to interact with the flash
memory and RAM onboard the MSP430 microcontroller. Specifically, the user can interact
with the MSP430 via a host PC during prototype development. Data is exchanged between the
host and the microcontroller via a serial link [slau319x].
Interrupt Vectors
Interrupts provide the microcontroller the capability to break out of routine processing and
temporarily respond to a higher priority event. When an interrupt occurs, the microcontroller
will temporarily suspend normal program execution and, instead, execute an interrupt service
routine for the specific interrupt. The interrupt vectors between memory locations (0FF80)16
and (0FFFF)16 show the starting locations for each of the interrupt service routines.
264 6. MSP430 MEMORY SYSTEM
1 The information on pointers and examples provided were adapted from Dr. Jerry Cupal’s, EE4390 Microprocessors class
notes.
6.3. ASIDE: MEMORY OPERATIONS IN C USING POINTERS 265
A pointer is another name for an address. To declare a pointer, an asterisk () is placed in
front of the variable name. The compiler will designate the variable as an address to the variable
type specified.
Shown below is the syntax to declare an integer and a pointer (address of ) for an integer.
It is helpful to choose a variable name that helps you remember that a pointer variable has been
declared. A pointer may be declared as a global or local variable.
int x;
int *ptr_x;
Once a pointer has been declared, there is other syntax that may be used in the body of a
program to help manipulate memory addresses and data. The ampersand (&) is used to reference
the address of a variable. Whereas, the asterisk () is used as a dereference operator to refer to
the contents of a memory location that a pointer is referencing.
Example: Given the code snapshot below, what is the final value in variable n?
int m,n; //declare integers m and n
int *ptr_m; //declare pointer to integer type
Answer: The final value of n will be 10. The dereference operator in the last line of code refers
to the contents of the memory location referenced.
Example: In this example, a technique is provided to point to a location in memory space.
char *ptr_mem; //configure a pointer to 8 bit locations
:
:
The next example shows how a pointer may be used to move about memory locations by
using some basic mathematical operations.
266 6. MSP430 MEMORY SYSTEM
//************************************************************************
// This function fills a buffer located between memory locations 2000h
// 2FFFh in memory space with incrementing 16 bit numbers. The values
// loaded into memory start with 0000h and increments up to 0FFFh.
//************************************************************************
void main( )
{
ptr_buffer = (int*) 0x2000; //cast a pointer equal to 2000
for(x=0x0000; x<=0x0fff; x++)
{
*ptr_buffer = x; //move the variable x into buffer
ptr_buffer++; //increment the pointer
}
}
//***********************************************************************
JTAG Active
NMI Interrupt Request
Halt ENNMI
DMA0TSEL ROUNDROBIN
5 DMADT
DMADSTINCR
DMA0TRIG0 00000 2 DMADSTBYTE 3
DMA0TRIG1 00001
DMA Channel 0
DMA0SA
DMA0DA
DMA0SZ
DMA0TRIG31 11111 2 DMASRSBYTE
DMASRCINCR
to USB DMAEN
if available
2 DMASRSBYTE
DMA1TRIG31 11111 DMASRCINCR
DMAEN
to USB
if available DMADT
DMADSTINCR
2 DMADSTBYTE 3
DMAnTSEL
5 DMA Channel n
DMAnSA
DMAnTRIG0 00000
DMAnTRIG1 00001 DMAnDA
DMAnSZ
2
DMASRSBYTE DMAEN
DMASRCINCR
DMARMWDIS
DMAnTRIG31 11111
Halt CPU
to USB
if available
Figure 6.5: DMA block diagram [SLAU367O, 2017]. (Illustration used with permission of
Texas Instruments (www.ti.com).)
268 6. MSP430 MEMORY SYSTEM
DMA0TSELx
DMADSTINCR–DMA destination increment
5 DMADSTBYTE–DMA destination byte
DMA0TRIG0 00000 Halt DMADT–sets the DMA transfer mode type
DMA0TRIG1 00001 2 3
DMA0TRIGx Sources
0 DMAREQ 16 UCA1RXIFG
1 TA0CCR0 CCIFG 17 UCA1TXIFG
2 TA0CCR2 CCIFG T 18 UCB0RXIFG (SPI)
3 TA1CCR0 CCIFG UCB0RXIFG0 (I2C)
4 TA1CCR2 CCIFG T 19 UCB0TXIFG (SPI)
5 TA2CCR0 CCIFG UCB0TXIFG0 (I2C)
6 TA3CCR0 CCIFG T 20 UCB0RXIFG1 (I2C)
7 TB0CCR0 CCIFG 21 UCB0TXIFG1 (I2C)
8 TB0CCR2 CCIFG T 22 UCB0RXIFG2 (I2C)
9 TA4CCR0 CCIFG 23 UCB0TXIFG2 (I2C)
10 Reserved 24 UCB0RXIFG3 (I2C)
11 AES Trigger 0 25 UCB0TXIFG3 (I2C)
12 AES Trigger 1 26 ADC12 end of conversion
13 AES Trigger 2 27 LEA ready(2)
14 UCA0RXIFG 28 Reserved
15 UCA0TXIFG 29 MPY ready
30 DMA0IFG
31 DMAE0
Figure 6.6: DMA channel. (Illustration used with permission of Texas Instruments (www.ti.c
om).)
6.4. DIRECT MEMORY ACCESS (DMA) CONTROLLER 269
DMA channel as shown in Figure 6.6. This information is provided to the DMA channel via
the DMA Source Address Register (DMAxSA) and the DMA Destination Register Address
Register (DMAxDA). The “x” designates the DMA channel number. The DMAxSA, a 32-bit
register, specifies the source address for a single transfer or the first source address for a block
transfer. Similarly, the DMAxDA register specifies the destination address for single transfers
or the first destination address for block transfers [SLAU367O, 2017].
The number of byte/word transfers must also be specified using the DMA Size Address
Register (DMAxSZ). Since the DMAxSZ register is 16 bits, the maximum transfer size that
may be specified is 65,535 bytes or words. During the DMA transfer event, the value within
the DMAxSZ decrements with each byte/word transfer. Generally, two MCLK clock cycles are
required to complete each transfer [SLAU367O, 2017].
Other parameters to tailor the DMA transfer for a specific application are provided within
the DMA Channel x Control Register (DMAxCTL) by the following bits.
• DMASRCBYTE specifies the DMA source as either a byte (1) or a word (0).
• DMADT specifies the type of DMA transfer mode. There are six different transfer modes
that may be specified. In general, the transfer mode dictates the type of transfer (single,
burst, burst-block) and the type of triggered required.
The DMA transfer event may be initiated via a variety of different trigger sources as spec-
ified by the DMAxTSELx bits within DMA Control Register 0 (DMACTL0). We now take
a more detailed look at each of these features.
(a) Fixed address to fixed address (b) Fixed address to block of addresses
(c) Block of addresses to fixed address (d) Block of addresses to block of addresses
DMA Triggering
Figure 6.8 summarizes the different triggering requirements for a specific DMA transfer mode.
The actual source of the triggering signal must also be specified. Figure 6.6 provided the various
triggering sources available to a given DMA channel. The specific trigger signal is selected using
the DMA0TSELx bits.
6.4. DIRECT MEMORY ACCESS (DMA) CONTROLLER 271
DMAEN After
DMADTx Transfer Mode Trigger Description
Transfer
Each transfer requires a trigger
000 Single transfer 0
A complete block is
101 Repeated block transfer transferred with one trigger 1
7 6 5 4 3 2 1 0
0 0 0 0 0 0 0 0
r0 r0 r0 r0 r0 r0 r0 r0
7 6 5 4 3 2 1 0
ROUND
0 0 0 0 0 DMARMWDIS ENNMI
ROBIN
r0 r0 r0 r0 r0 rw-0 rw-0 rw-0
0 0 0 0 0 0 0 0
r0 r0 r0 r0 r0 r0 r0 r0
7 6 5 4 3 2 1 0
0 0 DMAIV 0
r0 r0 r0
7 6 5 4 3 2 1 0
DMA DMA DMALEVEL DMAEN DMAIFG DMAIE DMAABORT DMAREQ
DSTBYTE SRCBYTE
rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0)
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop WDT
//Configure GPIO for LED
276 6. MSP430 MEMORY SYSTEM
P1OUT = 0;
P1DIR = BIT0;
while(1)
{
P1OUT |= 0x01; //P1.0 = 1, LED on
DMA0CTL |= DMAREQ; //Trigger block transfer
P1OUT &= ~0x01; //P1.0 = 0, LED off
}
}
//********************************************************************
• In the section on DMA transfer, an example was provided to move 32 integers from a
given source address to a destination address using DMA channel 0. Develop a UML
activity diagram for this example.
• Verify proper code execution by observing memory source and destination addresses using
Code Composer Studio features.
• Write a new function that takes the contents of the source address and transfers its contents
to the destination address on the first transfer. On subsequent transfers the original value
is incremented and stored at subsequent destination addresses. Develop a UML activity
diagram for this example.
• Verify proper code execution by observing memory source and destination addresses using
Code Composer Studio features.
6.9 SUMMARY
In this chapter, with the help of the memory map, we presented the memory system of the
MSP430 microcontroller. We demonstrated how contents of a memory location are accessed
via read and write operations. We described the types of memories including RAM, ROM, and
FRAM memory. We then discussed the organization and operation of onboard flash memory
and the DMA system.
6.10. REFERENCES AND FURTHER READING 279
6.10 REFERENCES AND FURTHER READING
FRAM–New Generation of Non-Volatile Memory, Texas Instruments, 2010. www.ti.com/fram
MultiMedia Card Product Manual, SanDisk Corporate Headquarters, Sunnyvale, CA, 2000.
www.sandisk.com 261
Texas Instruments MSP430 FRAM Quality and Reusability, (SLAA526A), Texas Instruments,
2014. 261
Texas Instruments MSP430 FRAM Technology-How to and Best Practices, (SLAA628), Texas In-
struments, 2014. 261
Advanced
1. Research the interface between the MSP430 and a MMC/SD card.
2. Sketch the memory map of the MSP430FR5994 microcontroller.
Challenging
1. Develop a MMC/SD card interface for the MSP430 microcontroller.
2. Write a function to clear a block of memory addresses in RAM memory. The start address
and the number of memory locations to clear are passed into the function as arguments.
3. Write a function to transfer a block of memory locations from one address to another
using DMA channel 2. The start address and the size of the memory block are passed into
the function as arguments.
281
Authors’ Biographies
STEVEN F. BARRETT
Steven F. Barrett, Ph.D., P.E., received a B.S. in Electronic Engineering Technology from
the University of Nebraska at Omaha in 1979, an M.E.E.E. from the University of Idaho at
Moscow in 1986, and a Ph.D. from The University of Texas at Austin in 1993. He was formally
an active duty faculty member at the United States Air Force Academy, Colorado and is now
the Associate Dean of Academic Programs at the University of Wyoming. He is a member of
IEEE (senior) and Tau Beta Pi (chief faculty advisor). His research interests include digital and
analog image processing, computer–assisted laser surgery, and embedded controller systems. He
is a registered Professional Engineer in Wyoming and Colorado. He co-wrote with Dr. Daniel
Pack several textbooks on microcontrollers and embedded systems. In 2004, Barrett was named
“Wyoming Professor of the Year” by the Carnegie Foundation for the Advancement of Teaching
and in 2008 was the recipient of the National Society of Professional Engineers (NSPE) in
Higher Education, Engineering Education Excellence Award.
DANIEL J. PACK
Daniel J. Pack, Ph.D., P.E., is the Dean of the College of Engineering and Computer Science
at the University of Tennessee, Chattanooga (UTC). Prior to joining UTC, he was Professor
and Mary Lou Clarke Endowed Department Chair of the Electrical and Computer Engineer-
ing Department at the University of Texas, San Antonio (UTSA). Before his service at UTSA,
Dr. Pack was Professor (now Professor Emeritus) of Electrical and Computer Engineering at
the United States Air Force Academy (USAFA), CO, where he served as founding Director of
the Academy Center for Unmanned Aircraft Systems Research. He received a B.S. in Electri-
cal Engineering, an M.S. in Engineering Sciences, and a Ph.D. in Electrical Engineering from
Arizona State University, Harvard University, and Purdue University, respectively. He was a
visiting scholar at the Massachusetts Institute of Technology-Lincoln Laboratory. Dr. Pack has
co-authored seven textbooks on embedded systems (including 68HC12 Microcontroller: Theory
and Applications and Embedded Systems: Design and Applications with the 68HC12 and HCS12)
and published over 160 book chapters, technical journal/transactions, and conference papers on
unmanned systems, cooperative control, robotics, pattern recognition, and engineering educa-
tion. He is the recipient of a number of teaching and research awards including Carnegie U.S.
Professor of the Year Award, Frank J. Seiler Research Excellence Award, Tau Beta Pi Outstand-
ing Professor Award, Academy Educator Award, and Magoon Award. He is a member of Eta
282 AUTHORS’ BIOGRAPHIES
Kappa Nu (Electrical Engineering Honorary), Tau Beta Pi (Engineering Honorary), IEEE,
and the American Society of Engineering Education. He is a registered Professional Engineer
in Colorado, serves as Associate Editor of IEEE Systems Journal, and is a member on a number
of executive advisory or editorial boards including the Journal of Intelligent & Robotic Systems,
International Journal of Advanced Robotic Systems, and SimCenter Enterprise. His research inter-
ests include unmanned aerial vehicles, intelligent control, automatic target recognition, robotics,
and engineering education. E-mail: [email protected]
283
Index