Microcontrollerprogramming Msp430fr2433andmsp430fr5994 Part2 PDF
Microcontrollerprogramming Msp430fr2433andmsp430fr5994 Part2 PDF
BARRETT • PACK
Series Editor: Mitchell A. Thornton, Southern Methodist University
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
Instruments MSP430FR2433
consumption and integrated digital and analog hardware.Variants of the MSP430 microcontroller
have been in production since 1993. This provides for a host of MSP430 products including
evaluation boards, compilers, software examples, and documentation. A thorough introduction
and MSP430FR5994 - Part II
Second Edition
to the MSP430 line of microcontrollers, programming techniques, and interface concepts 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.
This 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 already 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.
Steven F. Barrett
Daniel J. Pack
About SYNTHESIS
This volume is a printed version of a work that appears in the Synthesis
Digital Library of Engineering and Computer Science. Synthesis
books provide concise, original presentations of important research and
store.morganclaypool.com
Microcontroller Programming
and Interfacing with
Texas Instruments
MSP430FR2433 and
MSP430FR5994 – Part II
Second Edition
Synthesis Lectures on Digital
Circuits and Systems
Editor
Mitchell A. Thornton, Southern Methodist University
The Synthesis Lectures on Digital Circuits and Systems series is comprised of 50- to 100-page books
targeted for audience members with a wide-ranging background. The Lectures include topics that
are of interest to students, professionals, and researchers in the area of design and analysis of digital
circuits and systems. Each Lecture is self-contained and focuses on the background information
required to understand the subject matter and practical case studies that illustrate applications. The
format of a Lecture is structured such that each will be devoted to a specific topic in digital circuits
and systems rather than a larger overview of several topics such as that found in a comprehensive
handbook. The Lectures cover both well-established areas as well as newly developed or emerging
material in digital circuits and systems design and analysis.
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 #56
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 II
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
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 12.9 provides a brief review of microcontroller terminology and a short history
followed 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 12.9 provides a brief introduction to programming in C. The chapter contains
multiple examples for a new programmer. It also serves as a good review for seasoned program-
mers. Also, software programming tools including Energia, Code Composer Studio IDE, and
debugging 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 Em-
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
bedded system developers will find a seamless transition between the MSP430 and MSP432
line of processors.
Chapter 12.9 introduces the MSP430 hardware architecture, software organization, and
programming model. The chapter also presents an introduction to the MSP430 orthogonal in-
struction set, including its 27 instructions and 9 emulated instructions.
Chapter 12.9 describes a wide variety of input and output devices and how to properly
interface them to the MSP430 microcontroller. We believe it is essential for the embedded sys-
tem designer to understand the electrical characteristics of the processor so a proper interface
to peripheral 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 12.9 provides an in–depth discussion of the MSP430 power management system.
The power management system provides for ultra-low power operation and practices.
Chapter 12.9 is dedicated to the different memory components onboard the MSP430
including the new FRAM nonvolatile memory, RAM, EEPROM and the associated memory
controllers. The Direct Memory Access (DMA) controller is also discussed.
Chapter 7 discusses the clock and timer systems aboard the MSP430. The chapter begins
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 8 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 9 discusses the analog systems aboard the MSP430. The chapter discusses the
analog–to–digital converters (ADCs), the digital–to–analog converters (DACs), and the com-
parators.
Chapter 10 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 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 12 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 7
Timer Systems
Objectives: After reading this chapter, the reader should be able to
• illustrate the use of the Watchdog timer;
• explain the operation of the real-time timer;
• explain the need and operation for the RTC;
• describe the timer features of Timer_A and Timer_B;
• program capture and compare subsystems to interface with external devices; and
• write basic programs using the timer subsystems (Watchdog, RTC, and capture/compare
subsystems) and their interrupt modules.
7.1 INTRODUCTION
One of the main reasons for the proliferation of microcontrollers as the “brain” of embedded
systems is their ability to interface with multiple external devices such as sensors, actuators, and
display units among others. In order to communicate with such devices, however, microcon-
trollers must have capabilities to meet time constraints enforced by those devices. For example,
an actuator which is controlled by a servo motor requires what is called a PWM signal with
precise timing requirements as its input, while a communication device may need a unique pulse
with a specified width to initiate its process. In other applications, microcontrollers need to
capture the time of an external event or distinguish periodic input signals by computing their
frequencies and periods. To meet these time constraints, embedded systems must have a fairly
sophisticated timer system to generate a variety of clock signals, capture external events, and
produce desired output time-related signals. The goal of this chapter is to address these capa-
bilities of MSP430. We first present the clock systems of MSP430 followed by the Watchdog
timer, basic timer, RTC, input capture, and output compare timer subsystems.
7.3.1 FREQUENCY
Consider a signal, x.t/, that repeats a pattern over time. We call this signal periodic with period
T , if it satisfies the following equation:
x.t / D x.t C T /:
To measure the frequency of a periodic signal, we count the number of times a particular
event repeats within one second period. The unit of frequency is the Hertz or cycles per second.
For example, a sinusoidal signal with the 60 Hz frequency means that a full cycle of a sinusoid
signal repeats itself 60 times each second or once every 16.67 ms.
7.3.2 PERIOD
The reciprocal of frequency is defined as period. If an event occurs with a rate of 1 Hz, the period
of that event is 1 s. To find a period, given a frequency, or vice versa, we simply need to remember
7.3. TIME-RELATED SIGNAL PARAMETERS 283
1
their inverse relationship, f D T
,
where f and T represent a frequency and the corresponding
period, respectively. Both periods and frequencies of signals are often used to specify timing
constraints of embedded systems. For example, when your car is on a wintery road and slipping,
the engineers who designed your car configured the anti-slippage unit to react within some
millisecond period, say 20 ms. The constraint then forces the design team that monitors the
slippage to program their monitoring system to check a slippage at a minimum rate of 50 Hz.
50%
100%
25% (a)
100%
(b)
Figure 7.1: Two signals with the same period but different duty cycles. Frame (a) shows a periodic
signal with a 50% duty cycle and frame (b) displays a periodic signal with a 25% duty cycle.
284 7. TIMER SYSTEMS
7.3.4 PULSE WIDTH MODULATION
In this section, we show how the speed of a DC motor can be controlled by a PWM signal.
Suppose you have the circuit setup shown in Figure 7.2. The figure shows that the batteries are
connected to power the motor through a switch. It is obvious that when we close the switch
the DC motor will rotate and continue to rotate with a speed proportional to the DC voltage
provided by the batteries. Now suppose we can open and close the switch rapidly. It will cause
the motor to rotate and stop rotating per the switch position. As the time between the closing
and opening of the switch decreases, the motor will not have time to make a complete stop and
will continue to rotate with a speed proportional to the average time the switch is closed. This
is the underlying principle of controlling DC motor speed using the PWM signal. When the
logic of the PWM signal is high, the motor is turned on, and when the logic of the waveform is
low, the motor is turned off. By controlling the time the motor is on, we can control the speed
of the DC motor.
The duty cycle is defined as the fractional time the logic is high with respect to one cycle
time (period) of the PWM signal. Thus, 0% duty cycle means the motor is completely turned
off while 100% duty cycle means the motor is on all the time. Aside from motor speed control
applications, PWM techniques are used in a wide variety of applications such as audio amplifiers,
power supplies, heating units, and inverters.
Switch
DC
Batteries
Motor
Example: In this example, time-related Energia functions are used to debounce an external
switch input.
//***********************************************************************
//This example is provided with the Energia distribution and is used with
//permission of Texas Instruments, Inc.
//
//Debounce
//***********************************************************************
//Each time the input pin goes from LOW to HIGH (e.g., because of a
//push-button press), the output pin is toggled from LOW to HIGH or
//HIGH to LOW.
//
//The circuit:
//- LED attached from pin 13 to ground
//- Pushbutton attached from pin 2 to +3.3V
//- 10K resistor attached from pin 2 to ground
//
//created: 21 Nov 2006, David A. Mellis
7.5. ENERGIA-RELATED TIME FUNCTIONS 287
//modified: 30 Aug 2011, Limor Fried
//modified: 27 Apr 2012, Robert Wessels
//
//This example code is in the public domain.
//***********************************************************************
void setup()
{
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop()
{
//read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
//***********************************************************************
7 6 5 4 3 2 1 0
The 7th bit (WDTHOLD) is used to turn-on or turn-off the Watchdog timer. Setting
this bit disables the Watchdog counter, and clearing this bit configures the system to function
normally. Bits 6 and 5 are not used. Bit 4 (WDTTMSEL) determines the mode of operation
for the Watchdog timer: setting this bit selects the interval timer mode while clearing this bit
designates the Watchdog mode. Writing a logic one to bit 3 (WDTCNTCL) clears the counter.
This is how your program can prevent the Watchdog timer from generating a PUCR. Once the
WDTCNT is cleared, this bit is reset (0) automatically. The WDTSSEL bit (bit 2) selects the
clock source for the counter. Setting this bit chooses the ACLK clock while clearing this bit
selects the SMCLK clock. Finally, WDTISx bits (bits 1 and 0) are used to select the Watchdog
timer reset periods as shown below:
WDTSSEL
SMCLK WDTCNT
ACLK
Watchdog
Interrupt
System
GIE WDTIE
Limit Reached
WDTIFG
//
//An external watch crystal is installed on XIN XOUT for the ACLK.
//(ACLK = LFXT1 = 32768Hz, MCLK = SMCLK = default DCO)
//
//D. Pack and S. Barrett, July 2018, Built with CCS v8
//***********************************************************************
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW + WDTHOLD; //Stop WDT during initialization
PMSCTL0 &= ~LOCKLPMS; //Disable GPIO high-impedance mode
P1DIR |= BIT0; //Set P1.0 (red LED) to output
P1DIR |= 0x01; //Set P1.0 to output direction
WDTCTL = WDT_ADLY_1000; //WDT 1 sec, ACLK, interval timer
SFRIE1 |= WDTIE; //Enable WDT interrupt
__enable_interrupt(); //Enable global interrupt
while(1)
{
292 7. TIMER SYSTEMS
} //Wait for interrupts
//***********************************************************************
//Watchdog timer interrupt service routine
//***********************************************************************
#pragma vector=WDT_VECTOR
__interrupt void watchdog_timer(void)
{
P1OUT ^= 0x01; //Toggle P1.0 using exclusive-OR
}
//***********************************************************************
Reserved 00
Device Specific Reset
01
XT1CLK 10 Pre-Divider 16-bit Counter Interrupt
VLOCLK 11
Request
Overflow
Compare Logics S Q
RTCSS RTCPS R
Reload
16-bit Shadow Register
Overflow Event
to Other Modules
16-bit Modulo Register
15 14 13 12 11 10 9 8
Reserved RTCSS Reserved RTCPS
r0 r0 rw-(0) rw-(0) r0 rw-(0) rw-(0) rw-(0)
7 6 5 4 3 2 1 0
Reserved RTCSR Reserved RTCIE RTCIFG
r0 w-(0) r0 r0 r0 r0 rw-(0) r-(0)
Figure 7.6: MSP430FR2433 RTC counter. (Illustration used with permission of Texas Instru-
ments (www.TI.com).)
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
// MSP430FR243x Demo - RTC, toggle P1.0 every 1s
//
294 7. TIMER SYSTEMS
// Description: Configure ACLK to use 32kHz crystal as RTC clock,
// ACLK=XT1=32kHz, MCLK = SMCLK = default DCODIV = ~1MHz.
//
// MSP430FR2433
// -----------------
// /|\| |
// | | |
// | | XIN(P2.0)|--
// --|RST | ~32768Hz
// | XOUT(P2.1)|--
// | |
// | P1.0|-->LED
//
//Ling Zhu, Texas Instruments Inc., Feb 2015
//Built with IAR Embedded Workbench v6.20 & Code Composer Studio v6.0.1
//*********************************************************************
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop watchdog timer
P2SEL0 |= BIT0 | BIT1; //set XT1 pin as second function
do
{
CSCTL7 &= ~(XT1OFFG | DCOFFG); //Clear XT1 and DCO fault flag
SFRIFG1 &= ~OFIFG;
}while (SFRIFG1 & OFIFG); //Test oscillator fault flag
//Initialize RTC
//Source = 32kHz crystal,
//divided by 1024
RTCCTL = RTCSS__XT1CLK | RTCSR | RTCPS__1024 | RTCIE;
__bis_SR_register(LPM3_bits | GIE); // Enter LPM3, enable interrupt
}
//*********************************************************************
// RTC interrupt service routine
//*********************************************************************
//*********************************************************************
RT0IP
RT0PS EN
BCLK 3
Q0 Q1 Q2 Q3 Q4 Q5 Q6 Q7
111
RTCOCALS RTCOCAL 110
101 Set_RT0PSIFG
8 100
011
EN Calibration
Logic 010
001
8 000
RTCTCMPS RTCTCMP
RT1IP
RT1PS EN
3
Q0 Q1 Q2 Q3 Q4 Q5 Q6 Q7
111
110
101 Set_RT1PSIFG
100
011
010
001
000
Set_RTCRDYIFG
Keepout
Logic
RTCBCD
EN
Calendar EN
Alarm EN Set_RTCAIFG
Figure 7.7: RTC [SLAU367O, 2017]. (Illustration used with permission of Texas Instruments
(www.ti.com).)
7.8. REAL-TIME CLOCK-MSP430FR2433 297
a 1 Hz time base to the time-keeping registers. The register contains place holders for sec-
onds (RTCSEC), minutes (RTCMIN), hours (RTCHOUR), day of the week (RTCDOW),
day (RTCDAY), month (RTCMON) , and year (RTCYEARH, RTCYEARL). Data may be
stored in BCD or hexadecimal binary format. BCD represents each digit in a number individ-
ually from 0–9 [SLAU367O, 2017].
The RTC_C is also equipped with an alarm function. The alarm is configured for a spe-
cific minute (RTCAMIN), hour (RTCAHOUR), day (RTCADAY), and day of the week (RT-
CADOW). The write operation for RTC control, clock, calendar, prescale, and offset error are
key protected [SLAU367O, 2017].
The RTC_C is supported by six prioritized interrupts designated RT0PSIFG,
RT1PSIFG, RTCRDYIFG, RTCTEVIFG, RTCAIFG, and RTCOFIFG. The six interrupt
signal flags are combined to provide a single interrupt signal. When an interrupt occurs the
interrupt vector register (RTCIV) provides the specific interrupt source [SLAU367O, 2017].
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
//MSP430FR5x9x Demo - RTC in Counter Mode toggles P1.0 every 1s
//
//This program demonstrates operation of the RTC in counter mode
//configured to source from the ACLK to toggle P1.0 LED every 1s.
//
// MSP430FR5994
// -----------------
// /|\ | |
// | | XIN|--
298 7. TIMER SYSTEMS
// ---|RST | 32768Hz
// | XOUT|--
// | |
// | P1.0|-->LED
//
//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
P1OUT &= ~BIT0;
P1DIR |= BIT0;
PJSEL0 = BIT4 | BIT5; //Initialize LFXT pins
//*******************************************************************
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=RTC_C_VECTOR
__interrupt void RTC_ISR(void)
#elif defined(__GNUC__)
//********************************************************************
Example. In this example the RTC is used in clock mode to trigger an interrupt every minute
and second.
300 7. TIMER SYSTEMS
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
//MSP430FR5x9x Demo - RTC in real time clock mode
//
//Description: This program demonstrates the RTC mode by triggering an
//interrupt every second and minute. This code toggles P1.0 every
//second. This code recommends an external LFXT crystal for RTC
//accuracy.
//
// ACLK = LFXT = 32768Hz, MCLK = SMCLK = default DCO = 1MHz
//
// MSP430FR5994
// -----------------
// /|\ | XIN|-
// | | | 32768Hz
// ---|RST XOUT|-
// | |
// | P1.0 |--> Toggles every second
// | |
//
//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 Watchdog timer
P1DIR |= BIT0; //Set P1.0 as output
PJSEL0 = BIT4 | BIT5; //Initialize LFXT pins
//********************************************************************
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=RTC_C_VECTOR
302 7. TIMER SYSTEMS
__interrupt void RTC_ISR(void)
#elif defined(__GNUC__)
Programmed
Event
Timer Output
- Toggle
Flag
- Logic High
- Logic Low
you find the pulse width when the free running counter is counting at 2 MHz? You will need to
follow through the process similar to the one described next. We first need to convert the two
values into their corresponding decimal values, 16 and 276. The pulse width of the signal in the
number of counter value is 260. Since we already know how long it takes for the system to count
one, we can readily compute the pulse width as 260 0.5 s D 130 s.
Our calculations do not take into account time increments lasting longer than the rollover
time of the counter. When a counter rolls over from its maximum value back to zero, a flag is
set to notify the processor of this event. In such cases, the rollover incidents are incorported to
correctly determine the overall elapsed time of an event.
Elapsed time may be calculated using the following:
In this first equation, “n” is the number of timer overflows that occur between the start
and stop of an event, and “b ” is the number of bits in the timer counter. The equation yields the
elapsed time in clock ticks. To convert it to seconds, the number of clock ticks are multiplied by
the period of the clock source of the free running counter.
7.9. INPUT CAPTURE AND OUTPUT COMPARE FEATURES 305
7.9.2 APPLICATIONS
In this section, we consider important uses of the timer system of a microcontroller to (1) mea-
sure an input signal timing event (input capture), (2) to count the number of external signal
occurrences (input capture), and (3) to generate timed signals (output compare). The specific
implementation details are presented in Section 7.9.2. We present the overall applications in
this section, starting with a case of measuring the time duration of an incoming signal.
Microcontroller
Figure 7.9: Use of the timer input and output systems of a microcontroller. The signal on top is
fed into a timer input port. The captured signal is subsequently used to compute the input signal
frequency. The signal on the bottom is generated using the timer output system. The signal is
used to control an external device.
306 7. TIMER SYSTEMS
Once the timer is turned on and the clock rate is selected, a programmer must configure
the physical port to which the incoming signal arrives. This step is done using a special input
timer port configuration register. The next step is to configure the timer system to capture the
intended input event. In the current example, we design our system to capture two consecutive
rising edges or falling edges of an incoming signal. Again, the programming portion is done by
storing an appropriate setup value to a special register.
Assuming that the input timer system is configured appropriately, you now have two op-
tions to accomplish the desired task. The first one is the use of a polling technique; the micro-
controller continuously polls a flag, which holds a logic high signal when a programmed event
occurs on the physical pin. Once the microcontroller detects the flag, it needs to clear the flag
and record the time when the flag was set using another special register that captures the time
of the associated free running counter value (see Section 7.10.1). The program needs to con-
tinue to wait for the next flag which indicates the end of one period of the incoming signal. A
program then needs to record the newly acquired captured time represented in the form of a
free running counter value again. The period of the signal can now be computed by calculating
the time difference between the two captured event times, and, based on the clock speed of the
microcontroller, the programmer can compute the actual time changes and consequently the
frequency of the signal.
In many cases, a microcontroller can’t afford the time or resources to poll for any one
event. Such a situation calls for the second method: interrupt systems. Most microcontroller
manufacturers have developed built-in interrupt systems with their timer system. In an interrupt
system, instead of continuously polling for a flag, a microcontroller performs other tasks while
relying on its interrupt system to detect a programmed event. The task of computing the period
and the frequency is the same as the polling technique, except that the microcontroller will not
be tied down to constantly checking the flag, increasing the efficient use of the microcontroller
resources. To use interrupt systems, of course, we must pay the price by appropriately configuring
interrupt systems to be triggered when a desired event is detected. Typically, additional registers
must be configured, and a special program called an interrupt service routine must be written.
Suppose that for the input capture scenario of the current interest, the captured times for
the two rising edges are $1000 and $5000, respectively. Note that these values are not absolute
times but the representations of times reflected as the values of the free running counter. The
period of the signal is $4000 or 16384 in decimal. Also, no timer overflows have been detected.
If we assume that the timer clock runs at 10 MHz, the period of the signal is 1.6384 ms, and
the corresponding frequency of the signal is approximately 610.35 Hz.
Counting Events
The same capability of measuring the period of a signal can also be used to simply count external
events. Suppose we want to count the number of logic state changes of an incoming signal for
a given period of time, as it may contain valuable information. Again, we can use the polling
7.10. MSP430 TIMERS: TIMER_A AND TIMER_B 307
technique or the interrupt technique to accomplish the task. For both techniques, the initial steps
of turning on a timer and configuring a physical input port pin are the same. In this application,
however, the programmed event should be any logic state changes instead of looking for a rising
or a falling edge as we have done in the previous scenario. If the polling technique is used, at
each event detection, the corresponding flag must be cleared and a counter must be updated. If
the interrupt technique is used, one must write an interrupt service routine within which the
flag is cleared and a counter is updated.
Timer Block
TASSEL ID IDEX Timer Clock MC
2 3 15 0
2 2
TAxCLK 00 Divider Divider 16-bit Timer
TAxR Count
/1/2/4/8 /1.../8 Mode EQU0
ACLK 01 Clear RC
SMCLK 10
INCLK 11 Set TAxCTL
TACLR TAIFG
CCR0
CCR1
CCR2
CCR3
CCR4
CCR5
CCR6
CCI Comparator 6
EQU6
CAP
A
SCCI Y 0
EN Set TAxCCR6
1 CCIFG
OUT
Output
EQU0 Unit4 D Set Q OUT6 Signal
Timer Clock
Reset
3 POR
OUTMOD
Figure 7.10: Timer_A block diagram [SLAU445G, 2016, SLAU367O, 2017]. (Illustration used
with permission of Texas Instruments (www.ti.com).)
310 7. TIMER SYSTEMS
15 14 13 12 11 10 9 8
Reserved TASSEL
rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0)
7 6 5 4 3 2 1 0
ID MC Reserved TACLR TAIE TAIFG
rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) w-(0) rw-(0) rw-(0)
Figure 7.11: Timer_A registers [SLAU445G, 2016, SLAU367O, 2017]. (Illustration used with
permission of Texas Instruments (www.ti.com).)
MCx
Counting
TASSELx Mode
Clock Selection
7 6 5 4 3 2 1 0
IDx MCx Unused TACLR TAIE TAIFG
• 00 – increase (decrease) the TAR counter by one at each (rising/falling edge) clock cycle
• 01 – increase (decrease) the TAR counter by one every two clock cycles
• 10 – increase (decrease) the TAR counter by one every four clock cycles
• 11 – increase (decrease) the TAR counter by one every eight clock cycles
Using the pre-scalar factors, one can slow down the frequency of the free running counter
by factor of 1, 2, 4, or 8, respectively. The mode control (MCx) bits (bits 5 and 4) of the TACTL
register govern how the counter operates as follows.
• 00 – stop counter
• 01 – count up from 0 to a value stored in the Timer_A Capture/Compare 0 (TACCR0)
register
• 10 – count from 0 to 216 (0x0000 to 0xFFFF)
• 11 – count up/down: count from 0 to the value in the TACCR0 register, then count back-
ward to 0. Repeat the process.
Thus, one can setup the counter to operate in one of the four operating modes. The Up mode
(MCx bits: 01) increments the TAR value by one until it reaches the value stored in the TACCR0
register. When the value in the TAR register changes from the value in the TACCR0 register -
1 to the value in the TACCR0 register, the TACCRO capture/compare interrupt flag (CCIFG)
bit is set, and when the value in the TAR changes from the value in TACCRO to zero during
the next clock cycle, the Timer_A Interrupt Flag (TAIFG) flag in the TACTL register is set.
When operating in the continuous mode (MCx bits: 10), the TAIFG flag is set when
the value in TAR register changes from 0xFFFFh to 0x0000h. In the Up/Down mode, the
312 7. TIMER SYSTEMS
TACCRO CCIFG flag is set when the timer TAR value changes from the value stored in the
TACCR0 register -1 to the value stored in the TACCR0 register (Up), and the TAIFG flag is
set when the timer TAR value changes from 0x01h to 0x00h (Down). Setting the TACLT bit
(bit 2) of the Timer_A Control Register (TACTL) register clears the TAR counter, resets the
divider, and changes the direction of the Up/Down counter, if the MCx bits are both set. Each
time the free running counter reaches its limit states, the TAIFG bit (bit 0) of the TACTL is
set, where the limit state is defined as follows.
• MCx: 00 – no changes to TAIFG
• MCx: 01 – TAR value changes from the value in TACCR0 to 0
• MCx: 10 – TAR value changes from 0xFFFF to 0x0000
• MCx: 11 – no changes to TAIFG
Now that we understand how to configure the counter, TAR, that is used as the basis for
all MSP430 Timer_A and Timer_B activities, we now present three different capabilities: input
capture, output compare, and a variation of the output compare—pulse width modulation. A
similar, a parallel discussion for Timer_B for the current and next sections can be derived using
Timer_B registers. For example, the explanation of the free running counter register, TAxR,
can be replaced with the one for the Timer_B system and its free running counter, TBxR.
TAR
CCISx
CMx CCI1A
CCI1B
TACCRx
Capture VCC
Interrupt GND
System
GIE CCI
CCIFGx
Latch
7 6 5 4 3 2 1 0
OUTMOD2 OUTMOD1 OUTMOD0 CCIE CCI OUT COV CCIFG
• 10 – Ground
#include <msp430.h>
#define NUMBER_TIMER_CAPTURES 20
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop watchdog timer
//Configure GPIO
P1OUT &= ~0x01; //Clear P1.0 output
P1DIR |= 0x01; //Set P1.0 to output direction
//*********************************************************************
// Timer0_A3 CC1-4, TA Interrupt Handler
//*********************************************************************
//*********************************************************************
TAR
OUTMODx
Comparator
Capture OUTx
Interrupt TACCRx
System EQU0
CCIFGx
Latch
• 001 – set the logic on the output pin high (continuous counting mode)
• 010 – toggle the logic state on the output pin (Up/Down counting mode)
• 011 – set or resets the logic state on the output pin (Up counting mode)
• 100 – toggle the logic state on the output pin (continuous counting mode)
• 101 – reset (logic zero) the logic state on the output pin (continuous counting mode)
• 110 – toggle the logic state on the output pin (Up/Down counting mode)
• 111 – set or reset the logic state on the output pin (Up counting mode)
The EQU0 signal, shown in Figure 7.16, governs modes 010, 011, 110, and 111. When
the comparison of values in TAxCCRn and TAxR results in a match, the CCIFG flag is also set
(logic 1), and if the CCI bit along with the GIE bit is set, the corresponding output compare
interrupt system is enabled. One can also use more than one channel to generate a periodic pulse.
By directing the output signal onto a single output pin and configuring two channels, say channel
0 with TAxCCR0 and channel 1 with TARCCR1, appropriately, one can generate a periodic
signal. For example, suppose we configure both channels to be output compare channels, output
event to set and reset the output logic state. If we assume continuous counting mode from
0x0000 to 0xFFFF for the free running counter, by setting the TAxCCR0 value to be zero and
the TAxCCR1 value to be 0x8000, we can generate a pulse width modulated signal with 50%
duty cycle. One can also achieve the same output signal using a single channel, say channel 0,
setting the output mode to toggle the logic states. Note that the frequency of the signal is half
of the signal generated using two channels.
In the remainder of this section, we show how register TAxIV (Timer_Ax Interrupt Vec-
tor) is used to configure a desired interrupt service routine. The first column of Table 7.1 shows
the values need to be loaded to the TAxIV register to program a particular interrupt system. The
second column of the same table shows the corresponding interrupt source for the numerical
values shown in the first column. When an interrupt occurs, the appropriate interrupt service
routine must clear the associated flag of the interrupt, shown in the last column of the table.
Thus, Timer_A capture/compare 1–6 (TAxCCR1 - TAxCCR6) or timer overflow (TAxR)
can cause interrupts in the Timer_A system. To have the corresponding interrupt to be enabled,
one must set the capture/compare interrupt enable (CCIE) bit, or Timer_A Interrupt Enable
(TAIE) bit in the Capture/Compare Control (TAxCCTLn) register or the Timer_A control
(TAxCTL) register.
7.10. MSP430 TIMERS: TIMER_A AND TIMER_B 319
Table 7.1: How register TAxIV (Timer_Ax Interrupt Vector) is used to configure a desired
interrupt service routine
The code snapshot below shows how one can setup the Timer_A system for an interrupt
to occur every fixed period. Lines 1 and 2 are directives to define the subroutine TA_wake. Line
3 of the program contains the label of the subroutine, and the following line of code determines
the duration of the period using the TAxCCR1 register. The desired period should be calculated
based on the clock speed, and the resulting numerical number should replace symbol num on
line 4 of this program. Instructions on lines 5–7 enable the local interrupt, set up the counter
to choose the ACLK clock and the continuous count mode, and turns on the global interrupt
switch, respectively. The ret instruction on line 8 returns the program flow to the portion of
the program that called the subroutine. Instructions on lines 9–13 show how one can write a
corresponding interrupt service routine. The test instruction on line 10 clears the interrupt flag.
Your program code that performs the desired task every time the interrupt occurs will go in
the space designated by line 11. The add instruction on line 12 updates the TAxCCR1 register,
designating the period for the next interrupt to occur by adding the same amount of time to the
current time in TAxCCR1. This program can be used to wake-up the controller, periodically, to
perform required tasks using the built-in Timer_A interrupt system.
;----------------------------------------------------------------------
1 .def TA_wake
2 .text
3 TA_wake
4 mov.w #num, &TAxCCR1 ;use appropriate time number
5 mov.w #CCIE, &TAxCCTL1 ;TACCR1 interrupt enabled
6 mov.w #TASSEL_1+MC_2, &TAxCTL ;ACLK, continuous mode
7 bis.b #GIE, SR ;enable global interrupt
8 ret
320 7. TIMER SYSTEMS
9 TA_ISR
10 tst.w &TAxIV ;read clears flag
11 : ;perform required task
12 add.w #num, &TAxCCR1 ;update next interrupt time
13 reti
;----------------------------------------------------------------------
The second interrupt associated with theTimer_A system is the one related to the TAx-
CCR0 channel. When an TAxCCR0 interrupt is initiated, the CCIFG flag in the TAxCCTL0
register is set, and when the CCIE bit is set, the interrupt is serviced. The following programs,
one in C and the other in assembly, show how one can configure an output pin to toggle its logic
state using the Timer_A TAxCCRO0 interrupt vector.
;----------------------------------------------------------------------
mov.w #WDTPW+WDTHOLD,&WDTCTL ;turn off WDT
mov.b #0x01, &P1DIR ;program P1.0 as output
mov.w #0x1000, &TAxCCR0 ;initialize TAxCCR0 value
mov.b #TASSEL_1+MC_1,&TAxCTL ;select ACLK, up mode
mov.b #CCIE, &TAxCCTL0 ;enable local interrupt
mov.b #GIE, &SR ;enable global interrupt
Loop bra Loop ;wait
;----------------------------------------------------------------------
In C:
//******************************************************************
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; //disable watchdog timer
P1DIR |= 0x01; //program P1.0 as output
TAxCCR0 = 0x1000; //initialize TACCR0 value
TAxCTL = TASSEL_1 + MC_1; //select ACLK, count up mode
TAxCCTL0 = CCIE; //enable TAxCCR0 interrupt
SR = GIE; //turn on global interrupt switch
7.10. MSP430 TIMERS: TIMER_A AND TIMER_B 321
//******************************************************************
//Timer_A TAxCCR0 interrupt service routine
//******************************************************************
Interrupt(TIMERA0_VECTOR) TimerA_procedure(void)
{
P1OUT ^= 0x01; //toggle logic state
}
//******************************************************************
3 The small free running counter difference value is governed by the time required to upload a new value from TBxCCRn
to TBxCLn.
322 7. TIMER SYSTEMS
Referring to Figure 7.17, note that the CCLDx bits (bits 10 and 9) of the TBxCCTLn register
govern the time when the value from the TBxCCRn register is transferred to the TBxCLn
register as shown below.
• 00 – immediate
• 01 – update when TBxR value is zero
• 10 – same as 01 for continuous up count mode. If Up/Down count mode is chosen, the
transfer occurs either when TBxR = 0 or TBxCLn = TBxR
• 11 – update when TBxR = old TBxCLn
TBR
Comparator
Update
TBCLx
CLLDx
TBCCRx
Before we leave this section, we show an example program that uses the capabilities of
the Timer_A system of the MSP430FR2433 to generate two pulse-width modulated signals
on pins P1.4 and P1.5. The signal out of P1.4 has 75% duty cycle and the signal out of P1.5
has 25% duty cycle. The program utilizes the counting up mode along with the TA1CCR0,
TA1CCR1, and TA1CCR2 systems to generate the pulses. The duration specified by the con-
tents of the TA1CCR0 register determine the pulse periods while the values in TA1CCR1 and
TA1CCR2 registers determine the duty cycles for the two pulses. We assume that the ACLK
clock is connected to the LFX1CLK clock signal generator with 32 kHz crystal.
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
7.10. MSP430 TIMERS: TIMER_A AND TIMER_B 323
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
//MSP430FR243x Demo - Timer1_A3, PWM TA1.1-2, Up Mode, DCO SMCLK
//
//Description: This program generates two PWM outputs on P1.4,P1.5
//using Timer1_A configured for up mode. The value in CCR0, 1000-1,
//defines the PWM period and the values in CCR1 and CCR2 the PWM duty
//cycles. Using ~1MHz SMCLK as TACLK, the timer period is ~1ms with
//a 75
//
// ACLK = n/a, SMCLK = MCLK = TACLK = 1MHz
//
// MSP430FR2433
// ---------------
// /|\| |
// | | |
// --|RST |
// | |
// | P1.5/TA1.1|--> CCR1 - 75
// | P1.4/TA1.2|--> CCR2 - 25
//
//
//Ling Zhu, Texas Instruments Inc., Feb 2015
//Built with IAR Embedded Workbench v6.20 & Code Composer Studio v6.0.1
//*********************************************************************
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop WDT
//Configure GPIO
P1DIR |= BIT4 + BIT5;
P1SEL1 |= BIT4 + BIT5;
//*********************************************************************
• use the output compare system to modify the duty cycle of the output waveform,
• use the input capture system to monitor the number of pulses generated by the output
compare system and adjust the duty cycle of the output waveform appropriately,
• verify the output waveform by connecting the output pin on Port 1 to an oscilloscope.
Duty Cycle
50%
0%
0 3 6 9
t(sec)
axis shows the desired duty cycle, and the x-axis shows the time duration for the entire profile.
The duty cycle should increase from 0–50% during the first three seconds, maintain the 50%
duty cycle for another 3 s, and decrease to 0% duty cycle during the last three second period.
The waveform period should be adjusted to 20 ms. (This is the time for the TA1R register to
count from 0–65,536.). You must generate approximately 457 total 20 ms pulses for the total
9 s. The duty cycle should increase linearly from 0–50% in 3 s, or in 152 pulses. Using P1.2 pin
as the output pin, the TA1CCR2 register value should change from 0000–8000h in 152 pulses
or by adding approximately 216 counts to the TA1CCR2 register at each pulse.
Procedure: To generate the desired pulse width modulated signal, use P1.2 pin as the output
compare pin and P1.1 as the input capture pin.
326 7. TIMER SYSTEMS
• Turn on the Timer System.
– Set the logic states on the output pin to be low (off ) when successful compares are
made by configuring bits in the TA1CCTL2 register.
– Use the TA1CCR1 register to set logic state of the pulse to be high (on) using the
TA1CCTL1 register.
– We are using the square wave period of 20 ms. We can find a corresponding number
that represents a desired duty cycle. For example, 8000h represents 50% duty cycle.
When 8000h is stored in the TA1CCR2 register and the TA1R register value matches
with the one in TA1CCR2, the designated action (logic off ) takes place on the output
pin.
– During the acceleration period, you must add 216 to the current value in TA1CCR2,
which will increase the duty cycle at each of the 152 changes between time 0–3 s,
assuming that the TT1CCR2 value started with 0000h. During the deceleration pe-
riod, the opposite action must occur. At each pulse, the value in TA1CCR2 is decre-
mented by 216 counts. At the end of the three second period of deceleration, the duty
cycle decreases to zero.
– Use the input capture system P1.1 to monitor the incoming pulses. You should con-
nect P1.2 to P1.1, which feeds the output compare signal back to input capture pin.
Use the TA1CCTL1 register to configure the input capture system to capture each
pulse entering. By counting the pulses, we can keep tract of the current time with
respect to the desired time profile. Thus, during the first 152 pulses, the input capture
system interrupt should be the one who modifies the TA1CCR2 register contents.
During the next 152 pulses, no changes should be made to the TA1CCR2 register,
and during the last 152 pulses, the value in TA1CCR2 should be decreased by 216
counts after each pulse arrives on the P1.1 pin using the input capture interrupt.
• Once the controller is configured with the steps shown above, the P1.2 pin should be
connected to an oscilloscope, and the output waveform with varying duty cycle should be
verified.
7.12. SUMMARY 327
7.12 SUMMARY
In this chapter, we showed the clock system of MSP430 microcontrollers and the timer-related
capabilities to include the Watchdog timer, basic timer, RTC, input capture system, output
compare system, and PWM system. The architects of the controller seek to provide embed-
ded system designers with flexibility and minimum power usage by implementing three differ-
ent clock signal generators (LFX1CLK, XT2CLK, and DCOCLK) and three clocks (ACLK,
MCLK, and SMCLK) that can be configured for specific application use. The controller also
allows peripheral systems, which usually run slower than the CPU, to run on a separate clock
(ACLK), different from the clock used by the central processing unit, allowing the minimum
use of power. This chapter also showed how the Watchdog timer can be used either to maintain
software execution integrity or to generate periodic time intervals.
The RTC is used to keep track of calendar time with ability to inform year, month, day,
hour, minute, and second. The input capture and output compare capabilities of the controller
are used to interact with external world with time-related events. The input capture system can
capture the time of an incoming event, which can be used to measure the pulse width of a signal
and compute the period or frequency of an incoming periodic signal. It can also be used to count
the number of event occurring externally. The output compare system is used to generate desired
events on external pins at a desired time. For example, the system can generate a logic change, a
pulse, a periodic pulse with a desired duty cycle. The timer system with its clock system and the
capture/compare capabilities allows programmers to implement any time critical applications
using MSP430.
Texas Instruments MSP430FR4xx and MSP430FR2xx Family User’s Guide, (SLAU445G), Texas
Instruments, 2016. 309, 310
1. What is the motivation for having three clock signal generators and three different clocks
in MSP430 controllers?
2. To save power usage, how does one turn off the LFXT1CLK clock signal generator?
3. We want to configure the MCLK clock to run on the XT2CLK clock signal generator.
Which register should be modified? What value should be in the register?
5. How does one select the clock for the Basic Timer?
6. The Basic Timer 2 (BTCNT 2) has two scaling factors, which control register is used for
the two scaling factors?
7. What is the password value and where should you write it to access the Watchdog timer
system control register?
8. Give an example application where one might use the count Up/Down count mode for
the free running counter, TAR.
9. The TAIFG flag when set indicates the free running counter TAR reached its limit. Why
would you not want the flag to set when you are operating in the Up/Down counter mode?
Advanced
2. Program your MSP430 controller to accept a pulse on the P1.0 pin and compute the pulse
width.
3. Given a periodic pulse-width input signal, write a segment of code to compute the duty
cycle using the input capture interrupt system of the MSP430 controller.
4. Program your MSP430 controller to generate a pulse (0–5 V and back down to 0 V) with
2 ms width using the Timer_A system.
5. Program your MSP430 using Timer_B system to generate a pulse-width modulated signal
with frequency of 50 Hz and duty cycle of 40%.
7.14. CHAPTER PROBLEMS 329
Challenging
1. Program your MSP430 to accept any input periodic signal with varying frequency ranging
from 10–1000 Hz and compute the input signal frequency.
2. Write a program that only activates itself if your MSP430 controller receives a 200 s
pulse (10% tolerance on the pulse width) from an external device on P1.0 pin, updates
the number of times the designated pulse was received, displays the number on an LCD
display unit for 5 s, and “sleeps” until the next pulse arrives.
331
CHAPTER 8
8.1 MOTIVATION
One of the primary reasons to select a MSP430 microcontroller is its ability to minimize power
usage by allowing a programmer to configure the microcontroller to run with different oper-
ational modes based on environmental factors or timed events. The subject of this chapter is
332 8. RESETS AND INTERRUPTS
closely related to different means for the controller to implement mechanisms to switch be-
tween two or more different power consumption operating modes. Typically, while a controller
is waiting for a designated event to occur, whether it is an arrival of a particular external signal
or after a programmed elapsed time period, it operates in a power save mode with all or most of
its clocks turned off. When the time comes, the microcontroller switches the operating mode
(wake up from “sleep”), performs necessary tasks, and switches back to the power saving mode
until the next designated event occurs. The back and forth switching between operating modes
is accomplished using the built-in interrupt system, which is the topic of this chapter.
8.2 BACKGROUND
Typical embedded systems operate in environments where electrical and mechanical noises
abound. These noise sources can often interfere with the proper operation of a microcontroller
in an embedded system, which can cause skipping of intended instructions and unintentional
change of register contents. One of the primary means to combat such undesired operation in
the MSP430 microcontroller is the Watchdog timer system. By forcing the program to up-
date special registers periodically, one can make sure that intended instructions are executed in
a proper order. Otherwise, the microcontroller resets itself before resuming its operation. The
Watchdog timer system reset example illustrates the function of microcontroller resets. They are
used to bring the internal processing state of the controller to a default state.
An interrupt, on the other hand, is a software or hardware induced request which is ex-
pected to occur during the controller operation but whose time of occurrence is not known in
advance. It is the programmer’s responsibility to plan (write a special program called an interrupt
service routine) to respond to an interrupt when it occurs. For example, suppose that you know
a user will push an external button to halt a process sometime during the course of an operation
of your MSP430 microcontroller but do not know the exact time when it will occur. A button
push, in this example, is a hardware induced interrupt, and a programmer must write a separate
“program” that will respond to the event appropriately to halt the process.
In general, there is another way for a microcontroller to detect an event, called polling. The
polling method relies on using the resources of the controller to continuously monitor whether
or not an event has occurred. This can be in the form of checking a flag continuously to see the
flag status change (bit changes from 1 to 0, or vice versa) or the change of the logic level on an
input pin. As the reader can imagine, the resources of the controller is “tied up” when polling
is used to “wait” for an event to occur. The advantage of using the interrupt system, which we
focus in this chapter, compared to the polling technique is the better usage of resources. Using
the interrupt system, the controller does not have to poll an event but perform other operations
or even turn itself off to save power. When an event occurs, the controller initiates a special
routine associated with the interrupt.
8.3. MSP430 RESETS/INTERRUPTS OVERVIEW 333
Naturally, the polling method is simple to implement compared to the steps required to
implement the interrupt method. The benefit, however, of the interrupt method is the conser-
vation of limited, precious power resources.
r0 r0 r0 r0 r0 r0 r0 r0
7 6 5 4 3 2 1 0
Reserved Reserved Reserved Reserved SYSRSTRE SYSRSTUP SYSNMIIES SYSNMI
Port Wakeup
Security
RST/NMI Violation
(reset wakeup)
DoBOR
RST/NMI⇉ BOR Event
(reset event)
SVMH OVP-Fault
Load Calibration Data
SVSH Fault
SVML OVP-Fault DoPOR
Event
SVSL Fault POR
WDT Active
Time Expired, Overflow PMM
Password Violation
WDT Active
Password Violation PUC
Flash
Password Violation
Peripheral Area Fetch
To Active Mode
Figure 8.2: Reset activity of the MSP430 microcontroller. (Figure used with permission of Texas
Instruments (www.ti.com).)
8.5. INTERRUPTS 335
The third type of resets, the PUC reset, are initiated, in addition to the POR signal, by nine
and five different events for the MSP430FR5994 and MSP430FR2433 controllers, respectively.
For both controllers, whenever the controller detects a POR, the PUC reset is also triggered. For
both controllers, the first and the second PUC reset events are associated with the Watchdog
timer system. When the Watchdog timer expires or the Watchdog timer password is violated,
the PUC reset is triggered. The other three common events that trigger the PUC reset for both
controllers are the password violation to access the onboard flash memory, the password violation
to access the PMM, and fetching from memory areas not populated.1 A password to access the
flash memory is necessary to prevent a runaway program from corrupting stored software. For
the MSP430FR5994 controller, the following four additional events trigger the PUC reset:
(1) memory protection unit password violation, (2) memory segmentation violation, (3) CS
password violation, and (4) uncorrectable FRAM bit error.
In terms of the level of resets, the BOR initializes all systems while the POR and the
PUC resets restore MSP430 conditions partially. Throughout the documents for the MSP430
microcontroller, one finds the POR and PUC reset values annotated using symbols such as rw-
(1 or 0). For example, rw-0 indicates that the register bit value can be read or written and the
initial value is 0 after the PUC reset, while rw-(0) denotes that the register bit can be read and
written and the initial value is 0 after the POR (the parentheses are used to distinguish between
POR and PUC). For the latter example case, the register value remains the same after the PUC
reset. The general conditions of the MSP430 microcontroller after a system reset are:
• the RTS=NMI pin is configured as the reset mode,
• all input and output pins are configured as input,
• the program counter register is loaded with the boot code start address (ex. 0xFFFE),
• the status register (SR) is cleared,
• all peripheral modules and registers are initialized, and the
• Watchdog timer is initialized (Watchdog mode).
Due to the steps taken by the MSP430 microcontroller after a reset, the programmer must
make sure that, at the start of the proper program module, the stack pointer, the Watchdog
specifications, and peripheral modules are initialized [SLAU445G, 2016, SLAU367O, 2017].
8.5 INTERRUPTS
A microcontroller normally executes instructions in an orderly fetch-decode-execute sequence
as dictated by a user-written program as shown in Figure 8.3. All microcontrollers, however,
1 The VMAIE (vacant memory access interrupt enable flag) bit must be set(1) for this reset to initiate.
336 8. RESETS AND INTERRUPTS
restore
context
Interrupt
Fetch Service
Routine
store
context
Decode
Execute
are equipped to handle unscheduled, higher priority events that might occur inside or outside a
microcontroller. To process such events, a microcontroller requires an interrupt system.
The interrupt system onboard a microcontroller allows it to respond to higher priority
events. These events are expected events, but we do not know when they will occur. When an
interrupt event does occurs, a microcontroller normally completes the instruction it is currently
executing, stores key register values (context) on the stack, and transitions its program control to
a special routine written to respond to the interrupt event. The special routine is a function called
an interrupt service routine (ISR). Each interrupt will normally have its own interrupt specific
ISR. Once the ISR is completed, the microcontroller will restore key register values from the
stack and resume processing where it left off before the interrupt event occurred.
Applying the general concept of an interrupt, one can consider resets as interrupts with
two exceptions. A reset does not cause the program counter to return to the point of operation
when the reset was detected, and reset routines are fixed, not available to a programmer. Stretch-
ing the discussion a bit more, resets may be considered as non-maskable interrupts (NMI) with
pre-programmed initialization routines.
8.5. INTERRUPTS 337
Besides resets, there are two other types of NMIs supported by MSP430 microcontroller.
The first type is the system generated NMIs (SNMI), and the second type are the ones gen-
erated by the user (UNMI). One example of an SNMI type interrupt, is the JTAG mailbox
event. Recall that the JTAG interface is available for all MSP430 microcontrollers for the pur-
pose of programming, debugging and testing the MSP430. The JTAG interface allows access
to the CPU during program execution. One can configure the interface such that when data is
read through the interface, a non-maskable interrupt occurs. The second SNMI occurs when
FRAM errors occur and the last type of SNMI is caused by accessing a vacant memory loca-
tion [SLAU445G, 2016, SLAU367O, 2017].
For the user-specified NMIs, there are two sources that can generate an UNMI. The first
one is caused by an oscillator fault. The controller monitors the crystal oscillator frequency. An
UNMI is triggered when the frequency falls outside an acceptable range. The second UNMI is
caused by the logic state on the RTS=NMI pin when the pin is configured for the NMI mode.
The MSP430 microcontroller has many MI sources. The difference between NMIs and
MIs is that unlike NMIs, MIs can be programmed to be ignored by the CPU by turning off the
GIE bit of the status register. To enable a maskable interrupt, not only the GIE bit must be set,
but also each subsystem interrupt in use must be enabled. These subsystems are enabled using
appropriate bits in the interrupt enable register (SFRIE1), shown in Figure 8.4. When one of
these interrupts occurs, the corresponding flag in the interrupt flag register (SFRIFG1), shown
in Figure 8.5, is set.
In most microcontrollers, including the MSP430, the starting address for each interrupt
service routine, the special function to perform in response to an interrupt, is stored in a pre-
designated location which the CPU recognizes. The addresses reside in consecutive memory
locations and are collectively designated as interrupt vectors. For the MSP430 microcontroller,
the memory locations are 0xFFFF through 0xFF80, where each vector takes up two memory
locations. Memory space is available in the interrupt vector table for up to 64 different interrupt
sources. Figure 8.6 provides the table of interrupt vectors for MSP430 microcontroller.
During the development phase, it is handy to configure the top of RAM space as alterna-
tive locations for interrupt vectors by setting the SYSRIVECT (RAM-based interrupt vectors)
bit in the System Control Register (SYSCTL) register, shown in Figure 8.7.
15 14 13 12 11 10 9 8
Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved
r0 r0 r0 r0 r0 r0 r0 r0
7 6 5 4 3 2 1 0
JMBOUTIE JMBINIE NMIIE VMAIE Reserved OFIE WDTIE
2. Store the contents of the program counter (PC) onto the stack.
3. Store the contents of the status register (SR) onto the stack.
6. Clear the Status Register to prevent additional interrupts from occurring and to switch
from the low power mode to the normal power mode (if configured).
7. Load the contents of the interrupt vector onto the program counter.
9. Once the service routine is finished (with the RETI instruction), restore the SR and then
PC values from the stack.
r0 r0 r0 r0 r0 r0 r0 r0
7 6 5 4 3 2 1 0
JMBOUTIFG JMBINIFG Reserved NMIIFG VMAIFG Reserved OFIFG WDTIFG
. .
Watchdog Timer WDTIFG . .
. . . .
. . . .
r0 r0 r0 r0 r0 r0 r0 r0
7 6 5 4 3 2 1 0
Reserved Reserved SYSJTAGPIN SYSBSLIND Reserved SYSPMMPE Reserved SYSRIVECT
Once an interrupt is detected, it takes six clock cycles for the MSP controller to begin
interrupt processing, and it takes five clock cycles to restore the SR and PC values and resume
executing normally after the interrupt service ends. Figure 8.8 shows the stack configuration
before and after step 3 and step 9.
Following the procedure described above, everything seems to be straightforward if for
each interrupt source, there was only a single and unique interrupt flag. Unfortunately, that is
not always the case for the MSP430 microcontroller. For example, for all interrupts associated
with the Timer_A module, a single flag, TAIFG (Timer_A interrupt flag), is set. It becomes
a programmer’s responsibility to resolve the ambiguity as a part of the interrupt service routine
Memory Address
Increasing
SR Top of Stack
Stack Pointer
PC
Value Top of Stack Value
Stack Pointer
r0 r0 r0 r0 r0 r0 r0 r0
7 6 5 4 3 2 1 0
0 0 SYSRSTVEC 0
r0 r0 r0 r0 r0 r0 r0 r0
7 6 5 4 3 2 1 0
0 0 0 SYSSNVEC 0
When a MSP430 microcontroller is shipped, the interrupt service routines for resets and
system non-maskable interrupts are already programmed and should not be altered. We de-
scribed the above process to illustrate a similar process to resolve the source of a non-maskable
user interrupt or maskable interrupt in your interrupt service routine. We should also note that
some devices have separate bus error interrupts, which can also be serviced in the same manner
as shown above using the SYSBERRIV (Bus Error Interrupt Vector) register.
8.5. INTERRUPTS 343
r0 r0 r0 r0 r0 r0 r0 r0
7 6 5 4 3 2 1 0
0 0 0 SYSUNVEC 0
System Word
Interupt Source Interrupt Flag Priority
Interrupt Address
System Reset
SVSHIFG
Power up, brownout, supply
PMMRSTIFG
supervisor
WDTIFG
External reset RST
WDTPW, FRCTLPW, MPUPW, CSPW, PMMPW,
Watchdog time-out (watchdog mode)
UBDIFG Reset 0FFFEh Highest
WDT, FRCTL, MPU, CS,
MPUSEGIIFG, MPUSEG1IFG, MPUSEG2IFG,
PMM password violation
MPUSEG3IFG
FRAM uncorrectable bit error detection
PMMPORIFG, PMMBORIFG
MPU segment violation
(SYSRSTIV)(1)(2)
Software POR, BOR
System NMI
VMAIFG
Vacant memory access
JMBINIFG, JMBOUTIFG
JTAG mailbox
ACCTEIFG, WPIFG
FRAM access time error (Non)maskable 0FFFCh
MPUSEGIIFG, MPUSEG1IFG,
FRAM write protection error
MPUSEG2IFG, MPUSEG3IFG
FRAM bit error detection
(sYSSNIV)(1)(3)
MMPU segment violation
User NMI
NMIFG, OFFIFG
External NMI (Non)maskable 0FFFAh
(SYSUNIV)(1)(3)
Oscillator fault
CEIFG. CEIIFG
Comparator_E Maskable 0FFF8h
(CEIV)(1)
TB0 TB0CCR0.CCIFG Maskable 0FFF6h
TB0CCR1.IFG ... TB0CCR6. CCIFG, TB0CTL.
TB0 TBIFG Maskable 0FFF4h
(TB0IV)(1)
Watchdog timer (interval timer mode) WDTIFG Maskable 0FFF2h
UCA0IFG: UCRXIFG, UCTXIFG (SPI mode)
UCA0IFG: UCSTTIFG,
eUSCI_A0 receive or transmit UCTXCPTIFG, UCRXIFG, Maskable 0FFF0h
UCTXIFG (UART MODE)
(UCADIV)(1)
UCB0IFG: UCRXIFG, UCTXIFG (SPI mode)
UCB0IFG: UCALIFG, UCNACKIFG, UCSTTIFG,
UCSTPIFG, UCRXIFG0, UCTXIFG0, UCRXIFG1,
eUSCI_B0 receive or transmit Maskable 0FFEEh
UCTXIFG1, UCRXIFG2, UCTXIFG2, UCRXIFG3,
UCTXIFG3, UCCNTIFG, UCBIT9IFG (I2C mode)
(UCB0IV)(1)
ADC12IFG0 to ADC12IFG31
ADC12LOIFG, ADC12INIFG,
ADC12_B ADC12HIIFG, ADC12RDYIFG, Maskable 0FFECh
ADC21OVIFG, ADC12TOVIFG
(ADC12IV)(1)(4)
TA0 TA0CCR0.CCIFG Maskable 0FFEAh
(1) Multiple source flags
(2) A reset is generated if the CPU tries to fetch instructions from peripheral space.
(3) (Non)maskable: the individual interrupt enable bit can disable an interrupt event, but the general interrupt enable bit cannot disable it.
(4) Only on devices with ADC, otherwise reserved.
Figure 8.13: Interrupt priority list for MSP430FR5994. (Illustration used with permission of
Texas Instruments (www.ti.com).)
346 8. RESETS AND INTERRUPTS
System Word
Interupt Source Interrupt Flag Priority
Interrupt Address
TA0CCR1.CCIFG, TA0CCR2.CCIFG,
TA0 TA0CTL.TAIFG Maskable 0FFE8h
(TA0IV)(1)
UCA1IFG: UCRXIFG, UCTXIFG (SPI mode)
UCA1IFG: UCSTTIFG, UCTXCPTIFG, UCRXIFG,
EUSCI_A1 receive or transmit Maskable 0FFE6h
UCTXIFG (UART mode)
(UCA1IV)(1)
DMA0CTL.DMAIFG, DMA1CTL.DMAIFG,
DMA DMA2CTL.DMAIFG Maskable 0FFE4h
(DMAIV)(1)
TA1 TA1CCR0.CCIFG Maskable 0FFE2h
TA1CCR1.CCIFG, TA1CCR2.CCIFG,
TA1 TA1CTL.TAIFG Maskable 0FFE0h
(TA1IV)(1)
P1IFG.0 to P1IFG.7
I/O port P1 Maskable 0FFDEh
(P1IV)(1)
TA2 TA2CCR0.CCIFG Maskable 0FFDCh
TA2CCR1.CCIFG
TA2 TA2CTL.TAIFG Maskable 0FFDAh
(TA2IV)(1)
P2IFG.0 to P2IFG.7
I/O port P2 Maskable 0FFD8h
(P2IV)(1)
TA3 TA3CCR0.CCIFG Maskable 0FFD6h
TA3CCR1.CCIFG
TA3 TA3CTL.TAIFG Maskable 0FFD4h
(TA3IV)(1)
P3IFG.0 to P3IFG.7
I/O port P3 Maskable 0FFD2h
(P3IV)(1)
P4IFG.0 to P4IFG.2
I/O port P4 Maskable 0FFD0h
(P4IV)(1)
RTCRDYIFG, RTCTEVIFG, RTCAIFG, RT0PSIFG,
RTC_C RT1PSIFG, RTCOFIFG Maskable 0FFCEh
(RTCIV)(1)
AES AESRDYIFG Maskable 0FFCCh
TA4 TA4CCR0.CCIFG Maskable 0FFCAh
TA4CCR1.CCIFG
TA4 TA4CTL.TAIFG Maskable 0FFC8h
(TA4IV)(1)
P5IFG.0 to P5IFG.2
I/O port P5 Maskable 0FFC6h
(P5IV)(1)
P6IFG.0 to P6IFG.2
I/O port P6 Maskable 0FFC4h
(P6IV)(1)
UCA2IFG: UCRXIFG, UCTXIFG (SPI mode)
UCA2IFG: UCSTTIFG, UCTXCPTIFG, UCRXIFG,
eUSCI_A2 receive or transmit Maskable 0FFC2h
UCTXIFG (UART mode)
(UCA2IV)(1)
UCA3IFG: UCRXIFG, UCTXIFG (SPI mode)
UCA3IFG: UCSTTIFG, UCTXCPTIFG, UCRXIFG,
eUSCI_A3 receive or transmit Maskable 0FFC0h
UCTXIFG (UART mode)
(UCA3IV)(1)
UCB1IFG: UCRXIFG, UCTXIFG (SPI mode)
UCB1IFG: UCALIFG, UCNACKIFG, UCSTTIFG,
UCSTPIFG, UCRXIFG0, UCTXIFG0, UCRXIFG1,
eUSCI_B1 receive or transmit Maskable 0FFBEh
UCTXIFG1, UCRXIFG2, UCTXIFG2, UCRXIFG3,
UCTXIFG3, UCCNTIFG, UCBIT9IFG (I2C mode)
(UCB1IV)(1)
(1) Multiple source flags
Figure 8.14: Interrupt priority list for MSP430FR5994. (Illustration used with permission of
Texas Instruments (www.ti.com).)
8.5. INTERRUPTS 347
System Word
Interupt Source Interrupt Flag Priority
Interrupt Address
UCB2IFG: UCRXIFG, UCTXIFG (SPI mode)
UCB2IFG: UCALIFG, UCNACKIFG, UCSTTIFG,
UCSTPIFG, UCRXIFG0, UCTXIFG0, UCRXIFG1,
eUSCI_B2 receive or transmit Maskable 0FFBCh
UCTXIFG1, UCRXIFG2, UCTXIFG2, UCRXIFG3,
UCTXIFG3, UCCNTIFG, UCBIT9IFG (I2C mode)
(UCB2IV)(1)
UCB3IFG: UCRXIFG, UCTXIFG (SPI mode)
UCB3IFG: UCALIFG, UCNACKIFG, UCSTTIFG,
UCSTPIFG, UCRXIFG0, UCTXIFG0, UCRXIFG1,
eUSCI_B3 receive or transmit Maskable 0FFBAh
UCTXIFG1, UCRXIFG2, UCTXIFG2, UCRXIFG3,
UCTXIFG3, UCCNTIFG, UCBIT9IFG (I2C mode)
(UCB3IV)(1)
P7IFG.0 to P7IFG.2
I/O port P7 Maskable 0FFB8h
(P7IV)(1)
P6IFG.0 to P6IFG.2
I/O port P8 Maskable 0FFB6h
(P8IV)(1)
CMDIFG, SDIIFG, OORIFG,TIFG, COVLIFG
LEA (MSP430FR599x only) Maskable 0FFB4h
LEAIV(1)
(1) Multiple source flags
Figure 8.15: Interrupt priority list for MSP430FR5994. (Illustration used with permission of
Texas Instruments (www.ti.com).)
#include <msp430.h>
int main(void)
8.5. INTERRUPTS 349
{
WDTCTL = WDTPW | WDTHOLD; //Stop WDT
//*******************************************************************
//Timer0_A1 interrupt service routine
//*******************************************************************
#if defined(__TI_COMPILER_VERSION__)||defined(__IAR_SYSTEMS_ICC__)
#pragma vector = TIMER0_A0_VECTOR
__interrupt void Timer0_A0_ISR (void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(TIMER0_A0_VECTOR)))Timer0_A0_ISR (void)
#else
#error Compiler not supported!
#endif
{
P1OUT ^= BIT0;
TA0CCR0 += 50000; //Add Offset to TA0CCR0
}
//*******************************************************************
In this example, the MSP430F5438 Timer0_A is again used with the associated interrupt
vector generator demonstrated.
350 8. RESETS AND INTERRUPTS
//********************************************************************
// 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--
//*********************************************************************
//MSP430FR5x9x Demo - Timer0_A3, Toggle P1.0, Overflow ISR, 32kHz ACLK
//
//Description: Toggle P1.0 using software and the Timer0_A overflow ISR.
//In this example, an ISR triggers when TA overflows. Inside the ISR
//P1.0 is toggled. Toggle rate is exactly 0.5Hz. Proper use of the
//TAIV interrupt vector generator is demonstrated.
//
//ACLK = TACLK = 32768Hz, MCLK = SMCLK = CD0/2 = 8 MHz/2 = 4MHz
//
// MSP430FR5994
// --------------------------
// /|\ | XIN | -
// | | |
// -- | RST XOUT | -
// | |
// | P1.0 | --> LED
//
//William Goh, Texas Instruments Inc., October 2015
//Built with IAF Embedded Workbench V6.30 & Code Composer Studio V6.1
//**********************************************************************
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop WDT
8.5. INTERRUPTS 351
//**********************************************************************
// Timer0_A1 Interrupt Vector (TAIV) handler
//**********************************************************************
//*********************************************************************
In this final example, the Watchdog timer interrupt is used to toggle MSP430 microcon-
troller pin P1.0.
//*********************************************************************
// 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--
//*********************************************************************
//MSP430FR5x9x Demo-WDT, Toggle P1.0, Interval Overflow ISR, DCO SMCLK
//
//Description: Toggle P1.0 using software timed by the WDT ISR. Toggle
//rate is approximately 30ms = {(1MHz) / 32768} based on DCO = 8MHz
//clock source used in this example for the WDT.
// ACLK = n/a, SMCLK =1MHz
//
8.5. INTERRUPTS 353
// MSP430FR5994
// --------------------------
// /|\ | |
// | | |
// -- | RST |
// | |
// | P1.0 | --> LED
//
//William Goh, Texas Instruments Inc., October 2015
// Built with IAF Embedded Workbench V6.30 & Code Composer Studio V6.1
//***********************************************************************
#include <msp430.h>
void main(void)
{
WDTCTL = WDTPW | WDTSSEL__SMCLK | WDTTMSEL | WDTCNTCL | WDTIS__32k;
//***********************************************************************
// Watchdog timer interrupt service routine
//***********************************************************************
354 8. RESETS AND INTERRUPTS
//***********************************************************************
It should be noted, if recursive interrupts or nesting interrupts are desired, the GIE bit
in SR should be set inside an ISR. If nesting interrupts are allowed on purpose, a programmer
must be sure that the stack will have enough space to accommodate the number of consecutive
nested interrupts.
Temperature
Controller
Power Status Signals
Heater/Air-Conditioner
Control Signals
Window
Living Room
Advanced
1. Why did the designers of MSP430 come up with three different types of resets?
2. Refer to the Interrupt Handling Process (Section 8.5.1) and explain the purpose for each
of the ten steps.
3. Write a segment of code to initialize the MSP430 microcontroller to operate in the power
save LPM3.5 mode and only operate in the normal mode during an interrupt.
Challenging
1. It is challenging to handle nested interrupts. What might be some applications where
nested interrupts are necessary?
2. Consider the exercise in Section 8.6. Write a program for the central station that accepts
the data from the temperature controller and log them in memory. Use an interrupt service
routine since the power level data is only sent every 5 min.
357
CHAPTER 9
Analog Peripherals
Objectives: After reading this chapter, the reader should be able to:
• describe the function of an ADC and a DAC;
• explain the method used to perform analog conversions in the MSP430 microcontroller;
• configure the MSP430 microcontroller to accept analog signals and convert them into
digital forms;
• describe the operation of the MSP430 comparators;
• use interrupts associated with the MSP430 microcontroller’s ADC systems; and
• configure the MSP430 analog conversion process by writing an appropriate program.
We live in an analog world! When we represent physical phenomena as signals over time,
the signal may have any of an infinite number of values. For example, if we display the pitch of
your voice over time, it will be a continuous signal with your pitch varying over the period. The
intensity of sunlight, wind speed, air temperature, the rate of a bird flapping its wings, and the
speed of your car are all analog in nature. On the other hand, digital signals have a finite number
of values over time. For a binary signal, the value is either logic one or zero, which computers use.
To interact with the analog world, computers must have the capability to accept and generate
analog signals.
In this chapter, we discuss the subsystems of a microcontroller that allows input of an
analog signal: the MSP430’s ADC system. We also explore the DAC process. We also describe
the comparator system, which indicates whether a signal sample is within a set of defined voltage
thresholds.
60
40
Magnitude
20
−20
−40
−60
0 2 4 6 8 10
Time (sec)
9.1.1 SAMPLING
The sampling process allows for a digital system to capture an analog signal at a specific time.
One can consider the sampling process as similar to taking snap shots of changing scenery using
a camera.
Suppose we want to capture the movement of a baseball pitcher as he throws a ball toward
home plate. Assume the only means for you to capture the motion of the pitcher is a camera.
Suppose it takes 2 s for the pitcher to throw a baseball. If you take a picture at the start of
the pitch and another one 2 s later, you have missed most of the action and will not be able to
accurately represent the motion of the pitcher and the details of the pitch path.
The time between sampled snap shots is the period specified in seconds. The inverse of
the period is the sampling frequency with the unit of Hertz (Hz). In this example, since there is
a two second interval between samples, the sampling rate is 1=2 D 0:5 Hz (f D 1=T ). As you
can imagine, the faster you take the pictures the more accurately you can recreate the pitcher’s
motion and the pitch path by sequencing photos.
The example illustrates the primary issue of the sampling process, that of the sampling
frequency. A correct sampling frequency depends on the characteristics of the analog signal. If
9.1. ANALOG-TO-DIGITAL CONVERSION PROCESS 359
the analog signal changes quickly, the sampling frequency must be high, while if the signal does
not change rapidly the sampling frequency can be slow and one can still capture the essence of
the incoming signal.
You may wonder what harm is there, then, in sampling at the highest possible rate, re-
gardless of the frequency content of the analog signal? Just as it would be a waste of resources
to take multiple pictures of the same stationary object, it would not be a good use of resources
to sample with a high frequency rate regardless of the nature of an analog signal. In the 1940s,
Henry Nyquist, who worked at Bell Laboratory, developed the concept that the minimum re-
quired sampling rate to capture the essence of an analog signal is a function of the highest input
analog signal frequency: fs 2 fh . The frequency fs and fh are the sampling frequency
and the highest frequency of the signal we want to capture, respectively. That is, the sampling
frequency must be greater than or equal to two times the highest frequency component of the
input signal. We illustrate the Nyquist sampling rate using Figure 9.2.
Figure 9.2a shows the analog signal of interest, a sinusoidal signal. Frame (b) of the fig-
ure shows sampling points with a rate slower than the Nyquist rate and frame (c) shows the
reconstruction of the original signals using only the sampled points shown in frame (b). Frame
(d) shows the sampled points at the Nyquist rate and the corresponding reconstructed signal is
shown in frame (e). Finally, frame (f ) shows sampled points at a rate higher than the Nyquist
sampling rate and frame (g) shows the reconstructed signal. As can be seen from this simple
example, when we sample an analog signal at the Nyquist sampling rate, we can barely generate
the characteristics of the original analog signal. While at a higher sampling rate, we can retain
the nature of an input analog signal more accurately, but at a higher cost, requiring a faster clock,
additional processing power, and more storage for the accumulated data. Let us examine one
final example before we move on to the quantization process.
Example: An average human voice contains frequencies ranging from about 200 Hz to 3.5 kHz.
What should be the minimum sampling rate for an ADC system?
Answer: According to the Nyquist sampling rate rule, we should sample at 3.5 kHz 2 D
7 kHz, which translates to taking a sample every 142.9 usec. Your telephone company uses a
sampling rate of 8 kHz to sample your voice.
9.1.2 QUANTIZATION
Once a sample is captured, then the second step of the conversion process, quantization, can
commence. Before we explain the process, we first need to define the term quantization level.
Suppose we are working with an analog voltage signal whose values can change from 0–5 V.
Now suppose we pick a point in time. The analog signal, at that point in time, can have any
value between 0–5 V, an infinite number of possibilities (think of real numbers). Since we do
not have a means to represent an infinite number of different values in a digital system, we limit
the possible values to a finite number. So, what should this number be? Previously, we saw that
360 9. ANALOG PERIPHERALS
(a) (b)
(c) (d)
(e) (f )
(g)
Quantized Level 8
Resolution
Quantized Level 7
Quantized Level 3
Quantized Level 2
Quantized Level 1
Quantized Level 0
As you may suspect, there is a tradeoff between using a large number of bits for an accurate
representation vs. the hardware cost of designing and manufacturing a converter. A converter
which employs more bits will yield more accurate representations of the sampled signal values.
A decision made by an ADC designer determines the accuracy of a sampled data and the cost
to manufacture the converter. The number of bits used to quantize a sampled value determines
the available quantization levels. Therefore, a converter which uses 8 bits has 256 quantization
levels while a converter that uses 10 bits has 1024 quantization levels.
We need to also define what is known as the resolution of an ADC. Simply put, the reso-
lution is the smallest quantity a converter can represent or the “distance” between two adjacent
quantization levels. The resolution will naturally vary depending on the range of input analog
signal values. Suppose the input range is from 0–5 V, a typical input range of an ADC, and we
have an 8-bit converter. The resolution, ı , is then
analog input highest value analog input lowest value 5 0
ıD D D 19:5312 mV:
2b 256
Example: Given an application that requires an input signal range of 10 V and the resolution
less than 5 mV, what is the minimum number of bits required for the ADC?
362 9. ANALOG PERIPHERALS
Answer: 102100 D 9:77 mV and 102110 D 4:88 mV. Thus, the minimum required number of bits
for the ADC is 11 bits.
We can now combine both sampling and quantization processes together to identify a
quantized level of a sampled value. Suppose a sampled analog signal value is 3.4 V and the
input signal range is 0–5 V. Using a converter with 8 bits, we can find the quantized level of the
sampled value using the following equation:
sampled input value lowest possible input value
Quantized level D :
ı
Thus, given the input sample value of 3.4 V, the quantized level becomes 3:4 V 0V
19:53 mV
Š
174:09. Since we can only have integer levels, the quantized level becomes 174.
The sampling error is the difference between the true analog value and the sampled value.
It is the amount of approximation the converter had to make. See Figure 9.4 for a pictorial view
of this concept. For the example, the input sampled value 3.4 V is represented as the quantized
level 174 and the quantized error is 0:09 ı D 1:76 mV. Note that the maximum quantization
error is the resolution of the converter.
Example: Given a sampled signal value of 7.21 V, using a 10-bit ADC with input range of 0 V
and 10 V, find the corresponding quantization level and the associated quantization error.
Answer: First, we find the quantized level:
7:21 0
Quantized level D ;
ı
where ı D 210
10 D 9:77 mV. Thus, the quantized level is 738.3059. Since we always round
down, the quantized level is 738 and the associated quantization error is 0:3059 9:77 mV Š
2:987 mV.
9.1.3 ENCODING
The last step of the ADC process is the encoding. The encoding process converts the quan-
tized level of a sampled analog signal value into a binary number representation. Consider
the following simple case. Suppose we have a converter with four bits. The available quan-
tization levels for this converter are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15.
Using 4 bits, we can represent the quantization levels in binary as 0000, 0001, 0010, 0011,
0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, and 1111. Once we iden-
tify a quantization level, we can uniquely represent the quantization level as a binary number.
This process is called encoding. Similar to a decimal number, the position of each bit in a bi-
nary number represents a different value. For example, binary number 1100 is decimal number
.1 23 / C .1 22 / C .0 21 / C .0 20 / D 12. Knowing the weight of each bit, it is a straight
forward process to represent a decimal number as a binary number.
9.1. ANALOG-TO-DIGITAL CONVERSION PROCESS 363
Sampled Value
Quantization Error
Quantization Level n
d igi t al i nput
Analog output D Vrefmax ;
2N
where N stands for the number of bits used in the converter and Vrefmax represents the maximum
analog reference voltage of the converter. The DAC uses the summing technique where each of
the input digital bits asserts a switch to turn on its associated weighted voltage. All voltages are
summed to generate an output analog voltage. Figure 9.5 illustrates a 4-bit DAC converter with
the maximum and minimum output values of 2.5 V and 0 V, respectively.
9.3. MSP430 ADC SYSTEMS 365
MSB
0
1.25 V
1
LPF
0
Output
0.3125 V
1
Summer
LSB
0
0.15625 V
1
MSB LSB
Digital input value determines which
switches are closed (1) and which
switches remain open (0).
Figure 9.5: A sample 4-bit digital to analog converter. The DAC digital input governs the posi-
tions of the switches. The digital input values determine if the corresponding reference voltage
values should contribute to the converter output value. The output of the summer is typically
connected to a low pass filter (LPF) to reduce sharp signal edges resulting from the conversion
process.
Input Voltage
Select Reference
Voltage
Select
VR- VR+
Input
Sample Sample Successive Timing Source
Voltage
Input and Hold Approximation
Select
(S/H) Converter Trigger Source
mux
n
Results Interrupts
Registers
Digital-to-Analog
Converter
Unknown Sample
Sample and Hold Voltage
Voltage (S/H) Comparator
n
ss
ss
s
ue
ue
ue
G
ADCSR
Auto ADCCONSEQx
Reference 10
Buffer 01 From on-chip
Reference Voltage
A0 0000
A1 0001 VSS VCC
A2 0010
A3 ADC ADC
0011 1 0 11 10 01 00
ADC
SREF2 SREFx
A4 0100 ADCON ADCDIVx ADCPDIVx SSELx Time Base
A5 0101 Select
A6 0110 VR- VR+ 00 MODOSC
A7 0111 Sample Divider 00 01 ACLK
ADC Core 01 +4
A8 1000 and Hold +1 – +8 11 10 MCLK
Convert +64
A9 1001 11 SMCLK
A10 1010 ADC ADC ADCCLK Trigger Source
A11 1011 MSC SHTx
Select
A12 1100 ADC
00 ADCSC
A13 1101 BUSY Sample Timer
1 01 Timer Trigger 0
A14 1110 1 +4 – +1024
0
Sync
10 Timer Trigger 1
A15 1111 0
ADCDF 11 Timer Trigger 2
ADC
SHP ADC ADC
ISSH SHSx
Data Format ADCHIx Comparator Interrupt
Output Processing Window Comparator To Interrupt Logic
ADCLOx
ADCMEM
Figure 9.7: Block diagram of the MSP430 10-bit analog-to-digital converter. (Illustration used
with permission of Texas Instruments (www.ti.com).)
reference voltage, which can be supplied by a user with external voltage sources or using the
MSP430 internal reference voltage generator module.
Input A12 is connected to a built-in temperature diode which measures the environmental
temperature of the controller (useful for a variety of meters where MSP430 controllers are used),
and input A13 is connected to a DC voltage whose value is 0.5 * (AVcc - AVss), if required for
an application.
Once an analog signal (or multiple signals) enters the converter, bits ADCINCHx (bits
3-0) of the ADC memory control register (ADCMCTLx) determine which input channel or a
starting channel of a group of input channels will be used in the converter.
Reference voltage select. The ADCSREFx bits (bits 6-4) in the ADC memory control
register x (ADCMCTLx) are used to select one of eight possible voltage reference selections as
shown in Table 9.1. The ADC uses 10 bits to sample analog signals, providing 1024 different
9.3. MSP430 ADC SYSTEMS 369
Table 9.1: Voltage reference
quantized levels (000h - 3FFh) to represent a sample value. If an input voltage value is equal to
reference low (REF ) value, 000h results while an input voltage equal to reference high (REFC)
voltage is represented as 3FFh. The results are encoded either as unsigned or 2’complement
binary values as specified by the ADC read back format (ADCDF) bit in ADC Control 2
(ADCCTL2) register.
Clock source select. ADC clock source selection is determined by the ADCSSELx bits
(bits 4-3) of the ADC control 1 (ADCTL1) register. Selecting these bits determines whether
the source clock is MODOSC (00), ACLK (01), MCLK (10), or SMCLK (11). The selected
clock source can be divided by two different stages: the ADC predivider (ADCPDIV bits) and
the ADC clock divider. The ADCPDIV bits (bits 9-8) of ADC control 2 (ADCCTL2) register
provide for a divide by 1 (00), 4 (01), or 64 (10) of the selected clock source. The ADCDIVx
bits (bits 7-5) in the ADCCTL1 register allow for an additional divide factor of 1 (000) to 8
(111).
ADC interrupts. Monitoring the ADC system is a series of six interrupts to flag differ-
ent events during ADC operation. These monitoring interrupts are normally off and must be
individually enabled as shown in Figure 9.8. Also, as with all interrupts, the GIE bit in the SR
must also be enabled. If a specific interrupt is enabled for a given application, a corresponding
interrupt service routine (ISR) must be provided.
The six ADC interrupts are [SLAU445G, 2016]:
• ADC memory interrupt flag (ADCIFGO)
• ADCMEM0 overflow (ADCOVIFG)
• Conversion time overflow (ADCTOVIFG)
• ADCLO interrupt flag (ADCLOIFG)
370 9. ANALOG PERIPHERALS
A CH IFGG
A CIN IFG
A CO VIF
A CL IFG
IF G
0
C IF
G
D O
D V
D O
D I
A CT
D
D
A
ADC Interrupt Flag
(ADCIFG) register
0
ADCIFGO
1
0
ADCHIIFG
1
D I
D V
A IN
D I
C
A TO
C
C
C
D
A
As shown in Figure 9.8, a specific interrupt must be enabled by asserting its corresponding
bit in the ADC interrupt enable register (ADCIE). When an enabled interrupt event occurs, the
corresponding flag bit is set in the ADC interrupt flag (ADCIFG) register. The numerical value
of the highest priority active interrupt may be read from the ADC interrupt vector (ADCIV)
register.
9.3. MSP430 ADC SYSTEMS 371
All ADC interrupt sources are provided to the ADC interrupt vector (ADCIV) register.
When an ADC interrupt(s) occurs, the interrupt source are sent to the ADCIV register where
it is prioritized.
Results register. The result(s) of sampled and converted signal(s) is stored in the ADC
conversion memory (ADCMEM0) register. Prior to storage in the result register, the result is
formatted to a user specified configuration. Also, if the comparator features are asserted, appro-
priate interrupts are set.
15 14 13 12 11 10 9 8
Reserved ADCSHTx
r0 r0 r0 r0 rw-(0) rw-(0) rw-(0) rw-(1)
7 6 5 4 3 2 1 0
ADCMSC Reserved ADCON Reserved ADCENC ADCSC
rw-(0) r0 r0 rw-(0) r0 r0 rw-(0) rw-(0)
(a) ADC Control 0 register (ADCCTL0)
ADCCTL0[4]: ADC on: ADCON: 0 = ADC off, 1 = ADC on
ADCCTL0[1]: ADC enable conversion: ADCENC: 0 = disabled, 1 = enabled
ADCCTL0[0]: ADC start conversion: ADCSC: 0 = no conversion, 1 = start conversion
15 14 13 12 11 10 9 8
Reserved ADCSHSx ADCSHP ADCISSH
r0 r0 r0 r0 rw-(0) rw-(0) rw-(0) rw-(0)
7 6 5 4 3 2 1 0
ADCDIVx ADCSSELx ADCCONSEQx ADCBUSY
rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) r-(0)
(b) ADC Control 1 register (ADCCTL1)
ADCCTL1[7-5]: ADC clock divider: ADCDIVx: 000 = 1 to 111 = 8
ADCCTL1[4-3]: ADC clock source select: ADCSSELx: MODCLK (00), ACLK (01), MCLK (10), SMCLK (11)
ADCCTL1[2-1]: ADC conversion sequence: ADCCONSEQx:
single channel, single conversion (00): sequence of channels, single conversion (01),
single channel, repeat conversion (10): sequence of channels, repeat conversion (11)
ADCCTL1[0]: ADC busy: 0 = inactive, 1 = active
15 14 13 12 11 10 9 8
Reserved ADCPDIVx
r0 r0 r0 r0 r0 r0 rw-(0) rw-(0)
7 6 5 4 3 2 1 0
Reserved ADCRES ADCDF ADCSR Reserved
r0 r0 rw-(0) rw-(1) rw-(0) rw-(0) r0 rw-(0)
(c) ADC Control 2 register (ADCCTL2)
ADCCTL2[9-8]: ADC predivider: ADCPDIVx: 00 = 1, 01 = 4, 10 = 64
ADCCTL2[5-4]: ADC resolution: ADCRES: 00 = 8 bit, 01 = 10 bit, 10 = 12 bit
ADCCTL2[3]: ADC read back format: ADCDF: 0: unsigned binary, 1= 2's complement signed binary
ADCCTL2[2]: ADC sampling rate: ADCSR: 0 = 200 ksps, 1 = 50 ksps
15 14 13 12 11 10 9 8
Reserved Reserved
r0 r0 r0 r0 r0 r0 r0 rw-(0)
7 6 5 4 3 2 1 0
Reserved ADCSREFx ADCINCHx
r0 rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0)
(d) ADC Conversion Memory Control Register (ADCMCTL0)
ADCSREFx [6-4]: Voltage reference select
ADCINCHx [3-0]: Input channel select 0000 = A0 through 1111 = A15
Figure 9.9: MSP430FR2433 ADC control registers [SLAU445G, 2016]. (Illustration used with
permission of Texas Instruments (www.ti.com).)
9.3. MSP430 ADC SYSTEMS 373
– INTERNAL1V5: sets ADC high reference level to internal 1.5 VDC reference.
– INTERNAL2V5: sets ADC high reference level to internal 2.5 VDC reference.
– EXTERNAL: sets ADC high reference level to the VREF pin value.
• map: As its name implies the map function maps a range of integers (fromLow, fromHigh)
to a new range of integers (toLow, toHigh).
• analogWrite: The analogWrite function generates a pseudo analog output signal using a
pulse width modulated signal. The analogWrite function generates a 490 Hz signal on the
specified pin with a duty cycle specified from 0–255.
1. ADC pins are multiplexed with other I/O functions. Configure (set to logic one) the
proper field of the MSP430FR2433 System Configuration Register 2 (SYSCFG2) for
ADC access.
2. Select the desired ADC reference voltage via ADCSREFx bits in the ADCMCTLx reg-
ister.
6. Configure the converter for proper operation: single channel, single conversion; single
channel, multiple conversion; multiple channels, single conversion; or multiple channels,
multiple conversions using ADCCONSEQx bits in ADCTL1.
9. Use the results of the conversion located in the corresponding result register
(ADC12MEM0).
Example: In this example, we show how to configure the analog-to-digital converter for a single-
channel, single-conversion mode. A single sample is made on input A1 with default reference to
AVcc. In the mainloop, the MSP430 waits in LPM0 to save power until the ADC conversion is
374 9. ANALOG PERIPHERALS
complete. The ADC_ISR will force exit from low power mode LPM0. If A1 > 0.5*AVcc, P1.0
set, else P1.0 is reset.
Note how the #if, #elif, #else, and #endif directives are used to implement conditional
compilation. This allows the same interrupt service routine to be used by the TI, IAR, or the
GNU compiler.
//*******************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2014, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//*******************************************************************
//MSP430FR24xx Demo - ADC, Sample A1, AVcc Ref, Set LED
// if A1 > 0.5*AVcc
//
//Description: This example works on Single-Channel Single-Conversion
//Mode. A single sample is made on A1 with default reference to AVcc.
//Software sets ADCSC to start sample and conversion. ADCSC
//automatically cleared at EOC. ADC internal oscillator times sample
//(16x) and conversion.
//In mainloop MSP430 waits in LPM0 to save power until the ADC
//conversion complete, ADC_ISR will force exit from LPM0 in mainloop
//on reti. If A1 > 0.5*AVcc, P1.0 set, else reset.
//
//ACLK = default REFO ~32768Hz, MCLK = SMCLK = default DCODIV ~1MHz.
//
// MSP430FR2433
// -----------------
// /|\| |
// | | |
// --|RST |
// | |
// >---|P1.1/A1 P1.0|--> LED
//
//
//Wei Zhao, Texas Instruments Inc., Jan 2014
//Built with IAR Embedded WB v6.20 & Code Composer Studio v6.0.1
//*******************************************************************
9.3. MSP430 ADC SYSTEMS 375
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop WDT
//Configure GPIO
P1DIR |= BIT0; //Set P1.0/LED to output
P1OUT &= ~BIT0; //P1.0 LED off
//*******************************************************************
• ADC12_B is a SAR type converter. A SAR converter takes the same amount of time for
converting an unknown voltage regardless of its magnitude. We discuss the operation of a
SAR type converter in the next section.
• The maximum conversion rate of ADC12_B is 200 kilo samples per second (ksps).
• ADC12_B is equipped with 32 individual input channels. The inputs may be configured
for single-ended conversion where the input signal is referenced to ground. The inputs
may also be configured for differential input. In this type of conversion, two signals are
subtracted from one another and their difference is converted. This is especially useful in
noisy environments. Signals that are common to both inputs (noise) are canceled and the
actual signal is amplified.
• Specific internal signals within the MSP432 processor may be selected for ADC conver-
sion.
• The ADC12_B may be set to provide conversion on a single channel, multiple conversions
of a single channel, a single conversion of a sequence of channels, or multiple conversions
of a sequence of channels.
Figure 9.10: ADC12_B block diagram. (Illustration used with permission of Texas Instruments
(www.ti.com).)
As seen in the figure, an input analog channel is selected for conversion by the input volt-
age select multiplexer by the ADC12INCHx bits. The selected signal is held constant by the
sample and hold (S/H) circuitry during the conversion process. The stable signal is then fed to
the SA converter. The SA converter receives input from the reference voltage select, the tim-
ing source, and trigger source for conversion. The specific reference voltage is selected by the
ADC12VRSEL bits. The specific timing source (MODCLK, SYSCLK, ACLK, MCLK, SM-
CLK, or HSMCLK) is selected by the ADC12SSELx bits. The selected clock source may be
9.4. MSP430FR5994 ANALOG-TO-DIGITAL CONVERTER 379
further divided by the ADC12PDIV and the ADC12DIVx bit settings. The overall result is the
ADC12CLK signal. The trigger source to initiate the analog-to-digital conversion is the SAM-
PCON signal. The specific trigger source is selected by the ADC12SHSx bits. The digital result
of the conversion provided as n bits is stored in the ADC12MEM0 result registers. Specific in-
terrupts may be selected to signal different significant events in the ADC process [SLAU367O,
2017].
MSP430FR5994 ADC Interrupts. Monitoring the ADC12_B system is a series of mul-
tiple interrupts to flag different events during ADC operation. These monitoring interrupts are
normally off and must be individually enabled, as shown in Figure 9.11. Also, as with all inter-
rupts, the GIE bit in the SR must also be enabled. If a specific interrupt is enabled for a given
application, a corresponding interrupt service routine (ISR) must be provided.
The ADC interrupts include [SLAU367O, 2017]:
As shown in Figure 9.11, a specific interrupt must be enabled by asserting its corre-
sponding bit in the ADC interrupt enable registers (ADC12IE0 to ADC12IE2). When an
enabled interrupt event occurs, the corresponding flag bit is set in the ADC12_B interrupt flag
(ADC12IFG1 to ADC12IFG3) registers. The numerical value of the highest priority active
interrupt may be read from the ADC12_B interrupt vector (ADC12IV) register.
All ADC interrupt sources are provided to the ADC interrupt vector (ADC12IV) regis-
ter. When an ADC interrupt(s) occurs, the interrupt sources are sent to the ADC12IV register
where they are prioritized.
Results register. The result(s) of sampled and converted signal(s) are stored in the ADC
conversion memory (ADCMEMx) registers. Prior to storage in the result registers, the result is
formatted to user specified configuration. Also, if the comparator features are asserted, appro-
priate interrupts are set.
A C1 VI IFG
A C12 II G
C N G
A C1 OI G
IF G
D 2H F
D 2I F
x
D L F
A C12 OV
12 I F
G
D O
D 2T
ADC12_B Interrupt Flags
A C1
(ADCIFGR1-3) register
D
A
0
ADC12IFGx
0
ADC12OVIFG
1
0
ADC12TOVIFG
1
Interrupt Source
0
ADC12LOIFG
1
0
ADC12INIFG
1
0
ADC12HIIFG
1
C O
D N
C H
12
(ADC12IER0 - 2) registers
D O
D L
A 1 2T
C
C
D
A
Figure 9.12: MSP430FR5994 ADC control registers [SLAU367O, 2017]. (Illustration used
with permission of Texas Instruments (www.ti.com).)
9.4. MSP430FR5994 ANALOG-TO-DIGITAL CONVERTER 383
• analogReference(): The analogReference function provides for changing the high-level
reference voltage for the ADC. The different settings include the following.
• map: As its name implies the map function maps a range of integers (fromLow, fromHigh)
to a new range of integers (toLow, toHigh).
• analogWrite: The analogWrite function generates a pseudo analog output signal using a
pulse width modulated signal. The analogWrite function generates a 490 Hz signal on the
specified pin with a duty cycle specified from 0–255.
1. Select the desired ADC reference voltage via ADC12SREFx bits in the ADC12MCTLx
register.
5. Configure the converter for proper operation: single channel, single conversion; single
channel, multiple conversion; multiple channels, single conversion; or multiple channels,
multiple conversions using ADC12CONSEQx bits in ADC12CTL1.
8. Use the results of the conversion located in the corresponding result register
(ADC12MEMx).
Example: In this example a single sample is made on analog input A1 with reference to AVcc. In
the mainloop, the MSP430FR5994 waits in LPM0 to save power until the ADC12 conversion
is complete. The ADC12 interrupt service routine will force exit from LPM0 in the mainloop
384 9. ANALOG PERIPHERALS
on the return from the interrupt. If the sampled value of A1 is greater than 0.5*AVcc, P1.0 is
set, else it is reset. The full, correct handling of the ADC12 interrupt is shown.
Note how the #if, #elif, #else, and #endif directives are used to implement conditional
compilation. This allows the same interrupt service routine to be used by the TI, IAR, or the
GNU compiler.
//******************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//******************************************************************
//MSP430FR5x9x Demo - ADC12, Sample A1, AVcc Ref,
//Set P1.0 if A1 > 0.5*AVcc
//
//Description: A single sample is made on A1 with reference to AVcc.
//Software sets ADC12SC to start sample and conversion - ADC12SC
//automatically cleared at EOC. ADC12 internal oscillator times
//sample (16x) and conversion. In mainloop MSP430 waits in LPM0 to
//save power until ADC12 conversion complete, ADC12_ISR will force
//exit from LPM0 in mainloop on reti. If A1 > 0.5*AVcc, P1.0 set,
//else reset. The full, correct handling of and ADC12 interrupt is
//shown as well.
//
// MSP430FR5994
// -----------------
// /|\| XIN|-
// | | |
// --|RST XOUT|-
// | |
// >---|P1.1/A1 P1.0|-->LED
//
//William Goh, Texas Instruments Inc., October 2015
//Built with IAR Embedded Workbench V6.30 & Code Composer
//Studio V6.1
//******************************************************************
#include <msp430.h>
9.4. MSP430FR5994 ANALOG-TO-DIGITAL CONVERTER 385
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop WDT
//GPIO Setup
P1OUT &= ~BIT0; //Clear LED to start
P1DIR |= BIT0; //Set P1.0/LED to output
P1SEL1 |= BIT1; //Configure P1.1 for ADC
P1SEL0 |= BIT1;
//Configure ADC12
ADC12CTL0 = ADC12SHT0_2 | ADC12ON; //Sample time,S&H=16, ADC12 on
ADC12CTL1 = ADC12SHP; //Use sampling timer
ADC12CTL2 |= ADC12RES_2; //12-bit conversion results
ADC12MCTL0 |= ADC12INCH_1; //A1 ADC input select; Vref=AVCC
ADC12IER0 |= ADC12IE0; //Enable ADC conv complete
//interrupt
while(1)
{
__delay_cycles(5000);
ADC12CTL0 |= ADC12ENC | ADC12SC; //Start sampling/conversion
__bis_SR_register(LPM0_bits | GIE); //LPM0, ADC12_ISR will force exit
__no_operation(); //For debugger
}
}
//******************************************************************
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector = ADC12_B_VECTOR
__interrupt void ADC12_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(ADC12_B_VECTOR))) ADC12_ISR (void)
386 9. ANALOG PERIPHERALS
#else
#error Compiler not supported!
#endif
{
switch(__even_in_range(ADC12IV, ADC12IV__ADC12RDYIFG))
{
case ADC12IV__NONE: break; //Vector 0: No interrupt
case ADC12IV__ADC12OVIFG: break; //Vector 2: ADC12MEMx Overflow
case ADC12IV__ADC12TOVIFG: break; //Vector 4: Conv time overflow
case ADC12IV__ADC12HIIFG: break; //Vector 6: ADC12BHI
case ADC12IV__ADC12LOIFG: break; //Vector 8: ADC12BLO
case ADC12IV__ADC12INIFG: break; //Vector 10: ADC12BIN
case ADC12IV__ADC12IFG0: //Vector 12: ADC12MEM0 Interrupt
if(ADC12MEM0 >= 0x7ff) //ADC12MEM0 = A1 > 0.5AVcc?
P1OUT |= BIT0; // P1.0 = 1
else
P1OUT &= ~BIT0; //P1.0 = 0
// Exit from LPM0 and continue executing main
__bic_SR_register_on_exit(LPM0_bits);
break;
//******************************************************************
//******************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//******************************************************************
//MSP430FR5x9x Demo - COMPE output Toggle in LPM4; input channel C1;
//Vcompare is compared against internal 2.0V reference
//
//Description: Use CompE and internal reference to determine if
//input'Vcompare' is high or low. When Vcompare exceeds 2.0V COUT
//goes high and when Vcompare is less than 2.0V then CEOUT goes low.
//
// MSP430FR5994
// ------------------
// /|\| |
// | | |
// --|RST P1.1/C1|<--Vcompare
// | |
// | P1.2/COUT|----> 'high'(Vcompare>2.0V);
// | | 'low'(Vcompare<2.0V)
// | |
//
//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
9.6. ADVANCED ANALOG PERIPHERALS 389
//Configure P1.1 as C1 and P1.2 as COUT
P1SEL0 |= BIT1;
P1SEL0 &= ~(BIT2);
P1SEL1 |= BIT1 | BIT2;
P1DIR |= BIT2;
//Setup Comparator_E
CECTL0 = CEIPEN | CEIPSEL_1; //Enable V+, input ch CE1
CECTL1 = CEPWRMD_1; //normal power mode
CECTL2 = CEREFL_2 | CERS_3 | CERSEL; //VREF is applied to -term
//R-ladder off; bandgap ref
//voltage supplied to ref
//amplifier to get Vcref=2.0V
CECTL3 = BIT1; //Input Buffer Disable @P1.1/CE1
CECTL1 |= CEON; //Turn On Comparator_E
__delay_cycles(75); //delay for the ref to settle
__bis_SR_register(LPM4_bits); //Enter LPM4
__no_operation(); //For debug
}
//*******************************************************************
Advanced
1. Write a program segment using the ADC to (1) operate with the 12 bit resolution, (2) use
internal reference voltages of 2.5 V and 0 V, (3) continuously sample analog signals from
pins A0 and A1, (4) use the unsigned binary format, (5) compare the input analog values,
(6) turn the logic state on Pz.x pin high if the signal on A0 is higher than the one on A1,
otherwise, turn the logic state low, and (7) turn the logic state on Pz.y pin high if the signal
on A1 is higher than the one on A1, otherwise, turn the logic state low.
2. A weather station is equipped with a vane to indicate wind direction. The output voltage
of the weather vane is linearly related to wind direction. The vane provides 0 V for wind
heading North (0 degrees) and 3.3 V for 360ı . Write a program to convert the output of
the weather vane to wind direction in degrees. Display the result on a serial configured
liquid crystal display.
3. The LM34 is a precision Fahrenheit temperature sensor. The LM34 provides a linear out-
put of 10 mV per degree Fahrenheit. Sketch the required circuit for the LM34. Write a
program to convert the output of the LM34 to temperature. Display the result on a serial
configured liquid crystal display.
9.9. CHAPTER PROBLEMS 393
Challenging
1. Present your design and write a program to construct a smart home that locate your posi-
tion in room whose size is 10 ft wide, 10 ft long, and 9 ft high. Assume that you need to use
infrared sensors to do the job. You can use as many sensors as you need but want to mini-
mize the number used. Suppose the infrared sensor output is fed to an ADC of a MSP430
and you have means to communicate among MSP430s. Design the sensor positions and
write a program to locate a person in the room.
2. Extend the weather vane example above to include eight LEDs to indicate the closest wind
direction (e.g., N, NE, E, etc.).
395
CHAPTER 10
Communication Systems
Objectives: After reading this chapter, the reader should be able to:
• describe the differences between serial and parallel communication methods;
• present the features of the MSP430 microcontroller’s eUSCI systems A and B;
• illustrate the operation of the UART mode of the eUSCI;
• program the UART for basic transmission and reception;
• describe the operation of the SPI mode of the eUSCI;
• configure a SPI-based system to extend the features of the MSP430 microcontroller;
• describe the purpose and function of the inter-integrated communication (I2 C) mode of
the eUSCI; and
• program the I2 C communication system for read and write to compatible devices.
Microcontrollers must often exchange data with other microcontrollers or peripheral de-
vices. For such applications, data may be exchanged by using parallel or serial techniques. With
parallel techniques, an entire byte (or a set of n bits) of data is typically sent simultaneously from
a transmitting device to a receiving device or received at the same time from an external device.
While this is efficient from a time point of view, it requires eight separate lines (or n separate
lines) for the data transfer. Parallel connections are typically limited to short lengths.
In serial transmission, data is sent or received a single bit at a time. For a byte-size data
transmission, once eight bits have been received at the receiver, the data byte is reconstructed.
While this is inefficient from a time point of view, it only requires a line (or two) to trans-
mit and receive the data. Serial transmission techniques also help minimize the use of precious
microcontroller I/O pins.
10.1 BACKGROUND
The MSP430 microcontroller is equipped with the eUSCI, with subsystems shown in Fig-
ure 10.1. The eUSCI consists of two different communication subsystems: eUSCI_A type mod-
ules and eUSCI_B modules. Each microcontroller in the MSP430 line has a complement of A
and B type eUSCI modules. Should a specific MSP430 microcontroller type have more than
396 10. COMMUNICATION SYSTEMS
eUSCI_A0 eUSCI_B0
eUSCI_A1 eUSCI_B0
one of the A and/or B type modules, they are numbered sequentially starting with zero (e.g., eU-
SCI_A0, A1, etc.) [SLAU445G, 2016, SLAU367O, 2017]. The MSP430FR2433 is equipped
with two eUSCI_A channels (A0, A1) and one eUSCI_B channel (B0). The MSP430FR5994
is equipped with four eUSCI_A channels (A0 to A3) and four eUSCI_B channels (B0 to B3).
As can be seen in Figure 10.1, eUSCI_A modules provide support for [SLAU445G, 2016,
SLAU367O, 2017] the following.
• Universal asynchronous serial receiver and transmitter (UART). The UART provides 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 optical protocol for IR linked devices. It is
used in various communication devices, personal area networks, and instrumentation.
• The serial peripheral interface (SPI). The SPI provides synchronous communications be-
tween a receiver and a transmitter. The SPI system maintains synchronization between
the transmitter and receiver pair using a common clock provided by the master designated
microcontroller. An SPI serial link has a much faster data rate than UART.
10.2. SERIAL COMMUNICATION CONCEPTS 397
2
• The I C bus is a two-wire bus with a serial data line (SDL) and the serial clock line (SCL).
I2 C compatible devices, each with a unique address, are connected to the two-wire bus
as either a master device or a slave device. The MSP430 eUSCI device allows its I2 C
communication unit to operate either in the standard mode (100 kbps) or in the fast mode
(400 kbps) with either a 7- or 10-bit device addressing [SLAU445G, 2016, SLAU367O,
2017].
The eUSCI_B modules also provide support for SPI communications and inter-integrated
communication (I2 C) communications. The I2 C bus is a two-wire bus with a serial data line
(SDL) and the serial clock line (SCL). By configuring devices connected to the common I2 C
bus as either a master device or a slave device, multiple devices can share information. 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 [SLAU445G, 2016, SLAU367O,
2017].
Space does not permit an in-depth discussion of all communication features of the eUSCI
system. We concentrate on the basic operation of the UART, SPI and I2 C systems. For each
system, we provide a technical overview, a review of system registers, and code examples. We
begin with a review of serial communication concepts.
Figure 10.2: ASCII code. The ASCII code is used to encode alphanumeric characters. The “0x”
indicates the hexadecimal notation in the C programming language.
UCABEN
UCSSELx
Receive Baudrate Generator
UC0BRx
UCAxCLK 00 16
ACLK 01 Receive Clock
Prescaler/Divider
SMCLK 10 BRCLK
SMCLK 11 Modulator
Transmit Clock
4 3
UCBRFx UCBRSx UCOS16
1
UCAxTXD
IrDA Encoder
Transmit Buffer UCAxTXBUF
6
UCIRTXPLx
Transmit State Machine Set UCTXIFG
UCTXBRK
UCTXADDR
UCMODEx UCSPB
Figure 10.3: Block diagram of the eUCSI_Ax module configured for UART mode (UCSYNC
bit D 0) [SLAU445G, 2016, SLAU367O, 2017]. (Illustration used with permission of Texas
Instruments (www.ti.com).)
402 10. COMMUNICATION SYSTEMS
in the eUSCI_Ax Control Register 1 (UCAxCTL1). The source selected becomes the Baud-
Rate clock (BRCLK). The Baud-Rate clock may then be prescaled and divided to set the Baud
rate for the transmit and receive clock.
The receive portion of the UART system is in the upper part of Figure 10.3. Serial data is
received via the UCAxRXD pin. The serial data is routed into the Receive Shift Register when
the UCLISTEN bit located within the eUSCI_Ax Status Register (UCAxSTAT) is set to zero.
If required by the specific application, the data may first be routed through the IrDA Decoder.
The configuration of the Receive Shift Register is set by several bits located within the
eUSCU_Ax Control Register 0 (UCAxCTL0). These include the:
• MSB first select, UCMSB (0: LSB first, 1: MSB first), and
The Receive State Machine controls the operation of the receive associated hardware. It
has control bits to:
• select the number of stop bits, UCSPB (0: one stop bit, 1: two stop bits),
• select the synchronous mode, UCSYNC (0: asynchronous mode, 1: synchronous mode).
The hardware associated with serial data transmission is very similar to the receive hard-
ware with the direction of data routed for transmission out of the UCAxTXD pin.
Mark
Start Data Bits Addr Parity
Stop Bit(s)
Bits (7 or 8) Bit Bit
Space
Figure 10.4: UART serial data format [SLAU445G, 2016, SLAU367O, 2017].
• Low-frequency Baud rate generation (UCOS16, Oversampling Mode Enable bit D 0).
The mode allows Baud rates to be set when the microcontroller is being clocked by a low-
frequency clock. A common choice is a 32,768 Hz crystal source. It is advantageous to do
this to reduce power consumption by using a lower frequency time base. In this mode, the
Baud-rate generator uses a prescaler and a modulator to generate the desired Baud rate.
The maximum selectable Baud rate in this mode is limited to one-third of the Baud rate
clock (BRCLK).
• Oversampling Baud rate generation (UCOS16 D 1). This mode employs a prescaler and
a modulator to generate higher sampling frequencies.
• The clock prescaler setting (UCBRx) in the Baud Rate Control Register 0 and 1
(UCAxBR0 and UCAxBR1) must be determined. The 16-bit value of the UCBRx
prescaler value is determined by UCAxBR0 C UCAxBR1 256.
• First modulation stage setting, UCBRFx bits in the eUSCI_Ax Modulation Control Reg-
ister (UCAxMCTL).
• Second modulation stage setting, UCBRSx bits in the eUSCI_Ax Modulation Control
Register (UCAxMCTL).
The documentation for the MSP430 microcontroller contains extensive tables for deter-
mining the UCBRx, UCBRFx, and UCBRSx bit settings for various combinations of the Baud
rate clock (BRCLK) and desired Baud rate [SLAU445G, 2016, SLAU367O, 2017].
Figure 10.5: eUSCI_Ax control word 0 [SLAU445G, 2016, SLAU367O, 2017]. (Illustration
used with permission of Texas Instruments (www.ti.com).)
10.4.1 ENERGIA
The Energia Integrated Development Environment has many built-in functions to support
UART operations (energia.nu). In the next several examples, we use:
• Serial.begin(baud_rate): sets the Baud rate for data transmission,
• Serial.print: prints data to the serial port as ASCII text, and
• Serial.println: prints data to the serial port as ASCII text followed by a carriage return.
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
using the onboard universal asynchronous receiver transmitter (UART). The UART is config-
ured for 8 bits, no parity, and one stop bit (8-N-1). The MSP-EXP430FR2433 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, P1.5) and pin 4 (TX, P1.4). Provided below is the sample
Energia code to print a test message to the LCD. Note the UART LCD channel 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:
406 10. COMMUNICATION SYSTEMS
// - RX: P1.5, pin 3
// - TX: P1.4, pin 4
//*******************************************************************
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);
}
//*******************************************************************
Example: Voice chip. For speech synthesis, we use the SP0-512 text to speech chip (www.sp
eechchips.com). The SP0-512 accepts UART compatible serial text stream. The text stream
should be terminated with the carriage return control sequence (backslash r). The text stream is
converted to phoneme codes used to generate an audio output. The chip requires a 9600 Baud bit
stream with no parity, 8 data bits and a stop bit. The associated circuit is provided in Figure 10.6.
Additional information on the chip and its features are available at www.speechchips.com.
//*******************************************************************
//SP0512
//Serial 1 accessible at:
// - RX: P1.5, pin 3
// - TX: P1.4, pin 4
//*******************************************************************
void setup()
{
//Initialize serial channel 1 to 9600 BAUD and wait for port to open
Serial1.begin(9600);
}
10.4. CODE EXAMPLES 407
10 K
SP0512
1- /TICLR AVDD- 28
2- N2 AVSS- 27
3- N3 DAC+- 26 10 uF 5 VDC
4- TX DAC- - 25
5- N5 N24- 24 3
6- RX N23- 23 + 6
TX:(9600 N81) 7- N7 N22- 22 10 K 100 u F
LM386N- 3
8- VSS1 N21- 21 2 - 5
9- N9 VCAP- 20 7 10 K
VSS2- 19 4.7 uF 4
Vcc = 3.3 VDC 10- N10 N18- 18
10 uF
11- N11 0.1 uF
12- N12 SPEAKING- 17 8 Ohm
13- VDD N16- 16 Speaker
14- N14 N15- 15
3. 3 VDC
LED
330
Speaking
+
MPS2222
10 K
UART TX,
P1. 4
Figure 10.6: Speech synthesis support circuit (www.speechchips.com). (Illustration used with
permission of Texas Instruments (www.ti.com).)
408 10. COMMUNICATION SYSTEMS
void loop()
{
Serial1.print("[BD]This [BD]is [BD]a [BD]test \r");
delay(3000);
}
//*******************************************************************
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop watchdog timer
PM5CTL0 &= ~LOCKLPM5; //Disable the GPIO power-on
//default high-impedance mode
//to activate previously
//configured port settings
P1DIR |= BIT0;
P1OUT &= ~BIT0; //P1.0 out low
//Configure UART pins
P1SEL0 |= BIT4 | BIT5; //set 2-UART pin as second
//function
//Configure UART
UCA0CTLW0 |= UCSWRST; //Put eUSCI in reset
UCA0CTLW0 |= UCSSEL__SMCLK;
//Baud Rate calculation
UCA0BR0 = 8; //1000000/115200 = 8.68
UCA0MCTLW = 0xD600; //1000000/115200
//INT(1000000/115200)=0.68
//UCBRSx value = 0xD6 (See UG)
UCA0BR1 = 0;
UCA0CTLW0 &= ~UCSWRST; //Initialize eUSCI
UCA0IE |= UCRXIE; //Enable USCI_A0 RX interrupt
while (1)
{
410 10. COMMUNICATION SYSTEMS
while(!(UCA0IFG & UCTXIFG));
UCA0TXBUF = TXData; //Load data onto buffer
__bis_SR_register(LPM0_bits|GIE); //Enter LPM0
__no_operation(); //For debugger
}
}
//********************************************************************
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=USCI_A0_VECTOR
__interrupt void USCI_A0_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(USCI_A0_VECTOR))) USCI_A0_ISR (void)
#else
#error Compiler not supported!
#endif
{
switch(__even_in_range(UCA0IV,USCI_UART_UCTXCPTIFG))
{
case USCI_NONE: break;
case USCI_UART_UCRXIFG:
UCA0IFG &=~ UCRXIFG; //Clear interrupt
RXData = UCA0RXBUF; //Clear buffer
if(RXData != TXData) //Check value
{
P1OUT |= BIT0; //If incorrect turn on P1.0
while(1); //trap CPU
}
TXData++; //increment data byte
__bic_SR_register_on_exit(LPM0_bits); // Exit LPM0 on reti
break;
case USCI_UART_UCTXIFG: break;
case USCI_UART_UCSTTIFG: break;
case USCI_UART_UCTXCPTIFG: break;
}
}
//********************************************************************
10.5. SERIAL PERIPHERAL INTERFACE-SPI 411
10.5 SERIAL PERIPHERAL INTERFACE-SPI
The SPI is also used for two-way serial communication between a transmitter and a receiver. In
the SPI system, the transmitter and receiver pair shares a common clock source (UCxCLK). This
requires an additional clock line between the transmitter and the receiver but allows for higher
data transmission rates as compared to the UART. The SPI system allows for fast and efficient
data exchange between microcontrollers or peripheral devices. There are many SPI compatible
external systems available to extend the features of the microcontroller. For example, a liquid
crystal display or a multi-channel DAC could be added to the microcontroller using the SPI
system.
MSP430 USCI
Master Device
UCxSOMI Slave Device
Transmit Buffer (UCxTXBUF)
SPI Data Register (SDR)
MSB Transmit Shift Register LSB MSB LSB
UCxSIMO MOSI
• independent transmit and receive shift registers which provide continuous transmit and
receive operation,
• selectable clock polarity and phase control,
• programmable clock frequency in master mode, and
• independent interrupt capability for receive and transmit.
UCLISTEN UCMST
Receive Buffer UCxRXBUF
UCxSOMI
1
0
Receive Shift Register 0
1
UCMSB UC7BIT
UCSSELx
Bit Clock Generator
UCxBRx UCCKPH UCCKPL
N/A 00
16
ACLK 01 UCxCLK
Clock Direction
Prescaler/Divider Phase and Polarity
SMCLK 10 BRCLK
SMCLK 11
UCMSB UC7BIT
UCxSIMO
Transmit Shift Register
UCMODEx
2
Transmit Buffer UCxTXBUF
Transmit Enable
Control Set UCFE
Transmit State Machine
Set UCxTXIFG
Figure 10.8: SPI hardware overview [SLAU445G, 2016, SLAU367O, 2017]. (Illustration used
with permission of Texas Instruments (www.ti.com).)
414 10. COMMUNICATION SYSTEMS
The Baud rate clock is fed to the Bit Clock Generator. The 16-bit clock prescaler is formed
using (UCxxBR0 C UCxxBR1 256). The values for UCxxBR0 and UCxxBR1 are contained
in the eUSCI_xx Bit Rate Control Registers 0 and 1 (UCxxBR0 and UCxxBR1).
The MSP430 eUSCI provides the flexibility to configure the SPI data transmission format
to match that of many different peripheral devices. Either a 7- or 8-bit data format may be
selected using the UC7BIT. Also, the phase and polarity of the data stream may be adjusted to
match peripheral devices. The polarity setting determines active high or low transmission while
the polarity bit determines if the signal is asserted in the first half of the bit frame or in the
second half. Furthermore, the data may be transmitted with the LSB first or the MSB first. In
summary, the serial data stream format is configured using the following bits in the eUSCI_Ax
(or Bx) control register 0 (UCAxCTL0) [SLAU445G, 2016, SLAU367O, 2017]:
• UCCKPH: clock phase select bit - 0: data changed on the first UCLK edge and captured
on the following edge; 1: data captured on the first edge and changed on the second edge
• UCCKPL: clock polarity select bit - 0: inactive state low; 1: inactive state high
• UCMSB: MSB first select bit - 0: LSB transmitted first; 1: MSB transmitted first
• UC7BIT: character length select bit - 0: 8-bit data; 1: 7-bit data
The clock signal is routed from the Bit Clock Generator to both the receive state ma-
chine and the transmit state machine. To transmit data, the data is loaded to the transmit buffer
(UCxTXBUF). Writing to the UCxTXBUF activates the Bit Clock Generator. The data begins
to transmit. Also, the SPI-system receives data when the transmission is active. The transmit
and receive operations occur simultaneously [SLAU445G, 2016, SLAU367O, 2017].
The SPI system is also equipped with interrupts. The UXTXIFG interrupt flag in the
eUSCI_Ax (or Bx) interrupt flag register (UCAxIFG, UCBxIFG) is set when the UCxxTXBUF
is empty indicating another character may be transmitted. The UCRXIFG interrupt flag is set
when a complete character has been received.
Details of specific register and bits settings are contained in SLAU367O and SLAU445G.
Figure 10.9 provides the bit settings of eUSCI_Ax Control Word 0 for basic SPI operation using
eUSCI_Ax.
416 10. COMMUNICATION SYSTEMS
15 14 13 12 11 10 9 8
UCCKPH UCCKPL UCMSB UC7BIT UCMST UCMODEx UCSYNC
rw-0 rw-0 rw-0 rw-0 rw-0 rw-0 rw-0 rw-0
7 6 5 4 3 2 1 0
UCSSELx Reserved UCSTEM UCSWRST
rw-0 rw-0 rw-0 rw-0 rw-0 rw-0 rw-0 rw-1
Can be modified only when UCSWRST = 1
UCAxCTLW0 Register
UCAxCTLW0[15]: Clock phase select: UCCKPH: 0 = data changed on first edge, captured on second
1 = data is captured on first edge, changed on second
UCAxCTLW0[14]: Clock polarity select: UCCKPL: 0 = inactive state is low, 1 = inactive state high
UCAxCTLW0[13]: MSB first select: UCMSB: 0 = LSB first, 1 = MSB first
UCAxCTLW0[12]: Character length: UC7BIT: 0 = 8-bit, 1 = 7-bit
UCAxCTLW0[11]: Master mode select: UCMST: 0 = slave mode, 1 = master mode
UCAxCTLW0[10-9]: eUSCI_A mode: UCMODEx: 00 = 3-pin SPI, 01 = 4-pin SPI with UCxSTE active high,
10 = 4-pin SPI with UCxSTE active low
UCAxCTLW0[8]: Synchronous mode enable: UCSYNC: 0 = Asynchronous, 1 = Synchronous
UCAxCTLW0[7-6]: eUSCI_A clock source select: UCSSELx: 00 = UCLK, 01 = ACLK, 10 or 11 = SMCLK
Figure 10.9: eUSCI_Ax control word 0 [SLAU445G, 2016, SLAU367O, 2017]. (Illustration
used with permission of Texas Instruments (www.ti.com).)
Example. In Chapter 12.9 we used the Energia SPI features to control a one meter, 32 RGB
LED strip available from Adafruit (#306) (www.adafruit.com). Recall the red, blue, and green
component of each RGB LED was independently set using an eight-bit code. The MSB was
logic one followed by seven bits to set the LED intensity (0–127). The component values were
sequentially shifted out of the MSP430FR2433 LaunchPad using the serial peripheral interface
(SPI) features.
Example. In this example we interface the MSP430FR2433 to Sparkfun’s SerLCD display
(LCD-14072). The display may be used with UART, SPI, or an I2 C interface. The connections
between the microcontroller and display are shown in Figure 10.10. The sample code example
illustrates how to display numerals and characters to the display.
//***********************************************************************
//LCD_SPI: Demonstrates use of the MSP430FR2433's SPI system
//with the Sparkfun 16x2 SerLCD (LCD-14072).
//
//LCD connections:
// - RAW: 3.3 VDC
// - -: Ground
// - Power supply grounds should be connected to common ground
// - Serial Data Out - LaunchPad pin 15 (MOSI pin), P2.6 - to LCD SDI
// - CLK - LaunchPad pin 7 (SCK pin), P2.4 - to LCD SCK
// - Chip Select - LaunchPad pin 18, P2.2 - to LCD /CS
// - Ground - black
//
//
//Notes:
// - SPI must be configured for least significant bit (LSB) first,
// Mode 0, SPI clock divide 128
//
//This example code is in the public domain.
418 10. COMMUNICATION SYSTEMS
G DC
d
un
ro
V
MOSI P2.6 (pin 15)
3
3.
Clock P2.4 (pin 7)
Sparkfun LCD-14072
16 × 2 SerLCD
#include <SPI.h>
void setup()
{
pinMode(chip_select, OUTPUT);
SPI.begin(); //SPI support functions
SPI.setBitOrder(MSBFIRST); //SPI bit order - MSB first
SPI.setDataMode(SPI_MODE0); //SPI mode
SPI.setClockDivider(SPI_CLOCK_DIV128);//SPI data clock rate
}
void loop()
{
digitalWrite(chip_select, HIGH); //chip select high
} //end void
//****************************************************************
Example. In this example the MSP430 SPI system is used to send numerical data to Spark-
fun’s 6.5” 7-segment displays (COM-08530). Two of the large digit displays are serially linked
together via Sparkfun’s Large Digit Driver (WIG-13279). The Large Digit Driver contains a
Texas Instruments TPIC6C696 Power Logic 8-bit Shift Register [TPIC6C596, 2015]. The
Large Digit Drivers are soldered to the back of the 6.5” 7-segment displays. The hardware con-
figuration is shown in Figure 10.11.
Numerical data is shifted out of the MSP430FR2433 to the TPIC6C696 shift register
within the Large Digit Driver (WIG-13279). In the first code example, LED_big_digit1, a
single display is sent an incrementing value from 0–9. The numerals are coded to match the
requirements of the Large Digit Driver.
In the second code example, LED_big_digit2, two displays are sent an incrementing value
from 00–99.
//***********************************************************************
//LED_big_digit1: Demonstrates use of the MSP430FR2433's SPI system
//to illuminate different numbers on Sparkfun's 6.5" 7-segment display
//(COM-08530). Numerals are sent from the MSP430 to Sparkfun's Large
//Digit Driver (WIG-13279).
//
//WIG-13279 pin connections:
// - External 12 VDC supply - red
// - External 5 VDC supply - orange
10.5. SERIAL PERIPHERAL INTERFACE-SPI 421
Sparkfun COM-08530 Sparkfun COM-08530
PRT-10366 PRT-10366
Ground
Latch P2.2 (pin 18)
Clock P2.4 (pin 7)
MOSI P2.6 (pin 15)
12 VDC
#include <SPI.h>
void setup()
{
pinMode(LATCH, OUTPUT);
SPI.begin(); //SPI support functions
SPI.setBitOrder(LSBFIRST); //SPI bit order - LSB first
SPI.setDataMode(SPI_MODE3); //SPI mode
10.5. SERIAL PERIPHERAL INTERFACE-SPI 423
SPI.setClockDivider(SPI_CLOCK_DIV32);//SPI data clock rate
Serial.begin(9600); //serial comm at 9600 bps
}
void loop()
{
digitalWrite(LATCH, LOW); //initialize LATCH signal
SPI.transfer(seven_seg_zero); //reset to zero
assert_latch();
if(troubleshooting)
{
Serial.println(numeral, DEC);
Serial.println(" ");
}
}
}
424 10. COMMUNICATION SYSTEMS
//****************************************************************
void assert_latch()
{
digitalWrite(LATCH, HIGH); //transmit latch pulse
delay(50);
digitalWrite(LATCH, LOW); //initialize LATCH signal
}
//****************************************************************
//***********************************************************************
//LED_big_digit2: Demonstrates use of the MSP430FR2433's SPI system
//to illuminate different numbers on Sparkfun's 6.5" 7-segment display
//(COM-08530). Numerals are sent from the MSP430 to Sparkfun's Large
//Digit Driver (WIG-13279).
//
//WIG-13279 pin connections:
// - External 12 VDC supply - red
// - External 5 VDC supply - orange
// - Power supply grounds should be connected to common ground
// - Serial Data Out - LaunchPad pin 15 (MOSI pin), P2.6 - yellow
// - CLK - LaunchPad pin 7 (SCK pin), P2.4 - green
// - Latch - LaunchPad pin 18, P2.2 - blue
// - Ground - black
//
//
//Notes:
// - SPI must be configured for least significant bit (LSB) first
// - The numerals 0 to 9 require the following data words as required
// by the interface between the Spakfun Large Digit Driver (WIG-13279)
// and the Sparkfun 6.5" 7-segment display (COM-08530).
//
// Numeral Data representation of numeral
// 0 0xDE
// 1 0x06
// 2 0xBA
10.5. SERIAL PERIPHERAL INTERFACE-SPI 425
// 3 0xAE
// 4 0x66
// 5 0xEC
// 6 0xFC
// 7 0x86
// 8 0xFE
// 9 0xE6
//
//This example code is in the public domain.
//********************************************************************
#include <SPI.h>
void setup()
{
pinMode(LATCH, OUTPUT);
SPI.begin(); //SPI support functions
SPI.setBitOrder(LSBFIRST); //SPI bit order - LSB first
SPI.setDataMode(SPI_MODE3); //SPI mode
SPI.setClockDivider(SPI_CLOCK_DIV32);//SPI data clock rate
426 10. COMMUNICATION SYSTEMS
Serial.begin(9600); //serial comm at 9600 bps
}
void loop()
{
digitalWrite(LATCH, LOW); //initialize LATCH signal
SPI.transfer(seven_seg_zero); //reset to zero
assert_latch();
//****************************************************************
void assert_latch()
{
digitalWrite(LATCH, HIGH); //transmit latch pulse
delay(50);
10.5. SERIAL PERIPHERAL INTERFACE-SPI 427
digitalWrite(LATCH, LOW); //initialize LATCH signal
}
//****************************************************************
return segment_data;
//****************************************************************
Example. In this example we interface the MSP430FR2433 LaunchPad to the Sparkfun Real
Time Clock (BOB-10160) and the Sparkfun 16x2 SerLCD (LCD-14072). Both devices are
interfaced to the MSP430FR2433 LaunchPad via the same SPI channel. The SPI channel is
time shared between the RTC and the LCD by using different device select lines as shown in
Figure 10.12. The two different devices use different SPI modes.
The Sparkfun RTC (BOB-10160) breakout board hosts the Maxim Integrated DS3234
RTC [DS3234, 2015]. Once set the RTC tracks date and time. The RTC has two sets of reg-
isters to read and write the time values. The read registers span RTC address space from 0x00
to 0x0D while the write registers span from 0x80 to 0x8D. DS3234 register details are available
428 10. COMMUNICATION SYSTEMS
in the DS3234 data sheet. Date and time information is stored in the DS3234 in BCD format.
The code example demonstrates how to covert from decimal representation to BCD format for
storage within the DS3234. The DS3234 is configured for operation via a control register at
0x8E (Maxim DS3234 [2015]).
In the example the RTC is initialized with the current date and time. This is only accom-
plished once. The RTC continues to monitor time while on battery power. To use the software
to read the RTC at a later time simply comment out the “set_RTC” function.
ro C
d
G VD
LCD chip select P2.2 (pin 18)
un
MOSI P2.6 (pin 15)
3
3.
Clock P2.4 (pin 7)
Ground
3.3 VDC
Sparkfun BOB-10160
Sparkfun LCD-14072
DeadOn Real Time Clock
16 × 2 SerLCD
(hosting Maxim DS3224)
SPI setting: MSBFIRST, Mode 0
SPI setting: MSBFIRST, Mode 1
Figure 10.12: MSP430FR2433 interface to Sparkfun’s real time clock (BOB-10160). (Illustra-
tion used with permission of Sparkfun Electronics (www.sparkfun.com).)
//***********************************************************************
//SPI_RTC_LCD: Demonstrates use of the MSP430FR2433's LaunchPad
//SPI system with Sparkfun's Real Time Clock (BOB-10160) hosting
//Maxim's DS3224 (Extremely Accurate SPI Bus RTC with Integrated
//Crystal and SRAM). RTC time data is displayed on Sparkfun's
//16x2 SerLCD (LCD-14072).
//
//Once the RTC time is initially set, the RTC will maintain
10.5. SERIAL PERIPHERAL INTERFACE-SPI 429
//clock time while on battery power.
//
//RTC SPI settings: MSBFIRST, Mode 1
//RTC connections:
// - VCC: 3.3 VDC
// - GND: Ground
// - Power supply ground should be connected to common ground
// - MOSI: LaunchPad pin 15 (MOSI pin), P2.6
// - MISO: LaunchPad pin 14 (MISO pin), P2.5
// - CLK: LaunchPad pin 7 (SCK pin), P2.4
// - SS: RTC Chip Select - LaunchPad pin 17, P3.2
//
//LCD SPI settings: MSBFIRST, Mode 0
//LCD connections:
// - RAW: 3.3 VDC
// - -: Ground
// - Power supply ground should be connected to common ground
// - SDI: LaunchPad pin 15 (MOSI pin), P2.6
// - SCK: LaunchPad pin 7 (SCK pin), P2.4
// - /SS: LCD Chip Select - LaunchPad pin 18, P2.2
//
//Note: RTC and LCD requires different SPI mode settings.
//
//RTC code adapted from code provided by Jim Lindblom of
//SparkFun Electronics (www.sparkfun.com)
//
//This example code is in the public domain.
//********************************************************************
#include <SPI.h>
unsigned int i;
unsigned char printstring[17] = " DS3234 RTC ";
int TimeDateGroup[7];
String TDG;
430 10. COMMUNICATION SYSTEMS
void setup()
{
pinMode(LCD_chip_select, OUTPUT);
pinMode(RTC_chip_select, OUTPUT);
Serial.begin(9600);
void loop()
{
digitalWrite(LCD_chip_select, HIGH); //LCD chip select de-assert
digitalWrite(RTC_chip_select, HIGH); //RTC chip select de-assert
TDG = ReadTimeDate(); //get current time
Serial.println(TDG); //display time to serial mon
clear_LCD(); //clear LCD, cursor to home
//Display RTC banner on LCD
SPI.setDataMode(SPI_MODE0); //SPI mode
digitalWrite(LCD_chip_select, LOW); //LCD chip select assert
for(i=0; printstring[i] != '\0'; i++)
{
SPI.transfer(printstring[i]); //transmit data via SPI
delay(100); //100 ms delay
} //end for
digitalWrite(LCD_chip_select, HIGH); //chip select high
display_time_LCD();
delay(3000);
} //end void
//****************************************************************
10.5. SERIAL PERIPHERAL INTERFACE-SPI 431
void clear_LCD(void)
{
SPI.begin(); //SPI support functions
SPI.setBitOrder(MSBFIRST); //SPI bit order - MSB first
SPI.setDataMode(SPI_MODE0); //SPI mode
SPI.setClockDivider(SPI_CLOCK_DIV128);//SPI data clock rate
delay(10);
digitalWrite(LCD_chip_select, LOW); //LCD chip select assert
SPI.transfer(0x7C); //enter LCD settings mode
SPI.transfer(0x2D); //clear display, cursor home
digitalWrite(LCD_chip_select, HIGH); //LCD chip select de-assert
}
//****************************************************************
void initialize_RTC(void)
{
SPI.begin(); //SPI support functions
SPI.setBitOrder(MSBFIRST); //SPI bit order - MSB first
SPI.setDataMode(SPI_MODE1); //SPI mode
SPI.setClockDivider(SPI_CLOCK_DIV128);//SPI data clock rate
delay(10);
//****************************************************************
//RTC code adapted from RTC code provided by Jim Lindblom of
//SparkFun Electronics (www.sparkfun.com)
//****************************************************************
void set_RTC(int day, int mon, int yr, int hr, int mn, int sec)
{
//assemble TimeDateGroup
int TimeDateGroup[7] = {sec, mn, hr, 0, day, mon, yr};
432 10. COMMUNICATION SYSTEMS
SPI.begin(); //SPI support functions
SPI.setBitOrder(MSBFIRST); //SPI bit order - MSB first
SPI.setDataMode(SPI_MODE1); //SPI mode
SPI.setClockDivider(SPI_CLOCK_DIV128);//SPI data clock rate
delay(10);
if(i==2)
{
if(b==2)
b=B00000010;
else if (b==1)
b=B00000001;
}
//assemble BCD digits to
//required storage
//configuration
TimeDateGroup[i]= a+(b<<4);
//****************************************************************
//RTC code adapted from RTC code provided by Jim Lindblom of
10.5. SERIAL PERIPHERAL INTERFACE-SPI 433
//SparkFun Electronics (www.sparkfun.com)
//****************************************************************
String ReadTimeDate()
{
String temp;
//****************************************************************
void display_time_LCD(void)
{
if (i !=0)
{
digitalWrite(LCD_chip_select, LOW); //LCD chip select assert
SPI.transfer(0x3A);
436 10. COMMUNICATION SYSTEMS
digitalWrite(LCD_chip_select, HIGH);//LCD chip select high
}
}
}
//****************************************************************
SPI C Example
In this example, code is provided for both the SPI master and the SPI slave configured processor
using the SPI 3-wire mode. Incrementing data is sent by the master configured processor starting
at 0x01. The slave configured processor received data is expected to be same as the previous
transmission TXData D RXData 1. The eUSCI RX interrupt service routine is used to handle
communication with the processor (www.ti.com).
Master configured SPI processor code:
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
//MSP430FR243x Demo - eUSCI_A0, SPI 3-Wire Master Incremented Data
//
//Description: SPI master talks to SPI slave using 3-wire mode.
//Incrementing data is sent by the master starting at 0x01. Received
//data is expected to be same as the previous transmission
//TXData = RXData-1. USCI RX ISR is used to handle communication
//with the CPU, normally in LPM0.
//
// ACLK = ~32.768kHz, MCLK = SMCLK = DCO ~ 1MHz. BRCLK = SMCLK/2.
//
// MSP430FR2433
// -----------------
// /|\| |
// | | |
// --|RST |
// | |
10.5. SERIAL PERIPHERAL INTERFACE-SPI 437
// | P1.4|-> Data In (UCA0SIMO)
// | |
// | P1.5|<- Data OUT (UCA0SOMI)
// | |
// | P1.6|-> Serial Clock Out (UCA0CLK)
//
//
//Ling Zhu, Texas Instruments Inc., Sept 2015
//Built with IAR Embedded Workbench v6.20 & Code Composer Studio v6.0.1
//**********************************************************************
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop watchdog timer
P1SEL0 |= BIT4 | BIT5 | BIT6; //set 3-SPI pin as second func
//***********************************************************************
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=USCI_A0_VECTOR
__interrupt void USCI_A0_ISR(void)
#elif defined(__GNUC__)
break;
//Transmit characters
case USCI_SPI_UCTXIFG: UCA0TXBUF = TXData;
UCA0IE &= ~UCTXIE;
break;
default: break;
}
}
//***********************************************************************
10.5. SERIAL PERIPHERAL INTERFACE-SPI 439
Slave configured SPI processor code:
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//**********************************************************************
//MSP430FR243x Demo - eUSCI_A0, SPI 3-Wire Slave Data Echo
//
//Description: SPI slave talks to SPI master using 3-wire mode.
//Data received from master is echoed back.
//ACLK = 32.768kHz, MCLK = SMCLK = DCO ~ 1MHz
//
//Note: Ensure slave is powered up before master to prevent delays due to
// slave initialization
//
// MSP430FR2433
// -----------------
// /|\| |
// | | |
// --|RST |
// | |
// | P1.4|<- Data In (UCA0SIMO)
// | |
// | P1.5|-> Data OUT (UCA0SOMI)
// | |
// | P1.6|<- Serial Clock In (UCA0CLK)
//
//
//Ling Zhu, Texas Instruments Inc., Nov 2015
//Built with IAR Embedded Workbench v6.20 & Code Composer Studio v6.0.1
//***********************************************************************
#include <msp430.h>
int main(void)
{
440 10. COMMUNICATION SYSTEMS
WDTCTL = WDTPW|WDTHOLD; //Stop watchdog timer
//***********************************************************************
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=USCI_A0_VECTOR
__interrupt void USCI_A0_ISR(void)
#elif defined(__GNUC__)
//***********************************************************************
10.6. INTER-INTEGRATED COMMUNICATION – I2 C MODULE 441
2
10.6 INTER-INTEGRATED COMMUNICATION – I C
MODULE
The MSP430’s USCI can be programmed to operate in the I2 C communication mode. As dis-
cussed earlier in this chapter, the eUSCI_Ax ports are programmed to operate in the UART,
IrDA, and SPI communication mode while the eUSCI_Bx ports are used for the I2 C and SPI
serial communication modes.
The I2 C module is a communication system used when multiple serial devices are inter-
connected using a serial bus. Devices on the bus are designated either as a master or slave device.
One of the reasons the I2 C serial communication became popular is its flexibility to allow mul-
tiple master devices to co-exist on the same bus.
The I2 C bus is a two-wire bus with a SDL and the SCL. I2 C compatible devices, each
with a unique address, are connected to the two-wire bus as either a master device or a slave
device. The master device initiates a communication transaction by means of either requesting
data from another device or sending data to a designated device. The master device must also
provide a clock signal (SCL) to the two-wire bus as shown in Figure 10.13a. Note how each bus
line requires a pull-up resistor. The MSP430 eUSCI device allows its I2 C communication unit
to operate either in the standard mode (100 kbps) or in the fast mode (400 kbps) with either a 7-
or 10-bit device addressing. Addressing capability is provided for up to four hardware designated
slave devices [SLAU445G, 2016, SLAU367O, 2017].
An I2 C communication transaction is initiated by the master device. The master device
pulls the SDA line low while the SCL line is idling high. The falling edge of the SDA line
triggers the transfer. The master then sends a single byte of data containing the desired slave
address. The LSB of the address is set for read (1) or write (0). The address is transmitted MSB
first. A single bit of the data byte is sent on each SCL clock pulse. A stop condition occurs
when the SCL line idles high and at the rising edge of the SDA line. The slave device with
the matching address responds appropriately with either a read or write response as shown in
Figure 10.13b.
10.6.1 I2 C INITIALIZATION
To initialize a eUSCI_Bx port as an I2 C communication port, you must: (1) set the UCSWRST
bit in the UCxCTL1 register to one, (2) configure the I2 C mode of operation by setting UC-
MODEx bits to 11 and initialize the eUSCI registers, and (3) set up an actual port with a
pull-up resistor. As soon as the UCSWRST bit is cleared, the I2 C communication of MSP430
can commence.
10.6.2 I2 C PROTOCOL
The communication performed on the I2 C bus must follow a set of agreed rules, including the
data format used on the bus. Data is transferred between devices connected on the bus in 8
442 10. COMMUNICATION SYSTEMS
Vcc
Pull-up 12C Compatible 12C Compatible
Resistors SCL Device SDA SCL Device SDA
SDA (data)
12C 12C
bus SCL (clock) bus
SCL, P1.3, 9
SDA, P1.2, 10
SDA
MSB Acknowledgment Acknowledgment
Signal from Receiver Signal from Receiver
SCL
1 2 7 8 9 1 2 8 9
START R/W ACK ACK STOP
Condition (S) Condition (P)
Figure 10.13: I2 C system overview. (Illustration used with permission of Texas Instruments
(www.ti.com).)
10.6. INTER-INTEGRATED COMMUNICATION – I2 C MODULE 443
bits per segment, followed by control bits. Each communication “session” is started by a master
device with a start condition, which is defined as the signal changing from logic high to low on
the SDA line while the logic state on the SCL line is high. Following the start condition, the
master device must send either the 7- or 10-bit unique address of a destination device on the
SDA line [SLAU445G, 2016, SLAU367O, 2017].
Following the address, the master device sends a Read/Write bit describing its intent and
listens on the bus to hear an acknowledge bit from the receiver on the 9th SCL clock for the
7-bit addressing mode or on the both 9th and 18th clocks for the 10-bit addressing mode.
For the 10-bit addressing mode, the 10-bit address is split into two segments: two MSBs
and eight LSBs. The MSBs are sent along with pre-designated bits (11110), and the LSBs
are sent separately. After the first part of the address is sent, a Read/Write bit, followed by an
acknowledgment bit, must appear on the bus before the second part of the address is sent. After
the second part of the address, an acknowledgment bit must appear before data is sent over the
bus. Figure 10.14 shows the format of data transfer between two devices, using both the 7-bit
and 10-bit addressing modes. For each communication session, it must end with a stop condition
(P in the figure), which is defined as the signal state on the SDA line changing from logic low
to logic high while the clock signal on the SCL line is high [SLAU445G, 2016, SLAU367O,
2017].
S - Start condition
A - Slave address (7-bit addressing mode)
A1 - MSB slave address - 11110 xx (10-bit addressing mode)
A2 - LSB slave address
R/W - Read or Write
D - Data
Ack - Acknowledgment
P - Stop condition
Figure 10.14: Data format for both 7-bit and 10-bit addressing modes.
444 10. COMMUNICATION SYSTEMS
10.6.3 MSP430 AS A SLAVE DEVICE
The MSP430 microcontroller can also be configured to be either as a slave device or as a master
device. To configure the controller as a slave device, the eUSCI_Bx ports must first be pro-
grammed to operate in the I2 C slave mode (UCMODEx D 11, UCSYNC D 1, UCMST D
0). The slave address of MSP430 is defined using UCBxI2COA register. The UCA10 bit in
the UCBx control register 0 (UCBxCTL0) determines whether the controller is using a 7-bit
address or a 10-bit address [SLAU445G, 2016, SLAU367O, 2017].
You can program the MSP430 microcontroller to respond to a general call by setting the
general call response enable bit (UCGCEN) in the UCBxI2COA register. To receive device
addresses sent by masters, the eUSCI_Bx ports must also be configured in the receiver mode
(UCTR D 0). When the start condition is detected on the bus, the address bits are compared,
and if there is a match, the UCSTTIFG flag is set [SLAU445G, 2016, SLAU367O, 2017].
After testing that the Read/Write bit is high, MSP430 uses the clock signal on the SCL
line to send data on the SDA line. To do so, the UCTR and UCTXIFG bits are set while
holding the SCL line logic low. While the logic state on the SCL line is low, the transmit buffer
register (UCBxTXBUF) is loaded with data. Once the buffer is loaded, the UCSTTIFG flag is
cleared, which sends the data out to the SDA line, and the UCTXIFG flag is automatically set
again for the next data to be transmitted, which occurs after an acknowledge bit is detected on
the bus. If the not-acknowledge (NACK) bit is detected, followed by a stop condition, instead,
the UCSTPIFG flag is set. If the NACK bit is detected followed by a start condition, MSP430
starts to monitor this device address, again, on the SDA line [SLAU445G, 2016, SLAU367O,
2017].
If the MSP430 controller should receive data from a slave device (the Read/Write bit is
low), the UCTR bit is cleared, the receive buffer (UCBxRXBUF) is loaded with the data from
the bus, and the UCRXIFG flag is set, acknowledging the receipt of the data. Once the data in
the bus is read, the flag is cleared, and the controller is ready to receive the next 8-bit data. The
controller has an option to send the UCTXNACK bit to a master to release the bus. When a
stop condition is detected on the bus, the UCSTPIFG flag is set. If two repeated start conditions
are detected or the UCSTPIFG flag is set, the MSP430 terminates its current session and starts
monitoring its address on the bus [SLAU445G, 2016, SLAU367O, 2017].
10.6.5 I2 C REGISTERS
I2 C associated registers include [SLAU445G, 2016, SLAU367O, 2017]:
• UCBxCTLW0 eUSCI_Bx Control Word 0
• UCBxCTL1 eUSCI_Bx Control 1
• UCBxCTL0 eUSCI_Bx Control 0
• UCBxCTLW1 eUSCI_Bx Control Word 1
• UCBxBRW eUSCI_Bx Bit Rate Control Word
• UCBxBR0 eUSCI_Bx Bit Rate Control 0
• UCBxBR1 eUSCI_Bx Bit Rate Control 1
• UCBxSTATW eUSCI_Bx Status Word
• UCBxSTAT eUSCI_Bx Status
• UCBxBCNT eUSCI_Bx Byte Counter Register
• UCBxTBCNT eUSCI_Bx Byte Counter Threshold Register
446 10. COMMUNICATION SYSTEMS
• UCBxRXBUF eUSCI_Bx Receive Buffer
• Wire.available(): returns the numbers of bytes available to be read with the Wire.read()
function.
• Wire.begin(addr): used by a device to join the I2 C bus. For a slave device, the unique slave
address is provided. If no address is provided, the device joins the bus as the master.
• Wire.requestFrom(addr, qty, stop): used by a master device to request data bytes from a
slave device.
TMP102 BLINKM
Digital Temperature Sensor 12C Controlled RGB LED
Sparkfun SEN-13314 Spartful COM-08579
C
nd
d
VD
VD
un
u
ro
ro
3
3
G
G
3.
3.
SDA
SDA P1.2, 10
ro C
d
G VD
SCL
un
SCL, P1.3, 9
3
3.
Sparkfun LCD-14072
16 × 2 SerLCD
Figure 10.15: MSP430FR2433 configured with peripheral devices via I2 C bus. (Figures used
courtesy of Texas Instruments (www.ti.com) and Sparkfun Electronics (www.sparkfun.com).)
448 10. COMMUNICATION SYSTEMS
In the next several examples we illustrate writing and reading data to peripheral devices
on an I2 C bus. Specifically, we connect a Sparkfun I2 C compatible LCD (LCD-14072), the
BLINKM I2 C controlled RGB LED (Sparkfun COM-08579), and a TMP102 digital temper-
ature sensor (Sparkfun SEN-13314), as shown in Figure 10.15.
I2 C LCD. In this example we configure the Sparkfun 16x2 SerLCD (LCD-14072) as an
I2 C slave device at address 0x72.
//*********************************************************************
//I2C_LCD: demonstrates initialization and operation of I2C compatible
// LCD (Sparkfun 16x2 SerLCD (LCD-14072).
//
//I2C code adapted from I2C code provided by Jim Lindblom of
//Sparkfun Electronics (www.sparkfun.com)
//*********************************************************************
#include <Wire.h>
int cycles = 0;
void setup()
{
void loop()
{
cycles++; //cycle count
i2cSendValue(cycles); //send the count to LCD -
//integer sent as four values
delay(50); //Maximum update rate of OpenLCD
//approximately 100Hz (10ms).
10.6. INTER-INTEGRATED COMMUNICATION – I2 C MODULE 449
//Shorter delay causes flicker
}
//*********************************************************************
//void i2cSendValue(int value): the function divides the integer into
//four bytes nteger into four values and sends them out over I2C
//*********************************************************************
//*********************************************************************
//*********************************************************************
//BlinkMFlash---simple demonstration of flashing a BlinkM
//Adapted from BlinkM code provided by THINKM at http://thingm.com
//*********************************************************************
#include "Wire.h"
void setup()
{
Wire.begin();
}
void loop()
450 10. COMMUNICATION SYSTEMS
{
BlinkM_setRGB(blinkm_addr, 0xff, 0x00, 0x00); //red
delay(500);
BlinkM_setRGB(blinkm_addr, 0x00, 0xff, 0x00); //green
delay(500);
BlinkM_setRGB(blinkm_addr, 0x00, 0x00, 0xff); //blue
delay(500);
}
//*********************************************************************
//void BlinkM_setRGB - sets an RGB color immediately
//*********************************************************************
static void BlinkM_setRGB(byte addr, byte red, byte grn, byte blu)
{
Wire.beginTransmission(addr);
Wire.write('n');
Wire.write(red);
Wire.write(grn);
Wire.write(blu);
Wire.endTransmission();
}
//*********************************************************************
//******************************************************************
//TMP102_Example
//Adapted from TMP102_Example provided by Texas Instruments
//******************************************************************
//TMP102: low power digital temperature sensor with a two-wire
// serial interface [SOBS397B].
10.6. INTER-INTEGRATED COMMUNICATION – I2 C MODULE 451
//******************************************************************
#include <Wire.h>
void setup()
{
Serial.begin(9600); //initialize for serial monitor
Wire.begin(); //initialize I2C communication
}
void loop()
{
//call the sensorRead function
double temperature = sensorRead(); //to retrieve the temperature
Serial.println(temperature, DEC); //displap temp serial monitor
delay(500); //wait 500 ms
}
//******************************************************************
//sensorRead: reads two bytes of temperature data from TMP102.
//Converts result to Centigrade and Fahrenheit.
//******************************************************************
double sensorRead(void)
{
uint8_t temp[2]; //holds two bytes of data
//read from TMP102
int16_t tempc; //holds modified data bytes
double tempf; //holds conversion from tempc
//******************************************************************
Programming the I2 C in C
In this example two MSP430FR2433 LaunchPads are connected via the I2 C bus. The master
configured device reads five bytes from the slave configured device.
Master configured processor:
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//******************************************************************
//MSP430FR243x Demo - eUSCI_B0 I2C Master RX multiple bytes
//from MSP430 Slave
//
//Description: This demo connects two MSP430's via the I2C bus.
//The master reads 5 bytes from the slave. This is the MASTER CODE.
//The data from the slave transmitter begins at 0 and increments
//with each transfer. The USCI_B0 RX interrupt is used to know
//when new data has been received.
//
// ACLK = default REFO ~32768Hz, MCLK = SMCLK = BRCLK = DCODIV ~1MHz.
//
// *****used with "msp430fr243x_euscib0_i2c_11.c"****
//
// /|\ /|\
10.6. INTER-INTEGRATED COMMUNICATION – I2 C MODULE 453
// MSP430FR2433 10k 10k MSP430FR2433
// slave | | master
// ----------------- | | -----------------
// | P1.2/UCB0SDA|<-|----|->|P1.2/UCB0SDA |
// | | | | |
// | | | | |
// | P1.3/UCB0SCL|<-|------>|P1.3/UCB0SCL |
// | | | P1.0|--> LED
//
//Cen Fang, Texas Instruments Inc., June 2013
//Built with IAR Embedded Workbench v6.20 & Code Composer Studio v6.0.1
//*********************************************************************
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD;
//Configure GPIO
P1OUT &= ~BIT0; //Clear P1.0 output latch
P1DIR |= BIT0; //For LED
P1SEL0 |= BIT2 | BIT3; //I2C pins
//*********************************************************************
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//*********************************************************************
//MSP430FR243x Demo - eUSCI_B0 I2C Slave TX multiple bytes to
//MSP430 Master
//
//Description: This demo connects two MSP430's via the I2C bus. The
//master reads from the slave. This is the SLAVE code. The TX data
//begins at 0 and is incremented each time it is sent. A stop condition
//is used as a trigger to initialize the outgoing data. The USCI_B0 TX
//interrupt is used to know when to TX.
//
// ACLK = default REFO ~32768Hz, MCLK = SMCLK = default DCODIV ~1MHz.
//
// *****used with "msp430fr243x_euscib0_i2c_10.c"****
//
// /|\ /|\
// MSP430FR2433 10k 10k MSP430FR2433
// slave | | master
// ----------------- | | -----------------
// | P1.2/UCB0SDA|<-|----|->|P1.2/UCB0SDA |
456 10. COMMUNICATION SYSTEMS
// | | | | |
// | | | | |
// | P1.3/UCB0SCL|<-|------>|P1.3/UCB0SCL |
// | | | |
//
//Cen Fang, Texas Instruments Inc., June 2013
//Built with IAR Embedded Workbench v6.20 & Code Composer Studio v6.0.1
//*********************************************************************
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD;
P1SEL0 |= BIT2 | BIT3; //Configure GPIO I2C pins
//*********************************************************************
//*********************************************************************
Configure two MSP430 LaunchPads to communicate using the UART and SPI.
458 10. COMMUNICATION SYSTEMS
10.8 SUMMARY
In this chapter we have discussed the complement of serial communication features aboard the
MSP430 microcontroller. The system is equipped with a host of different serial communication
subsystems including eUSCI_A type modules and eUSCI_B modules. Each microcontroller in
the MSP430 line has a complement of A and B type eUSCI modules.
TPIC6C596 Power Logic 8-Bit Shift Register, (SLIS093D), Texas Instruments, 2015. 420
2. If the communication cost is the primary issue, which communication methods (parallel,
series) should be used? Why?
Advanced
1. Write a function that properly initialize the SPI unit. Specify the configuration parameter
values used for the external device.
2. Describe interrupts associated with the I2 C unit.
3. There are multiple I2 C interrupts but a single interrupt vector. After detecting an inter-
rupt, the I2 C interrupt system must identify the source of the interrupt. How is this ac-
complished?
Challenging
1. Design and program three MSP430 controller systems to measure temperatures surround-
ing the three controllers. Create a wireless communication network using the three con-
trollers along with the CC2530-ZNP radio transceivers. The controllers should constantly
share the temperature sensor data among the members. Select a central controller and dis-
play the three temperature values on a LCD display once every 5 s.
2. Design and program an I2 C based system to measure and display temperature. The system
should also contain a tri-color LED to display a corresponding color based on measured
temperature.
3. Design and program an I2 C based system to provide for a peripheral EEPROM (Sparkfun
COM-00525).
4. Design and program an I2 C based system to provide for a peripheral DAC based on the
MPC47725 (Sparkfun BOB-12918).
461
CHAPTER 11
11.1 OVERVIEW
This chapter may be the most important chapter in the book. It contains essential information
about how to maintain the integrity of a microcontroller-based system.1 The chapter begins with
a discussion on EMI, also known as noise. Design practices to minimize EMI are then discussed.
The second section of the chapter discusses the concept of the CRC. This is a hardware-based
1 This chapter was adapted with permission from Embedded Systems Design with the Texas Instruments MSP432 32-bit
Processor, Morgan & Claypool Publishers, 2017.
462 11. MSP430 SYSTEM INTEGRITY
subsystem used to generate a checksum of a block of data. The checksum may be used to test
the integrity of data once it has been transmitted or loaded to a new location. The final section
covers the MSP430FR5994 advanced encryption standard module, the AES256. This module
is used to insure the integrity of data transmission using a key-based encryption and decryption
technique.
Radio
Lightning
Motors M Radiation
Radiated
Sources
MSP432
Appliances
Conduction
Electrostatic
Discharge (ESD)
e.g., Static Electricity
Microcontroller Conducted
System Sources
Components
Power
Supply
Figure 11.1: Noise sources in a microcontroller-based system. (Adapted from AN1705 [2004],
COP888 [1996].)
gently twisting the cable and also providing a ground conductor alternating with signal-
carrying conductors.
• Use shielded cable for signal conductors coming into the microcontroller-based system.
• If the microcontroller is being used to control a motor, use an opto-isolator between the
microcontroller and the motor interface circuit. Also, the motor and the microcontroller
should not share a common power supply.
464 11. MSP430 SYSTEM INTEGRITY
• Use filters for signals coming into a microcontroller-based system. Filters are commonly
available in the form of ferrite beads.
• Filter the power supply lines to the circuit. Typically, a 10–470 F capacitor is employed
for this purpose. Also, a 0.1 F capacitor should be used between the power and ground
pins on each integrated circuit.
• Ground the metal crystal time base case to insure it does not radiate a noise signal.
• There are several defensive programming techniques to help combat noise. One easy to
implement technique is to declare unused microcontroller pins as output.
The block of data to be protected via the checksum is considered the dividend. The divi-
dend is divided by a pre-selected CRC polynomial which serves as the divisor. At the comple-
tion of the division operation, a quotient and a remainder result. The remainder of the operation
serves as the CRC checksum.
Generation of a checksum is based on the concept that when a given block of data is
divided by a specific polynomial with the division hardware initialized with the same value (seed),
the same checksum will result every time the operation is performed. Similarly, if the input
data is different or in a different order, the polynomial is changed, or the division hardware is
seeded with a different initial value, a different checksum will result. A number of common
11.3. CYCLIC REDUNDANCY CHECK 465
polynomials have been developed to support CRC checksum generation. Two common ones
include [SLAU367O, 2017]:
• CRC16-CCITT defined as f .x/ D X 15 C X 12 C X 5 C 1
• CRC32-IS3309 defined as
f .x/ D X 32 C X 26 C X 23 C X 22 C
X 16 C X 12 C X 11 C X 10 C X 8 C
X 7 C X 5 C X 4 C X 2 C X C 1: (11.1)
A linear feedback shift register (LFSR) is used to generate the checksum. The polynomial
divisor chosen to generate the checksum specifies the hardware connection for the LFSR. For
example, the LFSR configuration for the CRC16-CCITT polynomial is shown in Figure 11.2.
Note how the polynomial terms specify the output connections of certain flip-flops within the
LFSR. To generate the checksum, the LFSR is initially configured to the seed value. The data
block is fed in as a serial data stream. The resulting remainder is used as the checksum and
appended to the original data block for transmission [SLAU367O, 2017].
D Q D Q D Q D Q D Q D Q D Q D Q D Q D Q D Q D Q D Q D Q D Q D Q
Data
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
In
Shift
Clock
CRC16INIRES/ CRC16DI/
CRC32INIRES CRC32DI
Details of specific register and bits settings are contained in MSP430P4xx Family Technical Ref-
erence Manual [SLAU367O, 2017].
Example: In this example the hardware and software techniques of generating a CRC16 check-
sum is compared.
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
//MSP430FR5x9x Demo - CRC16, Compare CRC output with software-based
//algorithm
//
//Description: An array of 16 random 16-bit values are moved through
//the CRC module, as well as a software-based CRC-CCIT-BR algorithm.
//The software-based algorithm handles 8-bit inputs only, the 16-bit
//words are broken into 2 8-bit words before being run through
//(lower byte first). The outputs of both methods are then compared to
//ensure that the operation of the CRC module is consistent with the
//expected outcome. If the values of each output are equal, set P1.0,
//else reset.
//
// MCLK = SMCLK = default DCO~1MHz
//
// MSP430FR5994
// -----------------
// /|\| |
// | | |
// --|RST |
// | |
468 11. MSP430 SYSTEM INTEGRITY
// | P1.0|--> LED
//
//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)
{
unsigned int i;
//********************************************************************
// Software algorithm - CCITT CRC16 code
//********************************************************************
return CCITT;
}
//********************************************************************
Example: In this example the hardware and software techniques of generating a CRC32 check-
sum is compared.
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2016, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
//********************************************************************
//MSP430FR5x9x Demo - CRC32, Compare CRC32 output with software-based
// algorithm
//
//Description: An array of 16 random 16-bit values are moved through
//the CRC32 module, as well as a software-based CRC32-ISO3309
//algorithm. The software-based algorithm handles 8-bit inputs only,
//the 16-bit words are broken into 2 8-bit words before being run
//through (lower byte first). The outputs of both methods are then
//compared to ensure that the operation of the CRC module is
//consistent with the expected outcome. If the values of each output
//are equal, set P1.0, else reset.
//
// MCLK = SMCLK = default DCO~1MHz
//
// MSP430FR5994
// -----------------
11.3. CYCLIC REDUNDANCY CHECK 471
// /|\| |
// | | |
// --|RST |
// | |
// | P1.0|--> LED
//
//William Goh, Texas Instruments Inc., April 2016
//Built with IAR Embedded Workbench V6.40 & Code Composer Studio V6.1
//********************************************************************
#include <msp430.h>
//Global flag indicating that the CRC32 lookup table has been initialized
unsigned int crc32TableInit = 0;
int main(void)
{
unsigned int i;
//********************************************************************
// Calculate the SW CRC32 byte-by-byte
//********************************************************************
if(!crc32TableInit)
{
initSwCrc32Table();
}
return crc;
}
//********************************************************************
// Initializes the CRC32 table
//********************************************************************
void initSwCrc32Table(void)
{
474 11. MSP430 SYSTEM INTEGRITY
int i, j;
unsigned long crc;
}
//********************************************************************
11.4.1 REGISTERS
The AES256 system is supported by a complement of registers including [SLAU367O, 2017]:
• AESACTL0 AES accelerator control register 0
• AESACTL1 AES accelerator control register 1
• AESASTAT AES accelerator status register
• AESAKEY AES accelerator key register
• AESADIN AES accelerator data in register
• AESADOUT AES accelerator data out register
• AESAXDIN AES accelerator XORed data in register
• AESAXIN AES accelerator XORed data in register (no trigger)
Details of specific register and bits settings are contained in MSP430FR58xx,
MSP430FR59xx, and MSP430FR6xx Family User’s Guide [SLAU367O, 2017] and will not be
repeated here.
AESADOUT
AES Control 128-bit AES
(AES accelerator
Registers 0, 1 State Memory data out)
AES
Encryption and
Decryption Core
256-bit AES
Key Memory
AESAKEY
(AES accelerator
key register)
(c) AES256 block diagram
Figure 11.4: AES256 encryption process: (a) AES256 algorithm, (b) AES256 encryption pro-
cess with 128-bit key, and (c) MSP430FR5994 AES256 block diagram [SLAU367O, 2017].
11.4. AES256 ACCELERATOR MODULE 477
• AES256_disableInterrupt
• AES256_enableInterrupt
• AES256_encryptData
• AES256_getDataOut
• AES256_getErrorFlagStatus
• AES256_getInterruptStatus
• AES256_isBusy
• AES256_reset
• AES256_setCipherKey
• AES256_setDecipherKey
• AES256_startDecryptData
• AES256_startEncryptData
• AES256_startSetDecipherKey
Example: In this example the AES256 module is used to encrypt/decrypt data using a cipher
key and APIs from DriverLib.
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
//***********************************************************************
//Below is a simple code example of how to encrypt/decrypt data using a
//cipher key with the AES256 module
//***********************************************************************
int main(void)
{
//Load a cipher key to module
478 11. MSP430 SYSTEM INTEGRITY
MAP_AES256_setCipherKey(AES256_MODULE, CipherKey,
AES256_KEYLENGTH_256BIT);
//Decrypt data with keys that were generated during encryption takes
//214 MCLK cyles. This function will generate all round keys needed for
//
decryption first and then the encryption process starts
MAP_AES256_decryptData(AES256_MODULE, DataAESencrypted,
DataAESdecrypted);
}
//***********************************************************************
Example: In this example the AES256 module is used for encryption and decryption. The orig-
inal plain text data is encrypted and then decrypted. The results are compared and if they agree
an LED on P1.0 is illuminated. A UML activity diagram for the example is provided in Fig-
ure 11.5.
//***********************************************************************
//MSP430P401 Demo - AES256 Encryption & Decryption
//
//Description: This example shows a simple example of encryption and
//decryption using the AES256 module.
//
// MSP430FR5994
// -----------------
// /|\| |
// | | |
// --|RST |
// | |
// | P1.0|-->LED
//
//Key: 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
11.4. AES256 ACCELERATOR MODULE 479
No
Wait for Data match?
No unit to finish
(~167 MCLK cycles)
Yes
Yes Turn on P1.0 LED
Write 128-bit block of encrypted
data back to DataAESencrypted
#include "msp.h"
#include <stdint.h>
uint8_t Data[16] =
{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff };
uint8_t CipherKey[32] =
{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f };
int main(void)
{
volatile uint32_t i;
uint16_t sCipherKey, tempVariable;
P1DIR |= BIT0;
P1OUT |= BIT0; //Turn on P1.0 LED = success
while(1);
//***********************************************************************
11.6 SUMMARY
This chapter contained essential information about how to maintain the integrity of a
microcontroller-based system. The chapter began with a discussion on EMI, also known as
noise. Design practices to minimize EMI were then discussed. The second section of the chapter
discussed the concept of the CRC. The final section covered the MSP430 advanced encryption
standard module, the AES256.
484 11. MSP430 SYSTEM INTEGRITY
11.7 REFERENCES AND FURTHER READING
Barrett, S. F. and Pack, D. J. Embedded Systems: Design and Applications with the 68HC12 and
HCS12, Prentice Hall, Upper Saddle River, NJ, 2004. 462
Federal Information Processing Standards Publication 197 (FIPS-197), November 26, 2001. 474,
475
MSP430 Peripheral Driver Library User’s Guide, Texas Instruments, 2015. 475
Advanced
4. Research common CRC polynomials. Sketch the corresponding LFSR for each polyno-
mial.
CHAPTER 12
System-Level Design
Objectives: After reading this chapter, the reader should be able to do the following:
• define an embedded system;
• list multiple aspects related to the design of an embedded system;
• provide a step-by-step approach to design an embedded system;
• discuss design tools and practices related to embedded systems design;
• discuss the importance of system testing;
• apply embedded system design practices in the prototype of a MSP430 based system with
several subsystems;
• provide a detailed design for a weather station including hardware layout and interface,
structure chart, UML activity diagrams, and an algorithm coded in Energia;
• provide a detailed design for a submersible remotely operated vehicle (ROV) including
hardware layout and interface, structure chart, UML activity diagrams, and an algorithm
coded in Energia; and
• provide a detailed design for a four-wheel drive (4WD) mountain maze navigating robot
including hardware layout and interface, structure chart, UML activity diagrams, and an
algorithm coded in Energia.
12.1 OVERVIEW
This chapter provides a step-by-step, methodical approach toward designing advanced embed-
ded systems. We begin with a definition of an embedded system. We then explore the process
of how to successfully (and with low stress) develop an embedded system prototype that meets
established requirements. The overview of embedded system design techniques was adapted
with permission from earlier Morgan & Claypool projects. Also, the projects have been adapted
with permission for the MSP430. We also emphasize good testing techniques. We conclude
the chapter with several extended examples. The examples illustrate the embedded system de-
sign process in the development and prototype of a weather station, a submersible ROV, and a
4WD mountain maze navigating robot. We use the MSP-EXP430FR5994 LaunchPad in the
examples to allow for the greatest project extension.
488 12. SYSTEM-LEVEL DESIGN
12.2 WHAT IS AN EMBEDDED SYSTEM?
An embedded system is typically designed for a specific task. It contains a processor to col-
lect system inputs and generate system outputs. The link between system inputs and outputs is
provided by a coded algorithm stored within the processor’s resident memory. What makes em-
bedded systems design so challenging and interesting is the design must also provide for proper
electrical interface for the input and output devices, potentially limited on-chip resources, human
interface concepts, the operating environment of the system, cost analysis, related standards, and
manufacturing aspects [Anderson, 2008]. Through careful application of this material you will
be able to design and prototype embedded systems based on MSP430.
No
Employ Design Tools Complete and Accurate Documentation
- Structure chart - System description
- UML activity diagram - Requirements
- Circuit diagram - Structure chart
- Supplemental information - UML activity diagram
- Circuit diagram
- Well-documented code
- Test plan
Deliver Prototype
12.3.3 PRE-DESIGN
The goal of the pre-design step is to convert a thorough understanding of the project into possi-
ble design alternatives. Brainstorming is an effective tool in this step. Here, a list of alternatives
is developed. Since an embedded system involves hardware and/or software, the designer can
investigate whether requirements could be met with a hardware only solution or some combi-
nation of hardware and software. Generally speaking, a hardware only solution executes faster;
however, the design is fixed once fielded. On the other hand, a software implementation provides
flexibility but a slower execution speed. Most embedded design solutions will use a combination
of both hardware and software to capitalize on the inherent advantages of each.
Once a design alternative has been selected, the general partition between hardware and
software can be determined. It is also an appropriate time to select a specific hardware device
to implement the prototype design. If a technology has been chosen, it is now time to select a
specific processor. This is accomplished by answering the following questions.
• What processor systems or features (i.e., ADC, PWM, timer, etc.) are required by the
design?
• What is the maximum anticipated operating speed of the processor expected to be?
Due to the variety of onboard systems, clock speed, and low cost; the MSP430 may be
used in a wide array of applications typically held by microcontrollers and advanced processors.
12.3.4 DESIGN
With a clear view of system requirements and features, a general partition determined between
hardware and software, and a specific processor chosen; it is now time to tackle the actual design.
It is important to follow a systematic and disciplined approach to design. This will allow for low
stress development of a documented design solution that meets requirements. In the design step,
several tools are employed to ease the design process. They include the following:
Let’s take a closer look at each of these. The information provided here is an abbreviated
version of the one provided in Microcontrollers Fundamentals for Engineers and Scientists. The
interested reader is referred there for additional details and an in-depth example [Barrett and
Pack, 2006].
Top-down design, bottom-up implementation. An effective tool to start partitioning
the design is based on the techniques of top-down design, bottom-up implementation. In this
approach, you start with the overall system and begin to partition it into subsystems. At this
point of the design, you are not concerned with how the design will be accomplished but how
the different pieces of the project will fit together. A handy tool to use at this design stage is
the structure chart. The structure chart shows how the hierarchy of system hardware and soft-
ware components will interact and interface with one another. You should continue partitioning
system activity until each subsystem in the structure chart has a single definable function. Di-
rectional arrows are used to indicate data flow in and out of a function.
UML activity diagram. Once the system has been partitioned into pieces, the next step
is to work out the details of the operation of each subsystem previously identified. Rather than
beginning to code each subsystem as a function, work out the information and control flow of
each subsystem using another design tool: the UML activity diagram. The activity diagram is
simply a UML compliant flow chart. UML is a standardized method of documenting systems.
The activity diagram is one of the many tools available from UML to document system design
and operation. The basic symbols used in a UML activity diagram for a processor based system
are provided in Figure 12.2 [Fowler, 2000].
To develop the UML activity diagram for the system, we can use a top-down, bottom-up,
or a hybrid approach. In the top-down approach, we begin by modeling the overall flow of the
algorithm from a high level. If we choose to use the bottom-up approach, we would begin at the
bottom of the structure chart and choose a subsystem for flow modeling. The specific course of
action chosen depends on project specifics. Often, a combination of both techniques, a hybrid
approach, is used. You should work out all algorithm details at the UML activity diagram level
prior to coding any software. If you cannot explain system operation at this higher level first, you
have no business being down in the detail of developing the code. Therefore, the UML activity
diagram should be of sufficient detail so you can code the algorithm directly from it [Dale and
Lilly, 1995].
In the design step, a detailed circuit diagram of the entire system is developed. It will serve
as a roadmap to implement the system. It is also a good idea at this point to investigate avail-
able design information relative to the project. This would include hardware design examples,
software code examples, and application notes available from manufacturers. As before, use a
subsystem approach to assemble the entire circuit. The basic building block interface circuits dis-
492 12. SYSTEM-LEVEL DESIGN
Figure 12.2: UML activity diagram symbols. (Adapted from Fowler [2000].)
cussed in the previous chapter may be used to assemble the complete circuit. At the completion
of this step, the prototype design is ready for implementation and testing.
12.4.1 REQUIREMENTS
The requirements for this system include:
• wind direction and temperature should be transmitted serially from the microcontroller to
the onboard microSD card for storage.
Weather Station
Wind
SPI ADC12 Direction
Display
Data for
Display
MicroSD
Card
Wind direction display: There are eight different LEDs to drive for the wind direction
indicator. An interface circuit is required for each LED as shown in the figure.
MSP-EXP430FR5994 LaunchPad
Vcc = 5 V
P1.3, A3 Temperature
pin 6 LM34 Sensor
75
Onboard 1uF
MicroSD
3.3 VDC
N NE E SE S SW W NW
J K G2 L M N G1 4 H
MPQ2222 1 7 8 14 1 7 14
2 6 9 13 2 6 9 13
3 5 10 12 3 5 10 12
10 K 10 K 10 K 10 K 10 K 10 K 10 K 10 K
38
32
34
35
31
36
33
37
n
n
in
in
n
in
n
pi
pi
pi
pi
pi
,p
,p
,
,
4,
,
J4
4,
4,
J4
J4
J4
J4
J
,J
,J
5,
,
6,
1,
3,
NE
.2
.5
NW
.3
3.
2.
4.
7.
3.
P4
P2
P4
:P
P
:P
:P
:P
E:
S:
W
E:
SE
N
SW
W
N
W E
SW SE
from MSP430 S
Figure 12.4: Circuit diagram for weather station. (Illustrations used with permission of Sparkfun
Electronics (www.sparkfun.com) and Texas Instruments (www.ti.com).)
12.4. MSP430FR5994: WEATHER STATION 497
Include files
Global variables
Function prototypes
Initialize ADC
Initialize SPI
While(1)
Convert temp
Delay(desired_update_time)
float wind_direction_float;
float temp_value_float;
void setup()
{
//LED indicators
pinMode(N_LED, OUTPUT); //config pin for digital out - N LED
pinMode(NE_LED, OUTPUT); //config pin for digital out - NE LED
pinMode(E_LED, OUTPUT); //config pin for digital out - E LED
pinMode(SE_LED, OUTPUT); //config pin for digital out - SE LED
12.4. MSP430FR5994: WEATHER STATION 499
pinMode(S_LED, OUTPUT); //config pin for digital out - S LED
pinMode(SW_LED, OUTPUT); //config pin for digital out - SW LED
pinMode(W_LED, OUTPUT); //config pin for digital out - W LED
pinMode(NW_LED, OUTPUT); //config pin for digital out - NW LED
void loop()
{
//read two sensors and append to the string
//analog read returns value between 0 and 1023
wind_dir_value = analogRead(wind_dir);
temp_value = analogRead(temp_sensor);
if(troubleshoot == 1)Serial.println(wind_dir_value);
if(troubleshoot == 1)Serial.println(temp_value);
//***********************************************************************
if(troubleshoot == 1)Serial.println(wind_dir_float);
//N - LED0
if((wind_dir_float <= 2.56)&&(wind_dir_float > 2.50))
500 12. SYSTEM-LEVEL DESIGN
{
digitalWrite(N_LED, HIGH); digitalWrite(NE_LED, LOW);
digitalWrite(E_LED, LOW); digitalWrite(SE_LED, LOW);
digitalWrite(S_LED, LOW); digitalWrite(SW_LED, LOW);
digitalWrite(W_LED, LOW); digitalWrite(NW_LED, LOW);
}
//NE - LED1
if((wind_dir_float > 1.46)&&(wind_dir_float <= 1.52))
{
digitalWrite(N_LED, LOW); digitalWrite(NE_LED, HIGH);
digitalWrite(E_LED, LOW); digitalWrite(SE_LED, LOW);
digitalWrite(S_LED, LOW); digitalWrite(SW_LED, LOW);
digitalWrite(W_LED, LOW); digitalWrite(NW_LED, LOW);
}
//E - LED2
if((wind_dir_float > 0.27)&&(wind_dir_float <= 0.33))
{
digitalWrite(N_LED, LOW); digitalWrite(NE_LED, LOW);
digitalWrite(E_LED, HIGH); digitalWrite(SE_LED, LOW);
digitalWrite(S_LED, LOW); digitalWrite(SW_LED, LOW);/
digitalWrite(W_LED, LOW); digitalWrite(NW_LED, LOW);
}
//SE - LED3
if((wind_dir_float > 0.57)&&(wind_dir_float <= 0.63))
{
digitalWrite(N_LED, LOW); digitalWrite(NE_LED, LOW);
digitalWrite(E_LED, LOW); digitalWrite(SE_LED, HIGH);
digitalWrite(S_LED, LOW); digitalWrite(SW_LED, LOW);
digitalWrite(W_LED, LOW); digitalWrite(NW_LED, LOW);
}
//S - LED4
if((wind_dir_float > 0.9)&&(wind_dir_float <= 0.96))
{
digitalWrite(N_LED, LOW); digitalWrite(NE_LED, LOW);
digitalWrite(E_LED, LOW); digitalWrite(SE_LED, LOW);
12.4. MSP430FR5994: WEATHER STATION 501
digitalWrite(S_LED, HIGH); digitalWrite(SW_LED, LOW);
digitalWrite(W_LED, LOW); digitalWrite(NW_LED, LOW);
}
//SW - LED5
if((wind_dir_float > 2.0)&&(wind_dir_float <= 2.06))
{
digitalWrite(N_LED, LOW); digitalWrite(NE_LED, LOW);
digitalWrite(E_LED, LOW); digitalWrite(SE_LED, LOW);
digitalWrite(S_LED, LOW); digitalWrite(SW_LED, HIGH);
digitalWrite(W_LED, LOW); digitalWrite(NW_LED, LOW);
}
//W - LED6
if((wind_dir_float > 3.02)&&(wind_dir_float <= 3.08))
{
digitalWrite(N_LED, LOW); digitalWrite(NE_LED, LOW);
digitalWrite(E_LED, LOW); digitalWrite(SE_LED, LOW);
digitalWrite(S_LED, LOW); digitalWrite(SW_LED, LOW);
digitalWrite(W_LED, HIGH); digitalWrite(NW_LED, LOW);
}
//NW - LED7
if((wind_dir_float > 2.83)&& (wind_dir_float <= 2.89))
{
digitalWrite(N_LED, LOW); digitalWrite(NE_LED, LOW);
digitalWrite(E_LED, LOW); digitalWrite(SE_LED, LOW);
digitalWrite(S_LED, LOW); digitalWrite(SW_LED, LOW);
digitalWrite(W_LED, LOW); digitalWrite(NW_LED, HIGH);
}
}
//***********************************************************************
• In Chapter 12.9 we discussed the onboard microSD card. Equip the weather station
project with the onboard microSD card to log time hacks and weather data.
12.5.1 APPROACH
This is a challenging project; however, we take a methodical, step-by-step approach to successful
design and construction of the ROV. We complete the design tasks in the following order.
1. Determine requirements.
12.5.2 REQUIREMENTS
The requirements for the ROV system include the following.
12.5. SUBMERSIBLE ROBOT 503
Vertical
Left Thruster
Float
Left Right
Thruster Float
Right
Thruster
Figure 12.6: SeaPerch ROV. (Adapted and used with permission of Bohm and Jensen, West
Coast Words Publishing.)
• Develop a control system to allow a three thruster (motor or bilge pump) ROV to move
forward, left (port) and right (starboard).
• The ROV will be pushed down to a shallow depth via a vertical thruster and return to
surface based on its own, slightly positive buoyancy.
• ROV movement will be under joystick control.
• LEDs are used to indicate thruster assertion.
• All power and control circuitry will be maintained in a surface support platform as shown
in Figure 12.7.
• An umbilical cable connects the support platform to the ROV.
504 12. SYSTEM-LEVEL DESIGN
L C R
Battery
Figure 12.7: Power and control are provided remotely to the SeaPerch ROV. (Adapted and used
with permission of Bohm and Jensen, West Coast Words Publishing.)
ring
clamp
3/4” diameter PVC
Shoreline
Bilge Pump
Bilge Pump
Shoreline
Per side:
ring Up/Down
clamp 2 each - 4-1/2”
Thruster 3 each - 4-1/2”
2 each - 7”
ring ring
clamp clamp
Umbilical Cable Side View
ring ring
clamp clamp
Shoreline
Bilge Pump ring
clamp
Waterproof
Bilge Pump
Interface
Shoreline
ring
clamp
Shoreline
Bilge Pump
ring ring
clamp clamp
Top View
Seaperch
Control System
ROV
Direction Direction
Five Position Motor
Joystick Control
Motor LED
Assertion Assertion
Motor Light-Emitting
Interface Diodes (LEDs)
Interface
3.3 VDC
3.3 VDC Voltage Reference
VERT 10 K
LM VCC
5.0 VDC 317T SEL to MSP430
240 SEL
HORZ
GND
0.1 uF 1.0 uF
390
Thumb Joystick
1 21 40 20 Y-Vertical
(analog)
GND
SEL
HORZ
VERT
V
CC
0 VDC
10 K
X-Horizontal X-Horizontal
Left Select Right
Select (analog) (analog)
(push)
(push) (port) 0 VDC 3.3 VDC (starboard)
10 30 31 11 Y-Vertical
(analog)
3.3 VDC (c) Joystick
(b) Sparkfun thumb joystick on breakout board and voltages
Reverse
Jameco Prototype Builder 1.6” × 2.7” PCB (#105100) (stern)
Figure 12.10: Thumb joystick mounted to a breakout board. (Illustration used with permission
of Jameco (www.jameco.com).)
12.5. SUBMERSIBLE ROBOT 509
+ + +
Left Vertical Right Vertical
M 1N4001
Thruster
10 KΩ 10 KΩ 10 KΩ
P4.1, P4.2, P4.3, 2N2222
J4 pin 31 J4 pin 32 J4 pin 33
470 Ω
TIP 120
PWM
LED Thruster Indicators
P5.7, J2, pin 19
MSP-EXP430FR5994 LaunchPad
12 VDC 12 VDC
470 Ω 470 Ω
TIP 120 TIP 120
PWM PWM
P3.7, J4, pin 40 P3.6, J4, pin 39
12 VDC
5 VDC 3.3 VDC
VERT 10 K
5A (P1.5, A5,
on/off LM 3.3 VDC VCC J3, pin 28)
7805 317T sel
SEL (P2.5,
390 J4, pin 34)
0.33 uF HORZ
(P1.3, A3 GND
12 VDC 0.1 uF J1, pin 6)
1.0 uF
Rechargeable
640
Battery Thumb Joystick
GND
SEL
HORZ
VERT
VCC
Battery
5A
Charger Select
(push)
Figure 12.11: SeaPerch ROV interface control. (Illustration used with permission of Texas In-
struments (www.ti.com).)
510 12. SYSTEM-LEVEL DESIGN
Jones Connector
4 Conductor
to ROV
220
220
220
10 K
10 K
10 K
c c c
b b b
e e e
1N4001
1N4001
1N4001
5A Fuse 7805 LM317
out
inp
adj
12 V I C O
TIP TIP TIP
120 120 120
on/off
0.33
0.1
B CE B CE B CE
390
640
12 VDC
Battery 1.0
10
10
10
Ground
)
)
)
5A
in k)
l)
M 0 p 1 (G
(P
r)
)
)
(B
Y
B
(W
(
30 0 (
(
(
CC
43 n 33
32
43 nd
39
V
19
SP ou
n
k
in
pi
p
pi
tic
n
i
g
pi
0
0
ys
43
gh r in , to 43
0
Battery P4
jo
t, SP4
43
SP
ut SP
SP
S
to
SP
M
Charger
M
M
in o M
M
V,
M
to
to
th D in to
o
3
o
,t
3.
t,
,t
,
ED t,
pu
LE und
ut
pu
pu
p
ut
np
in
np
ro
Vcc
ri
ED
G
ri
Ri ste
te
ste
L
us
L
ru
ft
ru
t
hr
10 K
rt
Le
th
tt
Ve
ft
gh
rt
Le
Ve
Ri
1 21 (Bk) (P) 40 20
40:left_thruster (Y)
GND
SEL
HORZ
VERT
VCC
joystick_hor: 6
34: joystick_sel
joystick_ver:28 Select 33:right_LED (O)
(push) 32:vertical_LED (B1)
10 30 31 11 31:left_LED:31(G)
Figure 12.12: SeaPerch ROV printed circuit board interface. (Illustration used with permission
of Jameco (www.jameco.com).)
12.5. SUBMERSIBLE ROBOT 511
As previously mentioned, the prime mover for the ROV are three bilge pumps. The left and
right bilge pumps are driven by pulse width modulation channels (MSP430 P2.4 and P2.6) via
power NPN Darlington transistors (TIP 120), as shown in Figure 12.11. The vertical thrust is
under digital pin control P2.5 equipped with NPN Darlington transistor (TIP 120) interface.
Both the LED and the pump interfaces were discussed in an earlier chapter.
The interface circuitry between the MSP430 LaunchPad and the bilge pumps is mounted
on a printed circuit board (PCB) within the control housing. The interface between MSP430,
the PCB, and the umbilical cable is provided in Figure 12.12.
Include files
Global Variables
Function prototypes
Configure pins
no
2000 ms? Bow
dive
yes
Port Starboard
Read joystick position
(e.g., bow, stern,
starboard, port, dive) Stern
yes
Zone 8? Proceed right and forward
no
Forward
(bow)
Y-Vertical
(analog)
0 VDC
Y-Vertical
Left X-Horizontal Select X-Horizontal Right (analog)
(port) (analog) (analog) (starboard) 0 VDC
0 VDC (push) 3.3 VDC
Forward
(bow)
Y-Vertical
(analog)
3.3 VDC
Reverse
1.6 V (496)
(stern) I
II VIII
1.6 V (496)
X-Horizontal X-Horizontal
Left III VII Right
(analog) (analog)
(port) (starboard)
0 VDC 3.3 VDC
1.7 V (527)
IV VI
Lorem ipsum
1.7 V (527)
V
Select
(push)
Reverse
(stern)
Y-Vertical
(analog)
3.3 VDC
//thruster outputs
#define left_thruster 40 //digital pin - left thruster
#define right_thruster 39 //digital pin - right thruster
#define vertical_thruster 19 //digital pin - vertical thruster
514 12. SYSTEM-LEVEL DESIGN
void setup()
{
//LED indicators
pinMode(left_LED, OUTPUT); //config pin for digital out - left LED
pinMode(vertical_LED, OUTPUT); //config pin for digital out -
//vertical LED
pinMode(right_LED, OUTPUT); //config pin for digital out - right LED
//thruster outputs
pinMode(left_thruster, OUTPUT); //config digital out - left thruster
pinMode(vertical_thruster, OUTPUT); //config digital out -
//vertical thruster
pinMode(right_thruster, OUTPUT); //config digital out - right thruster
void loop()
{
//set update interval
delay(1000);
if(troubleshoot == 1) Serial.println(joystick_hor_value);
if(troubleshoot == 1) Serial.println(joystick_ver_value);
//**************************************************************
//vertical thrust - active low pushbutton on joystick
//**************************************************************
if(joystick_thrust_on == 0)
{
digitalWrite(vertical_thruster, HIGH);
digitalWrite(vertical_LED, HIGH);
if(troubleshoot == 1) Serial.println("Thrust is on!");
}
else
{
digitalWrite(vertical_thruster, LOW);
digitalWrite(vertical_LED, LOW);
if(troubleshoot == 1) Serial.println("Thrust is off!");
}
//*************************************************************
//*************************************************************
//process different joystick zones
//*************************************************************
//Case 0: Joystick in null position
//Inputs:
516 12. SYSTEM-LEVEL DESIGN
// X channel between 1.60 to 1.70 VDC - null zone
// Y channel between 1.60 to 1.70 VDC - null zone
//Output:
// Shut off thrusters
//*************************************************************
{
if(troubleshoot == 1) Serial.println("Zone 0");
if(troubleshoot == 1)
{
if(troubleshoot == 1) Serial.println(joystick_hor_value);
if(troubleshoot == 1) Serial.println(joystick_ver_value);
if(troubleshoot == 1) Serial.println(joystick_thrust_on);
}
//assert LEDs
digitalWrite(left_LED, LOW); //de-assert left LED
digitalWrite(right_LED, LOW); //de-assert right LED
}
//*************************************************************
//*************************************************************
//process different joystick zones
//*************************************************************
//Case 1:
//Inputs:
// X channel between 1.60 to 1.70 VDC - null zone
// Y channel <= 1.60 VDC
//Output:
// Move forward - provide same voltage to left and right thrusters
//*************************************************************
12.5. SUBMERSIBLE ROBOT 517
if(troubleshoot == 1) Serial.println(joystick_hor_value);
if(troubleshoot == 1) Serial.println(joystick_ver_value);
if(troubleshoot == 1) Serial.println(joystick_thrust_on);
//assert LEDs
digitalWrite(left_LED, HIGH); //assert left LED
digitalWrite(right_LED,HIGH); //assert right LED
}
//**************************************************************
//**************************************************************
//Case 2:
//Inputs:
// X channel <= 1.60 VDC
// Y channel <= 1.60 VDC
//Output:
// Move forward and bare left
// - Which joystick direction is asserted more?
// - Scale PWM voltage to left and right thruster accordingly
//**************************************************************
if(troubleshoot == 1) Serial.println(joystick_hor_value);
if(troubleshoot == 1) Serial.println(joystick_ver_value);
if(troubleshoot == 1) Serial.println(joystick_thrust_on);
//assert LEDs
digitalWrite(left_LED, HIGH); //assert left LED
digitalWrite(right_LED, HIGH); //assert right LED
}
else
{
analogWrite(left_thruster, joystick_ver_value);
analogWrite(right_thruster, (joystick_ver_value - joystick_hor_value));
//assert LEDs
digitalWrite(left_LED, HIGH); //assert left LED
digitalWrite(right_LED, HIGH); //assert right LED
}
}
//************************************************************
//************************************************************
//Case 3:
//Inputs:
// X channel <= 1.60 VDC
// Y channel between 1.60 to 1.70 VDC - null zone
//Output:
// Bare left
//************************************************************
if(troubleshoot == 1) Serial.println(joystick_hor_value);
if(troubleshoot == 1) Serial.println(joystick_ver_value);
if(troubleshoot == 1) Serial.println(joystick_thrust_on);
//assert thrusters
analogWrite(left_thruster, 0);
analogWrite(right_thruster, joystick_hor_value);
//assert LEDs
digitalWrite(left_LED, LOW); //de-assert left LED
digitalWrite(right_LED, HIGH); //assert right LED
}
//**************************************************************
//**************************************************************
//Case 4:
//Inputs:
// X channel <= 1.60 VDC
// Y channel >= 1.70 VDC
//Output:
// Bare left to turn around
//**************************************************************
if(troubleshoot == 1) Serial.println(joystick_hor_value);
520 12. SYSTEM-LEVEL DESIGN
if(troubleshoot == 1) Serial.println(joystick_ver_value);
if(troubleshoot == 1) Serial.println(joystick_thrust_on);
//assert LEDs
digitalWrite(left_LED, LOW); //de-assert left LED
digitalWrite(right_LED, HIGH); //assert right LED
}
else
{
analogWrite(left_thruster, 0);
analogWrite(right_thruster, (joystick_ver_value-joystick_hor_value));
//assert LEDs
digitalWrite(left_LED, LOW); //de-assert left LED
digitalWrite(right_LED, HIGH); //assert right LED
}
}
//**************************************************************
//**************************************************************
//Case 5:
//Inputs:
// X channel between 1.60 to 1.70 VDC - null zone
// Y channel >= 1.70 VDC
//Output:
// Move backward - provide same voltage to left and right thrusters
//**************************************************************
if(troubleshoot == 1) Serial.println(joystick_hor_value);
if(troubleshoot == 1) Serial.println(joystick_ver_value);
if(troubleshoot == 1) Serial.println(joystick_thrust_on);
//assert thrusters
analogWrite(left_thruster, 0);
analogWrite(right_thruster, joystick_ver_value);
//assert LEDs
digitalWrite(left_LED, LOW); //de-assert left LED
digitalWrite(right_LED, HIGH); //assert right LED
}
//*************************************************************
//*************************************************************
//Case 6:
//Inputs:
// X channel >= 1.70 VDC
// Y channel >= 1.70 VDC
//Output:
// Bare left to turn around
//*************************************************************
if(troubleshoot == 1) Serial.println(joystick_hor_value);
if(troubleshoot == 1) Serial.println(joystick_ver_value);
if(troubleshoot == 1) Serial.println(joystick_thrust_on);
//assert LEDs
digitalWrite(left_LED, HIGH); //assert left LED
digitalWrite(right_LED, LOW); //de-assert right LED
}
else
{
analogWrite(left_thruster, (joystick_ver_value-joystick_hor_value));
analogWrite(right_thruster, 0);
//assert LEDs
digitalWrite(left_LED, HIGH); //assert left LED
digitalWrite(right_LED, LOW); //de-assert right LED
}
}
//**************************************************************
//**************************************************************
//Case 7:
//Inputs:
// X channel >= 1.70 VDC
// Y channel between 1.60 to 1.70 VDC - null zone
//Output:
// Bare right
//**************************************************************
if(troubleshoot == 1) Serial.println(joystick_hor_value);
12.5. SUBMERSIBLE ROBOT 523
if(troubleshoot == 1) Serial.println(joystick_ver_value);
if(troubleshoot == 1) Serial.println(joystick_thrust_on);
//assert thrusters
analogWrite(left_thruster, joystick_hor_value);
analogWrite(right_thruster, 0);
//assert LEDs
digitalWrite(left_LED, HIGH); //assert left LED
digitalWrite(right_LED, LOW); //de-assert right LED
}
//**************************************************************
//**************************************************************
//Case 8:
//Inputs:
// X channel >= 1.70 VDC
// Y channel <= 1.60 VDC
//Output:
// Move forward and bare right
// - Which joystick direction is asserted more?
// - Scale PWM voltage to left and right thruster accordingly
//**************************************************************
if(troubleshoot == 1) Serial.println(joystick_hor_value);
if(troubleshoot == 1) Serial.println(joystick_ver_value);
if(troubleshoot == 1) Serial.println(joystick_thrust_on);
//assert LEDs
digitalWrite(left_LED, HIGH); //assert left LED
digitalWrite(right_LED, HIGH); //assert right LED
}
else
{
analogWrite(left_thruster, (joystick_ver_value-joystick_hor_value));
analogWrite(right_thruster, joystick_ver_value);
//assert LEDs
digitalWrite(left_LED, HIGH); //assert left LED
digitalWrite(right_LED, HIGH); //assert right LED
}
}
}
//**************************************************************
To ROV
Structure
Center Thruster
Right Thruster
Left Thruster
13.6 VDC
on/off Batt
switch Access Inline Fuse
Hole
L Bracket L Bracket
Interface Printed
Circuit Board
Joystick
Joystick
12 VDC
for Recharger L Bracket
2. With the thumb joystick on the breakout board disconnected from MSP430 LaunchPad,
test each LED indicator (left, dive, and right). This is accomplished by applying a 3.3
VDC signal in turn to the base resistor of each LED drive transistor.
3. In a similar manner each thruster (left, right, and vertical) may be tested. If available,
a signal generator may be used to generate a pulse width modulated signal to test each
thruster.
4. With power applied, the voltage regulators aboard the printed circuit board should be
tested for proper voltages.
5. The output voltages from the thumb joystick may be verified at the appropriate header
pins.
6. With the software fully functional, the thumb joystick on the breakout board may be
connected to MSP430 LaunchPad for end-to-end testing.
• Provide a powered dive and surface thruster. To provide for a powered dive and surface
capability, the ROV must be equipped with a vertical thruster equipped with an H-bridge
to allow for motor forward and reversal. This modification is given as an assignment at the
end of the chapter.
• Left and right thruster reverse. Currently, the left and right thrusters may only be powered
in one direction. To provide additional maneuverability, the left and right thrusters could
be equipped with an H-bridge to allow bi-directional motor control. This modification is
given as an assignment at the end of the chapter.
• Proportional speed control with bi-directional motor control. Both of these advanced fea-
tures may be provided by driving the H-bridge circuit with PWM signals. This modifica-
tion is given as an assignment at the end of the chapter.
12.5. SUBMERSIBLE ROBOT 527
Figure 12.16: ROV fully assembled. (Photo courtesy of J. Barrett, Closer to the Sun Interna-
tional, Inc.)
528 12. SYSTEM-LEVEL DESIGN
12.6 MOUNTAIN MAZE NAVIGATING ROBOT
In this project we extend the Dagu Magician maze navigating project described in Chapter 12.9
to a three-dimensional mountain pass. Also, we use a robot equipped with four motorized
wheels. Each of the wheels is equipped with an H-bridge to allow bidirectional motor con-
trol. In this example we will only control two wheels. We leave the development of a 4WD
robot as an end-of-chapter homework assignment.
12.6.1 DESCRIPTION
For this project, a DF Robot 4WD mobile platform kit was used (DFROBOT ROB0003,
Jameco #2124285). The robot kit is equipped with four powered wheels. As in the Dagu Ma-
gician project, we equipped the DF Robot with three Sharp GP2Y0A21YKOF IR sensors as
shown in Figure 12.17. The robot will be placed in a three-dimensional maze with reflective
walls modeled after a mountain pass. The goal of the project is for the robot to detect wall place-
ment and navigate through the maze. The robot will not be provided any information about the
maze. The control algorithm for the robot is hosted on MSP430.
12.6.2 REQUIREMENTS
The requirements for this project are simple, the robot must autonomously navigate through the
maze without touching maze walls as quickly as possible. Furthermore, the robot must be able
to safely navigate through the rugged maze without becoming “stuck” on maze features.
Prototype Area
IR Sensor
Array
Drive Drive
Motor Motor
Prototype Area
IR Sensor
Array
Battery
Compartment
Sensor Connection:
5 VDC 5 VDC 5 VDC
- Red: 5 VDC
- Yellow: Signal output
- Black: Ground
.3 1,
,2 ,
,2 ,
.4 J3
.5 J3
P1 3, J
,6
8
P1 3,
P1 5,
A
A
Program
Note: 3.3 VDC
Sparkfun LCD-09067
DPDT jumper removed Basic 16 × 2 character LCD
5 VDC
Switch white on black, 3.3 VDC
9 VDC Power Umbilical
From TX pin
7805
Run
J1, P6.0, 4 line1
5 VDC
reg 5.0 VDC line2
LM1084-3.3
3.3 VDC
reg 3.3 VDC
9 VDC
2A
(#276)
+5 VDC
1M +5 VDC
2 4 l_fwd r_fwd
1 Left Front Right Front
l_motors_forward 3 LM324 l_rev r_rev
H-bridge H-bridge
J4, P3.7, 40, PWM 1M 11
1M
6 H-bridge
7
l_motors_reverse 5 LM324
J4, P3.6, 39, PWM 1M l_fwd r_fwd 7.5 VDC
Left Rear Right Rear
l_rev r_rev
H-bridge H-bridge
1M 200
200
9 TIP31
8 11DQ06 11DQ06 TIP31 1000μF
r_motors_forward 10 LM324
J4, P3.5, 38, PWM
1M
M
1M Forward
13 11DQ06 11DQ06
14 TIP31 TIP31
r_motors_reverse 12 LM324 470
TIP32 TIP32
J4, P3.4, 37, PWM 1M
Reverse
Figure 12.18: Robot circuit diagram. (Illustration used with permission of Texas Instruments
(www.ti.com).)
determine_robot
_action
Robot Sensor
Action Data
Desired
Motor Ch for Conv
Action Conv Data
Left Wheel Right
LCD ADC12 Count
putchar putcomm PWM_left PWM_right ReadADC12 Wheel Wheel
Initialize Initialize
Count Interrupts Count
Include files
Global variables
Function prototypes
Initialize pins
Initialize ADC
Initialize PWM
Initialize LCD
while(1)
Determine robot
action
Figure 12.20: Abbreviated robot UML activity diagram. The “determine robot action” consists
of multiple decision statements.
12.6. MOUNTAIN MAZE NAVIGATING ROBOT 533
12.6.6 ROBOT CODE
The code for the robot may be adapted from that for the Dagu Magician robot. Since the motors
are equipped with an H-bridge, slight modifications are required to the robot turning code. These
modifications include an additional signal (forward=reverse) for each H-bridge configuration to
provide forward and reverse capability. For example, when forward is desired a PWM signal is
delivered to one side of the H-bridge and a logic zero to the other side. A level shifter (Texas
Instruments PCA9306) is used to adapt the 3.3 VDC signal output from MSP430 LaunchPad
to 5.0 VDC levels.
We only provide the basic framework for the code here.
//***********************************************************************
//robot
//
//Three IR sensors (left, middle, and right) are mounted on the leading
//edge of the robot to detect maze walls. The sensors' outputs are
//fed to three separate ADC channels on pins 6, 27, and 28.
//
//The robot is equipped with:
// - serial LCD at Serial 1 accessible at:
// - RX: P6.1, pin 3
// - TX: P6.0, pin 4
// - LEDs to indicate wall detection: 31, 32, 33
// - Robot motors are driven by PWM channels via an H-bridge.
// - the same control signal is sent to left paired motors
// and the right paired motors.
// - For example, when forward robot movement is desired,
// PWM signals are sent to both of the left and right forwards
// signals and a logic zero signal to the left and right
// reverse signals.
// - To render a left robot turn, a PWM signal is sent to the
// left_reverse control line and a logic zero to the left_forward
// control line. Also, a PWM signal is sent to the right_forward
// control line and a logic zero to the right_reverse
// control line.
// The signals are held in this configuration until the wheel
// encoders indicate the turns have been completed. The wheel
// encoders provide ten counts per revolution.
// - A separate interrupt is used to count left and right wheel counts.
//
//This example code is in the public domain.
534 12. SYSTEM-LEVEL DESIGN
//*******************************************************************
//motor outputs
#define l_motors_forward 40 //digital pin - left motors forward
#define l_motors_reverse 39 //digital pin - left motors reverse
#define r_motors_forward 38 //digital pin - right motors forward
#define r_motors_reverse 37 //digital pin - right motors reverse
//sensor value
int left_IR_sensor_value; //declare variable for left IR sensor
int center_IR_sensor_value; //declare variable for center IR sensor
int right_IR_sensor_value; //declare variable for right IR sensor
void setup()
{
troubleshoot = 1;
//enable serial monitor
if(troubleshoot == 1) Serial.begin(9600);
//Initialize serial channel 1 to 9600 BAUD and wait for port to open
//Serial LCD, 3.3 VDC connected to P3.3, pin 4 Sparkfun LCD-09052
Serial1.begin(9600);
delay(1000); //allow LCD to boot up
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);
//to LCD
Serial1.write(254); //Command to LCD
delay(5);
Serial1.write(1); //Cursor to home position
delay(5);
delay(500);
}
}
//***********************************************************************
Figure 12.22: Robot in maze. (Photo courtesy of J. Barrett, Closer to the Sun International,
Inc.).
• Develop a 4WD system which includes a tilt sensor. The robot should increase motor
RPM (duty cycle) for positive inclines and reduce motor RPM (duty cycle) for negatives
inclines.
• Equip the robot with an analog inertial measurement unit (IMU) to measure vehicle tilt.
Use the information provided by the IMU to optimize robot speed going up and down
steep grades.
12.7 SUMMARY
In this chapter, we discussed the design process, related tools, and applied the process to a real-
world design. It is essential to follow a systematic, disciplined approach to embedded systems
design to successfully develop a prototype that meets established requirements.
12.8. REFERENCES AND FURTHER READING 543
12.8 REFERENCES AND FURTHER READING
Anderson, M. Help wanted: Embedded engineers why the United States is losing its edge in
embedded systems. IEEE—USA Today’s Engineer, February 2008. 488
Barrett, S. F. and Pack, D. J. Atmel AVR Processor Primer Programming and In-
terfacing, Morgan & Claypool Publishers, 2008. www.morganclaypool.com DOI:
10.2200/s00100ed1v01y200712dcs015.
Barrett, S. F. and Pack, D. J. Embedded Systems Design and Applications with the 68HC12 and
HCS12, Pearson Prentice Hall, Upper Saddle River, NJ, 2005.
Barrett, S. F. and Pack, D. J. Embedded Systems Design with the Atmel Microcontroller, Morgan
& Claypool Publishers, 2010. DOI: 10.2200/s00225ed1v01y200910dcs025.
Bohm, H. and Jensen, V. Build your Own Underwater Robot and Other Wet Projects, 11th ed.,
Westcoast Words, Vancouver, BC, Canada, 2012. 506
Christ, R. and Wernli, R. Sr. The ROV Manual—A User Guide for Remotely Operated Vehicle, 2nd
ed., Oxford, UK Butterworth–Heinemann imprint of Elsevier, 2014.
Dale, N. and Lilly, S. C. Pascal Plus Data Structures, 4th ed., Jones and Bartlett, Englewood
Cliffs, NJ, 1995. 491
Fowler, M. with K. Scott. UML Distilled A Brief Guide to the Standard Object Modeling Language,
2nd ed., Addison–Wesley, Boston, MA, 2000. 491, 492
Texas Instruments MSP430FR4xx and MSP430FR2xx Family User’s Guide, (SLAU445G), Texas
Instruments, 2016.
3. What is the purpose of the structure chart, UML activity diagram, and circuit diagram?
4. Why is a system design only as good as the test plan that supports it?
5. During the testing process, when an error is found and corrected, what should now be
accomplished?
9. For the Dagu Magician robot, modify the PWM turning commands such that the PWM
duty cycle and the length of time the motors are on are sent in as variables to the function.
10. For the Dagu Magician robot, equip the motor with another IR sensor that looks down for
“land mines.” A land mine consists of a paper strip placed in the maze floor that obstructs
a portion of the maze. If a land mine is detected, the robot must deactivate it by rotating
about its center axis three times and flashing a large LED while rotating.
11. For the Dagu Magician robot, develop a function for reversing the robot.
12. Provide a powered dive and surface thruster for the SeaPerch ROV. To provide for a
powered dive and surface capability, the ROV must be equipped with a vertical thruster
equipped with an H-bridge to allow for motor forward and reversal.
13. Provide a left and right thruster reverse for the SeaPerch ROV. Currently, the left and right
thrusters may only be powered in one direction. To provide additional maneuverability, the
left and right thrusters could be equipped with an H-bridge to allow bi-directional motor
control.
14. Provide proportional speed control with bi-directional motor control for the SeaPerch
ROV. Both of these advanced features may be provided by driving the H-bridge circuit
with PWM signals.
15. For the 4WD robot, modify the PWM turning commands such that the PWM duty cycle
and the length of time the motors are on are sent in as variables to the function.
12.9. CHAPTER EXERCISES 545
16. For the 4WD robot, equip the motor with another IR sensor that looks down for “land
mines.” A land mine consists of a paper strip placed in the maze floor that obstructs a
portion of the maze. If a land mine is detected, the robot must deactivate it by rotating
about its center axis three times and flashing a large LED while rotating.
17. For the 4WD robot, develop a function for reversing the robot.
18. For the 4WD robot, the current design is a two-wheel, front-wheel drive system. Modify
the design for a two-wheel, rear-wheel drive system.
19. For the 4WD robot, the current design is a two wheel, front wheel drive system. Modify
the design for a 4WD system.
20. For the 4WD robot, develop a 4WD system which includes a tilt sensor. The robot should
increase motor RPM (duty cycle) for positive inclines and reduce motor RPM (duty cycle)
for negatives inclines.
21. Equip the robot with an inertial measurement unit (IMU) to measure vehicle tilt. Use
the information provided by the IMU to optimize robot speed going up and down steep
grades.
22. Develop an embedded system controlled dirigible/blimp (www.microflight.com,www.
rctoys.com).
23. Develop a trip odometer for your bicycle (Hint: use a Hall Effect sensor to detect tire
rotation).
24. Develop a timing system for a four lane Pinewood Derby track.
25. Develop a playing board and control system for your favorite game (Yahtzee, Connect
Four, Battleship, etc.).
26. You have a very enthusiastic dog that loves to chase balls. Develop a system to launch balls
for the dog.
27. Construct the UML activity diagrams for all functions related to the weather station.
28. It is desired to updated weather parameters every 15 min. Write a function to provide a
15 min delay.
29. Add one of the following sensors to the weather station:
• anemometer
• barometer
• hygrometer
546 12. SYSTEM-LEVEL DESIGN
• rain gauge
• thermocouple
You will need to investigate background information on the selected sensor, develop an
interface circuit for the sensor, and modify the weather station code.
30. Modify the weather station software to also employ the 138 x 110 LCD. Display pertinent
weather data on the display.
31. Voice output (Hint: Use an ISD 4003 Chip Corder.)
32. Develop an embedded system controlled submarine (www.seaperch.org).
33. Equip the MSP430 with automatic cell phone dialing capability to notify you when a fire
is present in your home.
547
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
548 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]
549
Index