100% found this document useful (1 vote)
806 views301 pages

Microcontrollerprogramming Msp430fr2433andmsp430fr5994 Part2 PDF

Uploaded by

Andrei Lazar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
806 views301 pages

Microcontrollerprogramming Msp430fr2433andmsp430fr5994 Part2 PDF

Uploaded by

Andrei Lazar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 301

Series ISSN: 1932-3166

BARRETT • PACK
Series Editor: Mitchell A. Thornton, Southern Methodist University

Microcontroller Programming and Interfacing with Texas Instruments


MSP430FR2433 and MSP430FR5994, Second Edition
Microcontroller Programming
and Interfacing with Texas

MICROCONTROLLER PROGRAMMING AND INTERFACING WITH TEXAS


INSTRUMENTS MSP430FR2433 AND MSP430FR5994, SECOND EDITION
Steven F. Barrett, University of Wyoming
Daniel J. Pack, University of Tennessee Chattanooga

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

MORGAN & CLAYPOOL


development topics, published quickly, in digital and print formats.

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.

Microcontroller Programming and Interfacing with Texas Instruments MSP430FR2433


and MSP430FR5994 – Part II, Second Edition
Steven F. Barrett and Daniel J. Pack
2019

Synthesis of Quantum Circuits vs. Synthesis of Classical Reversible Circuits


Alexis De Vos, Stijn De Baerdemacker, and Yvan Van Rentergen
2018

Boolean Differential Calculus


Bernd Steinbach and Christian Posthoff
2017

Embedded Systems Design with Texas Instruments MSP432 32-bit Processor


Dung Dang, Daniel J. Pack, and Steven F. Barrett
2016

Fundamentals of Electronics: Book 4 Oscillators and Advanced Electronics Topics


Thomas F. Schubert and Ernest M. Kim
2016

Fundamentals of Electronics: Book 3 Active Filters and Amplifier Frequency


Thomas F. Schubert and Ernest M. Kim
2016
iii
Bad to the Bone: Crafting Electronic Systems with BeagleBone and BeagleBone Black,
Second Edition
Steven F. Barrett and Jason Kridner
2015

Fundamentals of Electronics: Book 2 Amplifiers: Analysis and Design


Thomas F. Schubert and Ernest M. Kim
2015

Fundamentals of Electronics: Book 1 Electronic Devices and Circuit Applications


Thomas F. Schubert and Ernest M. Kim
2015

Applications of Zero-Suppressed Decision Diagrams


Tsutomu Sasao and Jon T. Butler
2014

Modeling Digital Switching Circuits with Linear Algebra


Mitchell A. Thornton
2014

Arduino Microcontroller Processing for Everyone! Third Edition


Steven F. Barrett
2013

Boolean Differential Equations


Bernd Steinbach and Christian Posthoff
2013

Bad to the Bone: Crafting Electronic Systems with BeagleBone and BeagleBone Black
Steven F. Barrett and Jason Kridner
2013

Introduction to Noise-Resilient Computing


S.N. Yanushkevich, S. Kasai, G. Tangim, A.H. Tran, T. Mohamed, and V.P. Shmerko
2013

Atmel AVR Microcontroller Primer: Programming and Interfacing, Second Edition


Steven F. Barrett and Daniel J. Pack
2012

Representation of Multiple-Valued Logic Functions


Radomir S. Stankovic, Jaakko T. Astola, and Claudio Moraga
2012

Arduino Microcontroller: Processing for Everyone! Second Edition


Steven F. Barrett
2012
iv
Advanced Circuit Simulation Using Multisim Workbench
David Báez-López, Félix E. Guerrero-Castro, and Ofelia Delfina Cervantes-Villagómez
2012

Circuit Analysis with Multisim


David Báez-López and Félix E. Guerrero-Castro
2011

Microcontroller Programming and Interfacing Texas Instruments MSP430, Part I


Steven F. Barrett and Daniel J. Pack
2011

Microcontroller Programming and Interfacing Texas Instruments MSP430, Part II


Steven F. Barrett and Daniel J. Pack
2011

Pragmatic Electrical Engineering: Systems and Instruments


William Eccles
2011

Pragmatic Electrical Engineering: Fundamentals


William Eccles
2011

Introduction to Embedded Systems: Using ANSI C and the Arduino Development


Environment
David J. Russell
2010

Arduino Microcontroller: Processing for Everyone! Part II


Steven F. Barrett
2010

Arduino Microcontroller Processing for Everyone! Part I


Steven F. Barrett
2010

Digital System Verification: A Combined Formal Methods and Simulation Framework


Lun Li and Mitchell A. Thornton
2010

Progress in Applications of Boolean Functions


Tsutomu Sasao and Jon T. Butler
2009

Embedded Systems Design with the Atmel AVR Microcontroller: Part II


Steven F. Barrett
2009
v
Embedded Systems Design with the Atmel AVR Microcontroller: Part I
Steven F. Barrett
2009

Embedded Systems Interfacing for Engineers using the Freescale HCS08 Microcontroller
II: Digital and Analog Hardware Interfacing
Douglas H. Summerville
2009

Designing Asynchronous Circuits using NULL Convention Logic (NCL)


Scott C. Smith and JiaDi
2009

Embedded Systems Interfacing for Engineers using the Freescale HCS08 Microcontroller
I: Assembly Language Programming
Douglas H.Summerville
2009

Developing Embedded Software using DaVinci & OMAP Technology


B.I. (Raj) Pawate
2009

Mismatch and Noise in Modern IC Processes


Andrew Marshall
2009

Asynchronous Sequential Machine Design and Analysis: A Comprehensive Development


of the Design and Analysis of Clock-Independent State Machines and Systems
Richard F. Tinder
2009

An Introduction to Logic Circuit Testing


Parag K. Lala
2008

Pragmatic Power
William J. Eccles
2008

Multiple Valued Logic: Concepts and Representations


D. Michael Miller and Mitchell A. Thornton
2007

Finite State Machine Datapath Design, Optimization, and Implementation


Justin Davis and Robert Reese
2007
vi
Atmel AVR Microcontroller Primer: Programming and Interfacing
Steven F. Barrett and Daniel J. Pack
2007

Pragmatic Logic
William J. Eccles
2007

PSpice for Filters and Transmission Lines


Paul Tobin
2007

PSpice for Digital Signal Processing


Paul Tobin
2007

PSpice for Analog Communications Engineering


Paul Tobin
2007

PSpice for Digital Communications Engineering


Paul Tobin
2007

PSpice for Circuit Theory and Electronic Devices


Paul Tobin
2007

Pragmatic Circuits: DC and Time Domain


William J. Eccles
2006

Pragmatic Circuits: Frequency Domain


William J. Eccles
2006

Pragmatic Circuits: Signals and Filters


William J. Eccles
2006

High-Speed Digital System Design


Justin Davis
2006

Introduction to Logic Synthesis using Verilog HDL


Robert B.Reese and Mitchell A.Thornton
2006
vii
Microcontrollers Fundamentals for Engineers and Scientists
Steven F. Barrett and Daniel J. Pack
2006
Copyright © 2019 by Morgan & Claypool

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.

Microcontroller Programming and Interfacing with Texas Instruments MSP430FR2433


and MSP430FR5994, Second Edition
Steven F. Barrett and Daniel J. Pack
www.morganclaypool.com

ISBN: 9781681736242 paperback


ISBN: 9781681736266 ebook
ISBN: 9781681736273 hardcover
DOI 10.2200/S00937ED2V02Y201907DCS056

A Publication in the Morgan & Claypool Publishers series


SYNTHESIS LECTURES ON DIGITAL CIRCUITS AND SYSTEMS

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

SYNTHESIS LECTURES ON DIGITAL CIRCUITS AND SYSTEMS #56

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

7 Timer Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281


7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
7.2 Motivation: Real-Time Location Systems (RTLS) . . . . . . . . . . . . . . . . . . . . 281
7.3 Time-Related Signal Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
7.3.1 Frequency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
7.3.2 Period . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
7.3.3 Duty Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
7.3.4 Pulse Width Modulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
7.4 Overview of MSP430 Timer Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
7.5 Energia-Related Time Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
7.6 Watchdog Timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
7.6.1 Protecting from Software Failure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
7.6.2 Interval Timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
7.7 Real-Time Clock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
7.8 Real-Time Clock-MSP430FR2433 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
7.8.1 Real-Time Clock: RTC_B, RTC_C-MSP430FR5994 . . . . . . . . . . 295
7.8.2 RTC Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
7.9 Input Capture and Output Compare Features . . . . . . . . . . . . . . . . . . . . . . . . 302
7.9.1 Timing System Overview and Background Theory . . . . . . . . . . . . . . 302
7.9.2 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
7.10 MSP430 Timers: Timer_A and Timer_B . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
7.10.1 MSP430 Free Running Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
7.10.2 Input Capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
7.10.3 Output Compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
7.10.4 Timer_B System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
7.11 Laboratory Exercise: Generation of Varying Pulse Width Modulated
Signals to Control DC Motors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
xiv
7.12 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
7.13 References and Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
7.14 Chapter Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328

8 Resets and Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331


8.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
8.2 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
8.3 MSP430 Resets/Interrupts Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
8.4 MSP430 Resets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
8.5 Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
8.5.1 Interrupt Handling Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
8.5.2 Interrupt Priority . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
8.5.3 Interrupt Service Routine (ISR) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
8.6 Laboratory Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
8.7 References and Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
8.8 Chapter Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356

9 Analog Peripherals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357


9.1 Analog-to-Digital Conversion Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
9.1.1 Sampling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
9.1.2 Quantization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
9.1.3 Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
9.2 Digital-to-Analog Converter Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
9.3 MSP430 ADC Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
9.3.1 MSP 430 ADC Block Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
9.3.2 MSP430FR2433 10-bit Analog-to-Digital Converter . . . . . . . . . . . 366
9.3.3 MSP430FR2433 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . 371
9.3.4 Programming the MSP430FR2433 ADC in C . . . . . . . . . . . . . . . . 373
9.4 MSP430FR5994 Analog-to-Digital Converter . . . . . . . . . . . . . . . . . . . . . . . 376
9.4.1 ADC12_B Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
9.4.2 MSP430FR5994 ADC12_B Operation . . . . . . . . . . . . . . . . . . . . . . 377
9.4.3 MSP430FR5994 Register Summary . . . . . . . . . . . . . . . . . . . . . . . . . 379
9.4.4 Analysis of Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
9.4.5 Programming the MSP430FR5994 ADC12_B System . . . . . . . . . . 381
9.5 MSP430FR5994 Comparator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
9.6 Advanced Analog Peripherals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
xv
9.6.1 Smart Analog Combo (SAC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
9.6.2 Enhanced Comparator (eCOMP) . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
9.6.3 Transimpedance Amplifier (TIA) . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
9.7 Laboratory Exercise: Smart Home Sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
9.8 References and Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
9.9 Chapter Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392

10 Communication Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395


10.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
10.2 Serial Communication Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
10.3 MSP430 UART . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
10.3.1 UART Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
10.3.2 UART Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
10.3.3 Character Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
10.3.4 Baud Rate Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
10.3.5 UART Associated Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
10.3.6 UART Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
10.4 Code Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
10.4.1 Energia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
10.4.2 UART C Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
10.5 Serial Peripheral Interface-SPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
10.5.1 SPI Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
10.5.2 MSP430 SPI Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
10.5.3 MSP430 SPI Hardware Configuration . . . . . . . . . . . . . . . . . . . . . . . 412
10.5.4 SPI Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
10.5.5 SPI Code Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
10.6 Inter-Integrated Communication – I2 C Module . . . . . . . . . . . . . . . . . . . . . . 441
10.6.1 I2 C Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
10.6.2 I2 C Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
10.6.3 MSP430 as a Slave Device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
10.6.4 MSP430 as a Master Device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
10.6.5 I2 C Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
10.6.6 Programming the I2 C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
10.7 Laboratory Exercise: UART and SPI Communications . . . . . . . . . . . . . . . . . 457
10.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
10.9 References and Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
10.10 Chapter Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
xvi
11 MSP430 System Integrity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
11.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
11.2 Electromagnetic Interference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
11.2.1 EMI reduction Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
11.3 Cyclic Redundancy Check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
11.3.1 MSP430FR5994 CRC32 Module . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
11.3.2 CRC16 Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
11.3.3 CRC32 Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
11.4 AES256 Accelerator Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
11.4.1 Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
11.4.2 API Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
11.5 Laboratory Exercise: AES256 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
11.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
11.7 References and Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
11.8 Chapter Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484

12 System-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487


12.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
12.2 What is an Embedded System? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
12.3 Embedded System Design Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
12.3.1 Project Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
12.3.2 Background Research . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
12.3.3 Pre-Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
12.3.4 Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
12.3.5 Implement Prototype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
12.3.6 Preliminary Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
12.3.7 Complete and Accurate Documentation . . . . . . . . . . . . . . . . . . . . . . 493
12.4 MSP430FR5994: Weather Station . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
12.4.1 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
12.4.2 Structure Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
12.4.3 Circuit Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
12.4.4 UML Activity Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
12.4.5 Microcontroller Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
12.4.6 Project Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
12.5 Submersible Robot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
12.5.1 Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
xvii
12.5.2 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
12.5.3 ROV Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
12.5.4 Structure Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
12.5.5 Circuit Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
12.5.6 UML Activity Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
12.5.7 MSP430 Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
12.5.8 Control Housing Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
12.5.9 Final Assembly Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
12.5.10 Final Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
12.5.11 Project Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
12.6 Mountain Maze Navigating Robot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
12.6.1 Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
12.6.2 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
12.6.3 Circuit Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
12.6.4 Structure Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
12.6.5 UML Activity Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
12.6.6 Robot Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
12.6.7 Mountain Maze . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
12.6.8 Project Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
12.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
12.8 References and Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
12.9 Chapter Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544

Authors’ Biographies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547

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.

Steven F. Barrett and Daniel J. Pack


July 2019

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

Table 1: MSP-EXP430FR5994 and the MSP-EXP430FR2433 LaunchPad subsystems.

Chapter MSP- EXP430FR2433 MSP-EXP430FR5994


Ch. 1: Introduction
Ch. 2: Programming MSP430 port system MSP430 port system
Ch. 3: HW and SW Joint Test Action Group ( JTAG) Joint Test Action Group ( JTAG)
serial debug port, Enhanced serial debug port, Enhanced
Emulation Module (EEM) onboard Emulation Module (EEM) on-
debug tool, serial Spy-Bi-Wire board debug tool, serial Spy-Bi-
(SBY) JTAG Wire (SBY) JTAG
Ch. 4: Interfacing MSP430 port system MSP430 port system
Ch. 5: Power Mgt Power Mgt Module Power Mgt: LDO, SVS,
Brownout
Ch. 6: Memory FRAM: 15KB + 512B FRAM: 256KB
RAM: 4KB RAM: 4 KB + 4 KB
DMA Controller
Memory Protection Unit (MPU)
IP Encapsulation Segment (IPE)
Ch. 7: Timer Systems Clock system (CS), LFXT Clock system (CS),
- Clock Timer_A3(2), Timer_A2(2) TB0: Timer_B, TA0: Timer_A,
- Timers Watchdog, Real-Time Clock TA1: Timer_A, TA4: Timer_A,
Watchdog, Real-Time Clock
Ch. 8: Resets and Interrupts
Ch. 9: Analog Peripherals ADC: 8 ch, SE, 10-bit, 200 ksps Comp_E: 16 ch, Ref_A
ADC 12_B: 16 ch SE/8 DE, 12-bit
Ch. 10: Comm Sys eUSCI_A(2) eUSCI_A(4) (A0 to A3)
- UART, IrDA, SPI - UART, IrDA, SPI
eUSCI_B0 eUSCI_B(4) (B0 to B3)
- SPI, I2C - SPI, I2C
Ch. 11: System Integrity CRC16: 16-bit cyclic redun- CRC16: CRC-16-CCITT
dancy check CRC32: CRC-32-ISO-3309
AES 256: security encryption/
decryption
Ch. 12: System Design
xxv

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.

Steven F. Barrett and Daniel J. Pack


July 2019
281

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.2 MOTIVATION: REAL-TIME LOCATION SYSTEMS


(RTLS)
CenTrak, Incorporated provides tracking solutions for the medical community. One of their
products, the InTouch CareTM Real Time Location System is used to track doctors, nurses,
282 7. TIMER SYSTEMS
medical staff, patients, and medical equipment. The MSP430’s ability to operate with minimal
power allows the InTouch Care to operate for six months without the need for a change of
batteries. The timer system of the MSP430 embedded in the InTouch Care system is used to
inform the system’s location periodically to a central control location for tracking. Each InTouch
Care unit comes with the DualTrackTM communication system that utilizes radio frequency
and infrared signals to transmit locations and receive commands. The system is used currently
to streamline patient and equipment tracking in a number of medical facilities in the United
States.

7.3 TIME-RELATED SIGNAL PARAMETERS


Throughout the history of microcontrollers, one of the main challenges was the need to operate
with minimal power. The motivation comes from microcontroller applications that require a
controller operating remotely without a continuous external power source. Since the power used
by a microcontroller is directly proportional to the speed of transistors switching logic states,
computer designers implemented multiple methods to reduce the clock speed. One method was
to design a controller such that the CPU operates at a high clock speed while other subsystems
run at a lower clock speed.
Such architectures with multiple clock sources can also allow programmers/engineers to
turn off subsystems while they are not in use, saving more power for the overall embedded
system. The MSP430 designers adopted this philosophy of providing users with multiple clock
sources such that, depending on applications, one can have the flexibility to configure his or her
controller appropriately. The flexible clock features of the MSP430 were previously discussed in
Chapter 12.9.
Before proceeding forward, we briefly review time-related signal parameters.

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.

7.3.3 DUTY CYCLE


In many applications, periodic pulses are used as control signals of devices. A good example is
the use of a periodic pulse to control a servo motor. To control the direction and sometimes
the speed of a motor, a periodic pulse signal with a changing duty cycle over time is used. The
periodic pulse signal shown in Figure 7.1 frame (a) is on for 50% of the signal period and off
for the rest of the period. The pulse shown in frame (b) is on for only 25% of the same period as
the signal in frame (a) and off for 75% of the period. The duty cycle is defined as the percentage
of one period a signal is on. Therefore, we call the signal in frame (a) in Figure 7.1 as a periodic
pulse signal with a 50% duty cycle and the corresponding signal in frame (b), a periodic pulse
signal with a 25% duty cycle.

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

Figure 7.2: An example setup for controlling a DC motor.


7.4. OVERVIEW OF MSP430 TIMER FEATURES 285
7.4 OVERVIEW OF MSP430 TIMER FEATURES
Both the MSP430FR2433 and MSP430FR5994 LaunchPads are equipped with a host of timer
features as shown in Figure 7.3. Each of these features will be discussed in upcoming sections
along with code examples.

Clock and Timer


T.I. Product Processor
Features

MSP430FR2433 MSP430FR2433 TIMER0_A3


LaunchPad - 3 capture/compare registers
TIMER1_A3
- 3 capture/compare registers
TIMER2_A2
- 2 capture/compare registers
TIMER3_A2
- 2 capture/compare registers
Real-Time Counter
- 16-bit
Watchdog Timer (WDT_A)

MSP430FR5994 MSP430FR5994 TA0: Timer_A


LaunchPad - 3 capture/compare registers
TA1: Timer_A
- 3 capture/compare registers
TA2: Timer_A
- 2 capture/compare registers
TA3: Timer_A
- 2 capture/compare registers
TA4: Timer_A
- 3 capture/compare registers
TB0: Timer_B
- 7 capture/compare registers
Real-Time Clock B (RTC_B)
Real-Time Clock C (RTC_C)
Watchdog Timer (WDT_A)

Figure 7.3: MSP430 variants.


286 7. TIMER SYSTEMS
7.5 ENERGIA-RELATED TIME FUNCTIONS
For the remainder of the chapter we investigate time-related peripherals onboard the MSP430
including the Watchdog timer, Timer_A, and the Real-Time Clock (RTC_C). Before doing
so, we review time-related functions available within Energia.
The Energia Development Environment has several built-in functions related to timing
events, providing delays, or generating PWM signals. The functions include (www.energia.nu)
the following.
• millis(): This function provides the number of milliseconds that has occurred since the
processor began running the current program.
• micros(): This function provides the number of microseconds that has occurred since the
processor began running the current program.
• delay(): Provides a program pause for the specified number of milliseconds.
• delayMicroseconds(): Provides a program pause for the specified number of microsec-
onds. Note: This function is accurate for values 16,383 s or less.
• analogWrite(): The analogWrite function provides a 490 Hz pulse width modulated signal
on the specified PWM capable pin. The duty cycle is provided as an argument to the
function from 0–255. For example, to specify a 90% duty cycle, the value would be 230.

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.
//***********************************************************************

const int buttonPin = PUSH2; //number of the pushbutton pin


const int ledPin = GREEN_LED; //number of the LED pin

int ledState = HIGH; //current state of the output pin


int buttonState; //current reading from the input pin
int lastButtonState = LOW; //previous reading from the input pin

//the following variables are long's because the time, measured in


//miliseconds, will quickly become a bigger number than can be
//stored in an int.
long lastDebounceTime = 0; //last time output pin toggled
long debounceDelay = 50; //the debounce time; increase if the
//output flickers

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);

//check to see if you just pressed the button


//(i.e., the input went from LOW to HIGH), and you've waited
//long enough since the last press to ignore any noise:
//If the switch changed, due to noise or pressing:
if (reading != lastButtonState)
{
lastDebounceTime = millis();
}
288 7. TIMER SYSTEMS

if ((millis() - lastDebounceTime) > debounceDelay)


{
//whatever the reading is at, it's been there for longer
//than the debounce delay, so take it as the actual current state:
buttonState = reading;
}

//set the LED using the state of the button:


digitalWrite(ledPin, buttonState);

//save the reading. Next time through the loop,


//it'll be the lastButtonState:
lastButtonState = reading;
}

//***********************************************************************

7.6 WATCHDOG TIMER


As the name implies, the primary purpose of the Watchdog timer in a microcontroller is to watch
for and prevent software failure by forcing user code to refresh a designated control register peri-
odically throughout the execution of a program. The secondary purpose of the Watchdog timer
is to generate periodic time intervals for applications that require periodic, repeated services.
By software failure, we mean the execution of unintended instructions by MSP430,
whether it is an unintended infinite loop or a wrong segment of program being executed due
to hardware errors, programmer errors, or noise-related malfunctions. We now present how
the reader can configure the Watchdog system to function as a software failure preventer and a
periodic interval generator.

7.6.1 PROTECTING FROM SOFTWARE FAILURE


The Watchdog timer prevents software failure by enforcing the following rule. A 16-bit regis-
ter, called the Watchdog count (WDTCNT) register, counts up at each clock cycle. When it
reaches its limit, the Watchdog timer system initiates a power up clear reset (PUCR).1 Thus,
your program must clear the counter periodically before the counter reaches its limit. During
normal program execution, counter reset instructions may be placed strategically throughout the
code. When the code executes correctly, the Watchdog timer will be reset on a regular basis, in-
dicating normal operation. However, if the code is not operating correctly, the Watchdog timer
1 Unlike the power-on reset (POR), the power up clear reset (PUCR) does not change the values of the WDTCTL
register.
7.6. WATCHDOG TIMER 289
will not be reset as required ,thus generating a flag or an interrupt. A user can select the limit
values as 64, 512, 8192, or 32,768 (default), which correspond to using the WDTCNT register
as a 6-, 9-, 13-, or 15-bit counter, respectively. The source for the clock cycle can be chosen
either from the SMCLK (default) or the ACLK.
The function of the Watchdog timer is governed by programming the Watchdog timer
control register (WDTCTL). To avoid accidental write to this register, it is password protected,
which means to modify the contents of the register, one must first write 0x5A (password) to the
upper byte of WDTCTL before configuring the Watchdog system using the lower byte of the
same register. MSP430 designers also implemented another safety mechanism by resetting the
controller, if a wrong password is sent to the upper byte of WDTCTL. Figure 7.4 shows the
contents of the 16-bit register.

WatchDog Timer Register (WDTCTL)


15 14 13 12 11 10 9 8
Read as 069h
WDTPW must be written as 05Ah

7 6 5 4 3 2 1 0

WDTHOLD WDTNMIES WDTNMI WDTTMSEL WDTCNTCL WDTSSEL WDTISx

rw-0 rw-0 rw-0 rw-0 r0(w) rw-0 rw-0 rw-0

Figure 7.4: Watchdog timer register WDTCTL.

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:

• 00 – use 15 bit counter and count up to 32,768

• 01 – use 13 bit counter and count up to 8,192

• 10 – use 9 bit counter and count up to 512


290 7. TIMER SYSTEMS
• 11 – use 6 bit counter and count up to 64
The default value of the register selects the 15-bit counter using the SMCLK clock as the time
source.
Associated with the control register is the IFG1 register. When the WDTCNT register
reaches its limit, the WDTIFG flag (bit 0) in the IFG1 register, located at 0x0002, is set. This
flag can be polled or can be used to initiate an interrupt when the Watchdog timer is used as a
periodic interval timer.
Example: The following C code or the corresponding assembly code turns off the Watchdog
timer, which is recommended during program development. Assuming that the registers are al-
ready defined with the proper names, the Watchdog timer may be turned off using the following
C instruction:
WDTCTL = WDTPW + WDTHOLD
In Assembly Language, use:
MOV.W #WDTPW+WDTHOLD, &WDTCTL

7.6.2 INTERVAL TIMER


The Watchdog timer can also be configured to generate a periodic interval. To do so, the
WDTTMSEL bit (bit 4) of the WDTCTL register must be set and the interval period must
be selected using the WDTISx bits (bits 2 to 0) and the WDTSSEL bits (bits 6, 5) of the same
register. When the WDTCNT register reaches the designated limit, the WDTIFG flag in the
Special Function Register SFRIFG1 register is set. If the WDTIE bit (bit 0) in the Special
Function Register Interrupt Enable IE1 register 1 (SFRIE1.0) is set and the GIE bit (overall
maskable interrupt system enable bit in the Status Register) is set, the Watchdog timer interrupt
is triggered. Figure 7.5 shows the components of the interval timer along with the related inter-
rupt system. Once the interrupt is serviced (interrupt service routine is executed), the WDTIFG
flag is automatically cleared.
Example: Provided below is the C code segment that configures the MSP430FR5994 micro-
controller board to toggle the logic state on port 1 pin 0 (red LED onboard the launchpad) every
second.
//***********************************************************************
//MSP430FR5994 Example - WDT, Toggle P1.0, Use of WDT as a timer,
//
//Description: Toggle P1.0 using software timed by WDT ISR. Toggle rate
//is 1 sec based on 32kHz ACLK WDT clock source. In this example, the
//WDT is configured to divide 32768 watch-crystal by 2^15 with an ISR
//triggered at 1Hz.
7.6. WATCHDOG TIMER 291

WDTSSEL
SMCLK WDTCNT
ACLK

Watchdog
Interrupt
System

GIE WDTIE
Limit Reached

WDTIFG

Figure 7.5: Watchdog timer as an interval generator.

//
//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
}

//***********************************************************************

7.7 REAL-TIME CLOCK


RTC features provide microcontrollers the ability to generate a periodic interrupt to accomplish
periodic, important tasks. For example, while operating a motor, it is important to periodically
monitor motor current as an indication of safe, non-obstructed operation. RTC features also
provide the microcontroller to track calendar time based on seconds, minutes, hours, etc. Both
the MSP430FR2433 and the MSP430FR5994 are equipped with RTC features. Since the RTC
features onboard these two processors are different, they will be addressed separately.

7.8 REAL-TIME CLOCK-MSP430FR2433


The MSP430FR2433 is not equipped with calendar-based RTC features. Instead, the
MSP430FR2433 may be equipped with an external RTC (Maxim DS3234) via the serial pe-
ripheral interface. An example is provided in Chapter 10.
The MSP430FR2433 is equipped with a 16-bit counter as shown in Figure 7.6. The
counter may be used to generate a periodic interrupt. The time base for the RTC counter may
be the ACLK, XT1CLK, or VLOCLK depending on the operating mode. The clock may then
be pre-divided using the Real-time clock pre-divider select bits (RTCPS). The divided clock
source signal is provided to the 16-bit counter. The counter’s value is constantly compared to
the value of the 16-bit Shadow register. When the two values are the same, an RTC interrupt
is generated, if enabled.
Example: In this example the MSP430FR2433’s RTC counter is configured to generate a 1 s
periodic interrupt.
7.8. REAL-TIME CLOCK-MSP430FR2433 293
RTCIE
RTCCNT

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

RTCMOD RTCSR RTCIV RTCIF

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)

Real-Time Clock Control Register (RTCCTL)


RTCCTL[13:12]: RTCSS: clock source: 01 = device specific (SMCLK or ACLK) ,
10 = XT1CLK, 11 = VLOCLK
RTCCTL[10:8]: RTCPS: predivider:
000 = 1, 001 = 10, 010 = 100, 011 = 1000, 100 = 16, 101 = 64, 110 = 256, 111 = 1024
RTCCTL[6]: RTCSR: software reset: 1 = clear counter value,
reloads shadow register from modulo register
RTCCTL[1]: RTC interrupt enable: 0 = disabled, 1 = enabled
RTCCTL[0]: RTC interrupt flag: 0 = none pending, 1= interrupt pending

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

P1OUT &= ~BIT0; //Clear P1.0 output latch for


//a defined power-on state
P1DIR |= BIT0; //Set P1.0 to output direction

PM5CTL0 &= ~LOCKLPM5; //Disable the GPIO power-on


//default high-impedance mode
//to activate previously
//configured port settings

RTCMOD = 32-1; //RTC count re-load compare


7.8. REAL-TIME CLOCK-MSP430FR2433 295
//value at 32.
//1024/32768 * 32 = 1 sec.

//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
//*********************************************************************

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)


#pragma vector=RTC_VECTOR
__interrupt void RTC_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(RTC_VECTOR))) RTC_ISR (void)
#else
#error Compiler not supported!
#endif
{
switch(__even_in_range(RTCIV,RTCIV_RTCIF))
{
case RTCIV_NONE: break; //No interrupt
case RTCIV_RTCIF: //RTC Overflow
P1OUT ^= BIT0;
break;
default: break;
}
}

//*********************************************************************

7.8.1 REAL-TIME CLOCK: RTC_B, RTC_C-MSP430FR5994


RTC_B and RTC_C, the MSP430 RTC, provide a clock based on seconds, minutes, hours,
etc. The RTC time base is provided by a 32,768 Hz external crystal. This time base is shown as
the BCLK in Figure 7.7. The time base is routed to the RTOPS and RT1PS dividers to provide
296 7. TIMER SYSTEMS
RTCHOLD

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

RTCDOW RTCHOUR RTCMIN RTCSEC


RTCTEV
2
Minute Changed
00 Set_RTCTEVIFG
Hour Changed 01
Midnight 10
Noon 11

Calendar EN

RTCYEARH RTCYEARL RTCMON RTCDAY

Alarm EN Set_RTCAIFG

RTCADOW RTCADAY RTCAHOUR RTCAMIN

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

7.8.2 RTC REGISTERS


RTC_C is supported by a complement of registers. Details of specific register and bits set-
tings are contained in Texas Instruments MSP430FR58xx, MSP430FR59xx, and MSP430FR6xx
Family SLAU367O [2017] and will not be repeated here. The next two examples illustrate the
use of the RTC in counter and clock mode.
Example. In this example the MSP430FR5994 is employed within the counter mode. An LED
is toggled every second.

//********************************************************************
// --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

//Disable the GPIO power-on default high-impedance mode to activate


//previously configured port settings
PM5CTL0 &= ~LOCKLPM5;

//Configure LFXT 32kHz crystal


CSCTL0_H = CSKEY_H; //Unlock CS registers
CSCTL4 &= ~LFXTOFF; //Enable LFXT
do
{
CSCTL5 &= ~LFXTOFFG; //Clear LFXT fault flag
SFRIFG1 &= ~OFIFG;
}while (SFRIFG1 & OFIFG); //Test oscillator fault flag
CSCTL0_H = 0; //Lock CS registers

//Setup RTC Timer


RTCCTL0_H = RTCKEY_H; //Unlock RTC
RTCCTL0_L = RTCTEVIE_L; //RTC event interrupt enable

//Ctr Mode, RTC1PS, 8-bit ovf


RTCCTL13 = RTCSSEL_2 | RTCTEV_0 | RTCHOLD;
RTCPS0CTL = RT0PSDIV1; //ACLK, /8
7.8. REAL-TIME CLOCK-MSP430FR2433 299
//out from RT0PS, /16
RTCPS1CTL = RT1SSEL1 | RT1PSDIV0 | RT1PSDIV1;
RTCCTL13 &= ~(RTCHOLD); //Start RTC

__bis_SR_register(LPM3_bits | GIE); //Enter LPM3 mode w/int enabled


__no_operation();
return 0;
}

//*******************************************************************
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=RTC_C_VECTOR
__interrupt void RTC_ISR(void)
#elif defined(__GNUC__)

void __attribute__ ((interrupt(RTC_C_VECTOR))) RTC_ISR (void)


#else
#error Compiler not supported!
#endif
{
switch(__even_in_range(RTCIV, RTCIV__RT1PSIFG))
{
case RTCIV__NONE: break; //No interrupts
case RTCIV__RTCOFIFG: break; //RTCOFIFG
case RTCIV__RTCRDYIFG:break; //RTCRDYIFG
case RTCIV__RTCTEVIFG: //RTCEVIFG
P1OUT^= BIT0;//Toggle P1.0 LED
break;
case RTCIV__RTCAIFG: break; //RTCAIFG
case RTCIV__RT0PSIFG: break; //RT0PSIFG
case RTCIV__RT1PSIFG: break; //RT1PSIFG
default: break;
}
}

//********************************************************************

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

//Disable the GPIO power-on default high-impedance mode to activate


7.8. REAL-TIME CLOCK-MSP430FR2433 301
//previously configured port settings
PM5CTL0 &= ~LOCKLPM5;

//Configure LFXT 32kHz crystal


CSCTL0_H = CSKEY_H; //Unlock CS registers
CSCTL4 &= ~LFXTOFF; //Enable LFXT
do
{
CSCTL5 &= ~LFXTOFFG; //Clear LFXT fault flag
SFRIFG1 &= ~OFIFG;
}while (SFRIFG1 & OFIFG); //Test oscillator fault flag
CSCTL0_H = 0; //Lock CS registers
//Configure RTC_C
RTCCTL0_H = RTCKEY_H; //Unlock RTC
RTCCTL0_L = RTCTEVIE_L | RTCRDYIE_L; //enable RTC read ready int
//enable RTC time event int
RTCCTL13 = RTCBCD | RTCHOLD | RTCMODE; //RTC enable, BCD mode, RTC hold

RTCYEAR = 0x2019; //Year = 0x2019


RTCMON = 0x4; //Month = 0x04 = April
RTCDAY = 0x05; //Day = 0x05 = 5th
RTCDOW = 0x01; //Day of week = 0x01 = Monday
RTCHOUR = 0x10; //Hour = 0x10
RTCMIN = 0x32; //Minute = 0x32
RTCSEC = 0x45; //Seconds = 0x45
RTCADOWDAY = 0x2; //RTC Day of week alarm = 0x2
RTCADAY = 0x20; //RTC Day Alarm = 0x20
RTCAHOUR = 0x10; //RTC Hour Alarm
RTCAMIN = 0x23; //RTC Minute Alarm
RTCCTL13 &= ~(RTCHOLD); //Start RTC

__bis_SR_register(LPM3_bits | GIE); //Enter LPM3 mode w/int enabled


__no_operation();
return 0;
}

//********************************************************************
#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__)

void __attribute__ ((interrupt(RTC_C_VECTOR))) RTC_ISR (void)


#else
#error Compiler not supported!
#endif
{
switch(__even_in_range(RTCIV, RTCIV__RT1PSIFG))
{
case RTCIV__NONE: break; //No interrupts
case RTCIV__RTCOFIFG: break; //RTCOFIFG
case RTCIV__RTCRDYIFG: //RTCRDYIFG
P1OUT^=0x01; //Toggles P1.0 every second
break;
case RTCIV__RTCTEVIFG: //RTCEVIFG
__no_operation();// Int every minute - SET
//BREAKPOINT HERE
break;
case RTCIV__RTCAIFG: break; //RTCAIFG
case RTCIV__RT0PSIFG: break; //RT0PSIFG
case RTCIV__RT1PSIFG: break; //RT1PSIFG
default: break;
}
}
//********************************************************************

7.9 INPUT CAPTURE AND OUTPUT COMPARE


FEATURES
In this section, we study the input capture and output compare features of the MSP430 mi-
crocontroller. We begin with background information and the associated theory, followed by
MSP430 specific timer information and application examples.

7.9.1 TIMING SYSTEM OVERVIEW AND BACKGROUND THEORY


As we have learned earlier in this chapter, the heart of the timing system is the time base. The
time base frequency of an oscillating signal is used to generate a baseline clock signal. For a timer
system, the system clock is used to update the contents of a special register called a free running
7.9. INPUT CAPTURE AND OUTPUT COMPARE FEATURES 303
counter. The job of a free running counter is to count up (increment) each time it receives a
rising edge (or a falling edge) of a clock signal. Thus, if a clock is running at the rate of 2 MHz,
the free running counter will count up at every 0.5 s. All other timer-related units reference
the contents of the free running counter to perform I/O time-related activities: measurement of
time periods, capture of timing events, and generation of time-related signals.
For input time-related activities, all microcontrollers typically have timer hardware com-
ponents that detect signal logic changes on one or more input pins. Such components rely on
a free running counter to capture external event times. We can use such ability to measure the
period of an incoming signal, the width of a pulse, and the time of a signal logic change.
You can also use the timer input system to measure the pulse width of an aperiodic signal.
For example, suppose that the times for the rising edge and the falling edge of an incoming
signal are 1.5 s and 1.6 s, respectively. We can use these values to easily compute the pulse width
of 0.1 s.
The second overall goal of the timer system is to generate signals to control external de-
vices. Again, an event simply means a change of logic states on an output pin of a microcontroller
at a specified time. Now consider Figure 7.8. Suppose an external device connected to the mi-
crocontroller requires a pulse signal to turn itself on. Suppose the particular pulse the external
device needs is 2 millisecond wide. In such situations, we can use the free running counter value
to synchronize the time of desired logic state changes. Naturally, extending the same capability,
we can also generate a periodic pulse with a fixed duty cycle or a varying duty cycle.
For output timer functions, a microcontroller uses a comparator, a free running counter,
logic switches, and special purpose registers to generate time-related signals on one or more
output pins. A comparator checks the value of the free running counter for a match with the
contents of another special purpose register where a programmer stores a specified time in terms
of the free running counter value. The checking process is executed at each clock cycle and when
a match occurs, the corresponding hardware system induces a programmed logic change on a
programmed output port pin. Using such capability, one can generate a simple logic change at
a designated time incident: a pulse with a desired time width or a pulse width modulated signal
to control servo or direct current (DC) motors.
From the examples we discussed above, you may have wondered how a microcontroller
can compute absolute times from the relative free running counter values, say 1.5 s and 1.6 s.
The simple answer is that we cannot do so directly. A programmer must use the relative system
clock values and derive the absolute time values. Suppose your microcontroller is clocked by
a 2 MHz signal and the system clock uses a 16-bit free running counter. For such a system,
each clock period represents 0.5 s, and it takes approximately 32.78 ms to count from 0 to 216
(65,536). The timer input system then uses the clock values to compute frequencies, periods,
and pulse widths. Again, suppose you want to measure a pulse width of an incoming aperiodic
signal. If the rising edge and the falling edge occurred at count values $0010 and $0114,2 can

2 The $ symbol represents that the following value is in a hexadecimal form.


304 7. TIMER SYSTEMS

Special Storage Comparator Free-Running


Register Counter

Programmed
Event
Timer Output
- Toggle
Flag
- Logic High
- Logic Low

Timer Output Physical


Interrupt Output
System Pin

Figure 7.8: A diagram of a timer output system.

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:

elapsed clock ticks D .n  2b / C .stop count start count/Œclock ticks

elapsed time D .elapsed clock ticks/  .FRC clock period/ Œseconds:

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.

Input Capture—Measuring External Timing Event


In many applications, we are interested in measuring the elapsed time or the frequency of an
external event using a microcontroller. Using the hardware and functional units discussed in the
previous sections, we now present a procedure to accomplish the task of computing the frequency
of an incoming periodic signal. Suppose that we are interested in calculating the time features
of the signal shown in Figure 7.9, an incoming periodic signal to the microcontroller.
The first necessary step for the current task is to turn on the timer system. As discussed,
to reduce power consumption, a microcontroller usually does not turn on all of its functional
systems after reset until they are needed. In addition to a separate timer module, many micro-
controller manufacturers allow a programmer to choose the rate of a separate timer clock that
governs the overall functions of a timer module.

Microcontroller

Timer Input Port External


Device 1

Timer Output Port External


Device n

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.

Output Compare—Generating Timing Signals to Interface External Devices


In the previous two sections, we considered two applications of capturing external incoming
signals. In this section and the next one, we consider how a microcontroller can generate time
critical signals for use by external devices. Suppose in this application, we want to send a sig-
nal shown in Figure 7.9 to turn on an external device. The timing signal is arbitrary, but the
application will show that a timer output system can generate any desired time-related signals,
permitted under the timer clock speed limit of the microcontroller.
Similar to the use of the timer input system, one must first turn on the timer system
and configure a physical pin as a timer output pin using special registers. In addition, one also
needs to program the desired external event using a special register associated with the timer
output system. To generate the signal shown in Figure 7.9, one must compute the time required
between the rising and the falling edges. Suppose also that the external device requires a pulse
which is 2 ms wide to be activated. To generate the desired pulse, one must first program the
logic state for the particular pin to be low and set the time value using a special register with
respect to the contents of the free running counter. As was previously mentioned, at each clock
cycle, the special register contents are compared with the contents of the free running counter,
and when a match occurs, the programmed logic state appears on the designated hardware pin.
Once the rising edge is generated, the program then must reconfigure the event to be a falling
edge (logic state low) and change the contents of the special register to be compared with the
free running counter. For the particular example in Figure 7.9, let’s assume that the main clock
runs at 2 MHz, the free running counter is a 16-bit counter, and the name of the special register
(16-bit register) where we can put appropriate values is output timer register. To generate the
desired pulse, we can put $0000 first to the output timer register, and after the rising edge has
been generated, we need to change the program event to a falling edge and put $0FA0 or 4000
in decimal to the output timer register. As was the case with the input timer system module, we
can use output timer system interrupts to generate the desired signals as well.

7.10 MSP430 TIMERS: TIMER_A AND TIMER_B


All MSP430 microcontrollers have both Timer_A and Timer_B I/O ports that can be used to
capture external signal events and generate time-related signals for external devices. The captured
external signal events include time stamped logic state changes, the frequency of a periodic sig-
308 7. TIMER SYSTEMS
nal, a width of a pulse to name a few. The time-related output signals range from a simple change
of logic levels on an output pin at a designated time to generation of PWM signals. We present
both input capture and output compare subsystem capabilities in this section. Both Timer_A
and Timer_B systems can be configured to function as capture and compare input/output ports.
The Timer_A system is present in all MSP430 controllers while Timer_B, with more advanced
capture and compare capabilities, is found in higher-end MSP430 family members. Much of
the discussion on Timer_A applies to Timer_B. The MSP430FR2433 and the MSP430FR5994
are both equipped with a complement of Timer_A and Timer_B timers.
The block diagram for Timer_A is shown in Figure 7.10. The main timer feature is a 16-
bit configurable up/down timer (TAxR). The timer may be clocked from a variety of sources
including the TAxCLK, ACLK, and the SMCLK. The clock source may be reduced by a series
dividers (ID, IDEX). Timer_A (and B) may be used for multiple captures and compares, pulse
width modulation, interval timing, and timer-based interrupts. Timer features are configured
using the Timer_A Control Register (TAxCTL) shown in Figure 7.11. As shown in Figure 7.11,
Timer_A (and B) may be configured for up, continuous, and up/down modes.

7.10.1 MSP430 FREE RUNNING COUNTER


In the Timer_A system, there are two to three different I/O subsystems (channels) that can
be configured independently. For the Timer_B system, the number of I/O channels vary from
three to seven. Since each channel for Timer_A and Timer_B systems has the identical hard-
ware and functional capabilities, we present only a single channel of the Timer_A system. The
source of all timer subsystems, whether they are used to capture input signal characteristics or
to generate output time-related signals, is a free running 16-bit counter, the TAxR register and
TBxR register. The counter counts up (can count down for some applications) at a specified
interval, determined by the clock source used and a pre-scalar factor, and works as the universal
timer for all time-related events. Figure 7.12 shows the free running counter, TAxR, and the
features that govern its operation.
The programming of the counter is done with the help of the Timer_A control regis-
ter (TACTL). Figure 7.13 shows the contents of the 16 bit register. Referring to Figures 7.12
and 7.13 together, one can use bits 9 and 8 (TASSELx) of the TACTL register to choose the
clock used for the free running counter as follows:
• 00 – TACTL (external clock)
• 01 – ACLK (internal “slow” clock)
• 10 – SMCLK (internal “fast” clock)
• 11 – INCLK (external clock)
The Input Divider (IDx) bits (bits 7 and 6 in the TACTL register) are used to scale the
clock source before the free running counter updates itself. The pre-scale factors are
7.10. MSP430 TIMERS: TIMER_A AND TIMER_B 309

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

CCIS CM Logic COV


2 2 SCS
CCI6A 00 Capture
CCI6B 01 Mode 15 0
0
GND 10 TAxCCR6
Timer Clock Sync 1
VCC 11

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)

Timer_A Control Register (TAxCTL)


TAxCTL[9:8]: TASSEL: Timer_A clock source: 00 = TAxCLK, 01 = ACLK, 10 = SMCLK,
11 = INCLK
TAxCTL[7:6]: ID: input divider: 00 = 1, 01 = 2, 10 = 4, 11 = 8
TAxCTL[5:4]: MC: mode control: 00 = stop, 01 = up, 10 = continuous, 11 = up/down
TAxCTL[2]: TACLR: Timer_A clear: 1 = resets TAxR register
TAxCTL[1]: TAIE: Timer_A interrupt enable: 0 = disabled, 1 = enabled
TAxCTL[0]: TAIFG: Timer_A interrupt flag: 0 = none, 1 = pending

0FFFFh 0FFFFh 0FFFFh


TAxCCR0 TAxCCR0

00000h 00000h 00000h


Up Mode (MC = 01) Continous Mode (MC = 10) Up/Down Mode (MC = 11)

Figure 7.11: Timer_A registers [SLAU445G, 2016, SLAU367O, 2017]. (Illustration used with
permission of Texas Instruments (www.ti.com).)

MCx
Counting
TASSELx Mode

TACLK IDx TAR


ACLK TATFG
SMCLK
Free Running Counter
INCLK Pre-scalar

Clock Selection

Figure 7.12: 16-bit free running counter.


7.10. MSP430 TIMERS: TIMER_A AND TIMER_B 311
Timer_A Control Register (TACTL)
15 14 13 12 11 10 9 8
Unused TASSELx

rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0)

7 6 5 4 3 2 1 0
IDx MCx Unused TACLR TAIE TAIFG

rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) w-(0) rw-(0) rw-(0)

Figure 7.13: Timer_A control register.

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

7.10.2 INPUT CAPTURE


As mentioned earlier, the purpose of capture functions of the MSP430 microcontroller is to
capture the time of incoming external signal events. Again, all discussion pertaining to Timer_A
applies to Timer_B with appropriate register changes. In MSP430FR5994 microcontroller, for
each timer system, it contains seven channels that can be configured either as an input capture
or an output compare channel with associated interrupt sub-systems.
Suppose you want to capture the time period between two consecutive events, say cus-
tomers entering your retail store. You must have some means to record the time of the first event
and the second event. The input capture system in Timer_A and Timer_B systems give us those
capabilities, which we present in this section. Figure 7.14 shows components that make up an
input capture channel, and Figure 7.15 shows the contents of the control register to configure
the capture system. For the rest of the discussion, refer to both Figures 7.14 and 7.15.
The capture mode (CMx) bits (bits 15 and 14) of the TAxCCTLn register determine the capture
events as shown below.
• 00 – no capture
• 01 – capture rising edge
• 10 – capture falling edge
7.10. MSP430 TIMERS: TIMER_A AND TIMER_B 313

TAR
CCISx

CMx CCI1A
CCI1B
TACCRx
Capture VCC
Interrupt GND
System

GIE CCI

CCIFGx

Latch

Figure 7.14: Input capture system diagram.

Timer_A Capture Compare Control Register 0, 1, 2 (TACCTL0, 1, 2)


15 14 13 12 11 10 9 8
CMX1 CMXO CCIS1 CCIS0 SCS SSCI Unused CAP

rw-(0) rw-(0) rw-(0) rw-(0) rw-0 r r0 rw-(0)

7 6 5 4 3 2 1 0
OUTMOD2 OUTMOD1 OUTMOD0 CCIE CCI OUT COV CCIFG

rw-(0) rw-(0) rw-(0) rw-(0) r rw-(0) rw-(0) rw-(0)

Figure 7.15: Input capture and output compare control register.


314 7. TIMER SYSTEMS
• 11 – capture both edges
The capture/compare input select (CCISx) bits (bits 13 and 12) are used to select the input signal
to be captured as follows.
• 00 – capture compare input port A CCIxA

• 01 – capture compare input port B CCIxB

• 10 – Ground

• 11 – Supply voltage Vcc


The Capture Mode (CAP) bit (bit 8) of the Timer_A Capture Control Register (TAxCCTLn)
register is used to configure channel n to be either as an input capture channel (1) or as an output
compare channel (0). When the event designated by CMx bits appears on the input channel pin,
the current value of free running counter TAxR is captured in the Timer_A Capture/Compare
Register n (TAxCCRn) register and the corresponding flag, Capture/Compare Interrupt Flag
(CCIFG) (bit 0), in the TAxCCTLn register is set. If the capture/compare interrupt enable
(CCIE) bit (bit 4) is set and the GIE bit is activated, the interrupt system is configured to
service the interrupt. If another input capture event occurs before the TAxCCRn is read, the
capture overflow (COV) bit (bit 1) of the TAxCCTLn turns to 1 (set).
Example: In this input capture example, we use the MSP430FR5994 controller to capture the
VLO clock signal. The program captures rising edge of the clock signal and stores the free
running counter values in memory. When 20 rising edges are captured the logic state on pin
P1.0 changes.
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
//MSP430FR5x9x Demo - Timer0_A3 Capture of VLO Period using DCO SMCLK
//
//Description; Capture a number of periods of the VLO clock and store
//them in an array. When the set number of periods is captured the
//program is trapped and the LED on P1.0 is toggled. At this point
//halt the program execution read out the values using the debugger.
//
7.10. MSP430 TIMERS: TIMER_A AND TIMER_B 315
// ACLK = VLOCLK = 9.4kHz (typ.),
// MCLK = SMCLK = default DCO / default divider = 1MHz
//
// MSP430FR5994
// -----------------
// /|\| XIN|-
// | | |
// --|RST 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>

#define NUMBER_TIMER_CAPTURES 20

volatile unsigned int timerAcaptureValues[NUMBER_TIMER_CAPTURES];


unsigned int timerAcapturePointer = 0;

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

//Disable the GPIO power-on default high-impedance mode to activate


//previously configured port settings
PM5CTL0 &= ~LOCKLPM5;
//Clock System Setup
CSCTL0_H = CSKEY_H; //Unlock CS registers
CSCTL2 &= ~SELA_7;
CSCTL2 |= SELA__VLOCLK; //Select ACLK=VLOCLK
CSCTL0_H = 0x00; //Lock CS module
//use byte mode to upper byte
__delay_cycles(1000); //Allow clock system to settle
316 7. TIMER SYSTEMS
//Timer0_A3 Setup
TA0CCTL2 = CM_1 | CCIS_1 | SCS | CAP | CCIE;
//Capture rising edge,
//Use CCI2B=ACLK,
//Synchronous capture,
//Enable capture mode,
//Enable capture interrupt
TA0CTL = TASSEL__SMCLK | MC__CONTINUOUS;//Use SMCLK as clock source,
//Timer in continuous mode
__bis_SR_register(LPM0_bits | GIE);
__no_operation();
}

//*********************************************************************
// Timer0_A3 CC1-4, TA Interrupt Handler
//*********************************************************************

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)


#pragma vector = TIMER0_A1_VECTOR
__interrupt void Timer0_A1_ISR(void)
#elif defined(__GNUC__)

void __attribute__ ((interrupt(TIMER0_A1_VECTOR))) Timer0_A1_ISR (void)


#else
#error Compiler not supported!
#endif
{
switch (__even_in_range(TA0IV, TAIV__TAIFG))
{
case TAIV__TACCR1: break;
case TAIV__TACCR2:
timerAcaptureValues[timerAcapturePointer++] = TA0CCR2;
if(timerAcapturePointer >= 20)
{
while(1)
{
P1OUT ^= 0x01; //Toggle P1.0 (LED)
__delay_cycles(100000);
}
7.10. MSP430 TIMERS: TIMER_A AND TIMER_B 317
}
break;
case TAIV__TAIFG: break;
default: break;
}
}

//*********************************************************************

7.10.3 OUTPUT COMPARE


In this section, we present the MSP430 function opposite to the input capture capabilities. The
output compare function is designed to generate desired time critical signals on an output pin.
To do so, MSP430 architects designed the compare channels using almost the same registers
used in the input capture systems previously described. Refer to Figures 7.16 and 7.15 for the
following discussion. At each clock cycle, the comparator compares the current value in the TAR
with the one previously stored in the TAxCCRn register. When the two values match (identical),
the output logic state (either logic high or logic low) will appear on the output pin based on the

TAR

OUTMODx
Comparator
Capture OUTx
Interrupt TACCRx
System EQU0

GIE CCI EQU1

CCIFGx

Latch

Figure 7.16: Output compare diagram.


318 7. TIMER SYSTEMS
programmed states of OUTMODx bits (bits 7, 6, and 5) of the TAxCCTLn register as shown
below.

• 000 – output logic is controlled by the OUT bit (bit 2)

• 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

Register Contents Interrupt Source Associated Flag


00h No Interrupt
02h Channel 1 TAxCCR1 CCIFG
04h Channel 2 TAxCCR2 CCIFG
06h Channel 3 TAxCCR3 CCIFG
08h Channel 4 TAxCCR4 CCIFG
0Ah Channel 5 TAxCCR5 CCIFG
0Ch Channel 6 TAxCCR6 CCIFG
0Eh Timer Overflow TAxCTL TAIFG

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

Timer_A0_ISR ;ISR routine


xorb #Toggle, &P1OUT ;toggle logic state
rti

;----------------------------------------------------------------------

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

while(1) //wait for interrupt to occur


{
;
}
}

//******************************************************************
//Timer_A TAxCCR0 interrupt service routine
//******************************************************************

Interrupt(TIMERA0_VECTOR) TimerA_procedure(void)
{
P1OUT ^= 0x01; //toggle logic state
}

//******************************************************************

7.10.4 TIMER_B SYSTEM


The Timer_B system can be used as input capture and output compare timer units as we have
done with the Timer_A system. It contains up to seven different subsystems (channels) that
can be configured as capture or compare systems. The primary difference between Timer_A
and Timer_B system is that an extra buffer is introduced in the Timer_B system along with a
means to update the value of the register used to compare the free running timer value when
a channel is used as an output compare system and to capture the free running counter value
when configured as an input capture system.
Figure 7.17 shows the extra buffer used in Timer_B systems. Note that the free running
counter is now called TBxR instead of TAxR as you saw in the previous section. The TAxCTL
and TAxCCRn registers are replaced by 16 bit registers TBxCTL and TBxCCRn. When a
Timer_B channel is configured as an input capture channel and a programmed event appears
on the input pin, the free running counter value is captured in the TBxCCRn register as was
the case in the Timer_A system, but you have an option to upload that value into another 16-
bit register, TBxCLn. Why do you need this extra register? Suppose you have external events
that occur very quickly and you need to capture both events. By loading the first event time
and storing it quickly will allow the TBxCCRn register to be free to capture the second event.
Similarly, when a channel is configured as an output compare channel, the extra register allows a
programmer to generate output signals whose time values are separated by a “small1” number.3

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

Figure 7.17: Timer_B additional components.

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;

//Disable the GPIO power-on default high-impedance mode to activate


//previously configured port settings
PM5CTL0 &= ~LOCKLPM5;
324 7. TIMER SYSTEMS

TA1CCR0 = 1000-1; //PWM Period


TA1CCTL1 = OUTMOD_7; //CCR1 reset/set
TA1CCR1 = 750; //CCR1 PWM duty cycle
TA1CCTL2 = OUTMOD_7; //CCR2 reset/set
TA1CCR2 = 250; //CCR2 PWM duty cycle
TA1CTL = TASSEL__SMCLK | MC__UP | TACLR; //SMCLK, up mode, clear TAR
__bis_SR_register(LPM0_bits); //Enter LPM0
__no_operation(); //For debugger
}

//*********************************************************************

7.11 LABORATORY EXERCISE: GENERATION OF


VARYING PULSE WIDTH MODULATED SIGNALS TO
CONTROL DC MOTORS
Purpose: The purpose of this laboratory exercise is to program an MSP430 series controller
to generate a pulse-width modulated signal/waveform with varying duty cycle to control the
speed of a DC motor. The program requires you to use the input capture and output compare
capabilities of the controller. To meet the requirements of this laboratory exercise, you must

• 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,

• change the duty cycle based on a desired DC motor speed profile,

• configure Port 1 pins, and

• verify the output waveform by connecting the output pin on Port 1 to an oscilloscope.

Documentation: User Manual of your MSP430 microcontroller board.


Prelab: For the prelab, complete a flowchart and pseudocode for your program.
Description: As we learned in this chapter, the timer system of the MSP430 series micro-
controller is used for signal generation, measurement, and timing. In this lab, you are asked to
configure an MSP430 series controller to generate desired output waveforms using its output
7.11. LABORATORY EXERCISE: GENERATION OF VARYING PULSE WIDTH 325
compare system. The contents of the output compare system registers are programmed to set
and clear the logic states of an output pin and to cause an interrupt, related to the output pin.
The output event occurs when the free running counter (TAxR) value matches the value
stored in the designated output compare register (TAxCCRn). By adjusting the value in the
TAxCCRn register, one can program MSP430 to change the time when an output event occurs.
The input capture system is used to monitor the incoming signal. In this laboratory exercise, it
is used to count the number of pulses being generated by the output compare pin. By counting
the number of pulses, the input capture system can keep track of the time the output waveform
is generated and modify the duty cycle accordingly. The physical pins used in this laboratory are
P1.1 and P1.2, where P1.1 will be used as the input capture pin and the P1.2 pin will be used
as the output compare pin.
Tasks: In this lab, you need to write a program to modify the duty cycle of an output periodic
signal in real time. The desired speed profile (velocity vs. time) is shown in Figure 7.18. The y-

Duty Cycle

50%

0%
0 3 6 9
t(sec)

Figure 7.18: Desired speed profile for the DC motor.

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.

• Turn off the Watchdog timer.

• Generate the pulse width modulated signal.

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

• Set up the duty cycle.

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

• Measuring the number of pulses arriving at an input capture pin.

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

7.13 REFERENCES AND FURTHER READING


Barrett S. F. and Pack D. J. Embedded Systems Design with the Atmel Microcontroller, Morgan &
Claypool Publishers, 2010. DOI: 10.2200/S00138ED1V01Y200910DCS024.

Texas Instruments MSP430FG461x Code Examples, (SLAC118D). www.TI.com

Texas Instruments MSP430FR2433 Mixed-Signal Microcontroller, (SLASE59D), Texas Instru-


ments, Revised 2018.

Texas Instruments MSP430FR4xx and MSP430FR2xx Family User’s Guide, (SLAU445G), Texas
Instruments, 2016. 309, 310

Texas Instruments MSP430FR58xx, MSP430FR59xx, and MSP430FR6xx Family,


(SLAU367O), Texas Instruments, 2017. 296, 297, 309, 310

Texas Instruments MSP430FR599x, MSP430FR596x Mixed-Signal Microcontrollers,


(SLASE54C), Texas Instruments, 2018.
328 7. TIMER SYSTEMS
7.14 CHAPTER PROBLEMS
Fundamental

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?

4. Suppose the LFXT1CLK is connected to a high-frequency watch crystal. Identify the


register and the particular bit to configure the LFX1CLK clock signal generator on a high
frequency mode.

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

1. Program your MSP430 to generate clock signal frequency of 1.2 MHz.

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

Resets and Interrupts


Objectives: After reading this chapter, the reader should be able to:
• describe MSP430 resets and their functions;
• explain the general concept of and the need for interrupts;
• describe in general terms the steps required to implement an interrupt service routine;
• identify MSP430 microcontroller’s maskable and non-maskable interrupts;
• illustrate the process to assign priorities among resets and interrupts in the MSP430 mi-
crocontroller;
• explain the process to identify the source of resets and interrupts;
• describe the process to service interrupts; and
• properly configure the MSP430 microcontroller and write interrupt service routines to
respond to interrupts
In any computer operation, it is often necessary to bring the internal processing state of a
computer back to a known state due to program or system errors, or simply because it serves the
purpose of an application at hand. Bringing the internal processing state of a computer back to
a known state involves re-initializing registers, executing start-up instructions, and configuring
peripheral devices, including I/O sub-systems. This process is called a reset. In other applica-
tions, there arises a need to stop executing the current task of a computer and taking care of an
urgent request made by internal devices, external signals, or the result of the current or other
software programs. These requests are called interrupts.
Resets and interrupts are closely related. In fact, the process of bringing the internal pro-
cessing state of a computer back to a known state and performing a service routine as a response
to an urgent request is almost identical, as we will see in this chapter.

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.

8.3 MSP430 RESETS/INTERRUPTS OVERVIEW


The system control module (SYS) of the MSP430 governs the functions of resets and inter-
rupts. For resets, there are three types: BOR, POR, and PUC. For interrupts, two types exist:
non-maskable interrupts (NMI) or maskable interrupts (MI). The three different resets allow
the MSP430 to start at three different start up states, providing the desired flexibility. The non-
maskable interrupts are those that MSP430 controllers cannot or should not ignore, such as
the critical power level indication. The maskable interrupts, on the other hand, are those re-
quests, if necessary, that can be masked (ignored) by the CPU. The maskable interrupts require
a programmer to activate them by writing to specific registers [SLAU445G, 2016, SLAU367O,
2017].

8.4 MSP430 RESETS


The BOR is triggered by five different events for the MSP430FR5994 and MSP430FR2433
controllers. The first is when the microcontroller is turned on. The BOR also occurs when a
logic low is applied to the reset pin (RTS=NMI ), configured as a reset pin by the SYSNMI bit
in SFRRPCR (Special Function Register Reset Pin Control Register), which is the second
event. Figure 8.1 shows SFRRPCR. Note that a programmer can also use the same register
to configure (SYSRSTRE—Reset enable/disable, SYSRSTUP—Reset pin pull-up/pull-down,
and SYSNMIEES—edge select) the use of the pin. The third possible event that can cause the
BOR is when the MSP430 controller wakes up from operating mode LPM3.5 or LPM4.5. The

System Function Register Reset Pin Control Register (SFRRPCR) at $0104


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
Reserved Reserved Reserved Reserved SYSRSTRE SYSRSTUP SYSNMIIES SYSNMI

r0 r0 r0 r0 rw-1 rw-1 rw-0 rw-0

Figure 8.1: Special function register reset pin control register.


334 8. RESETS AND INTERRUPTS
fourth possible event for the reset is when the power management module (PMM) detects the
power level of the controller (SVS) falls below a threshold value. Finally, the last event that trig-
gers the BOR is software BOR events. For some applications, it is desired to trigger a Brownout
reset using a software instruction. Setting PMMSWBOR (Power Management Module Soft-
Ware BOR) bit in the PMMCTL0 register (Power Management Module Control Register 0)
initiates a software generated BOR [SLAU445G, 2016, SLAU367O, 2017].
The second type of reset, the POR, is automatically triggered when the BOR occurs as
shown in Figure 8.2. The POR is typically associated with the hardware system while the PUC
reset is generally linked to software events. In addition to a BOR event, the POR is triggered
by a software POR event.

LPMx.5: From Active Mode


VCORE = off
(all modules off RTC Wakeup Brownout
optional RTC) Fault

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

Figure 8.3: Microcontroller interrupt response.

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.

8.5.1 INTERRUPT HANDLING PROCESS


In this section, we describe the process of handling an interrupt event. Once a maskable interrupt
is configured to be active, and an interrupt event occurs, a flag that corresponds to the particular
interrupt event is asserted to indicate to the CPU that there is an interrupt waiting to be serviced.
The CPU then takes the following actions in the order shown to provide an orderly transition
from normal program operation to the interrupt service routine and back again.

1. Complete the current instruction.


338 8. RESETS AND INTERRUPTS
Interrupt Enable Register (SFRIE1)

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

rw-0 rw-0 rw-0 rw-0 rw-0 r0 rw-0 rw-0

0 - interrupt disabled 1 - interrupt enabled

JMBOUTIE - JTAG mailbox output interrupt enable


JMBINIE - JTAG mailbox input interrupt enable
NMIIE - NMI pin interrupt enable
VMAIE - Vacant memory access interrupt enable
OFIE - Oscillator fault interrupt enable
WDTIE - Watchdog timer interrupt enable

Figure 8.4: Interrupt enable register.

2. Store the contents of the program counter (PC) onto the stack.

3. Store the contents of the status register (SR) onto the stack.

4. Choose the highest priority interrupt if multiple interrupts are pending.

5. Reset the interrupt request flag.

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.

8. Execute the specified interrupt service routine.

9. Once the service routine is finished (with the RETI instruction), restore the SR and then
PC values from the stack.

10. Resume normal operation.


8.5. INTERRUPTS 339

Interrupt Flag Register (SFRIFG1)


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
JMBOUTIFG JMBINIFG Reserved NMIIFG VMAIFG Reserved OFIFG WDTIFG

rw-(1) rw-0 r0 rw-0 rw-0 r0 rw-(1) rw-0

0 - no interrupt 1 - interrupt pending

JMBOUTIFG - JTAG mailbox output interrupt flag


JMBINIFG - JTAG mailbox input interrupt flag
NMIIFG - NMI pin interrupt flag
VMAIFG - Vacant memory access interrupt flag
OFIFG - Oscillator fault interrupt flag
WDTIFG - Watchdog timer interrupt flag

Figure 8.5: Interrupt flag register.

Interrupt Source Flag Priority Vector Location


Resets WDTIFG, Highest FFFE
KEYV, ..
.
System NMI . FFFC
User NMI NMIFG, . FFFA
.
OFIFG, .
ACCVIFG,... .
Device Specific . FFF8
.

. .
Watchdog Timer WDTIFG . .
. . . .
. . . .

Figure 8.6: MSP430 interrupt vector table [SLASE54C, 2018].


340 8. RESETS AND INTERRUPTS
System Control Register (SYSCTL)
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
Reserved Reserved SYSJTAGPIN SYSBSLIND Reserved SYSPMMPE Reserved SYSRIVECT

r0 r0 rw-(0) r-0 r0 rw-(0) r0 rw-(0)

Figure 8.7: System control register.

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

Before an Interrupt After an Interrupt Handling


Process Started

Figure 8.8: Stack before and after an interrupt.


8.5. INTERRUPTS 341
by checking the TAIV register (Timer_A Interrupt Vector Register), which contains a value
identifying the interrupt source. Similarly, the source of a non-maskable interrupt or a reset is
resolved with the help of three interrupt vector registers: SYSRSTIV (Reset Interrupt Vector
register), SYSSNIV (System NMI Vector register), and SYSUNIV (User NMI Vector register).
When a reset occurs, based on the source, it generates an interrupt vector offset value in the
SYSRSTIV register, as shown in Figure 8.9.

Reset Interrupt Vector Registor (SYSRSTIV) at $019E


15 14 13 12 11 10 9 8
0 0 0 0 0 0 0 0

r0 r0 r0 r0 r0 r0 r0 r0

7 6 5 4 3 2 1 0
0 0 SYSRSTVEC 0

r0 r0 r-0 r-0 r-0 r-0 r-1 r0

SYSRSTIV Value Interrupt Type


0000h No interrupt
0002h Brownout (BOR)
0004h RST/NMI (BOR)
0006h PMMSWBOR (BOR)
0008h Wakeup from LPMx.5 (BOR)
000Ah Security violation (BOR)
000Ch SVSL (POR)
000Eh SVSH (POR)
0010h SVML_OVP (POR)
0012h SVMH_OVP (POR)
0014h PMMSWPOR (POR)
0016h WDT time out (PUC)
0018h WDT password violation (PUC)
001Ah Flash password violation (PUC)
001Ch PLL unlock (PUC)
001Eh PERF peripheral/configuration area fetch (PUC)
0020h PMM password violation (PUC)
0022–003Eh Reserved for future use

Figure 8.9: Reset interrupt vector register.


342 8. RESETS AND INTERRUPTS
The SYSRSTVEC bits (Reset interrupt vectors—bits 1–5) determine the interrupt vector
offset value. Similarly, the SYSSNIV and the SYSUNIV registers are used to identify the source
of an interrupt; see Figures 8.10 and 8.11. For example, when dealing with a user non-maskable
interrupt, as the first step of the service routine, the contents of the SYSUNIV and PC are added
as shown in Figure 8.12. The offset value governs the execution of the appropriate portion of the
interrupt service routine.

System NMI Vector Registor (SYSSNIV) at $019C


15 14 13 12 11 10 9 8
0 0 0 0 0 0 0 0

r0 r0 r0 r0 r0 r0 r0 r0

7 6 5 4 3 2 1 0
0 0 0 SYSSNVEC 0

r0 r0 r0 r-0 r-0 r-0 r-0 r0

SYSRSTIV Value Interrupt Type


0000h No interrupt
0002h SVMLIFG interrupt
0004h SVMHIFG interrupt
0006h SVSMLDLYIFG interrupt
0008h SVSMHDLYIFG interrupt
000Ah VMAIFG interrupt
000Ch JMBINIFG interrupt
000Eh JMBOUTIFG interrupt
0010h SVMLVLRIFG interrupt
0012h SVMHVLRIFG interrupt
0014h Reserved for future use

Figure 8.10: System non-maskable interrupt vector register.

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

User NMI Vector Registor (SYSUNIV) at $019A


15 14 13 12 11 10 9 8
0 0 0 0 0 0 0 0

r0 r0 r0 r0 r0 r0 r0 r0

7 6 5 4 3 2 1 0
0 0 0 SYSUNVEC 0

r0 r0 r0 r-0 r-0 r-0 r-0 r0

SYSRSTIV Value Interrupt Type


0000h No interrupt
0002h NMIIFG interrupt
0004h OFIFG interrupt
0006h ACCVIFG interrupt
0008h Reserved for future use

Figure 8.11: User non-maskable interrupt vector register.

SNI_ISR: ADD &SSSNIV,PC ; Add offset to jump table


RETI ; No interrupt
JMP SVML_ISR ; vector 2
JMP SVMH_ISR ; vector 4
:
JMP SVMHV_ISR ; vector 12
Invalid_ISR RETI ; vector 14
SVML_ISR: ; ISR for vector 2
:
RETI
SVMH_ISR: ; ISR for vector 4
:
RETI
:
SVMHV_ISR: ; ISR for vector 12
:
RETI

Figure 8.12: Sample ISR for user non-maskable interrupts.


344 8. RESETS AND INTERRUPTS
8.5.2 INTERRUPT PRIORITY
As there are multiple reset and interrupt sources associated with the MSP430 microcontroller,
shown in Figure 8.6, priorities among interrupts must be defined in advance to handle situations
when more than one interrupt occurs simultaneously. The MSP430 microcontroller sets the
priority in the following manner. The resets hold the highest priority, followed by the system
NMIs, the user NMIs, and the device specific maskable interrupts. Figures 8.13, 8.14, and
8.15 show the priority list for the MSP430FR5994 microcontroller. Since each version of the
MSP430 controller has a different number of interrupts associated with its subsystems, one
should always consult the datasheet for the particular controller to find the interrupt priority
list.
A typical MSP430 microcontroller configuration has built-in interrupt systems for a direct
memory access (DMA) controller, a DAC, an analog comparator (Comp_B), digital I/O ports
(P1 and P2), one or more Timer_A system, a Timer_B system, a real-time clock A (RTC_A)
system, a real-time clock B (RTC_B) system, analog-to-digital converter (ADC), a UART
system, and a USB system. Since it requires a detailed understanding of each system to use the
associated interrupt, we defer the discussion of each interrupt system to chapters that cover the
subsystems.

8.5.3 INTERRUPT SERVICE ROUTINE (ISR)


Most of the interrupt handling process described in this chapter takes place automatically (you,
as a programmer, do not need to program them). In fact, for the resets, all processing is com-
pleted automatically. For maskable interrupts, however, your responsibility as a programmer is
to (1) turn on the global interrupt enable (GIE), (2) initialize the stack pointer, (3) configure
the interrupt vector table (initialize the start address of your ISR), (4) enable the appropriate
interrupt local enable bit (SFRIE1 register), and (5) write the corresponding interrupt service
routine. In this section, we present the last task, writing an ISR.
Examples: In this example, we write an ISR using the Timer_A interrupt system. Recall that all
Timer_A system related interrupts have the same interrupt vector. Thus, a Timer_A ISR must
identify the source before executing a desired task. In MSP430-related microcontrollers, the
Timer_A system contains two separate subsystems, Timer0_A and Timer1_A. Each subsystem
has I/O channels, where each channel has the same interrupt vector table entry. Using assembly
language, we can write an ISR similar to the one provided in Figure 8.12. The ISR is shown in
Figure 8.16.
The next example shows how to implement a Timer0_A0 related ISR. Note how the ISR
is configured. The code snapshot below shows how to tie the starting address of the ISR to the
proper location in the ISR. We assume definitions for all MSP430FR5994-related interrupts
are properly made.
8.5. INTERRUPTS 345

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

TA_ISR: ADD &TA0IV,PC ; Add offset to jump table


RETI ; No interrupt
JMP CCIFG1_ISR ; vector 2
JMP CCIFG2_ISR ; vector 4
:
JMP CCIFG6_ISR ; vector 12
TA0IFG_ISR ; vector 14
:
RETI
CCIFG1_ISR: ; ISR for vector 2
:
RETI
CCIFG2_ISR: ; ISR for vector 4
:
RETI
:
CCIFG6_ISR: ; ISR for vector 12
:
RETI

Figure 8.16: Timer_A interrupt service routine.


348 8. RESETS AND INTERRUPTS
#pragma vector=TIMER0_A0_VECTOR
__interrupt void TIMER0_A0_ISR(void)
In this example, only a single Timer0_A0 related ISR is employed.
// ******************************************************************
// 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, CCR0 Cont Mode ISR,
// DCO SMCLK
//
//Description: Toggle P1.0 using software and TA_0 ISR. Timer0_A is
//configured for continuous mode, thus the timer overflows when TAR
//counts to CCR0. In this example, CCR0 is loaded with 50000.
//ACLK = n/o, MCLK = SMCLK = TACLK = default DC0 = ~1MHz
//
// 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>

int main(void)
8.5. INTERRUPTS 349
{
WDTCTL = WDTPW | WDTHOLD; //Stop WDT

P1DIR |= BIT0; //Configure GPIO


P1OUT |= BIT0;

//Disable the GPIO power-on default high-impedance mode to activate


//previously configured port settings
PM5CTL0 &= ~LOCKLPM5;

TA0CCTL0 = CCIE; //TACCR0 Interrupt enabled


TA0CCR0 = 50000;
TA0CTL = TASSEL__SMCLK | MC__CONTINOUS; //SMCLK, continuous mode
__bis_SR_register(LPM0_bits | GIE); //Enter LPM0 w/ interrupt
__no_operation(); //For debugger
}

//*******************************************************************
//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

P1DIR |= BIT0; //Configure GPIO


P1OUT |= BIT0;
PJSEL0 |= BIT4 | BIT5;

//Disable the GPIO power-on default high0impedance mode to activate


//previously configured port settings
PMSCTL0 &= ~LOCKLPM5; //Setup XT1
CSCTL0_H = CSKEY_H; //Unlock CS registers
CSCTL1 = DCOFSEL_6; //Set DC0 to 8MHz
//set ACLK = XT1; MCLK = DCO
CSCTL2 = SELA__ LFXTCLK | SELS__DCOCLK | SELM__DCOCLK;
CSCTL3=DIVA__1 | DIVS__2 | DIVM__2;//Set all dividers
CSCTL4 &= ~LFXTOFF;
do
{
CSCTL5 &= ~LFXTOFFG; //Clear XT1 fault flag
SFRIFG1 &= ~OFIFG;
}while (SFRIFG1 & OFIFG); //Test oscillator fault flag
CSCTL0_H = 0;

//ACLK, contmode, clear TAR, enable overflow interrupt


TA0CTL = TASSEL__ACLK | MC__CONTINUOUS | TACLR | TAIE;
__bis_SR_register(LPM0_bits | GIE); //Enter LPM0 w/ interrupt
__no_operation(); //For debugger
}

//**********************************************************************
// Timer0_A1 Interrupt Vector (TAIV) handler
//**********************************************************************

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)


#pragma vector = TIMER0_A1_VECTOR
__interrupt void Timer0_A1_ISR (void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(TIMER0_A1_VECTOR))) Timer0_A1_ISR (void)
#else
#error Compiler not supported!
#endif
352 8. RESETS AND INTERRUPTS
{
switch(__even_in_range(TA0IV, TAIV__TAIFG))
{
case TAIV__NONE; break; //No interrupt
case TAIV__TACCR1; break; //CCR1 not used
case TAIV__TACCR2; break; //CCR2 not used
case TAIV__TACCR3; break; //reserved
case TAIV__TACCR4; break; //reserved
case TAIV__TACCR5; break; //reserved
case TAIV__TACCR6; break; //reserved
case TAIV__TAIFG; P1OUT ^= BIT0; //overflow
break;
default: break;
}
}

//*********************************************************************
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;

P1DIR |= BIT0; //Configure GPIO

//Disable the GPIO power-on default high impedance mode to activate


//previously configured port settings
PMSCTL0 &= ~LOCKLPM5;

CSCTL0_H = CSKEY_H; //Unlock CS registers


CSCTL1 = DCOFSEL_6; //Set DCO = 8MHz
//Set ACLK = VL0, MCLK = DCO
CSCTL2 = SELA__VLOCLK | SELS__DCOCLK | SELM__DCOCLK;
//Set all dividers
CSCTL3 = DIVA__1 | DIVS__8 | DIVM__8;
CSCTL0_H = 0;
SFRIE1 |= WDTIE; //Enable WDT interrupt
__bis_SR_register(LPM0_bits+GIE); //Enter LPM0, enable interrupts
__no_operation(); //For debugger
}

//***********************************************************************
// Watchdog timer interrupt service routine
//***********************************************************************
354 8. RESETS AND INTERRUPTS

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)


#pragma vector = WDT_VECTOR
__interrupt void WDT_ISR (void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(WDT_VECTOR))) WDT_ISR (void)
#else
#error Compiler not supported!
#endif
{
P1OUT ^= BIT0;
}

//***********************************************************************
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.

8.6 LABORATORY EXERCISE


In many smart homes, electronic appliances are networked together to monitor power usage
throughout the day. The idea is to minimize collective power usage during the peak time and
perform tasks during the low power usage time. For example, a refrigerator can delay generating
ice cubes, if it detects that the electric fan is operating at the same time. An LCD may turn itself
off when it is not being used. Furthermore, assume that some of these electronic systems in house
are battery operated. In this laboratory exercise, you are to implement the controller for a battery
operated electronic temperature controller for a living room, which must periodically transmit
wirelessly its status (power level) to a central station, check to see whether the temperature is
within a programmed range, and turn on a heater/air conditioner if necessary until the desired
temperature is reached.
While it is not in use, the controller should be in a power saving mode, LPM3.5, and
should be turned on every 5 min to perform the periodic task. It should use its internal clock as
the timer and use the related interrupt system to “wake up” and “sleep” during and in between
consecutive tasks. Since we have not covered the wireless transmission capabilities of MSP430,
simply write 0x01h to Port 1 to indicate that the power level is healthy and 0xFFh to let the
central controller know that the power is below the desired level. Assume that the power level is
constantly updated at memory locations 0x1000h-0x1001h and values above 0x8000 represent
sufficient power capacity. To turn on the heater or the air conditioner, your program must write
0x01 or 0xFF to Port 2, respectively. Writing 0x00h to Port 2 turns off both systems.
8.7. REFERENCES AND FURTHER READING 355

Temperature
Controller
Power Status Signals
Heater/Air-Conditioner
Control Signals

Window

Living Room

Figure 8.17: Temperature controller for a smart home.

Figure 8.17 shows the setup for your temperature controller.

8.7 REFERENCES AND FURTHER READING


MSP430FR2433 LaunchPad Development Kit (MSP-EXP430FR2433), (SLAU739), Texas In-
struments, 2017.

MSP430FR2433 Mixed-Signal Microcontroller, (SLASE59D), Texas Instruments, 2018.

MSP430FR4xx and MSP430FR2xx Family User’s Guide, (SLAU445G), Texas Instruments,


2016. 333, 334, 335, 337

MSP430FR58xx, MSP430FR59xx, and MSP430FR6xx Family User’s Guide, (SLAU367O),


Texas Instruments, 2017. 333, 334, 335, 337
356 8. RESETS AND INTERRUPTS
MSP430FR5994 LaunchPad Development Kit (MSP-EXP430FR5994), (SLAU678A), Texas In-
struments, 2016.
MSP430FR599x, MSP430FR596x Mixed-Signal Microcontrollers, (SLASE54C), Texas Instru-
ments, 2018. 339

8.8 CHAPTER PROBLEMS


Fundamental
1. List three different types of resets in the MSP430 microcontroller.
2. State the purpose of resets and interrupts.
3. What is the main difference between a reset and an interrupt?
4. What is the differences between maskable and nonmaskable interrupts?
5. In addition to setting up a local interrupt enable bit, you must also set the global enable bit.
Where is the global enable bit for all MSP430 maskable interrupts? Write an instruction
to enable this global maskable interrupt enable bit.
6. What are the steps one must take to properly configure a maskable interrupt?
7. When more than one maskable interrupt occurs simultaneously, how does the MSP430
controller decide the order in which the controller service the interrupts?

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.

9.1 ANALOG-TO-DIGITAL CONVERSION PROCESS


Before a computer can process any physical signals, those signals must first be converted to their
corresponding digital forms. Figure 9.1 shows an example of an analog signal. Notice that for
a given time, t , shown on the x axis, the signal can hold any value of magnitude shown on the
y axis. So, how do analog signals such as the one shown in the figure get converted into digital
signals? The ADC process consists of the three separate sub-processes: sampling, quantization,
and encoding.
358 9. ANALOG PERIPHERALS
Sample Analog Signal
80

60

40

Magnitude
20

−20

−40

−60
0 2 4 6 8 10
Time (sec)

Figure 9.1: Sample analog signal.

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)

Figure 9.2: Sampling rate illustration.


9.1. ANALOG-TO-DIGITAL CONVERSION PROCESS 361
b
there are 2 number of values we can represent with b bits. If we have a 2-bit analog-to-digital
converter, 2 bits are used to represent the analog signal; there are four different representations
we can choose from. In a 4-bit converter, we have 16 different ways to do so. If we have an 8-bit
converter, we have 256 different representations, and so on. Figure 9.3 shows both quantization
levels and the corresponding resolution for a sample input signal for a 3-bit ADC.

Quantized Level 8
Resolution
Quantized Level 7

Quantized Level 6 Analog


signal
Quantized Level 5
input
Quantized Level 4 range

Quantized Level 3

Quantized Level 2

Quantized Level 1

Quantized Level 0

Figure 9.3: Quantization levels and the resolution of an ADC.

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

Highest Possible Input Value

Sampled Value

Quantization Error
Quantization Level n

Lowest Possible Input Value

Figure 9.4: Quantized error of a sampled input signal.


364 9. ANALOG PERIPHERALS
Example: Find the encoded value of the quantization found in the previous example: 738. Recall
we are using 10 bits.
Answer: Since we are using 10 bits to represent this number, the encoded value is
.1  29 / C .0  28 / C .1  27 / C .1  26 / C .1  25 / C .0  24 / C .0  23 / C
.0  22 / C .1  21 / C .0  20 / D 738.
Thus, the encoded value is 1011100010.

9.2 DIGITAL-TO-ANALOG CONVERTER PROCESS


The opposite function of an ADC is performed by a DAC. Some variants of the MSP430 are
equipped with an onboard DAC. Neither the MSP430FR2433 or the MSP430FR5994 micro-
controllers are equipped with an onboard DAC. However, the theory behind a DAC system is
important to understand. This allows the selection of an appropriate external DAC for a given
application.
The input to a DAC converter is an encoded value which specifies the desired output
analog value. Similar to the ADC, a DAC must have both minimum and maximum reference
analog voltages. The job of a DAC is then to map a minimum digital representation to its corre-
sponding minimum analog value, a maximum digital representation to the maximum reference
analog value, and representations in between minimum and maximum digital values to their ap-
propriate analog counterparts. The most common method used to perform a DAC conversion is
to pre-designate the analog weight of each bit in the digital input representation and then sum
up the contributions to form an analog output. For example, suppose the range of output values
for a DAC is from 0–5 V. If we have a 4-bit DAC, from the most to the LSBs, each specific
bit would be weighted 2.5 V, 1.25 V, 0.625 V, and 0.3125 V, respectively. Thus, a digital input
of 1010 to this converter will result in 2:5 C 0:625 D 3:125 V, and a digital input of 1111 to
the DAC converter would result in 2:5 C 1:25 C 0:625 C 0:3125 D 4:6875 V. Given an N-bit
converter, it is straightforward to develop the following equation to describe the relationships
among the input, the number of bits used, and the output:

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

Weighted Reference Voltages


0
0.625 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.

9.3 MSP430 ADC SYSTEMS


In this section we begin with a general discussion of the MSP430 ADC block diagram followed
by a detailed discussion of the MSP430FR2433 ADC and the MSP430FR5994 ADC and
comparator systems.

9.3.1 MSP 430 ADC BLOCK DIAGRAM


A basic block diagram of the MSP430 ADC system is shown in Figure 9.6a. An input analog
channel is selected for conversion by the input voltage select multiplexer (mux). 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 successive approximation converter. The SA converter receives
input from the reference voltage select, the timing source, and trigger source for conversion.
366 9. ANALOG PERIPHERALS
The digital result of the conversion, provided as n bits, is stored in the result register. Specific
interrupts may be selected to signal different significant events in the ADC process.
A block diagram of SA converter operation is provided in Figure 9.6b. As its name implies,
the SA converter will make successive guesses at the unknown sample voltage value. It begins
with a guess of one-half of the reference voltage, as shown in Figure 9.6c. This digital guess is
converted to a corresponding analog value by the DAC. The analog guess is compared to the
unknown sample voltage by the voltage comparator. The output from the comparator prompts
the SA to guess higher or lower. This process continues n times (one for each bit in the SA
register). The guess progresses from one-half of the reference voltage to one-fourth to one-
eighth, etc. When the conversion is complete, the end of conversion signal goes logic high. As
we present a detailed discussion of the MSP430FR2433 and MSP430FR5994 ADC systems,
it may be helpful to refer back to the block diagrams.

9.3.2 MSP430FR2433 10-BIT ANALOG-TO-DIGITAL CONVERTER


The MSP430FR2433 is equipped with a flexible and powerful ADC system. It has the following
features [SLAU445G, 2016]:
• eight channels for external conversion,
• converter resolution of 10-bits per sample,
• successive approximation converter,
• selectable reference voltages, and
• input voltage range from 0 to DVcc.
The ADC is quite flexible and may be configured for the following operations:
• a single conversion on a single ADC channel,
• a single conversion on a sequence of channels,
• a repeated conversion on a single channel, or
• a repeated conversion on a sequence of channels.
The block diagram of the MSP430FR2433 ADC is shown in Figure 9.7. Like the block
diagram provided in Figure 9.6, the MSP430FR2433 ADC system may be divided into input
select, voltage reference select, time base select, trigger source select, and the output processing
sections. The ADC process is configured and monitored by a set of ADC registers.
Input select. There are 16 different inputs to the converter as shown in the left of Fig-
ure 9.7: A0–A15. Of the 16 inputs, 8 inputs (A0–A7) are used to route analog input signals to
the converter. Inputs A14 and A15 are connected to a positive reference voltage and a negative
9.3. MSP430 ADC SYSTEMS 367

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

(a) Successive approximation ADC block diagram

Successive End of Conversion Signal


Approximation
Timing Source Register (SAR)
n
Current Digital “Guess”

Digital-to-Analog
Converter

Current Analog “Guess”

Unknown Sample
Sample and Hold Voltage
Voltage (S/H) Comparator

(b) Successive approximation ADC converter


1/2n (VR+ - VR-)
1/2 (VR+ - VR-)

1/4 (VR+ - VR-)


G s1
2

n
ss

ss
s
ue
ue

ue
G

(c) Successive approximation register (SAR)

Figure 9.6: Basic ADC block diagram.


368 9. ANALOG PERIPHERALS
Input Select Voltage Reference Select
ADCINCHx VEREF- VEREF+

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

ADCSREFx Reference Voltages


001 VR+ = AVcc and VR− = AVss
001 VR+ = VREF+ and VR− = AVss
010 VR+ = VeREF+ and VR− = AVss
011 VR+ = VeREF++ and VR− = AVss
100 VR+ = AVcc and VR− = VREF−/VeREF−
101 VR+ = VREF+ and VR− = VREF−/VeREF−
110 VR+ = VeREF+ and VR− = VREF−/VeREF−
111 VR+ = VeREF+ and VR− = VREF−/VeREF−

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

ADC Interrupt Vector (ADCIV) register


0
ADCOVIFG
1
Interrupt source?
0 00h: none
ADCTOVIFG 02h: ADCMEM0 overflow (ADCOVIFG)
1
04h: Conversion time overflow (ADCTOVIFG)
06h: ADCHI interrupt flag (ADCHIIFG)
0
ADCLOIFG 08h: ADCLO interrupt flag (ADCLOIFG)
1 0Ah: ADCIN interrupt flag (ADCINIFG)
0Ch: ADC memory interrupt flag (ADCIFGO)
0
ADCINIFG
1

0
ADCHIIFG
1

ADC Interrupt Enable


(ADCIE) register
A OVIE
A CH E
A LOIE
C E
D IE
0
IE
D I

D I
D V

A IN
D I

C
A TO

C
C
C
D
A

Figure 9.8: MSP430FR2433 ADC interrupts overview.

• ADCIN interrupt flag (ADCINIFG)

• ADCHI interrupt flag (ADCHIIFG)

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.

9.3.3 MSP430FR2433 REGISTER SUMMARY


ADC operation and feature selection are determined by user selected settings in the ADC reg-
isters. The ADC register set includes the following registers [SLAU445G, 2016]:
• ADCCTL0 ADC Control 0 register
• ADCCTL1 ADC Control 1 register
• ADCCTL2 ADC Control 2 register
• ADCMCTL0 ADC Memory Control register
• ADCMEM0 ADC Conversion Memory register. Conversion results are stored here.
• ADCIE ADC Interrupt Enable register. Used to enable individual interrupts.
• ADCIFG ADC Interrupt Flag register. Corresponding flags for individual ADC inter-
rupts are provided here.
• ADCIV ADC Interrupt Vector register. Provides numerical value of active interrupt.
Details of configuring each register is provided in SLAU445G. We highlight the settings
of the ADC Control Registers in Figure 9.9.

Programming the MSP430FR2433 ADC in Energia


The Energia library contains several functions to support analog conversions including ADC-
and DAC-related functions (www.energia.nu):
• analogRead(): The analogRead function performs an ADC conversion on the indicated
analog pin. The measured voltage is converted to an integer value between 0 and 1023,
where 0 corresponds to 0 VDC and 1023 corresponds to 3.3 VDC.
• analogReference(): The analogReference function provides for changing the high level
reference voltage for ADC conversion. The different settings include:
– DEFAULT: sets ADC high reference level to VCC 3.3 V.
372 9. ANALOG PERIPHERALS

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.

9.3.4 PROGRAMMING THE MSP430FR2433 ADC IN C


To successfully configure and program the converter, the following steps should be followed.

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.

3. Connect analog signal(s) for conversion to appropriate input pins (A0-A7).

4. Turn on the ADC: ADCON in ADCCTL0.

5. Select the clock source and the sampling mode in ADCCTL1.

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.

7. Initiate conversion: ADCENC bit in ADCCTL0.

8. Monitor for conversion completion using the ADCIFG0 flag.

9. Use the results of the conversion located in the corresponding result register
(ADC12MEM0).

10. Repeat the process starting at step 6.

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>

unsigned int ADC_Result;

int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop WDT

//Configure GPIO
P1DIR |= BIT0; //Set P1.0/LED to output
P1OUT &= ~BIT0; //P1.0 LED off

SYSCFG2 |= ADCPCTL1; //Configure ADC A1 pin

//Disable the GPIO power-on default high-impedance mode to activate


//previously configured port settings
M5CTL0 &= ~LOCKLPM5;
//Configure ADC10
ADCCTL0 |= ADCSHT_2 | ADCON; //ADCON, S&H=16 ADC clks
ADCCTL1 |= ADCSHP; //ADCCLK = MODOSC, sampling timer
ADCCTL2 |= ADCRES; //10-bit conversion results
ADCMCTL0 |= ADCINCH_1; //A1 ADC input select, Vref=AVC
ADCIE |= ADCIE0; //Enable ADC conv complete
//interrupt
while(1)
{
ADCCTL0 |= ADCENC | ADCSC; //Sampling and conversion start
bis_SR_register(LPM0_bits | GIE); //LPM0, ADC_ISR will force exit
__no_operation(); //For debug only
if(ADC_Result < 0x1FF)
P1OUT &= ~BIT0; //Clear P1.0 LED off
else
P1OUT |= BIT0; //Set P1.0 LED on
__delay_cycles(5000);
}
}
376 9. ANALOG PERIPHERALS
//*******************************************************************
// ADC interrupt service routine
//*******************************************************************
#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)
#pragma vector=ADC_VECTOR

__interrupt void ADC_ISR(void)


#elif defined(__GNUC__)

void __attribute__ ((interrupt(ADC_VECTOR))) ADC_ISR (void)


#else
#error Compiler not supported!
#endif
{
switch(__even_in_range(ADCIV,ADCIV_ADCIFG))
{
case ADCIV_NONE: break;
case ADCIV_ADCOVIFG: break;
case ADCIV_ADCTOVIFG: break;
case ADCIV_ADCHIIFG: break;
case ADCIV_ADCLOIFG: break;
case ADCIV_ADCINIFG: break;
case ADCIV_ADCIFG: ADC_Result = ADCMEM0;
//Clear CPUOFF bit from LPM0
__bic_SR_register_on_exit(LPM0_bits);
break;
default: break;
}
}

//*******************************************************************

9.4 MSP430FR5994 ANALOG-TO-DIGITAL CONVERTER


In this section we introduce the MSP430FR5994 system ADC referred to as ADC12_B. We
describe its features, operation, registers, and conclude with several programming examples.

9.4.1 ADC12_B FEATURES


The ADC12_B system is a flexible and powerful ADC system with an extensive list of fea-
tures [SLAU367O, 2017].
9.4. MSP430FR5994 ANALOG-TO-DIGITAL CONVERTER 377
• ADC12_B provides 14-bits of ADC resolution. Recall, the resolution of a converter pro-
vides 2b number of incremental steps between the high and low reference voltages.

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

• ADC12_B is supported by a variety of interrupts.

9.4.2 MSP430FR5994 ADC12_B OPERATION


A basic block diagram of ADC12_B is shown in Figure 9.6a. An input analog channel is se-
lected for conversion by the input voltage select multiplexer (mux). The selected signal is held
constant by the sample and hold (S/H) circuitry during the conversion process. The stable sig-
nal is then fed to the SA converter. The SA converter receives input from the reference voltage
select, the timing source, and trigger source for conversion. The digital result of the conver-
sion, provided as n bits, is stored in result registers. Specific interrupts may be selected to signal
different significant events in the ADC process.
A block diagram of SA converter operation is provided in Figure 9.6b. As its name im-
plies, the SA converter will make successive guesses at the unknown sample voltage value. It
begins with a guess of one-half of the reference voltage. This digital guess is converted to a cor-
responding analog value by the DAC. The analog guess is compared to the unknown sample
voltage by the voltage comparator. The output from the comparator prompts the SA to guess
higher or lower. This process continues n times (one for each bit in the SA register). The guess
progresses from one-half of the reference voltage to one-fourth to one-eighth, etc. as shown in
Figure 9.6c. When the conversion is complete, the end of conversion signal goes logic high.
378 9. ANALOG PERIPHERALS
The detailed block diagram of ADC12_B is provided in Figure 9.10. It may appear a bit
overwhelming at first; however, it is simply a more detailed version of the basic block diagram
you have seen in Figure 9.6. The operation of the ADC12_B is configured and controlled by
registers ADC12CTL0 through ADC12CTL4. The bit designators from these registers are
shown at various points on the diagram.

Reference Voltage Select


VREF+/VeREF+
REFOUT REFOUT
REFOUT
BUF_EXT 000
0 001
VREF+ 1 …
1 !REFOUT and ADC12VRSEL bit 0 …
VeREF- 0 … VREF 1.2V, 2.0 V, 2.5 V
AVSSAVCC BUF_INT 111 from shared reference
ADC12INCHx
5
Reference
Voltage
ADC12VRSEL bits 1-3
ADC12CH3MAP
A0 ADC12VRSEL
0000 Select
External A26 A1 0001
0 A2 0010
Internal 3 A3 0011 ADC12ON ADC12SSELx
1 A4 ADC12DIVx ADC12PDIV
ADC12CH2MAP
Sample Time Base Select
.. and Va- Va+ 00 MODCLK from UCS
. 00 :1
External A27 Hold Divider 01 :4 01 ACLK
0 12-bit ADC Core 10 :32
/1 ../8 10 MCLK
Internal 2 1 S/H 11 :64
Convert 11 SMCLK
ADC12CH1MAP A26 11010 ADC12CLK
External A28 A27 ADC12BUSY ADC12SHSx
11011 ADC12ISSH
0 ADC12SHP ADC12SHT0x ADC12ENC
Internal 1 1 4
000
Trigger Source
ADC12CH0MAP .. Sample Timer SHI 0 001
. /4 ../1024 …
1 1 Sync …
External A29 Trigger Sources
0 SAMPCON 0 4 …
Internal 0 111
1 A28 ADC12SHT1x
11100 ADC12MSC
ADC12TCMAP
External A30 A29 ADC12MEM0 ADC12MCTL0 ADC12HIx
0 11101 - - To Interrupt
TempSense 1 ADC12CSTARTADDx
32 × 12 32 × 16 Logic
Memory Memory 12-bit Window
ADC12BATMAP A30 Comparator
11110 ADC12CONSEQx Buffer Control
External A31 11111 - -
0 A31
Batt.Monitor 1 ADC12MEM31 ADC12MCTL31 ADC12HLOx

Result Storage and Processing

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]:

• ADC memory interrupt flags (ADC12IFG0 to ADC12IFG31)

• ADC12MEMx overflow (ADC12OVIFG)

• Conversion time overflow (ADC12TOVIFG)

• ADC12LO interrupt flag (ADC12LOIFG)

• ADC12IN interrupt flag (ADC12INIFG)

• ADC12HI interrupt flag (ADC12HIIFG)

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.

9.4.3 MSP430FR5994 REGISTER SUMMARY


ADC operation and feature selection are determined by user selected settings in the ADC reg-
isters. The ADC register set includes the following registers [SLAU367O, 2017]:
380 9. ANALOG PERIPHERALS

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

ADC12_B Interrupt Vector (ADC12IV) Register


1

0
ADC12OVIFG
1

0
ADC12TOVIFG
1
Interrupt Source
0
ADC12LOIFG
1

0
ADC12INIFG
1

0
ADC12HIIFG
1

ADC12_B Interrupt Enable 0-2


D O E
D 2 E
A 12 I I E
A 1 2I I E
C IE
x
IE
A 12 VI
A C1 VI

C O
D N
C H

12

(ADC12IER0 - 2) registers
D O

D L
A 1 2T
C
C
D
A

Figure 9.11: MSP430FR5994 ADC12_B interrupts overview.


9.4. MSP430FR5994 ANALOG-TO-DIGITAL CONVERTER 381
• ADC12CTL0 to ADC12CTL3, ADC Control registers 0–3
• ADC12MCTL0 to ADC12MCTL31, ADC Memory Control registers 0–31
• ADC12MEM0 to ADC12MEM31, ADC Conversion Memory register. Conversion re-
sults are stored here.
• ADC12IER0 to ADC12IER2, ADC Interrupt Enable registers. Used to enable individ-
ual interrupts.
• ADC12IFGR0 to ADC12IFGR2, ADC Interrupt Flag registers. Corresponding flags
for individual ADC interrupts are provided here.
• ADC12IV, ADC Interrupt Vector register. Provides numerical value of active interrupt.
Details of configuring selected registers is provided in SLAU367O [2017]. We highlight
the settings of selected ADC Control Registers in Figure 9.12.

9.4.4 ANALYSIS OF RESULTS


The ADC12_B provides a digital representation of the analog sample in a binary unsigned for-
mat. The values range from 0000h to 3FFFh . If the sampled signal is below the low reference
voltage, ADC12_B reports 0000h ; whereas, if the sampled signal exceeds the high reference,
ADC12_B reports 3FFFh . For analog sensed values between the low and high reference voltage,
ADC12_B reports a value of NADC when configured for single-ended operation [SLAU367O,
2017]:
NADC D 212  ..VinC C 1=2LSB VRC /=.VRC VR //;
where:
LSB D .VRC VR /=212 :
If configured for differential mode, ADC12_B reports a value of:
NADC D 211  ..VinC Vin /=.VRC VR // C 211 :

9.4.5 PROGRAMMING THE MSP430FR5994 ADC12_B SYSTEM


The ADC12_B system may be programmed using Energia, APIs contained in DriverLib, and
via register settings in C.

Programming the MSP430FR5994 with Energia


The Energia library contains several functions to support analog conversions including ADC-
and DAC-related functions (www.energia.nu).
• analogRead(): The analogRead function performs an ADC conversion on the indicated
analog pin. The measured voltage is converted to an integer value between 0 and 1023,
where 0 corresponds to 0 VDC and 1023 corresponds to 3.3 VDC.
382 9. ANALOG PERIPHERALS
15 14 13 12 11 10 9 8
ADC12SHT1x ADC12SHT0x
rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0)
7 6 5 4 3 2 1 0
ADC12MSC Reserved ADC12ON Reserved ADC12ENC ADC12SC
rw-(0) r-0 r-0 rw-(0) r-0 r-0 rw-(0) rw-(0)
Can be modified only when ADC12ENC = 0
(a) ADC12_B Control 0 register (ADC12CTL0)
ADC12CTL0[4]: ADC on: ADC12ON: 0 = ADC off, 1 = ADC on
ADC12CTL0[1]: ADC enable conversion: ADC12ENC: 0 = disabled, 1 = enabled
ADC12CTL0[0]: ADC start conversion: ADC12SC: 0 = no conversion, 1 = start conversion
15 14 13 12 11 10 9 8
Reserved ADC12PDIV ADC12SHSx ADC12SHP ADC12ISSH
r-0 rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0)
7 6 5 4 3 2 1 0
ADC12DIVx ADC12SSELx ADC12CONSEQx ADC12BUSY
rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) rw-(0) r-(0)
Can be modified only when ADC12ENC = 0
(b) ADC12_B Control 1 register (ADC12CTL1)
ADC12CTL1[14-13]: ADC12_B clock predivider: ADC12PDIV: 00 = 1, 01 = 4, 10 = 32, 11 =64
ADC12CTL1[7-5]: ADC clock divider: ADC12DIVx: 000 = 1 to 111 = 8
ADC12CTL1[4-3]: ADC clock source select: ADC12SSELx: MODCLK (00), ACLK (01), MCLK (10), SMCLK (11)
ADC12CTL1[2-1]: ADC conversion sequence: ADC12CONSEQx:
single channel, single conversion (00): sequence of channels, single conversion (01),
single channel, repeat conversion (10): sequence of channels, repeat conversion (11)
ADC12CTL1[0]: ADC12BUSY: 0 = inactive, 1 = active
15 14 13 12 11 10 9 8
Reserved
r0 r0 r0 r0 r0 r0 r0 r0
7 6 5 4 3 2 1 0
Reserved ADC12RES ADC12DF Reserved ADC12PWRMD
r0 r0 rw-(1) rw-(0) rw-(0) r0 r0 rw-(0)
(c) ADC12_B Control 2 register (ADC12CTL2)
ADC12CTL2[5-4]: ADC resolution: ADC12RES: 00 = 8 bit, 01 = 10 bit, 10 = 12 bit
ADC12CTL2[3]: ADC read back format: ADC12DF: 0: unsigned binary, 1= 2's complement signed binary
15 14 13 12 11 10 9 8
Reserved ADC12WINC ADC12DIF Reserved ADC12VRSEL
r0 rw-(0) rw-(0) r0 rw-(0) rw-(0) rw-(0) rw-(0)
7 6 5 4 3 2 1 0
ADC12EOS Reserved ADC12INCHx
rw-(0) r0 r0 rw-(0) rw-(0) rw-(0) rw-(0) rw-(0)
Can be modified only when ADC12ENC = 0
(d) ADC12_B Conversion Memory Control Register (ADCMCTLx)
ADCMCTLx [11-8]: ADC12VRSEL: Voltage reference select
ADCMCTLx[7]: ADC12EOS: 0 = not complete, 1 = complete
ADCMCTLx[4-0]: ADC12INCHx : Input channel select 00000 to 11111

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.

– DEFAULT: sets ADC high reference level to VCC 3.3 V.


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

Programming the MSP430FR5994 ADC12_B in C


To successfully configure and program the converter, the following steps should be followed.

1. Select the desired ADC reference voltage via ADC12SREFx bits in the ADC12MCTLx
register.

2. Connect analog signal(s) for conversion to appropriate input pins (A0-A31).

3. Turn on the ADC: ADC12ON in ADC12CTL0.

4. Select the clock source and the sampling mode in ADC12CTL1.

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.

6. Initiate conversion: ADC12ENC bit in ADC12CTL0.

7. Monitor for conversion completion using the ADC12IFG0 flag.

8. Use the results of the conversion located in the corresponding result register
(ADC12MEMx).

9. Repeat the process starting at step 6.

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;

//Disable the GPIO power-on default high-impedance mode to activate


//previously configured port settings
PM5CTL0 &= ~LOCKLPM5;

//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;

case ADC12IV__ADC12IFG1: break; //Vector 14: ADC12MEM1


case ADC12IV__ADC12IFG2: break; //Vector 16: ADC12MEM2
case ADC12IV__ADC12IFG3: break; //Vector 18: ADC12MEM3
case ADC12IV__ADC12IFG4: break; //Vector 20: ADC12MEM4
case ADC12IV__ADC12IFG5: break; //Vector 22: ADC12MEM5
case ADC12IV__ADC12IFG6: break; //Vector 24: ADC12MEM6
case ADC12IV__ADC12IFG7: break; //Vector 26: ADC12MEM7
case ADC12IV__ADC12IFG8: break; //Vector 28: ADC12MEM8
case ADC12IV__ADC12IFG9: break; //Vector 30: ADC12MEM9
case ADC12IV__ADC12IFG10: break; //Vector 32: ADC12MEM10
case ADC12IV__ADC12IFG11: break; //Vector 34: ADC12MEM11
case ADC12IV__ADC12IFG12: break; //Vector 36: ADC12MEM12
case ADC12IV__ADC12IFG13: break; //Vector 38: ADC12MEM13
case ADC12IV__ADC12IFG14: break; //Vector 40: ADC12MEM14
case ADC12IV__ADC12IFG15: break; //Vector 42: ADC12MEM15
case ADC12IV__ADC12IFG16: break; //Vector 44: ADC12MEM16
case ADC12IV__ADC12IFG17: break; //Vector 46: ADC12MEM17
9.5. MSP430FR5994 COMPARATOR 387
case ADC12IV__ADC12IFG18: break; //Vector 48: ADC12MEM18
case ADC12IV__ADC12IFG19: break; //Vector 50: ADC12MEM19
case ADC12IV__ADC12IFG20: break; //Vector 52: ADC12MEM20
case ADC12IV__ADC12IFG21: break; //Vector 54: ADC12MEM21
case ADC12IV__ADC12IFG22: break; //Vector 56: ADC12MEM22
case ADC12IV__ADC12IFG23: break; //Vector 58: ADC12MEM23
case ADC12IV__ADC12IFG24: break; //Vector 60: ADC12MEM24
case ADC12IV__ADC12IFG25: break; //Vector 62: ADC12MEM25
case ADC12IV__ADC12IFG26: break; //Vector 64: ADC12MEM26
case ADC12IV__ADC12IFG27: break; //Vector 66: ADC12MEM27
case ADC12IV__ADC12IFG28: break; //Vector 68: ADC12MEM28
case ADC12IV__ADC12IFG29: break; //Vector 70: ADC12MEM29
case ADC12IV__ADC12IFG30: break; //Vector 72: ADC12MEM30
case ADC12IV__ADC12IFG31: break; //Vector 74: ADC12MEM31
case ADC12IV__ADC12RDYIFG: break; //Vector 76: ADC12RDY
default: break;
}
}

//******************************************************************

9.5 MSP430FR5994 COMPARATOR


The MSP430FR5994 is equipped with a comparator system called COMP_E. COMP_E pro-
vides two channels of analog comparators. As its name implies, a comparator compares an analog
signal with a known reference. If the analog signal is greater than the reference, the output of
the comparator is logic high. On the other hand, if the analog signal is less than the reference,
the analog output is low.
The COMP_E system is controlled by a complement of registers. Register set-
tings are provided in MSP430FR58xx, MSP430FR59xx, and MSP430FR6xx Family User’s
Guide [SLAU367O, 2017].
• CECTL0 Comparator_E control register 0
• CECTL1 Comparator_E control register 1
• CECTL2 Comparator_E control register 2
• CECTL3 Comparator_E control register 3
• CEINT Comparator_E interrupt register
• CEIV Comparator_E interrupt vector word
388 9. ANALOG PERIPHERALS
Example: In this example, the comparator CompE is used with an internal reference to deter-
mine if the input “Vcompare” is high or low. When “Vcompare” exceeds 2.0 V, COUT goes
high and when “Vcompare” is less than 2.0 V, CEOUT goes low.

//******************************************************************
// --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;

//Disable the GPIO power-on default high-impedance mode to activate


//previously configured port settings
PM5CTL0 &= ~LOCKLPM5;

//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
}

//*******************************************************************

9.6 ADVANCED ANALOG PERIPHERALS


Although not available on the MSP430FR2433 and the MSP430FR5994 variants, this section
provides information on enhanced analog peripheral features.

9.6.1 SMART ANALOG COMBO (SAC)


Available on MSP430FR2355 and MSP430FR2311 microcontrollers, the Smart Analog
Combo is an analog peripheral module that removes needs for external Op Amps circuits for
interfacing sensors and measurement devices with the MSP430 controller. The module con-
nects the controller to a sensor whose output is a low amplitude analog signal that needs to be
amplified and digitized before it can be used by a microcontroller. It can also be configured to
generate an analog signal for driving an external device. Thus, it is a programmable submodule
of the controller that performs signal conditioning for analog input and output signals, removing
the needs for additional circuits and providing one-chip solution. The module is made of gain
390 9. ANALOG PERIPHERALS
amplifiers (gain value of up to 33) integrated with a 12-bit digital-to-analog converter (DAC).
For inputs, the module is connected internally to an internal analog-to-digital converter (ADC)
for MSP430FR2355, for example, again, allowing built-in, easy analog to digital conversion and
signal conditioning capabilities
Three configurations are available for the Smart Analog Combo module. Configuration
SAC-L1 allows only the integration of an operational amplifier function for an application.
Configuration SAC-L2 allows application of a programmable gain amplifier (PGA) with gain
up to 33, and configuration SAC-L3 allows the integration of PGA and DAC. MSP430 family
microcontrollers have varying number of SAC units in a SAC module, enabling different con-
figurations for a variety of applications. We refer the reader to obtain device specific data sheet
for details.

9.6.2 ENHANCED COMPARATOR (ECOMP)


The enhanced comparator of MSP430 controller compares an analog voltage signal with the
output of a built-in 6 bit DAC output, working as a reference signal. The comparator is available
to some of MSP430 family controllers (MSP430FR2111, MSP430FR2110, MSP430FR2100,
and MSP430FR2000) to allow a programmer to configure the controller for simple analog-to-
digital applications, applications not requiring high-resolution ADC capabilities. The enhanced
comparator is typically used to implement a simple ADC function.

9.6.3 TRANSIMPEDANCE AMPLIFIER (TIA)


Found in some of MSP430 controllers (MSP430F2274, MSP430FR2311, for example), the
transimpedance amplifier converts an electric current signal into a voltage signal. Using the
built-in analog-to-digital converter, TIA is used in an application where the input signal is in
the form of electric current. The unit contains an integrated operational amplifier, which needs
to be programmed according to requirements of an application along with a feedback resistor.
A typical application of TIA is to measure the amount of lights in an environment using a
photodiode connected to an MSP430 controller. The conversion allows a controller to initiate
actions appropriately, based on the light condition of an environment. The objective of designers
of the TIA module is to provide users with a tool to simplify an overall system design by taking
advantage of the onboard operational amplifier to create an ADC for electrical current signal
input.

9.7 LABORATORY EXERCISE: SMART HOME SENSOR


In this section, your task is to program both the ADC12 and DAC12 converters to perform two
smart home functions. How many times have you been told by your parents to turn off lights
as you were growing up? Or if you are a parent, how many times did you have to remind your
children to turn off lights when they leave their rooms? In the smart home of our choice, we
9.8. REFERENCES AND FURTHER READING 391
will solve this problem once and for all. We will do so using the MSP430 controller’s analog-
to-digital converters.
To that end, suppose that we installed infrared sensors at each room of the house to detect
human locations. A precise location of each human is measured using multiple infrared sensors,
and based on the locations of humans, in the house, lights will automatically be turned on and
turned off. An infrared sensor consists of a transmitter and a receiver. The transmitter sends out
an infrared signal and waits for any reflection of the transmitted signal. If a human is in the path
of the signal, the signal is reflected back to the receiver. By measuring the amount of reflection
of the light, we can compute the distance of a human from the particular sensor. By placing
these sensors at appropriate locations in each room and combining the sensor information, we
can compute the location of each person in the house. The job of the ADC is to convert the
received infrared light signal into appropriate distance from the sensor. That is, the received
signal strength is converted into a numerical number that represents the distance.
Suppose that the infrared light transmitter and receiver pair is calibrated such that when a
person is within 2 ft from the sensor mounted on a wall the receiver generates 2.5 VDC. When
a person is at distance 15 ft away from the sensor, the receiver generates a 1.0 VDC signal. The
output of the receiver changes linearly as the distance between the sensor and a person changes
from 2–15 ft. If no person is in front of the sensor, the receiver outputs 0 V. Suppose also that
for each sensor, a MSP430 microcontroller is attached. Your task is to write a program utilizing
the ADC module to do the following.
1. Use the 12-bit format of ADC.
2. Set reference voltages to be 2.5 V and 0 V.
3. Insure the receiver output is directly connected to pin A0. Continuously convert ADC12
inputs.
4. Using a four-sample sliding window and the associated interrupt system, continually com-
pute the average of four ADC outputs and send resulting average values to an array.
MSP430 controllers (sensors) around the smart home continuously send their data to a
central controller that controls which lights of the house get to be turned on and turned off. Of
course, some type of a high-level decision maker controller must also be involved to remove any
irritable system behavior such as turning lights off in an area when a person leaves the area for
a short time.

9.8 REFERENCES AND FURTHER READING


Analog Input to PWM Output Using the MSP430 MCU Enhanced Comparator, (SLAA833), Texas
Instruments, 2018.
MSP430F2273 Transimpedance Amplifier, (TIDU443),
392 9. ANALOG PERIPHERALS
MSP430FR4xx and MSP430FR2xx Family User’s Guide, (SLAU445G), Texas Instruments,
2016. 366, 369, 371, 372
MSP430FR58xx, MSP430FR59xx, and MSP430FR6xx Family User’s Guide, (SLAU367O),
Texas Instruments, 2017. Texas Instruments, 2014. 376, 379, 381, 382, 387

9.9 CHAPTER PROBLEMS


Fundamental
1. Using the Nyquist sampling rate, find the minimum sampling frequency of an ADC if the
highest frequency of an input analog signal is 2 kHz.
2. Given a sinusoidal input analog signal, 5 cos.210kt/, and sampling frequency of 1 KHz,
find the first three sampled values with starting time 0.
3. Given an 8-bit ADC and input range of 0 V and 5 V, what is the quantization level for
sampled value of 2.9 V?
4. What is the quantization error for the sampled signal in Problem 3?
5. What is the encoded value of quantization level from Problem 3?
6. Repeat questions 3–6 for a 3.3 VDC ADC.

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

Enhanced Universal Serial


Communication Interface (eUSCI)

eUSCI_A0 eUSCI_B0

- UART mode - I2C mode


- IrDA pulse shaping mode - SPI mode
- SPI mode

eUSCI_A1 eUSCI_B0

- UART mode - I2C mode


- IrDA pulse shaping mode - SPI mode
- SPI mode

Figure 10.1: MSP430 enhanced universal serial communication interface (eUSCI).

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.

10.2 SERIAL COMMUNICATION CONCEPTS


Before we delve into the serial communication technologies, we first review common serial com-
munication terminology.
Asynchronous vs. synchronous serial transmission: In serial communications, the trans-
mitting and receiving devices must agree on the “rules of engagement” by using a common data
rate and protocol. This allows both the transmitter and receiver to properly coordinate data trans-
mission/reception. There are two basic methods of maintaining coordination or “sync” between
the transmitter and receiver: asynchronous and synchronous.
In an asynchronous serial communication system, such as the UART aboard the MSP430
microcontroller, framing bits are used at the beginning and end of a data byte. The framing bits
alert the receiver that an incoming data byte has arrived and also signal the completion of the
data byte reception. The data rate for an asynchronous serial system is typically much slower than
the synchronous system, but it only requires a single wire between the transmitter and receiver
(and a common ground) for simplex (one way) communication.
A synchronous serial communication system maintains “sync” between the transmitter
and receiver by employing a common clock between the two devices. Data bits are sent and
received at the time when a clock edge appears. This allows higher data transfer rates than with
asynchronous techniques but the communication method requires a minimum of two lines (and
a common ground), data and clock, to connect a receiver and a transmitter for simplex commu-
nications.
398 10. COMMUNICATION SYSTEMS
Baud rate: Data transmission rates are typically specified as a Baud or bits per second rate.
For example, 9600 Baud indicates the data is being transferred at 9600 bits per second.
Full duplex: Often serial communication systems must both transmit and receive data
simultaneously. To do so requires separate hardware for transmission and reception at each end of
the communication link. A single duplex system has a single complement of hardware that must
be switched from transmission to reception configuration. A full duplex serial communication
system has separate hardware for transmission and reception.
Non-return to zero (NRZ) coding format: There are many different coding standards
used within serial communications. The important point is a transmitter and a receiver must
use a common coding standard so data may be interpreted correctly at the receiving end. The
MSP430 microcontroller uses a non-return to zero (NRZ) coding standard. In NRZ coding, a
logic one is signaled by a logic high during the entire time slot allocated for a single bit, whereas,
a logic zero is signaled by a logic low during the entire time slot allocated for a single bit.
The RS-232 communication protocol: When serial transmission occurs over a long dis-
tance, additional techniques may be used to insure data integrity. Over long distances, logic
levels degrade and may be corrupted by noise. When this happens at the receiving end, it is dif-
ficult to discern a logic high from a logic low. The RS-232 standard has been around for some
time. With the RS-232 standard (EIA RS-232), a logic one is represented with a 12 VDC
level while a logic zero is represented by a C12 VDC level. Chips are commonly available (e.g.,
MAX3232) that convert the output levels from a microcontroller to RS-232 compatible levels
and convert back to microcontroller compatible levels at the receiver. The RS-232 standard also
specifies other features for this communication protocol such as connector type and pinout.
Parity: To enhance data integrity during transmission, parity techniques may be used. A
parity bit is an additional bit (or bits) that is transmitted with the data byte. With a single parity
bit, a single-bit error may be detected. Parity may use an even or odd parity bit. In even parity, the
parity bit is set to one or zero such that the number of ones in the data byte including the parity
bit is an even number. In odd parity, the parity bit is set to one or zero such that the number
of ones in the data byte including the parity bit is odd. At the receiver, bits within a data byte,
including the parity bit, are counted to determine if parity has changed during transmission. A
change in parity indicates an error occurred during transmission. For single-bit error correction
or multiple-bit error detection, additional parity bits are required.
ASCII: The American Standard Code for Information Interchange (ASCII) is a stan-
dardized, seven bit method of encoding alphanumeric data. It has been in use for many decades,
so some of the characters and actions listed in the ASCII table are not in common use today.
However, ASCII is still the most common method of encoding alphanumeric data code, is
shown in Figure 10.2. For example, the capital letter “G” is encoded in ASCII as 0x47. The “0x”
symbol indicates the hexadecimal number representation. Unicode is the international counter-
10.3. MSP430 UART 399
part of ASCII. It provides standardized 16-bit encoding format for the written languages of the
world. ASCII is a subset of Unicode. The interested reader is referred to the Unicode home page
website at: www.unicode.org for additional information on this standardized encoding format.

Most Significant Digit


0x0_ 0x1_ 0x2_ 0x3_ 0x4_ 0x5_ 0x6_ 0x7_

0x_0 NUL DLE SP 0 @ P ` p


0x_1 SOH DC1 ! 1 A Q a q
0x_2 STX DC2 “ 2 B R b r
0x_3 ETX DC3 # 3 C S c s
Least Significant Digit

0x_4 EOT DC4 $ 4 D T d t


0x_5 ENQ NAK % 5 E U e u
0x_6 ACK SYN & 6 F V f v
0x_7 BEL ETB ‘ 7 G W g w
0x_8 BS CAN ( 8 H X h x
0x_9 HT EM ) 9 I Y i y
0x_A LF SUB * : J Z j z
0x_B VT ESC + ; K [ k {
0x_C FF FS ‘ < L \ l |
0x_D CR GS - = M ] m }
0x_E SO RS . > N ^ n ~
0x_F SI US / ? O _ o DEL

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.

10.3 MSP430 UART


The UART system is located within the eUSCI module A. In this section, we discuss UART
features, provide an overview of the UART hardware operation and character format, discuss
how to set the UART Baud rate, provide an overview of UART-related registers, and conclude
with several examples.

10.3.1 UART FEATURES


The MSP430 microcontroller is equipped with a powerful and flexible UART system. To select
the UART (asynchronous) mode the Synchronous Mode Enable bit (UCSYNC bit) located
in the eUCSI_Ax Control Register 0 (part of eUSCI_Ax Control Word 0) must be cleared to
0. This action places the system in the asynchronous mode. When in this mode, serial data is
transmitted from the microcontroller via the UCAxTXD pin and received via the UCAxRXD
400 10. COMMUNICATION SYSTEMS
pin. (Note: The “x” designates which eUSCI_A module is employed (e.g., 0, 1, 2)) [SLAU445G,
2016, SLAU367O, 2017].
The UART system provides features that allow the MSP430 to communicate with a wide
variety of peripheral devices or another microcontroller. These features include [SLAU445G,
2016, SLAU367O, 2017]:
• support for serial transmission protocols including the capability to transmit 7- or 8-bit
data with odd, even, or no parity;
• independent transmit and receive shift registers equipped with separate transmit and re-
ceive buffer registers;
• capability to send or receive data the LSB first or the MSB on both the transmit and
receive channels. This feature allows the MSP430 microcontroller to match the protocol
of an existing peripheral device;
• capability to operate within a multiprocessor system using the built-in, idle-line, and
address-bit communication protocols;
• auto wake-up feature from a low power mode (LPMx) when a start edge is received;
• extensive flexibility in setting programmable baud rates;
• system status flags for error detection, error suppression, and address detection; and
• interrupts for the data receive and transmit.
In the next section, we examine how these features are incorporated into the UART hard-
ware.

10.3.2 UART OVERVIEW


Provided in Figure 10.3 is a block diagram of the eUCSI_Ax module configured for UART
(asynchronous) mode (UCSYNC bit D 0). The UART module can be subdivided into the Baud-
-Rate Generator (center of Figure 10.3), the receiver-related hardware (top of figure), and the
transmit hardware (lower portion of figure). We discuss each in turn.
The eUSCI_Ax module communicates asynchronously with another device (e.g., periph-
eral) when the UCSYNC mode is set to zero. As previously mentioned, in an asynchronous
mode, the transmitter and receiver maintain synchronization with one another, using start and
stop bits to frame each data byte sent. It is essential that both transmitter and receiver are con-
figured with the same Baud rate, number of start and stop bits, and the type of parity employed
(odd, even, or none).
The Baud rate is set using the Baud-Rate Generator shown in the center of Figure 10.3.
The clock source for the Baud-Rate Generator may either be the UCAxCLK, ACLK, or SM-
CLK. The clock source is selected using the eUSCI clock source select bits (UCSSELx) located
10.3. MSP430 UART 401

UCRXEIE Error Flags UCRXERR


UCMODEx UCSPB UCDORM
UCRXBRKIE UCPE
2 UCFE
Set Flags UCOE
Receive State Machine
Set RXIFG Set UCRXIFG
Set UCBRK
Set UCADDR/UCIDLE
UCIRRXPL
UCIRRXFLx
UCIRRXFE
Receive Buffer UCAxRXBUF UCIREN 6 UCLISTEN
1
IrDA Decoder
1 0 UCAxRXD
Receive Shift Register 0
0
1
UCPEN UCPAR UCMSB UC7BIT

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

UCPEN UCPAR UCMSB UC7BIT UCIREN

Transmit Shift Register 0

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:

• parity enable bit, UCPEN (0: parity disabled, 1: parity enabled),

• parity select bit, UCPAR (0: odd parity, 1: even parity),

• MSB first select, UCMSB (0: LSB first, 1: MSB first), and

• character length bit, UC7BIT (0: 8-bit data, 1: 7-bit data)

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 eUSCI mode, UCMODEx (00: UART mode), and

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

10.3.3 CHARACTER FORMAT


As previously mentioned, the UART system has great flexibility in setting the protocol of the se-
rial data, including the number of bits (7 or 8), parity (even, odd, or none), MSB or LSB first, and
selection of transmit/receive operation. A typical serial data word is illustrated in Figure 10.4.
To verify the valid functionality of the communication using the MSP430 microcontroller, it
is very helpful to write a short program to transmit the same piece of data continuously from
the UART and observe the transmission on the UCAxTXD pin with an oscilloscope or a logic
analyzer.

10.3.4 BAUD RATE SELECTION


The MSP microcontroller also has considerable flexibility in setting the Baud rate for UART
transmission and reception. It has two different modes for Baud rate generation.
10.3. MSP430 UART 403

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.

To set a specific Baud rate, the following parameters must be determined:

• 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].

10.3.5 UART ASSOCIATED INTERRUPTS


The UART system has two associated interrupts. The transmit interrupt flag (UCTXIFG) is
set when the UCAxTXBUF is empty, indicating another data byte may be sent. The receive
interrupt flag (UCRXIFG) is set when the receive buffer (UCAxRXBUF) has received a com-
plete character. Both of these interrupt flags are contained within the eUSCI_Ax interrupt flag
register (UCAxIFG).
404 10. COMMUNICATION SYSTEMS
10.3.6 UART REGISTERS
As discussed throughout this section, the basic features of the UART system is configured and
controlled by the following UART-related registers [SLAU445G, 2016, SLAU367O, 2017]:
• UCAxCTLW0 eUSCI_Ax Control Word 0

• UCAxCTL0 eUSCI_Ax Control 0

• UCAxCTL1 eUSCI_Ax Control 1

• UCAxCTLW1 eUSCI_Ax Control Word 1

• UCAxBRW eUSCI_Ax Baud Rate Control Word

• UCAxBR0 eUSCI_Ax Baud Rate Control 0

• UCAxBR1 eUSCI_Ax Baud Rate Control 1

• UCAxMCTLW eUSCI_Ax Modulation Control Word

• UCAxSTATW eUSCI_Ax Status

• UCAxRXBUF eUSCI_Ax Receive Buffer

• UCAxTXBUF eUSCI_Ax Transmit Buffer

• UCAxABCTL eUSCI_Ax Auto Baud Rate Control

• UCAxIRCTL eUSCI_Ax IrDA Control

• UCAxIRTCTL eUSCI_Ax IrDA Transmit Control

• UCAxIRRCTL eUSCI_Ax IrDA Receive Control

• UCAxIE eUSCI_Ax Interrupt Enable

• UCAxIFG eUSCI_Ax Interrupt Flag

• UCAxIV eUSCI_Ax Interrupt Vector


Details of specific register and bits settings are contained in SLAU367O [2017]
and SLAU445G [2016]. Figure 10.5 provides the bit settings of eUSCI_Ax Control Word
0 for basic UART operation using eUSCI_Ax.

10.4 CODE EXAMPLES


The MSP430 UART features may be programmed using Energia, DriverLib APIs, or in C.
10.4. CODE EXAMPLES 405
15 14 13 12 11 10 9 8
UCPEN UCPAR UCMSB UC7BIT UCSPB 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 UCRXEIE UCBRKIE UCDORM UCTXADDR UCTXBRK 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]: Parity enable: UCPEN: 0 = off, 1 = on
UCAxCTLW0[14]: Parity select: UCPAR: 0 = odd, 1 = even
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]: Stop bit select: UCSPB: 0 = 1 stop bit, 1 = two stop bits
UCAxCTLW0[10-9]: eUSCI_A mode: UCMODEx: 00 = UART mode
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.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

Vcc = 3.3 VDC Vcc = 3.3 VDC

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);
}

//*******************************************************************

10.4.2 UART C EXAMPLE


Example: In this example the MSP430 UART’s TX pin is connected to the RX pin. The exam-
ple shows proper initialization of registers and interrupts to receive and transmit data. If data is
incorrect P1.0 LED is turned ON.
//********************************************************************
// --COPYRIGHT--,BSD_EX
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// MSP430 CODE EXAMPLE DISCLAIMER
//
//********************************************************************
//MSP430FR24xx Demo - USCI_A0 External Loopback test @ 115200 baud
//
//Description: This demo connects TX to RX of the MSP430 UART
//The example code shows proper initialization of registers
//and interrupts to receive and transmit data. If data is incorrect,
//P1.0 LED is turned ON.
// ACLK = n/a, MCLK = SMCLK = BRCLK = DCODIV ~1MHz.
//
// MSP430FR2433
// -----------------
// /|\| |
// | | |
// --|RST |
// | |
// | |
// | P1.4/UCA0TXD|----
// | | |
// | P1.5/UCA0RXD|----
// | |
10.4. CODE EXAMPLES 409
// | P1.0 |--> LED
// | |
//
//Ling Zhu, Texas Instruments Inc., July 2015
//Built with:
// IAR Embedded Workbench v6.20 & Code Composer Studio v6.0.1
//********************************************************************

#include <msp430.h>

unsigned char RXData = 0;


unsigned char TXData = 1;

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.

10.5.1 SPI OPERATION


The SPI may be viewed as a synchronous 16-bit shift register with an 8-bit, half residing in
the transmitter and the other 8-bit half residing in the receiver, as shown in Figure 10.7. The
transmitter is designated as the master since it provides the synchronizing clock source between
the transmitter and the receiver. The receiver is designated as the slave. A slave is chosen for
reception by taking its slave select (SS) line low. When the SS line is taken low, the slave’s
register shifting capability is enabled.
SPI transmission is initiated by loading a data byte into the master-configured transmit
buffer (UCxTXBUF). At that time, the UCSI SPI mode Bit Clock Generator provides clock
pulses to the master and also to the slave via the UCxCLK pin. A single bit is shifted out of
the master designated shift register on the slave in master out (UCxSIMO) microcontroller pin
on every SCK pulse. The data is received at the UCxSIMO pin of the slave designated device.
In some peripheral devices, this is referred to as master out slave in (MOSI). At the same time,
a single bit is shifted out of the slave out master in (UCxSOMI) pin of the slave device and
into the UCxSOMI pin of the master device. After eight master UCxCLK clock pulses, a byte
of data has been exchanged between the master and slave designated SPI devices. Completion
of data transmission in the master and data reception in the slave is signaled by SPI-related
interrupts in both devices. At that time, another data byte may be transmitted.

10.5.2 MSP430 SPI FEATURES


As previously mentioned, the MSP430 SPI system has many features that allow the system
to be interfaced to a wide variety of SPI configured peripheral devices. These features in-
clude [SLAU445G, 2016, SLAU367O, 2017]:
• 7- or 8-bit data length,
• LSB-first or MSB-first data transmit and receive capability,
• 3- or 4-wire SPI operation,
• master or slave modes,
412 10. COMMUNICATION SYSTEMS

MSP430 USCI
Master Device
UCxSOMI Slave Device
Transmit Buffer (UCxTXBUF)
SPI Data Register (SDR)
MSB Transmit Shift Register LSB MSB LSB

UCxSIMO MOSI

UCxCLK SCK Shift


Baud rate Enable
clock SPI Bit Clock Generator
UCxCLK SCK
Status Registers
USCI_Ax Status Register (UCAxSTAT)
USCI_Bx Status Register (UCBxSTAT) UCxSTE
Control Registers SS
USCI_Ax Control Register 0 (UCAxCTL0)
USCI_Bx Control Register 0 (UCBxCTL0)
USCI_Ax Control Register 1 (UCAxCTL1)
USCI_Bx Control Register 1 (UCBxCTL1)
USCI_Ax Bit Rate Control Register 0 (UCAxBR0)
USCI_Bx Bit Rate Control Register 0 (UCBxBR0)
USCI_Ax Bit Rate Control Register 1 (UCAxBR1)
USCI_Bx Bit Rate Control Register 1 (UCBxBR1)
USCI_Ax Modulation Control Register (UCAxMCTL)

Figure 10.7: SPI overview.

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

10.5.3 MSP430 SPI HARDWARE CONFIGURATION


The MSP430 provides support for SPI communication in both of the eUSCI_A and eUSCI_B
modules. A block diagram of an UCSI module configured for SPI operation is shown in Fig-
ure 10.8. SPI operation is selected by setting the UCSYNC (Synchronous mode enable) bit to
logic one in the module’s eUSCI_Ax or USCI_Bx Control Register 0 (UCAxCTL0 or UCBx-
CTL0).
Located in the center of the diagram, the clock source for the SPI Baud rate clock (BR-
CLK) is either provided by the ACLK or the SMCLK. The clock source is chosen using the
eUSCI clock source select (UCSSELx) bits in eUSCI_Ax (or B) control register 1 (UCAxCTL1
or UCBxCTL1).
10.5. SERIAL PERIPHERAL INTERFACE-SPI 413

Receive State Machine Set UCOE


Set UCxRXIFG

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.

10.5.4 SPI REGISTERS


As discussed throughout this section, the basic features of the SPI system is configured and
controlled by the following SPI-related registers [SLAU445G, 2016, SLAU367O, 2017]:

eUSCI_A SPI Registers


• UCAxCTLW0 eUSCI_Ax Control Word 0
• UCAxCTL1 eUSCI_Ax Control 1
• UCAxCTL0 eUSCI_Ax Control 0
• UCAxBRW eUSCI_Ax Bit Rate Control Word
10.5. SERIAL PERIPHERAL INTERFACE-SPI 415
• UCAxBR0 eUSCI_Ax Bit Rate Control 0

• UCAxBR1 eUSCI_Ax Bit Rate Control 1

• UCAxSTATW eUSCI_Ax Status

• UCAxRXBUF eUSCI_Ax Receive Buffer

• UCAxTXBUF eUSCI_Ax Transmit Buffer

• UCAxIE eUSCI_Ax Interrupt Enable

• UCAxIFG eUSCI_Ax Interrupt Flag

• UCAxIV eUSCI_Ax Interrupt Vector

eUSCI_B SPI Registers


• UCBxCTLW0 eUSCI_Bx Control Word 0

• UCBxCTL1 eUSCI_Bx Control 1

• UCBxCTL0 eUSCI_Bx Control 0

• 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

• UCBxRXBUF eUSCI_Bx Receive Buffer

• UCBxTXBUF eUSCI_Bx Transmit Buffer

• UCBxIE eUSCI_Bx Interrupt Enable

• UCBxIFG eUSCI_Bx Interrupt Flag

• UCBxIV eUSCI_Bx Interrupt Vector

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

10.5.5 SPI CODE EXAMPLES


Energia
The Energia Integrated Development Environment has several built-in functions to support
SPI operations (energia.nu). These include:
• SPI.begin(): initializes SPI bus
• SPI.setBitOrder(direction): may be set for MSBFIRST or LSBFIRST
• SPI.setDataMode(mode): may be set for SPI modes 0 to 3 for compatibility to different
peripheral devices. The four different modes include:
– SPI_MODE0: clock polarity = 0, clock phase = 0
– SPI_MODE1: clock polarity = 0, clock phase = 1
– SPI_MODE2: clock polarity = 1, clock phase = 0
– SPI_MODE3: clock polarity = 1, clock phase = 1
• SPI.setClockDivider: use to divide (slow) the SPI clock. May be set to
SPI_CLOCK_DIV2, 4, 8, 16, 32, 64, 128.
• SPI.transfer(data): transmits one byte of data on the SPI bus
Also, the slave select line of the desired device must be taken low for SPI transfer. It is
then taken high when the data transfer is complete. In the following examples we demonstrate
10.5. SERIAL PERIPHERAL INTERFACE-SPI 417
how to interface a number of SPI compatible devices to the MSP430FR2433 LaunchPad using
the SPI system. The SPI connections are:

• MOSI: LaunchPad pin 15, P2.6

• MISO: LaunchPad pin 14, P2.5

• SCK: LaunchPad pin 7, P2.4

• SS: LaunchPad pin 17, P3.2

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

Chip select P2.2 (pin 18)

G DC
d
un
ro
V
MOSI P2.6 (pin 15)

3
3.
Clock P2.4 (pin 7)

Sparkfun LCD-14072
16 × 2 SerLCD

Figure 10.10: MSP430FR2433 interface to Sparkfun’s LCD-14072 display. (Illustration used


with permission of Sparkfun Electronics (www.sparkfun.com).)
10.5. SERIAL PERIPHERAL INTERFACE-SPI 419
//********************************************************************

#include <SPI.h>

#define chip_select 18 //LaunchPad pin P2.2

unsigned int numeral, number, i;


unsigned char printstring[16] = "Hello World";

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

digitalWrite(chip_select, LOW); //chip select assert


SPI.transfer(0x7C); //enter LCD settings mode
SPI.transfer(0x2D); //clear display, cursor home
digitalWrite(chip_select, HIGH); //initialize chip select

for(numeral = 0; numeral<=9; numeral++)


{
number = numeral + 48; //convert to ASCII
digitalWrite(chip_select, LOW); //chip select assert
SPI.transfer(number); //transmit data via SPI
digitalWrite(chip_select, HIGH); //chip select high
delay(1000); //1s delay
} //end for

digitalWrite(chip_select, HIGH); //chip select high

for(i=0; i<=5; i++) //advance to line 2


420 10. COMMUNICATION SYSTEMS
{
digitalWrite(chip_select, LOW); //chip select assert
SPI.transfer(' ');
digitalWrite(chip_select, HIGH); //initialize chip select
}
//write characters to line 2
digitalWrite(chip_select, LOW); //chip select assert
for(i=0; printstring[i] != '\0'; i++)
{
SPI.transfer(printstring[i]); //transmit data via SPI
delay(1000); //1s delay
} //end for
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

Sparkfun WIG-13279 Sparkfun WIG-13279


(mounted to reverse side of (mounted to reverse side of
COM-08530) COM-08530)

Figure 10.11: MSP430FR2433 interface to Sparkfun’s 6.5” 7-segment displays (COM-08530).


(Illustration used with permission of Sparkfun Electronics (www.sparkfun.com).)

// - 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
422 10. COMMUNICATION SYSTEMS
// 2 0xBA
// 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>

//Seven-segment numeral code


#define seven_seg_zero 0xDE
#define seven_seg_one 0x06
#define seven_seg_two 0xBA
#define seven_seg_three 0xAE
#define seven_seg_four 0x66
#define seven_seg_five 0xEC
#define seven_seg_six 0xFC
#define seven_seg_seven 0x86
#define seven_seg_eight 0xFE
#define seven_seg_nine 0xE6

#define LATCH 18 //LaunchPad pin P2.2

const byte strip_length = 1; //number of 7-segment LEDs


unsigned char troubleshooting = 0; //allows printouts to serial
unsigned int numeral;
unsigned char segment_data;

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();

for(numeral = 0; numeral<=9; numeral++)


{
switch(numeral) //convert numeral to
{ //7-segment code
case 0: segment_data = seven_seg_zero; break;
case 1: segment_data = seven_seg_one; break;
case 2: segment_data = seven_seg_two; break;
case 3: segment_data = seven_seg_three; break;
case 4: segment_data = seven_seg_four; break;
case 5: segment_data = seven_seg_five; break;
case 6: segment_data = seven_seg_six; break;
case 7: segment_data = seven_seg_seven; break;
case 8: segment_data = seven_seg_eight; break;
case 9: segment_data = seven_seg_nine; break;
default: break;
}

SPI.transfer(segment_data); //transmit data via SPI


assert_latch();

delay(1000); //1s delay

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
}

//****************************************************************

The two-digit example follows.

//***********************************************************************
//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>

//Seven-segment numeral code


#define seven_seg_zero 0xDE
#define seven_seg_one 0x06
#define seven_seg_two 0xBA
#define seven_seg_three 0xAE
#define seven_seg_four 0x66
#define seven_seg_five 0xEC
#define seven_seg_six 0xFC
#define seven_seg_seven 0x86
#define seven_seg_eight 0xFE
#define seven_seg_nine 0xE6

#define LATCH 18 //LaunchPad pin P2.2

const byte strip_length = 1; //number of 7-segment LEDs


unsigned char troubleshooting = 0; //allows printouts to serial
unsigned int numeral, first_digit, second_digit;
unsigned char segment_data_return;

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();

for(numeral = 0; numeral<=99; numeral++)


{
if(numeral <= 9)
{
segment_data_return = determine_segments(numeral);
SPI.transfer(segment_data_return); //transmit data via SPI
SPI.transfer(seven_seg_zero);
assert_latch();
delay(1000); //1s delay
} //end if
else //numeral >=10 - two digit analysis
{
first_digit = numeral
second_digit = (int)((numeral-first_digit)/10);
segment_data_return = determine_segments(first_digit);
SPI.transfer(segment_data_return); //transmit data via SPI
segment_data_return = determine_segments(second_digit);
SPI.transfer(segment_data_return); //transmit data via SPI
assert_latch();
delay(1000); //1s delay
}//end else
} //end for
} //end void

//****************************************************************

void assert_latch()
{
digitalWrite(LATCH, HIGH); //transmit latch pulse
delay(50);
10.5. SERIAL PERIPHERAL INTERFACE-SPI 427
digitalWrite(LATCH, LOW); //initialize LATCH signal
}

//****************************************************************

unsigned char determine_segments(unsigned int segment_number)


{

unsigned char segment_data;

switch(segment_number) //convert numeral to


{ //7-segment code
case 0: segment_data = seven_seg_zero; break;
case 1: segment_data = seven_seg_one; break;
case 2: segment_data = seven_seg_two; break;
case 3: segment_data = seven_seg_three; break;
case 4: segment_data = seven_seg_four; break;
case 5: segment_data = seven_seg_five; break;
case 6: segment_data = seven_seg_six; break;
case 7: segment_data = seven_seg_seven; break;
case 8: segment_data = seven_seg_eight; break;
case 9: segment_data = seven_seg_nine; break;
default: break;
}

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

MOSI P2.5 (pin 14)

RTC chip select P3.2 (pin 17)

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>

#define RTC_chip_select 17 //LaunchPad pin P3.2


#define LCD_chip_select 18 //LaunchPad pin P2.2

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);

initialize_RTC(); //Initialize RTC


//int day (1 to 31)
//int month (1 to 12)
//int year (0 to 99)
//int hour (0 to 23)
//int minute (0 to 59)
//int second (0 to 59)
set_RTC(12, 10, 18, 5, 0, 0); //set current time in RTC
}

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);

digitalWrite(RTC_chip_select, LOW); //RTC chip select assert


SPI.transfer(0x8E); //0x8E: RTC control register
SPI.transfer(0x60); //turn on RTC clock
digitalWrite(RTC_chip_select, HIGH); //RTC chip select de-assert
}

//****************************************************************
//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);

//Parse out portions of TimeDateGroup. Convert digits of each portion


//of TimeDateGroup to BCD. Transmit BCD charara ers to DS3234
//Timekeeping registers. Reference Table 1 of DS3234 data sheet.
//The DS3234 write registers begin at address location 0x80.

for(int i=0; i<=6; i++)


{
if(i==3) i++; //skip over position three
//isolate bit positions
int b= TimeDateGroup[i]/10; //10's place
int a= TimeDateGroup[i]-b*10; //1's place

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);

digitalWrite(RTC_chip_select, LOW); //RTC chip select assert


SPI.transfer(i+0x80);
SPI.transfer(TimeDateGroup[i]);
digitalWrite(RTC_chip_select, HIGH);//RTC chip select assert
}
}

//****************************************************************
//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;

//Assemble portions of TimeDateGroup from DS3234 memory.


//Read BCD chararaters from DS3234 Timekeeping registers.
//Reference Table 1 of DS3234 data sheet. The DS3234 read
//registers begin at address location 0x00.
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);

for(int i=0; i<=6;i++)


{
if(i==3) i++; //skip position 3

digitalWrite(RTC_chip_select, LOW); //RTC chip select assert


SPI.transfer(i+0x00); //read DS3234 register
unsigned int n = SPI.transfer(0x00);
digitalWrite(RTC_chip_select, HIGH);//RTC chip select assert

int a=n & B00001111; //assemble BCD digits


if(i==2) //null space
{
int b=(n & B00110000)>>4; //24 hour mode
if(b==B00000010)
b=20;
else if(b==B00000001)
b=10;
TimeDateGroup[i]=a+b;
}
else if(i==4) //days
{
int b=(n & B00110000)>>4;
434 10. COMMUNICATION SYSTEMS
TimeDateGroup[i]=a+b*10;
}
else if(i==5) //month
{
int b=(n & B00010000)>>4;
TimeDateGroup[i]=a+b*10;
}
else if(i==6) //year
{
int b=(n & B11110000)>>4;
TimeDateGroup[i]=a+b*10;
}
else
{
int b=(n & B01110000)>>4;
TimeDateGroup[i]=a+b*10;
}
}
temp.concat(TimeDateGroup[4]); //day
temp.concat("/") ;
temp.concat(TimeDateGroup[5]); //month
temp.concat("/") ;
temp.concat(TimeDateGroup[6]); //year
temp.concat(" ") ;
temp.concat(TimeDateGroup[2]); //hour
temp.concat(":") ;
temp.concat(TimeDateGroup[1]); //minute
temp.concat(":") ;
temp.concat(TimeDateGroup[0]); //seconds
return(temp);
}

//****************************************************************

void display_time_LCD(void)
{

for(int i=4; i<=6; i++)


{
10.5. SERIAL PERIPHERAL INTERFACE-SPI 435
int b= TimeDateGroup[i]/10; //10's place
int a= TimeDateGroup[i]-b*10; //1's place
//convert to ASCII
b = b + 48;
a = a + 48;

digitalWrite(LCD_chip_select, LOW); //LCD chip select assert


SPI.transfer(b);
digitalWrite(LCD_chip_select, HIGH);//LCD chip select high

digitalWrite(LCD_chip_select, LOW); //LCD chip select assert


SPI.transfer(a);
digitalWrite(LCD_chip_select, HIGH);//LCD chip select high
}

digitalWrite(LCD_chip_select, LOW); //LCD chip select assert


SPI.transfer(0x20);
digitalWrite(LCD_chip_select, HIGH);//LCD chip select high

for(int i=2; i>=0; i--)


{
int b= TimeDateGroup[i]/10; //10's place
int a= TimeDateGroup[i]-b*10; //1's place
//convert to ASCII
b = b + 48;
a = a + 48;

digitalWrite(LCD_chip_select, LOW); //LCD chip select assert


SPI.transfer(b);
digitalWrite(LCD_chip_select, HIGH);//LCD chip select high

digitalWrite(LCD_chip_select, LOW); //LCD chip select assert


SPI.transfer(a);
digitalWrite(LCD_chip_select, HIGH);//LCD chip select high

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>

unsigned char RXData = 0;


unsigned char TXData;

int main(void)
{
WDTCTL = WDTPW | WDTHOLD; //Stop watchdog timer
P1SEL0 |= BIT4 | BIT5 | BIT6; //set 3-SPI pin as second func

UCA0CTLW0 |= UCSWRST; //**Put state machine in reset**


UCA0CTLW0 |= UCMST|UCSYNC|UCCKPL|UCMSB; //3-pin, 8-bit SPI master
//Clock polarity high, MSB
UCA0CTLW0 |= UCSSEL__SMCLK; //SMCLK
UCA0BR0 = 0x01; // /2,fBitClock=fBRCLK/(UCBRx+1).
UCA0BR1 = 0; //
UCA0MCTLW = 0; //No modulation
UCA0CTLW0 &= ~UCSWRST; //**Init USCI state machine**
UCA0IE |= UCRXIE; //Enable USCI_A0 RX interrupt
TXData = 0x01; //Holds TX data

PM5CTL0 &= ~LOCKLPM5; //Disable the GPIO power-on


//default high-impedance mode
//to activate previously
//configured port settings
while(1)
{
UCA0IE |= UCTXIE; //Enable TX interrupt
438 10. COMMUNICATION SYSTEMS
__bis_SR_register(LPM0_bits | GIE); //enable global interrupts,
//enter LPM0
__no_operation(); //For debug, remain in LPM0
__delay_cycles(2000); //Delay before next transmis
TXData++; //Increment transmit data
}
}

//***********************************************************************
#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_SPI_UCTXIFG))
{
case USCI_NONE: break; //Vector 0 - no interrupt
case USCI_SPI_UCRXIFG: RXData = UCA0RXBUF;
UCA0IFG &= ~UCRXIFG;
//Wake up to setup next TX
__bic_SR_register_on_exit(LPM0_bits);

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

P1SEL0 |= BIT4 | BIT5 | BIT6; //3-SPI pin as second function


UCA0CTLW0 |= UCSWRST; //**State machine in reset**
UCA0CTLW0 |= UCSYNC|UCCKPL|UCMSB; //3-pin, 8-bit SPI slave
//Clock polarity high, MSB
UCA0CTLW0 |= UCSSEL__SMCLK; //SMCLK
UCA0BR0 = 0x01; // /2,fBitClock =
//fBRCLK/(UCBRx+1).
UCA0BR1 = 0;
UCA0MCTLW = 0; //No modulation
UCA0CTLW0 &= ~UCSWRST; //**Initialize USCI state
//machine**
UCA0IE |= UCRXIE; //Enable USCI_A0 RX interrupt

PM5CTL0 &= ~LOCKLPM5; //Disable the GPIO power-on


//default high-impedance mode
//to activate previously
//configured port settings
__bis_SR_register(LPM0_bits | GIE); //Enter LPM0, enable interrupts
}

//***********************************************************************
#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
{
while (!(UCA0IFG&UCTXIFG)); // USCI_A0 TX buffer ready?
UCA0TXBUF = UCA0RXBUF; // Echo received data
}

//***********************************************************************
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

(a) 12C bus connection

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)

(b) 12C transaction waveform (SLAU445G)

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

7-bit Addressing Mode


# Clocks 1 7 1 1 8 1 8 1 1
Data on SDA Line S A R/W Ack D Ack D Ack P

10-bit Addressing Mode


# Clocks 1 7 1 1 8 1 8 1 8 1 1
Data on SDA Line S A1 R/W Ack A2 Ack D Ack D Ack P

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.4 MSP430 AS A MASTER DEVICE


To configure the MSP430 controller to function as a master device, the eUSCI_Bx ports must
be programmed to operate in the I2 C mode (UCMODEx D 11, UCSYNC D 1), and one
must configure the MSP430 to operate in the master mode by setting the UCMST bit. Since
the I2 C bus can handle more than one master device and if there are multiple master devices,
the MSP430 needs to be programmed as one of many master devices on the bus by setting the
UCMM bit and storing the address (either 7 or 10 bits) of MSP430 in the UCBxI2COA regis-
ter. As in the case of the slave mode, the address size is determined by the UCA10 bit, and the
10.6. INTER-INTEGRATED COMMUNICATION – I2 C MODULE 445
general call response is programmed using the UCGCEN bit [SLAU445G, 2016, SLAU367O,
2017].
To initiate a session to transmit data, the UCTR bit and the UCTxSTT bit are set, the
UCSLA10 bit is configured to match the slave address size, and the address of a slave device is
loaded to the UCBxI2CSA. When the start condition is generated by setting the UCTxSTT
bit, the data can be loaded to the UCBxTXBUF, and the UCTxIFG bit is set. Once a slave
address acknowledges its address, the UCTxSTT and UCTxIFG bits are cleared. Once the
data is sent, the UCTxIFG flag bit is set, again, for the next set of data transfer. To generate
a stop condition, set UCTxSTP bit while UCTxIFG and UCTxSTP bits are set. If a repeated
start conditions are necessary, set UCTxSTT bit. During a data transfer session, if a slave does
not respond (i.e., send acknowledge bits), the MSP430 must either send a stop condition or a
repeated start conditions [SLAU445G, 2016, SLAU367O, 2017].
When the MSP430 controller needs to receive data from a slave, the UCTR bit must
be cleared, and the UCTxSTT bit must be set to generate a start condition. When a slave
device sends an acknowledgment, the UCTxSTT bit is cleared, and the data is received. Upon
receiving an 8-bit data set, the UCRxIFG flag is set. Once the data is read from the buffer, the
UCRxIFG flag is cleared, and the next data can be received. If only a single 8-bit byte should
be received, the controller must set the UCTxSTP bit while the byte is received [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

• UCBxTXBUF eUSCI_Bx Transmit Buffer

• UCBxI2COA0 eUSCI_Bx I2C Own Address 0

• UCBxI2COA1 eUSCI_Bx I2C Own Address 1

• UCBxI2COA2 eUSCI_Bx I2C Own Address 2

• UCBxI2COA3 eUSCI_Bx I2C Own Address 3

• UCBxADDRX eUSCI_Bx Received Address Register

• UCBxADDMASK eUSCI_Bx Address Mask Register

• UCBxI2CSA eUSCI_Bx I2C Slave Address

• UCBxIE eUSCI_Bx Interrupt Enable

• UCBxIFG eUSCI_Bx Interrupt Flag

• UCBxIV eUSCI_Bx Interrupt Vector

10.6.6 PROGRAMMING THE I2 C


Programming the I2 C in Energia
The Energia IDE supports the following I2 C functions:

• 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.beginTransmission(addr): used to begin transmission to a slave device.

• Wire.endTransmission(stop): ends transmission to a slave device.

• Wire.read(): reads a byte that was transmitted from a slave device.

• Wire.requestFrom(addr, qty, stop): used by a master device to request data bytes from a
slave device.

• Wire.write(val), Wire.write(str), Wire.write(data, length): variety of functions used to


write data from a slave designated device.
10.6. INTER-INTEGRATED COMMUNICATION – I2 C MODULE 447

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>

#define lcd_addr 0x72 //OpenLCD address

int cycles = 0;

void setup()
{

Wire.begin(); //Join I2C bus as master


//bus speed: 100 kHz

Wire.beginTransmission(lcd_addr); //write mode LCD


Wire.write(0x7c); //LCD in setting mode
Wire.write(0x2d); //clear LCD display
Wire.endTransmission();
}

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
//*********************************************************************

void i2cSendValue(int value)


{
Wire.beginTransmission(lcd_addr); //write to LCD
Wire.write(0x7c); //LCD in setting mode
Wire.write(0x2d); //clear LCD display
Wire.print("Cycles: ");
Wire.print(value);
Wire.endTransmission(); //Stop I2C transmission
}

//*********************************************************************

I2 C BLINKM LED. The BLINKM LED is a tri-color LED manufactured by


THINGM (www.thingm.com). An I2 C compatible breakout board is available from Spark-
fun Electronics (COM-08579). The BLINKM I2 C address is 0x09. The LED color is set by
sending a triplet of color values (R,G,B) to the BLINKM via the I2 C bus.

//*********************************************************************
//BlinkMFlash---simple demonstration of flashing a BlinkM
//Adapted from BlinkM code provided by THINKM at http://thingm.com
//*********************************************************************

#include "Wire.h"

int blinkm_addr = 9; //default address of a blinkm

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 I2 C Temperature Sensor. The TMP102 is a low-power digital temperature


sensor compatible with the I2 C bus. A breakout board is available from Sparkfun (SEN-13314).
The TMP102 has the unique address of 0x4B. Temperature data is stored as two bytes. The
two bytes are read from the TMP102 and then assembled as a single value. It is important to
note that the least significant nibble of the second byte does not contain temperature data. The
TMP102 has a resolution of 0.0625 degrees Centigrade per bit. In this example, temperature
data is gathered from the TMP102 converted to Centigrade and Fahrenheit and displayed on
the serial monitor [SBOS397B].

//******************************************************************
//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

Wire.beginTransmission(0x48); //point to device 0x48


Wire.write(0x00); //point to temp register
Wire.endTransmission(); //relinquish control of I2C line
delay(10); //delay for conversion time
Wire.requestFrom(0x48, 2); //request temperature data

if(2 <= Wire.available()) //if two bytes returned


{
452 10. COMMUNICATION SYSTEMS
temp[0] = Wire.read(); //read out the data
temp[1] = Wire.read();
temp[1] = temp[1] >> 4; //ignore lower 4 bits of byte 2
tempc = ((temp[0] << 4) | temp[1]);//combine for 12 bit binary number
tempc = tempc*0.0625; //convert to celcius given
//0.0625C resolution
tempf = tempc * 9/5 + 32; //convert to fahrenheit
return tempf;
}
}

//******************************************************************

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>

volatile unsigned char RXData;

int main(void)
{
WDTCTL = WDTPW | WDTHOLD;
//Configure GPIO
P1OUT &= ~BIT0; //Clear P1.0 output latch
P1DIR |= BIT0; //For LED
P1SEL0 |= BIT2 | BIT3; //I2C pins

//Disable the GPIO power-on default high-impedance mode to activate


//previously configured port settings
PM5CTL0 &= ~LOCKLPM5;
//Configure USCI_B0 for I2C mode
UCB0CTLW0 |= UCSWRST; //Software reset enabled
UCB0CTLW0 |=UCMODE_3|UCMST|UCSYNC; //I2C mode, Master mode, sync
UCB0CTLW1 |= UCASTP_2; //Automatic stop generated
// after UCB0TBCNT is reached
UCB0BRW = 0x0008; //baudrate = SMCLK / 8
UCB0TBCNT = 0x0005; //number of bytes to be received
UCB0I2CSA = 0x0048; //Slave address
UCB0CTL1 &= ~UCSWRST;
UCB0IE |= UCRXIE | UCNACKIE | UCBCNTIE;
454 10. COMMUNICATION SYSTEMS
while (1)
{
__delay_cycles(2000);
while (UCB0CTL1 & UCTXSTP); //Ensure stop condition got sent
UCB0CTL1 |= UCTXSTT; //I2C start condition
__bis_SR_register(LPM0_bits|GIE);//Enter LPM0 w/ interrupt
}
}

//*********************************************************************

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)


#pragma vector = USCI_B0_VECTOR
__interrupt void USCIB0_ISR(void)
#elif defined(__GNUC__)

void __attribute__ ((interrupt(USCI_B0_VECTOR))) USCIB0_ISR (void)


#else
#error Compiler not supported!
#endif
{
switch(__even_in_range(UCB0IV, USCI_I2C_UCBIT9IFG))
{
case USCI_NONE: break; //Vector 0: No interrupts
case USCI_I2C_UCALIFG: break; //Vector 2: ALIFG
case USCI_I2C_UCNACKIFG: //Vector 4: NACKIFG
UCB0CTL1 |= UCTXSTT; //I2C start condition
break;
case USCI_I2C_UCSTTIFG: break; //Vector 6: STTIFG
case USCI_I2C_UCSTPIFG: break; //Vector 8: STPIFG
case USCI_I2C_UCRXIFG3: break; //Vector 10: RXIFG3
case USCI_I2C_UCTXIFG3: break; //Vector 14: TXIFG3
case USCI_I2C_UCRXIFG2: break; //Vector 16: RXIFG2
case USCI_I2C_UCTXIFG2: break; //Vector 18: TXIFG2
case USCI_I2C_UCRXIFG1: break; //Vector 20: RXIFG1
case USCI_I2C_UCTXIFG1: break; //Vector 22: TXIFG1
case USCI_I2C_UCRXIFG0: //Vector 24: RXIFG0
RXData = UCB0RXBUF; //Get RX data
__bic_SR_register_on_exit(LPM0_bits); //Exit LPM0
10.6. INTER-INTEGRATED COMMUNICATION – I2 C MODULE 455
break;
case USCI_I2C_UCTXIFG0: break; //Vector 26: TXIFG0
case USCI_I2C_UCBCNTIFG: //Vector 28: BCNTIFG
P1OUT ^= BIT0; //Toggle LED on P1.0
break;
case USCI_I2C_UCCLTOIFG: break; //Vector 30: clock low timeout
case USCI_I2C_UCBIT9IFG: break; //Vector 32: 9th bit
default: break;
}
}
//***********************************************************************

Slave configured processor:

//********************************************************************
// --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>

volatile unsigned char TXData;

int main(void)
{
WDTCTL = WDTPW | WDTHOLD;
P1SEL0 |= BIT2 | BIT3; //Configure GPIO I2C pins

//Disable the GPIO power-on default high-impedance mode to activate


//previously configured port settings
PM5CTL0 &= ~LOCKLPM5;
//Configure USCI_B0 for I2C mode
UCB0CTLW0 = UCSWRST; //Software reset enabled
UCB0CTLW0 |= UCMODE_3 | UCSYNC; //I2C mode, sync mode
UCB0I2COA0 = 0x48 | UCOAEN; //own address is 0x48 + enable
UCB0CTLW0 &= ~UCSWRST; //clear reset register
UCB0IE |= UCTXIE0 | UCSTPIE; //transmit,stop interrupt enable
__bis_SR_register(LPM0_bits | GIE); //Enter LPM0 w/ interrupts
__no_operation();
}

//*********************************************************************

#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__)


#pragma vector = USCI_B0_VECTOR
__interrupt void USCIB0_ISR(void)
#elif defined(__GNUC__)
void __attribute__ ((interrupt(USCI_B0_VECTOR))) USCIB0_ISR (void)
#else
10.7. LABORATORY EXERCISE: UART AND SPI COMMUNICATIONS 457
#error Compiler not supported!
#endif
{
switch(__even_in_range(UCB0IV, USCI_I2C_UCBIT9IFG))
{
case USCI_NONE: break; //Vector 0: No interrupts
case USCI_I2C_UCALIFG: break; //Vector 2: ALIFG
case USCI_I2C_UCNACKIFG: break; //Vector 4: NACKIFG
case USCI_I2C_UCSTTIFG: break; //Vector 6: STTIFG
case USCI_I2C_UCSTPIFG: //Vector 8: STPIFG
TXData = 0;
UCB0IFG &= ~UCSTPIFG; //Clear stop condition int flag
break;
case USCI_I2C_UCRXIFG3: break; //Vector 10: RXIFG3
case USCI_I2C_UCTXIFG3: break; //Vector 14: TXIFG3
case USCI_I2C_UCRXIFG2: break; //Vector 16: RXIFG2
case USCI_I2C_UCTXIFG2: break; //Vector 18: TXIFG2
case USCI_I2C_UCRXIFG1: break; //Vector 20: RXIFG1
case USCI_I2C_UCTXIFG1: break; //Vector 22: TXIFG1
case USCI_I2C_UCRXIFG0: break; //Vector 24: RXIFG0
case USCI_I2C_UCTXIFG0:
UCB0TXBUF = TXData++;
break; //Vector 26: TXIFG0
case USCI_I2C_UCBCNTIFG: break; //Vector 28: BCNTIFG
case USCI_I2C_UCCLTOIFG: break; //Vector 30: clock low timeout
case USCI_I2C_UCBIT9IFG: break; //Vector 32: 9th bit
default: break;
}
}

//*********************************************************************

10.7 LABORATORY EXERCISE: UART AND SPI


COMMUNICATIONS

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.

10.9 REFERENCES AND FURTHER READING


DS3234 Extremely Accurate SPI Bus RTC with Integrated Crystal and SRAM, Maxim Integrated,
2015. www.maximintegrated.com 427, 428

MSP430FR2433 LaunchPad Development Kit (MSP-EXP430FR2433), (SLAU739), Texas In-


struments, 2017.

MSP430FR2433 Mixed-Signal Microcontroller, (SLASE59D), Texas Instruments, 2018.

MSP430FR4xx and MSP430FR2xx Family User’s Guide, (SLAU445G), Texas Instruments,


2016. 396, 397, 400, 401, 403, 404, 405, 411, 413, 414, 416, 441, 443, 444, 445

MSP430FR58xx, MSP430FR59xx, and MSP430FR6xx Family User’s Guide, (SLAU367O),


Texas Instruments, 2017. 396, 397, 400, 401, 403, 404, 405, 411, 413, 414, 416, 441, 443,
444, 445

MSP430FR5994 LaunchPad Development Kit (MSP-EXP430FR5994), (SLAU678A), Texas In-


struments, 2016.

MSP430FR599x, MSP430FR596x Mixed-Signal Microcontrollers, (SLASE54C), Texas Instru-


ments, 2018.

TPIC6C596 Power Logic 8-Bit Shift Register, (SLIS093D), Texas Instruments, 2015. 420

Unicode Consortium. www.unicode.org

10.10 CHAPTER PROBLEMS


Fundamental

1. Describe the difference between parallel and serial communications.

2. If the communication cost is the primary issue, which communication methods (parallel,
series) should be used? Why?

3. What is the difference between synchronous and asynchronous communications?


10.10. CHAPTER PROBLEMS 459
4. The eUSCI in the UART mode supports LIN and IrDA. For each, identify the protocol
used: serial/parallel and synchronous/asynchronous.
5. In the I2 C communication protocol, how does one configure the MSP430 to become a
master device? What must be done to configure it as a slave device?
6. Give a brief description of a communication protocol.

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

MSP430 System Integrity


Objectives: After reading this chapter, the reader should be able to:
• describe the concept of electromagnetic interference (EMI);
• describe the possible sources of EMI noise in a microcontroller system;
• differentiate between conducted and radiated EMI;
• list different sources of EMI;
• list design techniques to minimize EMI;
• describe how a cyclic redundancy check (CRC) may be used to insure the integrity of data;
• describe the features of the CRC32 system onboard the MSP430FR5994;
• sketch a linear feedback shift register for a given generator polynomial;
• list common generator polynomials used within CRC systems;
• program the MSP430FR5994 CRC32 system to generate a data checksum;
• describe how the MSP430FR5994 advanced encryption standard module, the AES256,
may be used to provide for data transmission integrity;
• describe the steps used to encrypt/decrypt data using the AES256 standard;
• sketch a block diagram of the MSP430FR5994 AES256 module; and
• program the MSP430 AES256 module to encrypt and decrypt data.

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.

11.2 ELECTROMAGNETIC INTERFERENCE


EMI, commonly referred to as noise, may come from a number of sources as shown in Fig-
ure 11.1. Noise causes program malfunction and data corruption, making it impossible to com-
plete the intended task of the controller. It is important to understand the sources of noise
and coupling mechanisms to a microcontroller-based project, so proper preventive techniques
may be employed during the design process. As shown in the figure, noise may be coupled to
a victim receptor system via radiated or conducted mechanisms. Radiated sources include radio
frequency sources such as radio stations and cell phones. Naturally occurring lightning is also
a source of noise. A nearby lightning strike generates a tremendous amount of noise at a vari-
ety of frequencies. Noise may also be generated by motors and motor based appliances such as
drills, mixers, and blenders. Often microcontrollers are used to control a motor. The motor, al-
though part of the designed system, may be a source of noise for the microcontroller controlling
its operation. Electrostatic discharge (ESD), e.g., static electricity, may inject noise or damage
a microcontroller-based system. Conducted sources of noise in a microcontroller-based system
include other system components or the power supply serving the system. It is interesting to
note the microcontroller itself may also serve as a noise source for other system components or
nearby systems [AN1705, 2004, COP888, 1996].

11.2.1 EMI REDUCTION STRATEGIES


There are several strategies to minimize EMI interference. These include [AN1705, 2004,
COP888, 1996]:
• implementing EMI suppression techniques early in the design process. It is very challeng-
ing to provide EMI suppression after a system has been implemented; and
• implementing noise suppression techniques at the source of the noise, disrupting the
source to receptor transmission path, protecting the receptor system from noise, and a
combination of all three techniques.
Provided below are specific techniques to suppress EMI noise in a microcontroller-based
system [Barrett and Pack, 2004, AN1705, 2004, COP888, 1996].
• If possible, incoming signal lines to a microcontroller-based system should be twisted. This
will minimize the chance of parallel conductors inducing noise in an adjacent conductor
via crosstalk. If signals are being transmitted by a multiple conductor ribbon cable, consider
11.2. ELECTROMAGNETIC INTERFERENCE 463

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.

• Mount the microcontroller-based project in a metal chassis.

• There are several defensive programming techniques to help combat noise. One easy to
implement technique is to declare unused microcontroller pins as output.

11.3 CYCLIC REDUNDANCY CHECK


In a previous professional life, one of the authors (sfb) served as a missileer in the United States
Air Force. On a routine basis, the guidance set aboard an assigned missile was updated with
critical data to insure the missile would serve its intended mission. Maintenance crews from a
nearby support base would transport information tapes out to the missile site where the onboard
missile guidance set was updated. A CRC checksum was generated on the information tapes
before they left the support base. After the information was loaded from the tapes to the mis-
sile guidance set, a CRC checksum was performed. If the checksum generated by the missile
guidance set matched the checksum generated at the support base, the missile was designated
as properly updated.
This scenario illustrates the application and importance of using a CRC to maintain data
integrity. This technique is often performed to ensure the integrity of transmitted or stored data.
The basic concept behind generating a CRC checksum is binary division. The basic oper-
ation of division can be defined as [AN370]:

Dividend=divisor D quotient C remainder:

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

Figure 11.2: CRC16-CCITT polynomial and LFSR configuration [SLAU367O, 2017].

11.3.1 MSP430FR5994 CRC32 MODULE


A block diagram for the MSP430FR5994 CRC32 module is provided in Figure 11.3a. The
MSP430FR5994 CRC32 module is quite flexible. It allows for 16- or 32-bit CRC generation.
It also provides for data bit 0 being the MSB or LSB. This allows for compatibility with both
modern and legacy hardware. Also, to speed up the calculation of the CRC checksum, the linear
feedback shift register operation is implemented with an equivalent XOR gate combinational
logic tree [SLAU367O, 2017].
The UML activity diagram for the CRC operation is provided in Figure 11.3b. The op-
eration is quite straight forward. The CRC polynomial is provided to the CRC32 system along
with the seed via the CRC16INIRES (CRC32INIRES) register. The data block to perform
the checksum operation is fed into the CRC16DI (CRC32DI) register. The CRC checksum
operation is performed and the checksum is available at the CRC16INIRES (CRC32INIRES)
register [SLAU367O, 2017].
466 11. MSP430 SYSTEM INTEGRITY

CRC16INIRES/ CRC16DI/
CRC32INIRES CRC32DI

Signature Seed Data In Set Polynomial

CRC Feed in Data


Checksum
Generator
Get Signature Result

(a) CRC32 block diagram

(b) CRC32 UML diagram

Figure 11.3: MSP430 CRC32 module.

11.3.2 CRC16 REGISTERS


The CRC16 system is supported by a set of the following registers [SLAU367O, 2017]:
• CRC16DI CRC16 Data Input Register
• CRCDIRB CRC16 Data In Reverse Register
• CRCINIRES CRC16 Initialization and Result Register
• CRCRESR CRC16 Result Reverse Register
Details of specific register and bit settings are contained in MSP430P4xx Family Technical Ref-
erence Manual [SLAU367O, 2017].

11.3.3 CRC32 REGISTERS


The CRC32 system is supported by a set of the following registers [SLAU367O, 2017]:
• CRC32DIW0 CRC32 Data Input Register
• CRC32DIRBW0 CRC32 Data In Reverse Register
• CRC32INIRESW0 CRC32 Initialization and Result Register 0
• CRC32INIRESW1 CRC32 Initialization and Result Register 1
• CRC32RESRW0 CRC32 Result Reverse Register 0
• CRC32RESRW1 CRC32 Result Reverse Register 1
11.3. CYCLIC REDUNDANCY CHECK 467
• CRC16DIW0 CRC16 Data Input Register

• CRC16DIRBW0 CRC16 Data In Reverse Register

• CRC16INIRESW0 CRC16 Initialization and Result Register

• CRC16RESRW0 CRC16 Result Reverse Register

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>

const unsigned int CRC_Init = 0xFFFF;

const unsigned int CRC_Input[] =


{
0x0fc0, 0x1096, 0x5042, 0x0010, //16 random 16-bit numbers
0x7ff7, 0xf86a, 0xb58e, 0x7651, //these numbers can be
0x8b88, 0x0679, 0x0123, 0x9599, //modified if desired
0xc58c, 0xd1e2, 0xe144, 0xb691
};

unsigned int CRC_Result; //Holds results obtained through


//the CRC16 module
unsigned int SW_Results; //Holds results obtained through
//SW

//Software Algorithm Function Declaration


unsigned int CCITT_Update(unsigned int, unsigned int);

int main(void)
{
unsigned int i;

WDTCTL = WDTPW | WDTHOLD; //Stop WDT


//Configure GPIO
P1OUT &= ~BIT0; //Clear LED to start
P1DIR |= BIT0; // P1.0 Output

//Disable the GPIO power-on default high-impedance mode to activate


//previously configured port settings
PM5CTL0 &= ~LOCKLPM5;
11.3. CYCLIC REDUNDANCY CHECK 469
//First, use the CRC16 hardware module to calculate the CRC...
CRC16INIRESW0 = CRC_Init; //Init CRC16 HW module

for(i = 0; i < (sizeof(CRC_Input) >> 1); i++)


{
//Input random values into CRC
//Hardware
CRC16DIRBW0 = CRC_Input[i]; //Input data in CRC
__no_operation();
}

CRC_Result = CRC16INIRESW0; //Save results (per CRC-CCITT


//standard)

//Now use a software routine to calculate the CRC...


SW_Results = CRC_Init; //Init SW CRC
for(i = 0; i < (sizeof(CRC_Input) >> 1); i++)
{
//First input upper byte
SW_Results = CCITT_Update(SW_Results, (CRC_Input[i] >> 8) & 0xFF);

//Then input lower byte


SW_Results = CCITT_Update(SW_Results, CRC_Input[i] & 0xFF);
}

//Compare data output results


if(CRC_Result == SW_Results) //if data is equal
P1OUT |= BIT0; //set the LED
else
P1OUT &= ~BIT0; //if not, clear LED

while(1); //infinite loop


}

//********************************************************************
// Software algorithm - CCITT CRC16 code
//********************************************************************

unsigned int CCITT_Update(unsigned int init, unsigned int input)


470 11. MSP430 SYSTEM INTEGRITY
{
unsigned int CCITT = (unsigned char) (init >> 8) | (init << 8);
CCITT ^= input;
CCITT ^= (unsigned char) (CCITT & 0xFF) >> 4;
CCITT ^= (CCITT << 8) << 4;
CCITT ^= ((CCITT & 0xFF) << 4) << 1;

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>

#define POLYNOMIAL_32 0xEDB88320

//Holds a CRC32 lookup table


unsigned long crc32Table[256];

//Global flag indicating that the CRC32 lookup table has been initialized
unsigned int crc32TableInit = 0;

const unsigned long CRC_Init = 0xFFFFFFFF;

const unsigned short CRC_Input[] =


{
0xc00f, 0x9610, 0x5042, 0x0010, // 16 random 16-bit numbers
0x7ff7, 0xf86a, 0xb58e, 0x7651, // these numbers can be
0x8b88, 0x0679, 0x0123, 0x9599, // modified if desired
0xc58c, 0xd1e2, 0xe144, 0xb691
};

//Holds results obtained through the CRC32 hardware module


unsigned long CRC32_Result;

//Holds results obtained through software algorithm


unsigned long SW_CRC32_Results;

// Software CRC32 algorithm function declaration


void initSwCrc32Table(void);
unsigned long updateSwCrc32(unsigned long crc, char c );
472 11. MSP430 SYSTEM INTEGRITY

int main(void)
{
unsigned int i;

WDTCTL = WDTPW | WDTHOLD; //Stop WDT


//Configure GPIO
P1OUT &= ~BIT0; //Clear LED to start
P1DIR |= BIT0; //P1.0 Output

//Disable the GPIO power-on default high-impedance mode to activate


//previously configured port settings
PM5CTL0 &= ~LOCKLPM5;

//First, use the CRC32 hardware module to calculate the CRC...


CRC32INIRESW0 = CRC_Init; //Init CRC32 HW module
CRC32INIRESW1 = CRC_Init; //Init CRC32 HW module

for(i = 0; i < (sizeof(CRC_Input) >> 1); i=i+2)


{
//Input values into CRC32 Hardware
CRC32DIW0 = (unsigned int) CRC_Input[i + 0];
CRC32DIW1 = (unsigned int) CRC_Input[i + 1];
}

//Save the CRC32 result


CRC32_Result = ((unsigned long) CRC32RESRW0 << 16);
CRC32_Result = ((unsigned long) CRC32RESRW1&0x0000FFFF)|CRC32_Result;

//Now use a software routine to calculate the CRC32...


//Init SW CRC32
SW_CRC32_Results = CRC_Init;

for(i = 0; i < (sizeof(CRC_Input) >> 1); i++)


{
//Calculate the CRC32 on the low-byte first
SW_CRC32_Results=updateSwCrc32(SW_CRC32_Results,(CRC_Input[i]&0xFF));

//Calculate the CRC on the high-byte


11.3. CYCLIC REDUNDANCY CHECK 473
SW_CRC32_Results=updateSwCrc32(SW_CRC32_Results,(CRC_Input[i] >> 8));
}

//Compare data output results


if(CRC32_Result == SW_CRC32_Results) //if data is equal
P1OUT |= BIT0; //set the LED
else
P1OUT &= ~BIT0; //if not, clear LED

while(1); //infinite loop


}

//********************************************************************
// Calculate the SW CRC32 byte-by-byte
//********************************************************************

unsigned long updateSwCrc32( unsigned long crc, char c )


{
unsigned long tmp, long_c;

long_c = 0x000000ffL & (unsigned long) c;

if(!crc32TableInit)
{
initSwCrc32Table();
}

tmp = crc ^ long_c;


crc = (crc >> 8) ^ crc32Table[ tmp & 0xff ];

return crc;
}

//********************************************************************
// Initializes the CRC32 table
//********************************************************************

void initSwCrc32Table(void)
{
474 11. MSP430 SYSTEM INTEGRITY
int i, j;
unsigned long crc;

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


{
crc = (unsigned long) i;

for(j = 0; j < 8; j++)


{
if(crc & 0x00000001L)
{
crc = ( crc >> 1 ) ^ POLYNOMIAL_32;
}
else
{
crc = crc >> 1;
}
}
crc32Table[i] = crc;
}
//Set flag that the CRC32 table is initialized
crc32TableInit = 1;

}
//********************************************************************

11.4 AES256 ACCELERATOR MODULE


The MSP430FR5994 is equipped with the AES256 Accelerator Module that allows encryption
and decryption of data using the Rijndael cryptographic algorithm. The algorithm allows the
encryption of a 128-bit plain text data block into a corresponding size cipher text block. The
data may then be transmitted in an encrypted format and decrypted using a similar algorithm
at the receiving end [FIPS-197, 2001, SLAU367O, 2017].
The data algorithm uses a 128-, 192-, or 256-bit cipher key to encrypt the plain text data
block. The length of the cipher key determines the number of rounds (10, 12, or 14, respectively)
of encryption performed on the plain text data to transform it into the cipher text block. The
basic encryption process is shown in Figure 11.4a,b. The plain text 128-bit block is formatted
into a state block. The state block then goes through a series of transformation rounds including
an initial round, the sub-byte round, the shift rows round, the mix columns round, the add key
round, and the final round to encrypt the data. As shown in Figure 11.4b, a specific round key is
11.4. AES256 ACCELERATOR MODULE 475
derived from the original cipher key and used in a given round [FIPS-197, 2001, SLAU367O,
2017].
A block diagram of the MSP430FR5994 AES256 Accelerator Module is provided in
Figure 11.4c. Input plain text data for encryption may be stored in register AESADIN or AE-
SAXDIN. Data input to AESAXDIN is XORed with the current state value. The operation of
the AES256 Accelerator module is controlled by AES Control Registers 0 and 1. The AES key
is provided to the AESAKEY register. The encrypted cipher text is output to the AESADOUT
Register [SLAU367O, 2017].

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.

11.4.2 API SUPPORT


Texas Instruments provides extensive support for many MSP430 subsystems through a series
of application program interfaces (APIs). Basically, they are a library of prewritten functions
that allow for the rapid prototyping of programs. Provided below is a list of APIs supporting
the AES256 Accelerator Modules. Details on API settings are provided in MSP430 Peripheral
Driver Library User’s Guide [Driver Library, 2015] and will not be repeated here.
• AES256_clearErrorFlag
• AES256_clearInterrupt
• AES256_decryptData
476 11. MSP430 SYSTEM INTEGRITY

Cipher Key Plain Text


out[0] out[4] out[8] out[12] (AESAKEY) (AESADIN)

out[1] out[5] out[9] out[13] Initial Key Initial Round

s[0,0] s[0,1] s[0,2] s[0,3] 10] out[14] Round Key 1 Round 1

s[1,0] s[1,1] s[1,2] s[1,3] 11] out[15] Round Key 2 Round 2

in[0] in[4] in[8] in[12] 2,2] s[2,3]

Round Key 9 Round 9


in[1] in[5] in[9] in[13] 3,2] s[3,3]
initial
sub-bytes Round Key 10 Round 10
in[2] in[6] in[10] in[14] shift rows
mix columns
add round key Ciphertext
final round
in[3] in[75] in[11] in[15] (AESADOUT)
(b) AES256 encryption process with
(a) AES256 algorithm a 128-bit key
AESADIN AESAXDIN
(AES accelerator (AES accelerator
data in) XORed data in)

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);

//Encrypt data with preloaded cipher key


MAP_AES256_encryptData(AES256_MODULE, Data, DataAESencrypted);

//Load a decipher key to module


MAP_AES256_setDecipherKey(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

Define data block for encryption

Reload AES key


Define 256-bit (32-byte) cipher key Set AES module to decrypt mode
Set AES key length to 256 bits
Declare encypted data variable Load 256-bit cypher key to AESAKEY register

Declare decrypted data variable No


Key written?

Stop watchdog timer Yes


Decrypt data with keys generated during encryption
(~214 MCLK cycles)
Set P1.0 as output, turn off P1.0 LED Generate all round keys needed for decryption
Begin encryption process
Load cipher key
Set AES key length the 256 bits Write 128-bit block of data to decrypt module
Load 256-bit cipher key to AESAKEY register
Wait for
No unit to finish
(~167 MCLK cycles)
No
Key written?
Yes
Yes Write 128-bit block encrypted data
Encrypt data and store to DataAESencrypted back to DataAESdecrypted
Load 128-bit block of data to encrypt to module
Confirm decrypt data is identical to original data
Initiate encryption by setting AESKEYWR to 1

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

Figure 11.5: AES256 encryption/decryption process [SLAU367O, 2017].


480 11. MSP430 SYSTEM INTEGRITY
//Plaintext: 00112233445566778899aabbccddeeff
//Ciphertext: 8ea2b7ca516745bfeafc49904b496089
//
//Dung Dang
//Texas Instruments Inc.
//Nov 2013
//Built with Code Composer Studio V6.0
//***********************************************************************

#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 };

uint8_t DataAESencrypted[16]; //Encrypted data


uint8_t DataAESdecrypted[16]; //Decrypted data

int main(void)
{
volatile uint32_t i;
uint16_t sCipherKey, tempVariable;

WDTCTL = WDTPW | WDTHOLD; //Stop WDT

P1DIR |= BIT0; //P1.0 set as output


P1OUT &= ~BIT0; //Turn off P1.0 LED

//Step 1: Load cipher key


AESACTL0 &= ~AESOP_3; //Set AES module to encrypt mode
11.4. AES256 ACCELERATOR MODULE 481
//Set AES key length to 256 bits
AESACTL0 = AESACTL0 & (~(AESKL_1 + AESKL_2)) | AESKL__256BIT;

//Load 256-bit cipher key to the AESAKEY register


for(i = 0; i < 256/8; i = i + 2)
{
//Concatenate 2 8-bit blocks into one 16-bit block
sCipherKey =(uint16_t)(CipherKey[i]);
sCipherKey = sCipherKey |((uint16_t)(CipherKey[i + 1]) << 8);

//Load 16-bit key block to AESAKEY register


AESAKEY = sCipherKey;
}

//Wait until key is written


while((AESASTAT & AESKEYWR ) == 0);

//Step 2: Encrypt data and store to DataAESencrypted


//Load 128-bit block of data to encrypt to module
for(i = 0; i < 16; i = i + 2)
{
//Concatenate 2 8-bit blocks into one 16-bit block
tempVariable =(uint16_t)(Data[i]);
tempVariable = tempVariable |((uint16_t)(Data[i + 1]) << 8);

//Load 16-bit key block to AESADIn register


AESADIN = tempVariable;
}

//Initiate encryption by setting AESKEYWR to 1


AESASTAT |= AESKEYWR;

//Wait unit finished ~167 MCLK


while( AESASTAT & AESBUSY );

//Write 128-bit block of encrypted data back to DataAESencrypted


for(i = 0; i < 16; i = i + 2)
{
482 11. MSP430 SYSTEM INTEGRITY
tempVariable = AESADOUT;
DataAESencrypted[i] = (uint8_t)tempVariable;
DataAESencrypted[i+1] = (uint8_t)(tempVariable >> 8);
}

//Step 3: Reload AES key


//Set AES module to decrypt mode
AESACTL0 |= AESOP_1;

//Set AES key length to 256 bits


AESACTL0 = AESACTL0 & (~(AESKL_1 + AESKL_2)) | AESKL__256BIT;

//Load 256-bit cipher key to the AESAKEY register


for(i = 0; i < 256/8; i = i + 2)
{
//Concatenate 2 8-bit blocks into one 16-bit block
sCipherKey =(uint16_t)(CipherKey[i]);
sCipherKey = sCipherKey |((uint16_t)(CipherKey[i + 1]) << 8);

//Load 16-bit key block to AESAKEY register


AESAKEY = sCipherKey;
}

//Wait until key is written


while((AESASTAT & AESKEYWR ) == 0);

//Step 4: Decrypt data with keys that were generated during


//encryption takes 214 MCLK. This function will generate all round
//keys needed for decryption first and then the encryption process
//starts.

//Write 128-bit block of data to decrypt to module


for(i = 0; i < 16; i = i + 2)
{
tempVariable = (uint16_t) (DataAESencrypted[i + 1] << 8);
tempVariable = tempVariable | ((uint16_t) (DataAESencrypted[i]));
AESADIN = tempVariable;
}
11.5. LABORATORY EXERCISE: AES256 483

//Wait until finished ~167 MCLK


while(AESASTAT & AESBUSY);

//Write 128-bit block of encrypted data back to DataAESdecrypted


for(i = 0; i < 16; i = i + 2)
{
tempVariable = AESADOUT;
DataAESdecrypted[i] = (uint8_t)tempVariable;
DataAESdecrypted[i+1] =(uint8_t)(tempVariable >> 8);
}

//Step 4: Confirm decrypted data is identical to original data


for(i = 0; i < 16; i ++)
if(DataAESdecrypted[i]!= Data[i])
while(1); //Set breakpoint here for error

P1DIR |= BIT0;
P1OUT |= BIT0; //Turn on P1.0 LED = success
while(1);

//***********************************************************************

11.5 LABORATORY EXERCISE: AES256


Develop an algorithm to encode a plain text block of data with the AES256 system, transmit
the cipher text to another microcontroller, and then decrypt back to plain text at the receiving
microcontroller.

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

MSP430FR58xx, MSP430FR59xx, and MSP430FR6xx Family User’s, (SLAU367O), Texas In-


struments, 2017. 465, 466, 467, 474, 475, 476, 479

Noise Reduction Techniques for Microcontroller-Based Systems, (AN1705/D), Freescale Semicon-


ductor, 2004. 462, 463

Understanding and Eliminating EMI in Microcontroller Applications, (COP888), Texas Instru-


ments, 1996. 462, 463

11.8 CHAPTER PROBLEMS


Fundamental

1. Describe sources of EMI.

2. Describe EMI coupling mechanisms.

3. Describe three strategies to combat EMI.

4. Describe specific techniques to combat EMI.

5. Describe defensive programming techniques.

Advanced

1. Sketch a UML activity diagram for the CRC algorithm.

2. What is the purpose of generating a CRC checksum?

3. What does a correct checksum indicate? An incorrect one?

4. Research common CRC polynomials. Sketch the corresponding LFSR for each polyno-
mial.

5. What is the purpose of the AES256 subsystem?


11.8. CHAPTER PROBLEMS 485
Challenging
1. What are the advantages and disadvantages of using different encryption key lengths with
the AES256?
2. Sketch a UML activity diagram for the AES256 encryption algorithm.
487

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.

12.3 EMBEDDED SYSTEM DESIGN PROCESS


There are many formal design processes that we could study. We concentrate on the steps that
are common to most. We purposefully avoid formal terminology of a specific approach and
instead concentrate on the activities that are accomplished during the development of a system
prototype. The design process we describe is illustrated in Figure 12.1 using a UML activity
diagram. We discuss the UML activity diagrams later in this section.

12.3.1 PROJECT DESCRIPTION


The goal of the project description step is to determine what the system is ultimately supposed to
do. Questions to raise and answer during this step include, but are not limited to, the following.
• What is the system supposed to do?
• Where will it be operating and under what conditions?
• Are there any restrictions placed on the system design?
To answer these questions, the designer interacts with the client to ensure clear agreement
on what is to be done. The establishment of clear, definable system requirements may require
considerable interaction between the designer and the client. It is essential that both parties agree
on system requirements before proceeding further in the design process. The final result of this
step is a detailed listing of system requirements and related specifications. If you are completing
this project for yourself, you must still carefully and thoughtfully complete this step.

12.3.2 BACKGROUND RESEARCH


Once a detailed list of requirements has been established, the next step is to perform back-
ground research related to the design. In this step, the designer will ensure they understand all
requirements and features required by the project. This will again involve interaction between
the designer and the client. The designer will also investigate applicable codes, guidelines, pro-
tocols, and standards related to the project. This is also a good time to start thinking about the
12.3. EMBEDDED SYSTEM DESIGN PROCESS 489

Project Description Implement Prototype


- What is the system supposed to do? - Top down vs. bottom up
- Operating conditions and environment - Develop low risk hardware test platform
- Formal requirements - Software implementation

Background Research Preliminary Testing


- Thoroughly understand desired requirements and features - Develop test plan to insure requirements
- Determine applicable codes, guidelines, and protocols have been met
- Test under anticipated conditions
- Determine interface requirements
- Test under abusive conditions
- Redo testing if errors found
Pre-Design - Test in low-cost, low-risk environment
- Brainstorm possible solutions - Full up test
- Thoroughly investigate alternatives
- Choose best possible solution
- Identify specific target microcontroller Yes System design
- Choose a design approach need correction?

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

Figure 12.1: Embedded system design process.


490 12. SYSTEM-LEVEL DESIGN
interface between different portions of the input and output devices peripherally connected to
the processor. The ultimate objective of this step is to have a thorough understanding of the
project requirements, related project aspects, and any interface challenges within the project.

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?

• How many I/O pins are required by the design?

• What type of memory components are required?

• 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:

• employing a top-down design, bottom-up implementation approach,

• using a structure chart to assist in partitioning the system,

• using a UML activity diagram to work out program flow, and


12.3. EMBEDDED SYSTEM DESIGN PROCESS 491
• developing a detailed circuit diagram of the entire system.

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

Starting Transfer Final State


Activity of Control

Branch Action State

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.3.5 IMPLEMENT PROTOTYPE


To successfully implement a prototype, an incremental approach should be followed. Again, the
top-down design, bottom-up implementation provides a solid guide for system implementation.
In an embedded system design involving both hardware and software, the hardware system in-
cluding the processor should be assembled first. This provides the software the required signals
to interact with. As the hardware prototype is assembled on a prototype board, each compo-
nent is tested for proper operation as it is brought online. This allows the designer to pinpoint
malfunctions as they occur.
Once the hardware prototype is assembled, coding may commence. It is important to
note that on larger projects software and hardware may be developed concurrently. As before,
software should be incrementally brought online. You may use a top-down, bottom-up, or hybrid
approach depending on the nature of the software. The important point is to bring the software
online incrementally such that issues can be identified and corrected early on.
It is highly recommended that low-cost stand-in components be used when testing the
software with the hardware components. For example, push buttons, potentiometers, and LEDs
may be used as low-cost stand-in component simulators for expensive input instrumentation
12.3. EMBEDDED SYSTEM DESIGN PROCESS 493
devices and expensive output devices such as motors. This allows you to insure the software is
properly operating before using it to control the actual components.

12.3.6 PRELIMINARY TESTING


To test the system, a detailed test plan must be developed. Tests should be developed to verify
that the system meets all of its requirements and also intended system performance in an oper-
ational environment. The test plan should also include scenarios in which the system is used in
an unintended manner. As before, a top-down, bottom-up, or hybrid approach can be used to
test the system. In a bottom-up approach individual units are tested first.
Once the test plan is completed, actual testing may commence. The results of each test
should be carefully documented. As you go through the test plan, you will probably uncover
a number of run-time errors in your algorithm. After you correct a run-time error, the entire
test plan must be repeated. This ensures that the new fix does not have an unintended effect on
another part of the system. Also, as you process through the test plan, you will probably think
of other tests that were not included in the original test document. These tests should be added
to the test plan. As you go through testing, realize your final system is only as good as the test
plan that supports it!
Once testing is complete, you should accomplish another level of testing where you in-
tentionally try to “jam up” the system. In other words, try to get your system to fail by trying
combinations of inputs that were not part of the original design. A robust system should con-
tinue to operate correctly in this type of an abusive environment. It is imperative that you design
robustness into your system. When testing on a low cost simulator is complete, the entire test
plan should be performed again with the actual system hardware. Once this is completed you
should have a system that meets its requirements!

12.3.7 COMPLETE AND ACCURATE DOCUMENTATION


With testing complete, the system design should be thoroughly documented. Much of the doc-
umentation will have already been accomplished during system development. Documentation
will include the system description, system requirements, the structure chart, the UML activity
diagrams documenting program flow, the test plan, results of the test plan, system schematics,
and properly documented code. To properly document code, you should carefully comment all
functions describing their operation, inputs, and outputs. Also, comments should be included
within the body of the function describing key portions of the code. Enough detail should be
provided such that code operation is obvious. It is also extremely helpful to provide variables
and functions within your code names that describe their intended use.
You might think that comprehensive system documentation is not worth the time or effort
to complete it. Complete documentation pays rich dividends when it is time to modify, repair,
or update an existing system. Also, well-documented code may be often reused in other projects:
a method for efficient and timely development of new systems.
494 12. SYSTEM-LEVEL DESIGN
In the next sections we provide detailed examples of the system design process for a
weather station, a submersible robot, and a 4WD robot capable of navigating through a moun-
tainous maze.

12.4 MSP430FR5994: WEATHER STATION


In this project, we design a weather station to sense wind direction and ambient temperature.
The wind direction will be displayed on LEDs arranged in a circular pattern. The wind direction
and temperature will also be transmitted serially via the SPI from the microcontroller to the
onboard microSD flash memory card for data logging.

12.4.1 REQUIREMENTS
The requirements for this system include:

• design a weather station to sense wind direction and ambient temperature;

• wind direction should be displayed on LEDs arranged in a circular pattern; and

• wind direction and temperature should be transmitted serially from the microcontroller to
the onboard microSD card for storage.

12.4.2 STRUCTURE CHART


To begin, the design process, a structure chart is used to partition the system into definable
pieces. We employ a top-down design/bottom-up implementation approach. The structure chart
for the weather station is provided in Figure 12.3. The three main microcontroller subsystems
needed for this project are the SPI for serial communication, the ADC12 system to convert the
analog voltage from the LM34 temperature sensor and weather vane into digital signals, and
the wind direction display. The system is partitioned until the lowest level of the structure chart
contains “doable” pieces of hardware components or software functions. Data flow is shown on
the structure chart as directed arrows.

12.4.3 CIRCUIT DIAGRAM


Analog sensors: The circuit diagram for the weather station is provided in Figure 12.4. The
weather station is equipped with two input sensors: the LM34 to measure temperature and the
weather vane to measure wind direction. Both of the sensors provide an analog output that is fed
to the MSP430. The LM34 provides 10 mV output per degree Fahrenheit. The weather vane
provides a voltage output from 0–3.3 VDC for different wind direction as shown in Figure 12.4.
The weather vane must be oriented to a known direction with the output voltage at this direction
noted. We assume that 0 VDC corresponds to North.
12.4. MSP430FR5994: WEATHER STATION 495

Weather Station

Wind
SPI ADC12 Direction
Display

Data Ch for Conv Wind Temp Wind


for TX Conv Data Direction Data Direction
SPI
Initialize AC12 Weather LM34 LED
Initialize ReadADC12 Vane Temp Sensor Interface
& Transmit

Data for
Display
MicroSD
Card

Figure 12.3: Weather station structure chart.

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.

12.4.4 UML ACTIVITY DIAGRAMS


The UML activity diagram for the main program is provided in Figure 12.5. After initializing
the subsystems, the program enters a continuous loop where temperature and wind direction is
sensed and displayed on the LCD and the LED display. The sensed values are then transmitted
via the SPI to the MMC/SD card. The system then enters a delay to set how often the temper-
ature and wind direction parameters are updated. We have you construct the individual UML
activity diagrams for each function as an end of chapter exercise.

12.4.5 MICROCONTROLLER CODE


For quick prototyping the first version of the code for this project is rendered in Energia. After
initializing the system, the code continuously loops and reads temperature and wind direction
data, and displays the data to the LED array. A delay should be inserted in the loop to determine
how often the weather data should be collected. During development code status is sent to the
serial monitor. Printing to the serial monitor is enabled with the variable “troubleshoot.”
496 12. SYSTEM-LEVEL DESIGN

MSP-EXP430FR5994 LaunchPad

Degrees Ohms Vout


0 33 k 2.53
22.5 6.57 k 1.31
45 8.2 k 1.49
67.5 891 0.27
90 1k 0.30
112.5 688 0.21
135 2.2 k 0.60
157.5 1.41 k 0.41
Sparkfun Weather 180 3.9 k 0.93
Meters (SEN-08942) 202.5 3.14 k 0.79
225 16 k 2.03
Vcc = 3.3 V 247.5 14.12 k 1.93
270 120 k 3.05
P1.5, A5 10 K 292.5 42.12 k 2.67
pin 28 4 315 64.9 k 2.86
1 337.5 21.88 k 2.26
1 4
Weather Vane

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

Convert wind direction

Display wind direction


on LED

Transmit results to MMC/SD


card via SPI

Delay(desired_update_time)

Figure 12.5: Weather station UML activity diagram.


498 12. SYSTEM-LEVEL DESIGN
//***********************************************************************
//weather station
//- Equipped with:
//- Sparkfun weather meters (SEN-08942)
// -- rain gauge
// -- anemometer
// -- wind vane
//- LM34 temperature sensor
//- Sparkfun LCD-09067, serial enabled 16x2 LCD, 3.3 VDC
//***********************************************************************

//analog input pins


#define wind_dir 28 //analog pin - weather vane
#define temp_sensor 6 //analog pin - LM34 temp sensor

//digital output pins - LED indicators


#define N_LED 31 //digital pin - N LED
#define NE_LED 32 //digital pin - NE LED
#define E_LED 33 //digital pin - E LED
#define SE_LED 34 //digital pin - SE LED
#define S_LED 35 //digital pin - S LED
#define SW_LED 36 //digital pin - SW LED
#define W_LED 37 //digital pin - W LED
#define NW_LED 38 //digital pin - NW LED

int wind_dir_value; //declare variable for wind dir


int temp_value; //declare variable for temp
int troubleshoot = 1; //1: serial monitor prints

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

//Serial monitor - open serial communications


if(troubleshoot == 1) Serial.begin(9600);
}

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);

//LM34 provides 10 mV/degree


temp_value =(int)(((temp_value/1023.0) * 3.3)/.010);
if(troubleshoot == 1)Serial.println(temp_value);

//display wind direction


display_wind_direction(wind_dir_value);
}

//***********************************************************************

void display_wind_direction(unsigned int wind_dir_int)


{
float wind_dir_float;
//convert wind direction to float
wind_dir_float = wind_dir_int/1023.0 * 3.3;

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);
}
}

//***********************************************************************

12.4.6 PROJECT EXTENSIONS


The control system provided above has a set of very basic features. Here are some possible ex-
tensions for the system.

• Equip the weather station with an LCD display.


502 12. SYSTEM-LEVEL DESIGN
• In addition to the wind vane, the Sparkfun weather meters (SEN-08942) includes a rain
gauge and anemometer. Add these features to the weather station.

• 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 SUBMERSIBLE ROBOT


The area of submersible robots is fascinating and challenging. To design a robot is quite com-
plex (yet fun). To add the additional requirement of waterproofing key components provides an
additional level of challenge. (Water and electricity do not mix!) In this section we provide the
construction details and a control system for a remotely operated vehicle, an ROV. Specifically,
we develop the structure and control system for the SeaPerch style ROV, as shown in Fig-
ure 12.6. By definition, an ROV is equipped with a tether umbilical cable that provides power
and control signals from a surface support platform. An autonomous underwater vehicle (AUV)
carries its own power and control equipment and does not require surface support [Seaperch].
Details on the construction and waterproofing of an ROV are provided in the excellent
and fascinating Build Your Own Underwater Robot and Other Wet Projects by Harry Bohm and
Vickie Jensen. For an advanced treatment, please see The ROV Manual-A User Guide for Remotely
Operated Vehicles by Robert Crist and Robert Wernli, Sr. There is a national-level competition
for students based on the SeaPerch ROV. The goal of the program is to stimulate interest in the
next generation of marine-related engineering specialties [Seaperch].

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.

2. Design and construct ROV structure.

3. Design and fabricate control electronics.

4. Design and implement control software using Energia.

5. Construct and assemble a prototype.

6. Test the prototype.

12.5.2 REQUIREMENTS
The requirements for the ROV system include the following.
12.5. SUBMERSIBLE ROBOT 503

Power and Control


Umbilical

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

12.5.3 ROV STRUCTURE


The ROV structure is shown in Figure 12.8. The structure is constructed with 0.75-in PVC
piping. The structure is assembled quickly using “T” and corner connectors. The pieces are con-
nected using PVC glue or machine screws. The PVC pipe and connectors are readily available
in hardware and home improvement stores.
The fore or bow portion of the structure is equipped with plexiglass panels to serve as
mounting bulkheads for the thrusters. The panels are mounted to the PVC structure using ring
clamps. Either waterproofed electric motors or submersible bilge pumps are used as thrusters. A
bilge pump is a pump specifically designed to remove water from the inside of a boat. The pumps
are powered from a 12 VDC source and have typical flow rates from 360 to over 3,500 gallons per
12.5. SUBMERSIBLE ROBOT 505
Stern Bow

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

Figure 12.8: SeaPerch ROV structure.


506 12. SYSTEM-LEVEL DESIGN
minute. They range in price from U.S. $20–$80 (www.shorelinemarinedevelopment.com).
Details on waterproofing electric motors are provided in Build Your Own Underwater Robot and
Other Wet Projects. We use three Shoreline Bilge Pumps rated at 600 gallons per minute (GPM).
They are available online from www.walmart.com.
The aft or stern portion of the structure is designed to hold the flexible umbilical cable.
The cable provides a link between the MSP430-based control system and the thrusters. Each
thruster may require up to 1–2 amps of current. Therefore, a four-conductor, 16 AWG, braided
(for flexibility) conductor cable is recommended. The cable is interfaced to the bilge pump leads
using soldered connections or Butt connectors. The interface should be thoroughly waterproofed
using caulk. For this design the interface was placed within a section of PVC pipe equipped with
end caps. The resulting container is filled with waterproof caulk.
Once the ROV structure is complete its buoyancy is tested. This is accomplished by plac-
ing the ROV structure in water. The goal is to achieve a slightly positive buoyancy. With positive
buoyancy the structure floats. With neutral buoyancy the structures hovers beneath the surface.
With negative buoyancy the structure sinks. A more positive buoyancy way be achieved by at-
taching floats or foam to the structure tubing. A more negative buoyancy may be achieved by
adding weights to the structure [Bohm and Jensen, 2012].

12.5.4 STRUCTURE CHART


The SeaPerch structure chart is provided in Figure 12.9. As can be seen in the figure, the
SeaPerch control system will accept input from the five position joystick (left, right, select,
up, and down). We use the Sparkfun thumb joystick (Sparkfun COM-09032) mounted to a
breakout board (Sparkfun BOB-09110), as shown in Figure 12.10. The joystick schematic and
connections to MSP430 are provided in Figures 12.11 and 12.12.
In response to user joystick input, the SeaPerch control algorithm will issue a control
command indicating desired ROV direction. In response to this desired direction command,
the motor control algorithm will issue control signals to assert the appropriate thrusters and
LEDs.

12.5.5 CIRCUIT DIAGRAM


The circuit diagram for the SeaPerch control system is provided in Figure 12.11. The thumb
joystick is used to select desired ROV direction. The thumb joystick contains two built-in po-
tentiometers (horizontal and vertical). A reference voltage of 3.3 VDC is applied to the VCC
input of the joystick. As the joystick is moved, the horizontal (HORZ) and vertical (VERT) ana-
log output voltages will change to indicate the joystick position. The joystick is also equipped
with a digital select (SEL) button. The SEL button is used to activate an ROV dive. The joystick
is interfaced to MSP430 as shown in Figure 12.11.
There are three LED interface circuits connected to MSP430 header pins P4.2, P4.4, and
P4.5. The LEDs illuminate to indicate the left, vertical, and right thrusters have been asserted.
12.5. SUBMERSIBLE ROBOT 507

Seaperch
Control System

ROV
Direction Direction
Five Position Motor
Joystick Control

Motor LED
Assertion Assertion

Motor Light-Emitting
Interface Diodes (LEDs)
Interface

Left Vertical Right Left Vertical Right


Thruster Thruster Thruster LED LED LED

Figure 12.9: SeaPerch ROV structure chart.


508 12. SYSTEM-LEVEL DESIGN

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

(a) 3.3 VDC regulator to Sparkfun thumb joystick interface


Forward
(bow)

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

5.0 VDC 5.0 VDC 5.0 VDC


12 VDC

220 Ω 220 Ω 220 Ω

+ + +
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

Left M 1N4001 Right M 1N4001


Thruster Thruster

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

To Left To Right To Vertical PCB


12 V Thruster Thruster Thruster mounting
12 V 5 V Ground hole for
spacer
hardware

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

39:right_thruster (Br)19:vert_thr (W)

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)

Sparkfun thumb joystick on breakout board and


Jameco Prototype Builder 1.6" × 2.7" PCB (#105100)

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.

12.5.6 UML ACTIVITY DIAGRAM


The SeaPerch control system UML activity diagram is provided in Figure 12.13. After initializ-
ing the MSP430 pins the control algorithm is placed in a continuous loop awaiting user input.
In response to user input, the algorithm determines desired direction of ROV travel and asserts
appropriate control signals for the LED and motors.

12.5.7 MSP430 CODE


In this example we use the thumb joystick to control the left and right thruster (motor or bilge
pump). The joystick provides a separate voltage from 0–3.3 VDC for the horizontal (HORZ)
and vertical (VERT) position of the joystick. We use this voltage to set the duty cycle of the
pulse width modulated (PWM) signals sent to the left and right thrusters. The select push-
button (SEL) on the joystick is used to assert the vertical thruster. The analog read function
(analogRead) is used to read the X and Y position of the joystick. A value from 0–1023 is re-
ported from the analog read function corresponding to 0–3.3 VDC. After the voltage readings
are taken they are scaled to 3.3 VDC for further processing. Joystick activity is divided into mul-
tiple zones (0–8), as shown in Figure 12.14. The joystick signal is further processed consistent
with the joystick zone selected.
//***********************************************************************
//ROV
//In response to joystick input, the SeaPerch control algorithm issues
//a control command indicating desired ROV direction. In response to
//desired direction command, the motor control algorithm issues
//control signals to assert the appropriate thrusters and LEDs.
//***********************************************************************

//analog input pins


#define joystick_hor 6 //analog pin - joystick horizontal in
#define joystick_ver 28 //analog pin - joystick vertical in

//digital input pin


512 12. SYSTEM-LEVEL DESIGN

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 Assert vertical thruster


Zone 0? and vertical LED
no no
Zone 1
:
Zone 7

yes
Zone 8? Proceed right and forward

no

Figure 12.13: SeaPerch ROV UML activity diagram.


12.5. SUBMERSIBLE ROBOT 513

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

Figure 12.14: Joystick position as related to thruster activity.

#define joystick_sel 34 //digital pin - joystick select in

//digital output pins - LED indicators


#define left_LED 31 //digital pin - left LED out
#define vertical_LED 32 //digital pin - vertical LED out
#define right_LED 33 //digital pin - right LED out

//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

int joystick_hor_value; //horizontal joystick value


int joystick_ver_value; //vertical joystick value
int joystick_sel_value; //joystick select value
int joystick_thrust_on; //1: thrust on; 0: off
int troubleshoot = 1; //1: serial monitor prints

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

//joystick select input


pinMode(joystick_sel, INPUT); //config pin for digital in - joystick sel

//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

//Serial monitor - open serial communications


if(troubleshoot == 1) Serial.begin(9600);
}

void loop()
{
//set update interval
delay(1000);

//turn off LEDs


digitalWrite(left_LED, LOW); //left LED - off
digitalWrite(vertical_LED, LOW); //vertical LED - off
digitalWrite(right_LED, LOW); //right LED - off

//read hor and vert joystick position


12.5. SUBMERSIBLE ROBOT 515
//analog read returns value between 0 and 1023
joystick_hor_value = analogRead(joystick_hor);
joystick_ver_value = analogRead(joystick_ver);

if(troubleshoot == 1) Serial.println(joystick_hor_value);
if(troubleshoot == 1) Serial.println(joystick_ver_value);

//Convert 0 to 1023 to 0 to 3.3 VDC value


joystick_hor_value = ((joystick_hor_value/1023.0) * 3.3);
if(troubleshoot == 1) Serial.println(joystick_hor_value);

joystick_ver_value = ((joystick_ver_value/1023.0) * 3.3);


if(troubleshoot == 1) Serial.println(joystick_ver_value);

//Read vertical thrust


joystick_thrust_on = digitalRead(joystick_sel); //vertical thrust?

//**************************************************************
//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((joystick_hor_value > 1.60)&&(joystick_hor_value < 1.70)&&


(joystick_ver_value > 1.60)&&(joystick_ver_value < 1.70))

{
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 thrusters to move forward


analogWrite(left_thruster, 0);
analogWrite(right_thruster, 0);

//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((joystick_hor_value > 1.60)&&(joystick_hor_value < 1.70)&&


(joystick_ver_value <= 1.60))
{
if(troubleshoot == 1) Serial.println("Zone 1");

//scale joystick vertical to value from 0 to 1


joystick_ver_value = 1.60 - joystick_ver_value;

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 to move forward


analogWrite(left_thruster, joystick_ver_value);
analogWrite(right_thruster, joystick_ver_value);

//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((joystick_hor_value <= 1.60)&&(joystick_ver_value <= 1.60))


{
if(troubleshoot == 1) Serial.println("Zone 2");

//scale joystick horizontal and vertical to value from 0 to 1


518 12. SYSTEM-LEVEL DESIGN
joystick_hor_value = 1.60 - joystick_hor_value;
joystick_ver_value = 1.60 - joystick_ver_value;

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 and LEDs


if(joystick_hor_value > joystick_ver_value)
{
analogWrite(left_thruster, (joystick_hor_value - joystick_ver_value));
analogWrite(right_thruster, joystick_hor_value);

//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((joystick_hor_value <= 1.60)&&(joystick_ver_value > 1.60)&&


12.5. SUBMERSIBLE ROBOT 519
(joystick_ver_value < 1.70))
{
if(troubleshoot == 1) Serial.println("Zone 3");

//scale joystick vertical to value from 0 to 1


joystick_hor_value = 1.60 - joystick_hor_value;

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((joystick_hor_value <= 1.60)&&(joystick_ver_value >= 1.70))


{
if(troubleshoot == 1) Serial.println("Zone 4");

//scale joystick horizontal and vertical to value from 0 to 1


joystick_hor_value = 1.60 - joystick_hor_value;
joystick_ver_value = joystick_ver_value - 1.70;

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 thrusters and LEDs


if(joystick_hor_value > joystick_ver_value)
{
analogWrite(left_thruster, 0);
analogWrite(right_thruster, (joystick_hor_value-joystick_ver_value));

//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((joystick_hor_value > 1.60)&&(joystick_hor_value < 1.70)&&


(joystick_ver_value >= 1.70))
{
if(troubleshoot ==1) Serial.println("Zone 5");
12.5. SUBMERSIBLE ROBOT 521
//scale joystick vertical to value from 0 to 1
joystick_ver_value = joystick_ver_value - 1.70;

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((joystick_hor_value >= 1.70)&&(joystick_ver_value >= 1.70))


{
if(troubleshoot == 1) Serial.println("Zone 6");

//scale joystick horizontal and vertical to value from 0 to 1


joystick_hor_value = joystick_hor_value - 1.70;
joystick_ver_value = joystick_ver_value - 1.70;

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 and LEDs


522 12. SYSTEM-LEVEL DESIGN
if(joystick_hor_value > joystick_ver_value)
{
analogWrite(left_thruster, (joystick_hor_value-joystick_ver_value));
analogWrite(right_thruster, 0);

//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((joystick_hor_value >= 1.70)&&(joystick_ver_value > 1.60)&&


(joystick_ver_value < 1.70))
{
if(troubleshoot == 1) Serial.println("Zone 7");

//scale joystick vertical to value from 0 to 1


joystick_hor_value = joystick_hor_value - 1.70;

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((joystick_hor_value >= 1.70)&&(joystick_ver_value <= 1.60))


{
if(troubleshoot == 1) Serial.println("Zone 8");

//scale joystick horizontal and vertical to value from 0 to 1


joystick_hor_value = joystick_hor_value - 1.70;
joystick_ver_value = 1.60 - joystick_ver_value;

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 and LEDs


if(joystick_hor_value > joystick_ver_value)
{
524 12. SYSTEM-LEVEL DESIGN
analogWrite(left_thruster, joystick_hor_value);
analogWrite(right_thruster, (joystick_hor_value-joystick_ver_value));

//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
}
}
}

//**************************************************************

12.5.8 CONTROL HOUSING LAYOUT


A Plano Model 1312-00 water-resistant field box is used to house the control circuitry and
rechargeable battery. The battery is a rechargeable, sealed, lead-acid battery, 12 VDC, with
an 8.5 amp-hour capacity. It is available from McMaster-Carr (#7448K82). A battery charger
(12 VDC, 4–8 amp-hour rating) is also available (#7448K67). The layout for the ROV control
housing is provided in Figure 12.15.
The control circuitry consists of two connected plastic panels, as shown in Figure 12.15.
The top panel has the on/off switch, the LED thruster indicators (left, dive, and right), an access
hole for the joystick, and a 1/4-in jack for the battery recharge cable.
The lower panel is connected to the top panel using aluminum spacers, screws, and corre-
sponding washers, lock washers, and nuts. The lower panel contains MSP430 equipped with the
thumb joystick on the breakout board. The MSP430 LaunchPad is connected to the lower panel
using a Jameco stand off kit (#106551). The MSP430 LaunchPad is interfaced to the thrusters
via interface circuitry described in Figures 12.11 and 12.12. The interface printed circuit board
is connected to the four-conductor thruster cable via a four-conductor Jones connector.

12.5.9 FINAL ASSEMBLY TESTING


The final system is tested a subassembly at a time. The following sequence is suggested.
12.5. SUBMERSIBLE ROBOT 525

To ROV
Structure

Center Thruster
Right Thruster
Left Thruster

13.6 VDC
on/off Batt
switch Access Inline Fuse
Hole
L Bracket L Bracket

LEFT DIVE RIGHT


LED LED LED

Interface Printed
Circuit Board

MSP432 with joystick


Boosterpack

Joystick

Joystick

12 VDC
for Recharger L Bracket

Figure 12.15: ROV control housing layout.


526 12. SYSTEM-LEVEL DESIGN
1. Recheck all waterproofed connections. Reapply waterproof caulk as necessary.

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.

12.5.10 FINAL ASSEMBLY


The fully assembled ROV is shown in Figure 12.16.

12.5.11 PROJECT EXTENSIONS


The control system provided above has a set of very basic features. Here are some possible ex-
tensions for the system.

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

12.6.3 CIRCUIT DIAGRAM


The circuit diagram for the robot is provided in Figure 12.18. The 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. The robot motors will be driven by PWM
channels via an H-bridge. The robot is powered by a 7.5 VDC battery pack (5 AA batteries)
which is fed to a 3.3 and 5 VDC voltage regulator. Alternatively, the robot may be powered by
a 7.5 VDC power supply rated at several amps. In this case, the power is delivered to the robot
by a flexible umbilical cable. The circuit diagram includes the inertial measurement unit (IMU)
to measure vehicle tilt and a liquid crystal display. Both were discussed in Chapter 12.9.

12.6.4 STRUCTURE CHART


The structure chart for the robot project is provided in Figure 12.19.

12.6.5 UML ACTIVITY DIAGRAMS


The UML activity diagram for the robot is provided in Figure 12.20.
12.6. MOUNTAIN MAZE NAVIGATING ROBOT 529

Prototype Area

IR Sensor
Array

Drive Drive
Motor Motor

(a) Front view

Prototype Area

IR Sensor
Array

Battery
Compartment

(b) Side view

Figure 12.17: Robot layout.


530 12. SYSTEM-LEVEL DESIGN
IR IR IR
Sensor Sensor Sensor
Left Middle Right

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 5 VDC 5 VDC

220 220 220

Wall Wall Wall


Left Center Right
10 K 10 K 10 K
2N2222 2N2222 2N2222
J4, P4.1, 31 J4, P4.2, 32 J4, P4.3, 33

+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

Figure 12.19: Robot structure diagram.


Liquid
Crystal Display motor_control ADC12

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

Left Right Left Middle Right Left Right


Motor Motor IR Sensor IR Sensor IR Sensor Wheel Wheel
Encoder Encoder
12.6. MOUNTAIN MAZE NAVIGATING ROBOT
531
532 12. SYSTEM-LEVEL DESIGN

Include files
Global variables
Function prototypes

Initialize pins
Initialize ADC
Initialize PWM
Initialize LCD

while(1)

Read IR sensor inputs


(left, middle, right)

Print walls detected to


LCD, illuminate LEDs
for wall detected

Determine robot
action

Issue motor and LED


control signals
Reset wheel counters

Monitor wheel rotation


via interrupts

Yes Robot action No


Complete?

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
//*******************************************************************

//analog input pins


#define left_IR_sensor 6 //analog pin - left IR sensor
#define center_IR_sensor 27 //analog pin - center IR sensor
#define right_IR_sensor 28 //analog pin - right IR sensor

//digital output pins


//LED indicators - wall detectors
#define wall_left 31 //digital pin - wall_left
#define wall_center 32 //digital pin - wall_center
#define wall_right 33 //digital pin - wall_right

//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

int troubleshoot; //asserts troubleshoot statements

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

//LED indicators - wall detectors


pinMode(wall_left, OUTPUT); //configure pin for digital output
12.6. MOUNTAIN MAZE NAVIGATING ROBOT 535
pinMode(wall_center, OUTPUT); //configure pin for digital output
pinMode(wall_right, OUTPUT); //configure pin for digital output

//motor outputs - PWM


pinMode(l_motors_forward, OUTPUT); //configure pin for digital output
pinMode(l_motors_reverse, OUTPUT); //configure pin for digital output
pinMode(r_motors_forward, OUTPUT); //configure pin for digital output
pinMode(r_motors_reverse, OUTPUT); //configure pin for digital output
}

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);

//Print sensor values to Serial Monitor


if(troubleshoot == 1)
{
Serial.print("Left IR sensor: ");
Serial.println(left_IR_sensor_value);
Serial.print("Center IR sensor: ");
Serial.println(center_IR_sensor_value);
Serial.print("Right IR sensor: ");
Serial.println(right_IR_sensor_value);
Serial.println("");
}

//to LCD
Serial1.write(254); //Command to LCD
delay(5);
Serial1.write(1); //Cursor to home position
delay(5);

Serial1.write(254); //Command to LCD


delay(5);
Serial1.write(128); //Cursor to home position
delay(5);
536 12. SYSTEM-LEVEL DESIGN
Serial1.write("Left Ctr Right");
delay(50);
Serial1.write(254); //Command to LCD
delay(5);
Serial1.write(192); //Cursor to line 2, position 1
delay(5);
Serial1.print(left_IR_sensor_value);
delay(5);
Serial1.write(254); //Command to LCD
delay(5);
Serial1.write(198); //Cursor to line 2, position 1
delay(5);
Serial1.print(center_IR_sensor_value);
delay(5);
Serial1.write(254); //Command to LCD
delay(5);
Serial1.write(203); //Cursor to line 2, position 1
delay(5);
Serial1.print(right_IR_sensor_value);
delay(5);

delay(500);

//robot action table row 0 - robot forward


if((left_IR_sensor_value < 300)&&(center_IR_sensor_value < 300)&&
(right_IR_sensor_value < 300))
{
//wall detection LEDs
digitalWrite(wall_left, LOW); //turn LED off
digitalWrite(wall_center, LOW); //turn LED off
digitalWrite(wall_right, LOW); //turn LED off
//motor control
analogWrite(l_motors_forward, 64); //0(off)-255(full speed)
analogWrite(l_motors_reverse, 0); //0(off)-255(full speed)
analogWrite(r_motors_forward, 64); //0(off)-255(full speed)
analogWrite(r_motors_reverse, 0); //0(off)-255(full speed)

if(troubleshoot == 1) Serial.print("Table row 0 \n\n");


12.6. MOUNTAIN MAZE NAVIGATING ROBOT 537
}

//robot action table row 1 - robot forward


else if((left_IR_sensor_value < 300)&&(center_IR_sensor_value < 300)&&
(right_IR_sensor_value > 300))
{
//wall detection LEDs
digitalWrite(wall_left, LOW); //turn LED off
digitalWrite(wall_center, LOW); //turn LED off
digitalWrite(wall_right, HIGH); //turn LED on
//motor control
analogWrite(l_motors_forward, 64); //0(off)-255(full speed)
analogWrite(l_motors_reverse, 0); //0(off)-255(full speed)
analogWrite(r_motors_forward, 64); //0(off)-255(full speed)
analogWrite(r_motors_reverse, 0); //0(off)-255(full speed)

if(troubleshoot == 1) Serial.print("Table row 1 \n\n");


}

//robot action table row 2 - robot right


else if((left_IR_sensor_value < 300)&&(center_IR_sensor_value > 300)&&
(right_IR_sensor_value < 300))
{
//wall detection LEDs
digitalWrite(wall_left, LOW); //turn LED off
digitalWrite(wall_center, HIGH); //turn LED on
digitalWrite(wall_right, LOW); //turn LED off
//motor control
analogWrite(l_motors_forward, 64); //0(off)-255(full speed)
analogWrite(l_motors_reverse, 0); //0(off)-255(full speed)
analogWrite(r_motors_forward, 0); //0(off)-255(full speed)
analogWrite(r_motors_reverse, 64); //0(off)-255(full speed)

if(troubleshoot == 1) Serial.print("Table row 2 \n\n");


}

//robot action table row 3 - robot left


else if((left_IR_sensor_value < 300)&&(center_IR_sensor_value > 300)&&
(right_IR_sensor_value > 300))
538 12. SYSTEM-LEVEL DESIGN
{
//wall detection LEDs
digitalWrite(wall_left, LOW); //turn LED off
digitalWrite(wall_center, HIGH); //turn LED on
digitalWrite(wall_right, HIGH); //turn LED on
//motor control
analogWrite(l_motors_forward, 0); //0(off)-255(full speed)
analogWrite(l_motors_reverse, 64); //0(off)-255(full speed)
analogWrite(r_motors_forward, 64); //0(off)-255(full speed)
analogWrite(r_motors_reverse, 0); //0(off)-255(full speed)

if(troubleshoot == 1) Serial.print("Table row 3 \n\n");

//robot action table row 4 - robot forward


else if((left_IR_sensor_value > 300)&&(center_IR_sensor_value < 300)&&
(right_IR_sensor_value < 300))
{
//wall detection LEDs
digitalWrite(wall_left, HIGH); //turn LED on
digitalWrite(wall_center, LOW); //turn LED off
digitalWrite(wall_right, LOW); //turn LED off
//motor control
analogWrite(l_motors_forward, 64); //0(off)-255(full speed)
analogWrite(l_motors_reverse, 0); //0(off)-255(full speed)
analogWrite(r_motors_forward, 64); //0(off)-255(full speed)
analogWrite(r_motors_reverse, 0); //0(off)-255(full speed)

if(troubleshoot == 1) Serial.print("Table row 4 \n\n");

//robot action table row 5 - robot forward


else if((left_IR_sensor_value > 300)&&(center_IR_sensor_value < 300)&&
(right_IR_sensor_value > 300))
{
//wall detection LEDs
digitalWrite(wall_left, HIGH); //turn LED on
12.6. MOUNTAIN MAZE NAVIGATING ROBOT 539
digitalWrite(wall_center, LOW); //turn LED off
digitalWrite(wall_right, HIGH); //turn LED on
//motor control
analogWrite(l_motors_forward, 64); //0(off)-255(full speed)
analogWrite(l_motors_reverse, 0); //0(off)-255(full speed)
analogWrite(r_motors_forward, 64); //0(off)-255(full speed)
analogWrite(r_motors_reverse, 0); //0(off)-255(full speed)

if(troubleshoot == 1) Serial.print("Table row 5 \n\n");

//robot action table row 6 - robot right


else if((left_IR_sensor_value > 300)&&(center_IR_sensor_value > 300)&&
(right_IR_sensor_value < 300))
{
//wall detection LEDs
digitalWrite(wall_left, HIGH); //turn LED on
digitalWrite(wall_center, HIGH); //turn LED on
digitalWrite(wall_right, LOW); //turn LED off
//motor control
analogWrite(l_motors_forward, 64); //0(off)-255(full speed)
analogWrite(l_motors_reverse, 0); //0(off)-255(full speed)
analogWrite(r_motors_forward, 0); //0(off)-255(full speed)
analogWrite(r_motors_reverse, 64); //0(off)-255(full speed)

if(troubleshoot == 1) Serial.print("Table row 6 \n\n");


}

//robot action table row 7 - robot reverse


else if((left_IR_sensor_value > 300)&&(center_IR_sensor_value > 300)&&
(right_IR_sensor_value > 300))
{
//wall detection LEDs
digitalWrite(wall_left, HIGH); //turn LED on
digitalWrite(wall_center, HIGH); //turn LED on
digitalWrite(wall_right, HIGH); //turn LED on
//motor control
analogWrite(l_motors_forward, 64); //0(off)-255(full speed)
540 12. SYSTEM-LEVEL DESIGN
analogWrite(l_motors_reverse, 0); //0(off)-255(full speed)
analogWrite(r_motors_forward, 0); //0(off)-255(full speed)
analogWrite(r_motors_reverse, 64); //0(off)-255(full speed)

if(troubleshoot == 1) Serial.print("Table row 7 \n\n");

}
}

//***********************************************************************

12.6.7 MOUNTAIN MAZE


The mountain maze was constructed from plywood, chicken wire, expandable foam, plaster
cloth, and Bondo. A rough sketch of the desired maze path was first constructed. Care was
taken to insure the pass was wide enough to accommodate the robot. The maze platform was
constructed from 3/8-in plywood on 2-by-4-in framing material. Maze walls were also con-
structed from the plywood and supported with steel L brackets.
With the basic structure complete, the maze walls were covered with chicken wire. The
chicken wire was secured to the plywood with staples. The chicken wire was then covered with
plaster cloth (Creative Mark Artist Products #15006). To provide additional stability, expand-
able foam was sprayed under the chicken wire (Guardian Energy Technologies, Inc. Foam It
Green 12). The mountain scene was then covered with a layer of Bondo for additional structural
stability. Bondo is a two-part putty that hardens into a strong resin. Mountain pass construction
steps are illustrated in Figure 12.21. The robot is shown in the maze in Figure 12.22

12.6.8 PROJECT EXTENSIONS


• Modify the 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.
• Develop a function for reversing the robot.
• Equip the motor with another IR sensor that looks down toward the maze floor 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 the maze by
moving slowly back and forth for 3 s and flashing a large LED.
• The current design is a two-wheel, front-wheel drive system. Modify the design for a two-
wheel, rear-wheel drive system.
• The current design is a two-wheel, front-wheel drive system. Modify the design for a 4WD
system.
12.6. MOUNTAIN MAZE NAVIGATING ROBOT 541

Figure 12.21: Mountain maze.


542 12. SYSTEM-LEVEL DESIGN

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.

Barrett, S. F. and Pack, D. J. Microcontrollers Fundamentals for Engineers and Sci-


entists, Morgan & Claypool Publishers, 2006. www.morganclaypool.com DOI:
10.2200/s00025ed1v01y200605dcs001. 491

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

Seaperch. www.seaperch.com 502

Texas Instruments MSP430FR2433 Mixed-Signal Microcontroller, (SLASE59D), Texas Instru-


ments, Revised 2018.

Texas Instruments MSP430FR4xx and MSP430FR2xx Family User’s Guide, (SLAU445G), Texas
Instruments, 2016.

Texas Instruments MSP430FR58xx, MSP430FR59xx, and MSP430FR6xx Family,


(SLAU367O), Texas Instruments, 2017.

Texas Instruments MSP430FR599x, MSP430FR596x Mixed-Signal Microcontrollers,


(SLASE54C), Texas Instruments, Revised 2018.
544 12. SYSTEM-LEVEL DESIGN
12.9 CHAPTER EXERCISES
1. What is an embedded system?

2. What aspects must be considered in the design of an embedded system?

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?

6. Discuss the top-down design, bottom-up implementation concept.

7. Describe the value of accurate documentation.

8. What is required to fully document an embedded systems design?

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

absolute addressing mode, 121 Boone, Gary, 3


AC device control, 199 bottom-up approach, 491
AC interfacing, 199 branch instructions, 117
ADC, 8
ADC conversion, 357 C bit, 97
ADC programming, 373 Code Composer Studio, 12
ADC, SA converter, 377 code re-use, 493
ADC, SAR converter, 366 comments, 56
ADC12_B, 376 COMP E, 387
ADC12_B programming, 383 comparator, 387
addressing modes, 119 counting events, 306
AES accelerator, 11 CRC check, 84
AES256 Accelerator Module, 474 CRC checksum, 464
ALU, 3 CRC generator, 10
analog sensor, 155 CRC polynomial, 464
annunciator, 198 CRC32 module, 465
arithmetic instructions, 114 current sink, 142
arithmetic operations, 66 current source, 140
ASCII, 398
assembly process, 109 DAC converter, 364
assembly vs. C, 125 data integrity, 464
data test instructions, 117
background research, 488 data transfer instructions, 111
Bardeen, Brattain, and Schockley, 2 DC fan, 199
bare metal, 60 DC motor, 176
battery operation, 249 decoder, 208
Baud rate, 398 design, 490
bilge pump, 199 design process, 488
binary number system, 259 DF robot, 528
bit instructions, 115 digital sensor, 153
bit twiddling, 70 Direct Memory Access (DMA), 11, 264
550 INDEX
directives, 101 function prototypes, 58
DMA addressing modes, 269 functions, 57
DMA controller, 266
General Interrupt Enable (GIE) bit, 97
DMA register set, 271
general purpose registers, 95
DMA transfer modes, 270
Grove starter kit, 205, 226
documentation, 493
gyroscope, 159
dot matrix display, 172
duty cycle, 283 H-bridge, 181
hardware multiplier, 8
Educational Booster Pack MkII, 203, 226 Harvard architecture, 260
EEPROM, 4 HC CMOS, 142
elapsed time, 304
electrical specifications, 140 I2 C module, 441
electromagnetic interference (EMI), 462 I/O port, 8, 59
electrostatic discharge (ESD), 462 ideal op amp, 164
Embedded Emulator Module (EEM), 84 immediate addressing mode, 121
embedded system, 488 include files, 57
EMI noise suppression, 462 indexed addressing mode, 119
indirect autoincrement addressing mode, 121
EMI reduction strategies, 462
indirect register addressing mode, 121
encoding, 362
inertial measurement unit, 159
Energia, 12, 22
inertial measurement unit (IMU), 159
Energia Development Environment, 22
input capture, 305, 312
enhanced Universal Serial Communication
input devices, 145
Interface (eUSCI), 9, 395
Instruction Set Architecture (ISA), 110
ENIAC, 2
integrated circuit, 2
eUSCI A module, 9
interrupt handler, 63
eUSCI B module, 9
interrupt priority, 344
eUSCI_A module, 395
interrupt processing, 337
eUSCI_B module, 395 interrupt service routine (ISR), 336, 344
interrupt system, 336
fireworks, 219
interrupt theory, 335
flow control instructions, 117
interrupt vectors, 263
free running counter, 308
interrupts, 336
frequency, 282
interval timer, 290
frequency measurement, 306
IR sensor, 157
full duplex, 398
IR sensors, 40
function body, 59
IrDA protocol, 9, 396
function call, 58
function call instructions, 118 joystick, 155, 506, 511
INDEX 551
keypad, 147 noise, 462
Kilby, Jack, 2 non-maskable interrupts, 337
non-volatile memory, 261
label field, 100 NRZ format, 398
laser light show, 178 Nyquist rate, 359
LCD, serial, 175
LED biasing, 168 octal buffer, 206
LED cube, 205, 208 op amp, 164
LED cube, construction, 208 op code, 119
light emitting diode (LED), 168 operating modes, 98
linear feedback shift register (LFSR), 465 operating parameters, 139
liquid crystal display (LCD), 172 operational amplifier, 164
logic instructions, 115 operators, 66
logical operations, 68 optical isolation, 197
loop, 71 orthogonal instruction set, 123
loop(), 23 output compare, 307, 317
low power modes, 98 output device, 165
low-power modes, 8 output timer, 303
overflow, 95
main program, 65
maskable interrupts, 337 parity, 398
Mauchly and Eckert, 2 period, 282
MAX3232, 398 photodiode, 162
maze, 40 pointers, 265
memory address bus, 256 Power Management Module (PMM), 10
memory concepts, 256 PowerSwitch Tail II, 200
memory data bus, 258 pre-design, 490
memory map, 262 preliminary testing, 493
program constants, 63
microcontroller, 1, 3
program constructs, 70
Mini round robot, 40
program counter (PC), 95
mini round robot, 40
programming, 124
MMC/SD, 277
programming in C, 53
MMC/SD card, 261
programming module, 90
MOSFET, 180
project description, 488
motor operating parameters, 180
prototyping, 492
motor, vibrating, 199
pulse width modulation (PWM), 284
mountain maze, 528, 540
multiplication module (MPY32), 114 quantization, 359
N bit, 97 RAM, 4, 260
552 INDEX
real-time clock (RTC), 11, 295 solenoid, 185
register addressing mode, 119 sonalert, 198
resets, 333 speech chip, SP)-512, 406
resolution, 361 SPI, 411
Rijndael algorithm, 474 SPI features, 411
RISC architecture, 7 SPI hardware, 412
robot IR sensors, 40 SPI operation, 411
robot platform, 40 SPI registers, 414
robot steering, 40 SRAM memory, 10
robot, autonomous, 528 stack, 95
robot, submersible, 502 stack pointer (SP), 95
ROM, 4, 261 status bits, 97
rotate instructions, 113 status register R2, 95
ROV, 502 stepper motor, 176, 185
ROV buoyancy, 506 strip LED, 32
ROV control housing, 524 switch, 75
ROV structure, 504 switch debouncing, 147
RS-232, 398 switch interface, 145
RTC C, 297 switches, 145
symbolic addressing mode, 121
sampling, 358
SeaPerch, 502, 511 test plan, 493
SeaPerch control system, 511 time base, 302
SeaPerch ROV, 502 timer, 84
sensor, level, 159 timer applications, 305
sensor, ultrasonic, 159 timers, 307
sensors, 153 timing parameters, 282
serial communications, 395 TMS 1000, 3
serial peripheral interface, 411 top-down approach, 491
servo motor, 176 top-down design, bottom-up
servos, Futaba, 178 implementation, 491
setup(), 23 transducer interface, 162
shift instructions, 111 transistor, 2
signal conditioning, 162 tri-state LED indicator, 172
signal generation, 307
simplex communication, 397 UART, 399
sketch, 24 UART character format, 402
sketchbook, 23 UART features, 399
software programming, 100 UART interrupts, 403
INDEX 553
UART module, 400 variable size, 64
UART registers, 404 variables, 63
ultra-low power consumption, 8 volatile memory, 260
UML, 44, 491 von Neumann architecture, 260
UML activity diagram, 124, 491
Watchdog timer, 288
Unified Modeling Language (UML), 490
weather station, 494
UNIVAC I, 2 while, 72

vacuum tube, 2 Z bit, 97

You might also like