Ssqu 017
Ssqu 017
Ssqu 017
using TIVA
SSQU017
Contents
Foreword……………………………………………………………………………………………..………10
1 Embedded Systems and Features ............................................................................................ 12
1.1 Introduction.......................................................................................................................................... 13
1.1.1 Hardware Components of Embedded System ....................................................................... 13
1.1.2 Instruction Set Architecture..................................................................................................... 19
1.2 ARM Architecture ................................................................................................................................ 20
1.2.1 A Basic architecture of the ARM7core .................................................................................... 21
1.2.2 Registers ................................................................................................................................. 21
1.2.3 Current Program Status Register (CPSR) .............................................................................. 22
1.2.4 Operating States ..................................................................................................................... 23
1.2.5 Operating Modes .................................................................................................................... 23
1.2.6 Programming Model ............................................................................................................... 24
1.2.7 Interrupt and Exception Handling ........................................................................................... 25
1.2.8 ARM Instruction Set ................................................................................................................ 26
1.2.9 Migration to Cortex Series ...................................................................................................... 33
1.2.10 ARM architecture v7 profile: ................................................................................................... 34
1.2.11 ARMv7-M architecture: ........................................................................................................... 35
1.2.12 Operating States and Operating Modes: ................................................................................ 38
1.2.13 Programming Model: .............................................................................................................. 39
1.2.14 Instruction Set: Tables with all categories of instructions with descriptions. Load/Store
instructions with addressing modes. ............................................................................................ 41
1.2.15 CMSIS: ................................................................................................................................... 49
1.2.16 Introduction to TIVA Microcontrollers ..................................................................................... 49
1.3 Summary ............................................................................................................................................. 53
1.4 Review Questions ............................................................................................................................... 54
2 Microcontroller Fundamentals for Basic Programming ......................................................... 55
2.1 Introduction.......................................................................................................................................... 56
2.2 Programming in Embedded Systems.................................................................................................. 56
2.2.1 Data Types.............................................................................................................................. 57
2.2.2 Bit-wise Operations................................................................................................................. 58
2.3 Programming Tiva CSeries ................................................................................................................. 58
2.3.1 Development Tools ................................................................................................................. 58
2.3.2 Introduction to Code Composer Studio .................................................................................. 58
2.4 Peripheral and Memory Address......................................................................................................... 60
List of Figures
Fig 1.1. Basic block diagram of an embedded system ................................................................................ 14
Fig 1.2. Processing Unit and System Bus ................................................................................................... 15
Fig 1.3. (a) Harvard Architecture and (b) Von-Neumann Architecture ........................................................ 16
Fig 1.4: Interconnection of RAM with Microprocessor ................................................................................. 17
Fig 1.5. Interconnection of external devices with Microprocessor ............................................................... 18
Fig 1.6. Stepper motor control embedded system ....................................................................................... 19
Fig 1.7. ARM 7 Architecture [an excerpt from Google image] ..................................................................... 20
Fig 1.8. User mode register set.................................................................................................................... 22
Fig 1.9. A generic CPSR Format ................................................................................................................. 22
Fig 1.11. Barrel Shifter with ALU.................................................................................................................. 28
Fig 1.12. Performance and capability graph of Classic ARM and Cortex embedded processors. .............. 33
Fig 1.13. Performance and capability graph of Classic ARM and Cortex application processors. ............. 34
Fig 1.14. Cortex M4 core architecture ......................................................................................................... 36
Fig 1.15. Operating States of ARM Core ..................................................................................................... 38
Fig 1.16. Operating Modes of ARM Core .................................................................................................... 39
Fig 1.17. Programming model...................................................................................................................... 40
Fig 1.18 xPSR diagram ................................................................................................................................ 41
Fig 1.22. IEEE 754 single precision format .................................................................................................. 47
Fig 1.20. TIVA TM4C123GH6PM Microcontroller block diagram. ............................................................... 50
Fig 1.21 TIVA TM4C129CNCZAD Microcontroller block diagram ............................................................... 51
Fig 2.1 Fire Alarm......................................................................................................................................... 56
Fig 2.2: Flowchart to glow onboard LED ...................................................................................................... 63
Fig 2.3 Memory Map File ............................................................................................................................. 64
Fig 2.4 Memory Configuration for the output file.......................................................................................... 64
Fig 2.5 Switches and RGB schematic connection to GPIO pins ................................................................. 68
Fig 2.6 Flowchart for line follower robot ....................................................................................................... 69
Fig 2.7 Operation of Watchdog Timer .......................................................................................................... 72
Fig 2.8 Flowchart for servicing timer interrupts ............................................................................................ 77
Fig 2.9 Debug Window ................................................................................................................................. 78
Fig 2.10 Power vs Flexibility ........................................................................................................................ 78
Fig 2.11 Block diagram of Hibernation module ............................................................................................ 79
Fig 3.1. Automatic Washing Machine .......................................................................................................... 86
Fig 3.2. GPTM block diagram ...................................................................................................................... 88
Fig 3.3. Real Time Clock with external power source.................................................................................. 91
Fig 3.4. Frequency Based Measurement System........................................................................................ 92
Fig 3.5. (a) Period based input Read with free running counter .................................................................. 93
Fig 3.5. (b) Period based input Read with counter that increments only while gate input is HIGH (Gate
connected to Period Based Input) .................................................................................................. 93
Fig 3.6. Block Diagram of working of an ADC ............................................................................................. 94
Fig 3.7. Implementation of two ADC blocks ................................................................................................. 94
Fig 3.8 ADC Module Block Diagram ............................................................................................................ 95
Fig 3.9 Structure of Comparator Unit ........................................................................................................... 98
Fig 3.10. Analog comparator module block diagram ................................................................................... 99
Fig 3.11. Analog Interfacing Network......................................................................................................... 100
Fig 3.12. The Analog-Digital-Analog signal path with real time processing .............................................. 101
Fig 3.13. The DMA controller Architecture ................................................................................................. 103
Fig 3.14. PWM Module Block Diagram ...................................................................................................... 105
Fig 3.15. PWM Generator Block Diagram ................................................................................................. 106
Figure 3.16 (a). PWM Count-Down Mode ................................................................................................. 107
Figure 3.16 (b) PWM Count- Up/Down Mode............................................................................................ 107
Fig 3.17. QEI Input Signal Logic ................................................................................................................ 109
Fig 3.18. QEI Block Diagram ..................................................................................................................... 110
Fig 3.19. Schematic for motor control using TIVA ..................................................................................... 112
Fig 3.20. Flowchart for DC motor control using PWM ............................................................................... 113
Fig 4.1. Weather monitoring using sensor hub balloon ............................................................................. 117
Fig 4.2. Frame for ASCII „A‟ (01000001) ................................................................................................... 119
Fig 4.3. MAX 232 and microcontroller connection ..................................................................................... 120
Fig 4.4. DB-9 Connector ............................................................................................................................ 120
Fig 4.5. Different encoding schemes for serial communication ................................................................. 121
Fig 4.6. Simplified block diagram of UART ................................................................................................ 123
Fig 4.7. Baud rate registers........................................................................................................................ 123
Fig 4.8. UART Control (UARTCTL) register .............................................................................................. 125
Fig 4.9. UART Line Control (UARTLCTH) register .................................................................................... 125
Fig 4.10. UART Date Register (UARTDR) ................................................................................................. 126
Fig 4.11. UART Date Register (UARTDDR) .............................................................................................. 127
Fig 4.12. I2C Bus ........................................................................................................................................ 131
Fig 4.13. I2C START and STOP bits ......................................................................................................... 132
Fig 4.14. I2C Frame Format ....................................................................................................................... 132
Fig 4.15. I2C combined address and data ................................................................................................ 133
Fig 4.16. I2C Networking using Tiva microcontroller .................................................................................. 134
Fig 4.17. RunMode Clock Gating Control Register.................................................................................... 134
Fig 4.18. I2C Master Time Period Register ............................................................................................... 135
Fig 4.20. I2C Master Slave Address Register ............................................................................................ 137
Fig 4.20. I2C Master Data Register ........................................................................................................... 137
Fig 4.22. I2C Master Control/Status Register ............................................................................................ 137
Fig 4.23. Data transmission using (a) Master Single Transmit, (b) Single Master receive........................ 139
Fig 4.24. DS1307 Interfacing with TIVA ..................................................................................................... 140
Fig 4.25. RTC Control Register.................................................................................................................. 140
Fig 4.26. Serial Peripheral Interface .......................................................................................................... 143
Fig 4.27. SPI Timing Diagram .................................................................................................................... 144
Fig 4.28. Synchronous Serial Interface Run Mode Clock Gating Control CRCG (SSI) Register .............. 146
Fig 4.29. SSI Control O Register ............................................................................................................... 146
Fig 4.30. SSI Clock Prescaler Register ..................................................................................................... 147
Fig 4.31. SSI Control 1 Register ................................................................................................................ 148
Fig 4.32. SSI Data Register ....................................................................................................................... 148
Fig 4.33. SSI Status Register..................................................................................................................... 148
Fig 4.35 Booster Pack Pinout Standard ..................................................................................................... 151
Fig 4.36. Flowchart: Interfacing TIVA with Sensor Hub Booster Pack ...................................................... 152
Fig 5.1. Embedded Network ...................................................................................................................... 156
List of tables
Table 1.1. ARM Architecture Features and Benefits ................................................................................... 20
Table 1.2. Processor mode with binary Pattern mode Control bits [4:0] ..................................................... 24
Table 1.3. Exceptions and attributes ........................................................................................................... 26
Table 1.5. Barrel shift operation syntax for data processing instructions. ................................................... 28
Table 1.6. Instruction set table ..................................................................................................................... 29
Table 2.1: Data types (ISO C90) ................................................................................................................. 57
Table 2.2: Data types (ISO C99) ................................................................................................................. 57
Table 2.3: General Bit wise operations ........................................................................................................ 58
Table 2.4: Development Tools for Tiva C Series ......................................................................................... 59
Table 2.5: Memory Mapping in TM4C123GH6PM Chip .............................................................................. 61
Table 2.7 Switches: RGB and GPIO pin connection to the microcontroller................................................. 69
Table 2.8: Clock setup for TM4C123GH6PM ............................................................................................. 70
Table 2.9 Interrupt Vector Table for ARM Cortex M4 .................................................................................. 74
Table 2.10: Power Modes of Tiva ................................................................................................................ 80
Table 3.1: General purpose Timer signals ................................................................................................... 88
Table 3.2 ADC signals with GPIO pins ........................................................................................................ 95
Table 3.3: Samples and FIFO Depth of Sequencers ................................................................................... 96
Table 4.1: RCG12C Register Description .................................................................................................. 135
Table 4.2. TPR Values for I2C modes ........................................................................................................ 136
Table 4.3: TPR Values for High-Speed Mode ........................................................................................... 136
Table 4.4: I2CMCR Register Description ................................................................................................... 136
Table 4.6: RTC Control Register Description ............................................................................................ 141
Table 4.7. SPI Modes ................................................................................................................................ 144
Table 4.8: SPI. Pins Mux Utility.................................................................................................................. 145
Table 4.9: SPI Modules base address ....................................................................................................... 146
Table 4.9. SSICRO Register Description ................................................................................................... 147
Table 4.10: SSI Status Register Description ............................................................................................. 148
Table 4.11. SSI Interrupt Mask Register .................................................................................................... 149
Table 5.1: Wi-Fi features............................................................................................................................ 174
In the present world, we are getting tech friendly. It has been observed that in our day to day life, we
interact with several systems which makes our life simpler and easier. From mobile phones, washing
machines, wrist watches to space craft‟s, submarines space rovers, automotive etc., everything relies
on design and development of such intelligent systems. These systems are smart enough to interact
with physical environment by themselves and act according to the conditions or information feed on
them.
Although, the embedded systems is not standalone technology, but the combination of various
technologies wisely implemented all together to develop an electronic product which could be user
friendly and could be adopted by the specific community depends on their needs. The functioning of
such gadgets and systems depends several aspects like the central processing unit capacity, inbuilt
memory and the input output devices connected to it. The devices connected are basically sensors
and actuators which could be analog or digital in nature. To make then compatible and synchronized
the developer need to choose the interfacing accordingly.
As it is clear now that, do develop such systems there is a need to understand the processing
elements and the way to address the desired function. The current adaptation of ARM architectures in
the modern controllers and processor is growing rapidly. The good reason behind that is scalability,
compatibility, energy efficiency and user friendliness offered by them. This book focus on ARM Cortex
–M family which is widely accepted by majority of manufactures and OEM‟s (Original Equipment
Manufacturers).
The Texas Instruments TIVA board or widely known as TIVA C series, is a high performance, cost
efficient device, having an ARM Cortex-M4 architecture. The board is used for code testing and
optimization. All the codes mentioned in this book can be executed on it.
In the current demanding environment, it is expected to get the hand on experience as soon as
possible, but it is hard to find a single source of information which can serve the purpose. The intention
to design this book is to help the researchers, students and embedded systems enthusiast, to
understand the basic principle of micro controllers, peripherals, embedded programing and interfacing
techniques with the help of practical application, which not only helps to develop the basic theoretic
concepts but also to observe how the processing unit handles the operation internally.
Considering current scenario, Embedded Systems curriculum requires an application and System
Design approaches balancing the performance, connectivity requirements and system cost with an eye
on power. This book is designed to inculcate this perspective in students using Cortex-M4 based TIVA,
an industrial standard hardware platform. This book helps in understanding 32-bit architecture and its
programming consideration using C language. The later part is focused on programming various inbuilt
features of the platform with a more focused approach on analog and digital interfacing concepts and
related protocols. Embedded systems, whether they are standalone or networked, needs various
communication interfaces and standards so that they communicate and process data from the external
world. This book covers topics on how to connect the device to external peripherals including those
need interconnectivity. Unit 5 of the book focuses on key wireless technologies that are the backbone
of Internet of Things. Implementing Wi-Fi capability in microcontroller is necessary to develop Internet
enabled products and IoT applications.
The under graduate curriculum implemented in most of the Universities related to Embedded Systems
Design, are not adequate to develop the necessary design skill needed at present. There is a wide gap
between the industry requirements and the design skill of students coming out from the university. The
purpose of developing new curriculum for the above-mentioned subject is to reduce the gap between
the requirements of the industry and the design skill of graduates coming out of the University.
Expected Outcomes:
It will help the teachers to teach the subject easily and make the students to learn the
subject in the class itself.
A systematic exposure of the subject will motivate the students to develop expertise in the
system design. Students will gain confidence in system design.
The gap between the design skill earned by the students and the Industry requirements will
get reduced.
The purpose of this book is to help beginners understand key concepts related to embedded system design
based on TIVA boards from Texas Instruments.
At the end of chapter 1, students should be able to recognize an embedded system and distinguish its
features from a general purpose computing system. This chapter covers basic hardware components
required to design an embedded system.
Readers will be able to acquire strong fundamental knowledge and develop skills for applications of core
knowledge on embedded system design. They will also acquire thorough knowledge on a mainstream
computing unit i.e. ARM processor with its basic architecture, programming considerations and different
architecture versions.
This chapter will guide readers on the parameters to select an appropriate ARM processor for specific
applications; enhanced features of ARM Cortex M4 core and how it differs from the basic ARM core. The
chapter also covers industry standard TIVA TM4C123X and TM4C129X, ARM Cortex M4 based platforms
and various applications that can be developed using these boards.
Topic Page
1.1 Introduction.......................................................................................................................................... 13
1.2 ARM Architecture ................................................................................................................................ 20
1.3 Summary ............................................................................................................................................. 53
1.4 Review Questions ............................................................................................................................... 54
1.1 Introduction
We live in an era where pervasive computing exists everywhere, right from a small handheld device
such as a mobile phone to the electronic control units within automobiles or avionics. Today, large
volumes of information is getting processed and communicated over the Internet every microsecond.
Buzz words such as Cloud Computing, Big Data Mining and Internet of Things are everywhere.
There are two broad classifications of computing systems - general purpose computing system and
embedded computing systems. If we define these in simple words, general purpose computing
systems are those used in desktop or laptop computers, which can process several different
applications. An embedded system refers to any device that has some computational intelligence in it.
It is generally used as a standalone system that repeatedly performs a specific task or as part of a
large system to perform multiple tasks with the requisite hardware and software embedded within.
Systems used in printers, washing machines, mp3 players, CT scan machines etc. are great examples
of embedded systems.
An embedded system is a constrained system and its design goals vary from a general purpose
system. The constraints are: high performance, low power consumption, small size and low cost of the
system.
The basic components of an embedded system include hardware, software and some mechanical
parts. Embedded hardware includes a processing unit, block of memory and I/O sub-unit which are
called as the system resources. The embedded software can be thought of as the application software
in a small computing system or both the system and the application software in case of a large
complex system. The system software mentioned here is the real time operating system (RTOS) used
to manage the usage of system resources by application software.
Embedded systems are used in every walk of life. Some of its application domains are: avionics,
automotives, industrial control, medical instrumentation, communication, networking, consumer
products, handheld electronic gadgets, surveillance, robotics system etc.
This chapter covers introduction of embedded systems with the basic functional blocks. It provides an
overview of the ARM processor core as a main computing element. The programmer‟s model of ARM7
processor is presented along with various operating modes of ARM core. The interrupt and exception
handling capabilities of ARM are also explained. The basic instruction set architecture is presented
with all its features. The next section introduces migration to ARM Cortex series of processors. In this
text book, Texas instruments TIVA development board is introduced with TIVATMTM4C123X and
TIVATMTM4c129X microcontrollers. These TI platforms are on Cortex-M4 core. So Cortex-M4
architecture with its programming model, operating modes and instruction set are introduced in the
subsequent sections.
the computational capability of the existing system or to make a system reprogrammable and
reconfigurable when the need arises.
Memory Block
The memory block consists of program and data memory. ROM is used as the program memory and
RAM is used as the data memory. There are two memory architectures: Harvard and Von-Neumann.
In Harvard architecture, the program and data memories are segregated with separate address and
data bus drawn to each. So there can be parallel access to both and performance of the system can
be improved at the cost of hardware complexity. On the other-hand, the Von-Neumann architecture
has one unified memory used for both program and data. The system is comparatively slower, but the
design implementation is simple and cost effective for an embedded system. Various ROM and RAM
devices are used in embedded systems based on the applications.
(a) (b)
static RAM (SRAM), dynamic RAM (DRAM), pseudo static RAM (PSRAM), non-volatile RAM
(NVRAM), synchronous DRAM, (SDRAM) etc.
Module 2 for the stepper motors 2 & 3 to make the motor 2 to rotate in counter clockwise and
motor 3 to rotate in clockwise both simultaneously so that the robot arm can pick and make a grip
on the component.
1.2.2 Registers
Registers are for temporary data storage within processor architecture. As shown in Fig.1.8, ARM
processor has sixteen numbers of general purpose registers, R0-R15 and a current program status
register (CPSR) defined for user mode of operation. Each of these registers is of 32-bits. Out of these
registers, R13, R14 and R15 have special purposes.
R13: Used as the stack pointer that holds the address of the top of the stack in the current processor
mode.
R14: Used as the link register that saves the content of program counter on control transfer due to the
occurrence of exceptions or using the branch instructions in the program.
R15: Used as the program counter that points to the next instruction to be executed. In ARM state, all
instructions are of 32-bits (four bytes) for which, PC is always aligned to a word boundary. This means
that the least significant two bits of the PC are always zero. The PC can also be halfword (16-bit)
aligned for Thumb state (16 bit instructions) or byte aligned for Jazelle state (8-bit instructions)
supported by different versions of ARM architecture.
These are processor specific features and are explained in detail in section 1.4.
by modifying the control bits of CPSR by writing its binary pattern as shown in table 1.1, being in a
privileged mode.
Table 1.2. Processor mode with binary Pattern mode Control bits [4:0]
request (IRQ). As more than one interrupt may occur simultaneously, exceptions are prioritized. In the
priorities list given in the table.2, the SWI and undefined exceptions have same priority as they are
mutually exclusive because both are caused by an instruction entering the execution stage. When any
exception occurs, the control transfers to the corresponding vector address. In the vector address,
certain branch instruction would be written to access the actual interrupt handler or ISR saved at a
different location. It is required as the vector addresses are sequentially separated by four bytes, only
one 32-bit ARM instruction can be written at each of it. The I and F bits in the control field of CPSR
register are disabled in combination while handling the exceptions. All the ARM exceptions are
executed in ARM state of the core. If the control is there in Thumb state it has to switch back to ARM
state to handle the exception. Table 1.2 gives information about all the attributes discussed here.
Table 1.3. Exceptions and attributes
Vector Address
Exceptions Operation Modes Priority I-bit in CPSR F-bit in CPSR
Low/High
Reset Supervisor 1 1 1 0x00000000/0xffff0000
Undefined Undefined 6 1 0 0x00000004/0xffff0004
SWI Supervisor 6 1 0 0x00000008/0xffff0008
Prefetch Abort Abort 5 1 0 0x0000000C/0xffff000C
Data Abort Abort 2 1 0 0x00000010/0xffff0010
IRQ IRQ 4 1 0 0x00000018/0xffff0018
FIQ FIQ 3 1 1 0x0000001C/0xffff001C
Exception Entry
When an exception occurs, ARM core goes through the following sequence of operations.
It changes to the operating mode corresponding to the particular exception.
It saves the return address, the content of PC (r15) in lr( r14) of the new mode.
It saves the previous state of the core, the content of the CPSR in the SPSR of the new mode.
It disables IRQs by setting bit 7 of the CPSR and, if the exception is a reset or fast interrupt,
disables further fast interrupts by setting bit 6 of the CPSR.
PC is loaded with the vector address to begin executing the relevant exception handler.
Exception Exit
The user program is resumed once the interrupt handler execution is completed. The following steps
are followed in doing so.
The saved context must be restored back from the handler's stack.
The CPSR must be restored from the appropriate SPSR.
The PC must be restored back from the link register of exception mode.
ARM architecture has two instruction sets. The ARM instruction set and Thumb instruction set. In ARM
instruction set, all instructions are 32 bits wide and are aligned at 4-bytes boundaries in memory. On
the other hand, in thumb instruction set, all instructions are of 16 bits wide and are aligned at even or
two bytes boundaries in memory.
The important features of the ARM and Thumb instruction set are:
Most of the instructions are executed in one cycle.
Load/Store architecture for accessing data from external memory with powerful auto-indexing
addressing modes.
Inclusion of load and store multiple register instructions.
3-address instructions: two source operand registers and the result register are all distinctly
specified.
Data processing instructions act only on registers.
Every instruction can be conditionally executed which improves the performance and code
density by reducing the number of branch instructions.
The ability to execute a barrel shift operation and an ALU operation of a single complex
instruction in a single clock cycle.
Inclusion of advanced DSP instructions in the ARM instruction set for the multiply and
accumulate (MAC) unit replaces the need of separate digital signal processor.
Implementation of coprocessor instruction set with extension of the programming model.
The Thumb instruction set is 16-bit compressed representation of the ARM instructions that
provides high code density.
ARM Instructions can be categorized into following broad classes:
Data movement instructions
Data Processing Instructions
o Arithmetic/logic Instructions
o Barrel shifting instructions
o Comparison Instructions
o Multiply Instructions
Branch Instructions
Load and store Instructions
o Load and Store register instruction
o Load and Store multiple register instructions
o Stack instructions
o Swap register and memory content
Program Status register Instructions
o Set the values of the conditional code flag
o Set the values of the interrupt enable bit
o Set the processor mode
Exception generating Instructions
o Software Interrupt Instruction
o Software Break Point instruction
or logic operation on these operands and the result is written back into the register bank through the
ALU bus. Both the barrel shifting and ALU operations happen in the same instruction cycle.
The data processing instructions that do not use the barrel shift are: the MUL (multiply), CLZ (count
leading zeros), and QADD (signed saturated 32-bit add) instructions.
Logical shift right „Rm‟ by shift_ immediate value Rm, LSR #shift_imm
Logical shift right „Rm‟ by the amount in register „Rs‟ Rm, LSR Rs
Arithmetic shift right „Rm‟ by shift immediate value Rm, ASR #shift_imm
Arithmetic shift right „Rm‟ by register „Rs‟ Rm, ASR Rs
Rotate right „Rm‟ by shift immediate value Rm, ROR #shift_imm
Rotate right „Rm‟ by the amount in register „Rs‟ Rm, ROR Rs
Rotate right „Rm‟ with extend Rm, RRX
Move this value to register R3. So R3=0X00000008 now. But data in R1 and R2 remain
unchanged.
Table 1.6. Instruction set table
3. Branch instructions
r1= [Sp+4]
r2= [Sp+8]
Load multiple registers from stack LDMED
LDM r3= [Sp+12] and Sp
memory Sp!, {r1, r3}
is updated by
[Sp+12]
[Sp-4]= r6
[Sp-8]= r5
STMFD
STM Store multiple registers to stack memory [Sp-12]=r4 and
Sp!, {r4,r6}
Sp is updated by
[Sp-12]
IV. Swap instruction ; Syntax: SWP{B}{<cond>} Rd,Rm,[Rn]
SWP swap a word between memory and a SWP/SWPB Load a 32 bit word
SUB R0, R1, R2 //subtract content of R2 from R1 and move the result to R0 //
BEQ LOOP // branch to LOOP if previous instruction sets the zero flag i.e, Z=1 //
ADD R0, R1, [R2]//add R1 with the data pointed by R2 and put the result into R0//
AND R0, R1, R2, LSR R3// (R2 >> R3), logically AND with R1 and move result to R0 //
Register based with Offset Addressing: Effective memory address has to be calculated
from a base address and an offset. Offset can be an immediate offset, register offset or scaled
register offset.
Pre-Indexed Addressing
LDR R2, [R3, #0x0F] // Immediate offset.
// Take value in R3, add to 0x0F, use it as address and load data from that address to
R2 //
Pre-Indexed with write back also called auto-indexing with pre-indexed addressing.
symbol indicates that the instruction saves the calculated address in the base address
register.
LDR R0, [R1, #4]! // Immediate offset //
// Use (R1+4) as address and load the data from that address to R0 and update R1 by
(R1+4)//
Fig 1.12. Performance and capability graph of Classic ARM and Cortex embedded processors.
Fig 1.13. Performance and capability graph of Classic ARM and Cortex application processors.
ARM architecture has been improved a lot in the road map from classic ARM to ARM Cortex. Fig1.7
and fig187 depict the performance and capability comparison of classic ARM with embedded cortex
and application cortex series of processors. Even though ARM had earlier versions of products i.e. v1,
v2, v3 and v4, the classic group of ARM starts with v4T. The classic group is divided into four basic
families called ARM7, ARM9, ARM10 and ARM11.
ARM7 has three-stage (fetch, decode, execute) pipeline, Von-Numann architecture where
both address and data use the same bus. It executes v4T instruction set. T stands for Thumb.
ARM9 has five-stage (fetch, decode, execute, memory, write) pipeline with higher
performance, Harvard architecture with separate instruction and data bus. ARM9 executes
v4T and v5TE instruction sets. E stands for enhanced instructions.
ARM10 has six-stage (fetch, issue, decode, execute, memory, write) pipeline with optional
vector floating point unit and delivers high floating point performance. ARM10 executes v5TE
instruction sets.
ARM11 has eight-stage pipeline, high performance and power efficiency and it executes v6
instructions set. With the addition of vector floating point unit, it performs fast floating point operations
1.2.9.2 Nomenclature
ARM processor implementation is described by the product nomenclature as given below
ARM [x][y][z][T][D][M][I][E][J][F][-S]
x - Family
y - Memory management/memory protection unit.
z - Ache size
T- Thumb state
D - JTAG debug option
M - Fast multiplier
I - Embedded ICE macrocell
E - Enhanced instructions
J - Jazzel state
F - Vector floating point unit
S - Synthesizable version
Referring to the nomenclature, ARM7TDMI can be understood as an ARM7 processor with thumb
implementation, JTAG debug, multiplier and ICE macro cell. Similarly ARM926EJ-S is an ARM9
processor with MMU and cache implementation, enhanced instructions, Jazzel state and has a
synthesizable core.
are typically designed for high end real time safety critical applications like automotive powertrain
system. Some
Cortex- A application products are smart phones, tablets, televisions and even high end computing
servers.
end processors. Cortex M4 comes under the nomenclature of ARMv7E-M. It was developed
as a high performance digital signal controller with 72 DSP instructions implemented along
with Cortex M3 instruction set retained. Single cycle execution of multiply and accumulate
instructions provides 45% speed improvement compared to Cortex M3.
Maskable Interrupt (NMI) and can provide up to 256 interrupt priority levels for each of 240 interrupts it
supports. A higher priority interrupt can preempt the currently running ISR facilitating interrupt nesting.
Wake Up Interrupt Controller (WIC):
To optimize low-power designs, the NVIC integrates with an optional peripheral called Wake up
interrupt controller to implement sleep modes and an optional deep sleep function. When the WIC is
enabled, the power management unit powers down the processor and makes it enter deep sleep
mode. When the WIC receives an interrupt, it takes few clock cycles to wake-up the processor and
restore its state. So it adds to interrupt latency in deep sleep mode. WIC is not programmable and
operates completely with hardware signals.
Memory Protection Unit:
In embedded OS, MPU is used for safeguarding memory used for kernel functions from unauthorized
access by user program. In OS environment, when any untrusted user program tries to access
memory protected by MPU, the processor generates a memory manage fault causing a fault
exception. MPU divides the memory map into a number of regions defining memory attributes for
each. MPU separates and protects the code, data and stack for each task required for safety critical
embedded systems. MPU can be implemented to enforce privilege access rules and separate tasks. It
is an optional block in Cortex M4.
Bus Matrix:
The processor contains a bus matrix that arbitrates the processor core and optional Debug
Access Port (DAP) memory accesses to both the external memory system, the internal System Control
Spaces and to various debug components. It arbitrates requests from different bus masters in the
system. Bus matrix is connected to the code interface for accessing the code memory, SRAM and
peripheral interface for data memory and other peripherals and the optional MPU for managing
different memory regions.
Debug Access Port (DAP):
DAP, the implementation of ARM debug interface enables debug access to various master ports on
the ARM SoC. It provides system access for the debugger tool using AHB-AP, APB-AP and JTAG-AP
without halting the processor. Embedded Trace Macrocell (ETM) generates instruction trace.
Instrumentation Trace Macrocell (ITM) allows software-generated debug messages and also to
generate timestamp information. Data Watchpoint and Trace (DWT) unit can be used to generate data
trace, event trace, and profiling trace information. Flash patch and break point (FPB) implements
hardware breakpoints, patches code and data from Code space to System space. Serial wire viewer
(SWV) is one bit ETM port. SWV provides different types of information like program counter values,
data read and write cycles, peripheral values, event counters and exceptions.
Floating Point Unit (FPU):
Cortex M4 architecture suggests an optional FPU which is IEEE 754 single precision compliant. The
core instruction set supports various signal processing operations. It executes single instruction
multiple data (SIMD) instructions with 16 bit data types. Floating point core supports addition,
multiplication and hardware division. It has a 32X32 multiply and accumulate (MAC) unit that produces
64 bit results. Embedded signal processing applications that involve data compression, statistical
signal processing, measuring, filtering and compressing real world analog signals can use Cortex M4
with FPU.
Floating point unit supports:
Conversions between fixed point and floating point data formats and instructions with floating
point immediate data.
Saturation math.
Decouple 3-stage pipeline.
Three modes of operations: full compliance mode, flush-to-zero mode and default NaN mode.
To be disabled when it is not in use to conserve energy.
counter (PC), so that program control can resume the calling program. If a function needs to call
another function, it needs to save the value of LR in the stack before entering to the new function.
1.2.14 Instruction Set: Tables with all categories of instructions with descriptions.
Load/Store instructions with addressing modes.
Mnemonic Operands Brief description
ADC, ADCS {Rd,} Rn, Op2 Add with Carry
ADD, ADDS {Rd,} Rn, Op2 Add
ADD, ADDW {Rd,} Rn, #imm12 Add
ADR Rd, label Load PC-relative Address
AND, ANDS {Rd,} Rn, Op2 Logical AND
ASR, ASRS Rd, Rm, <Rs|#n> Arithmetic Shift Right
B label Branch
BFC Rd, #lsb, #width Bit Field Clear
BFI Rd, Rn, #lsb, #width Bit Field Insert
BIC, BICS {Rd,} Rn, Op2 Bit Clear
BKPT #imm Breakpoint
BL label - Branch with Link -
Exchange GE
USUB16 {Rd,} Rn, Rm Unsigned Subtract 16 GE
USUB8 {Rd,} Rn, Rm Unsigned Subtract 8 GE
UXTAB {Rd,} Rn, Rm,{,ROR #} Rotate, extend 8 bits to 32 and Add
precision
VMOV Dd[x], Rt Copy ARM core register to scalar
VMOV Rt, Dn[x] Copy scalar to ARM core register
Move FPSCR to ARM core register or
VMRS Rt, FPSCR
APSR
Move to FPSCR from ARM Core
VMSR FPSCR, Rt
register FPSCR
VMUL.F32 {Sd,} Sn, Sm Floating-point Multiply
VNEG.F32 Sd, Sm Floating-point Negate
VNMLA.F32 Sd, Sn, Sm Floating-point Multiply and Add
VNMLS.F32 Sd, Sn, Sm Floating-point Multiply and Subtract
VNMUL {Sd,} Sn, Sm Floating-point Multiply
VPOP list Pop extension registers
VPUSH list Push extension registers
VSQRT.F32 Sd, Sm Calculates floating-point Square Root
VSTM Rn{!}, list Floating-point register Store Multiple
VSTR.F<32|64> Sd, [Rn] Stores an extension register to memory
VSUB.F<32|64> {Sd,} Sn, Sm Floating-point Subtract
WFE - Wait For Event
WFI - Wait For Interrupt
= +1.100111101 X 210000101-01111111
In IEEE 754 standard 32 bit single precision format:
0 10000101 10011110100000000000000
Sign bit is 0 as the number is positive. The 8-bit exponent is 10000101 which is binary equivalent of
133. The fraction part of the binary number after normalized is 100111101. It is of 9-bits.So the 23-bit
fraction is 10011110100000000000000 (zero extended to the right). When any binary number is
normalized, it infers that the bit before the binary point is a „1‟. So there is no need to save this bit.
1.2.15 CMSIS:
The CortexTM microcontroller software interface standard (CMSIS) is a vendor-independent hardware
abstraction layer developed by ARM. The CMSIS has generic software libraries and simple software
interfaces to the processor and the peripherals. It also provides common APIs for various RTOSs.
CMSIS provides a compiler independent layer and can be compiled by all mainstream compilers
(ARMCC, IAR, GCC and TI‟s CCS). CMSIS DSP library for Cortex M4 has sixty functions written in „C‟
both in fixed point and floating point implementation to utilize the signal processing capabilities of FPU.
Separate functions are there for operating on 8-bit, 16-bit, 32-bit integers and 32-bit floating point
values. DSP library performs about two times faster on Cortex M4 in comparison to cortex M3 and ten
times faster with FPU hardware implemented.
twelve 32/64 bit capture compare PWM, battery backed hibernation module and RTC
hibernation module, 2 watchdog timers and 43 GPIOs.
Few Applications:
Building automation system
Lighting control system
Data acquisition system
Motion control
IoT and Sensor networks.
Memory protection unit provides a privileged mode for protected operating system functionality
and floating point unit supports IEEE 754 compliant single precision operations.
JTAG/SWD/ETM for serial wire debug and trace.
Nested vector interrupt controller (NVIC) reduces interrupt response latency and high
performance interrupt handling for time critical applications.
The microcontroller has a set of memory integrated in it: 1MB flash memory, 256 KB SRAM, 6 KB
EEPROM and ROM loaded with TIVAware, software library and bootloader.
Serial communications peripherals such as: 2 CAN controllers, full speed and high speed USB
controller, 8 UARTs, 10 I2C modules and 4 Synchronous serial interface modules.
On chip voltage regulator, three analog comparators and two 12 channel 12-bit analog to digital
converter with sample rate 2 million samples per second and temperature sensor are the analog
functions in built to the device.
One quadrature encoder and one PWM module with 8 PWM outputs are the advanced motion
control functions integrated into the device that facilitate wheel and motor controls.
Various system functions integrated into the device are: Micro Direct Memory Access controller,
clock and reset circuitry with 16 MHz precision oscillator, eight 32-bit timers, low power battery
backed hibernation module and RTC hibernation module, 2 watchdog timers and 140 GPIOs.
Cyclic Redundancy Check (CRC) computation module is used for message transfer and safety
system checks. CRC module can be used in combination with AES and DES modules.
Advanced Encryption Standard (AES) and Data Encryption Standard (DES) accelerator module
provides hardware accelerated data encryption and decryption functions.
Secure Hash Algorithm/ Message Digest Algorithm (SHA/MD5) provides hardware accelerated
hash functions for secured data applications.
1.3 Summary
At the end of this chapter, readers should be able to understand basic concepts of embedded system
with its basic building blocks. Since this textbook is focused on TIVA series microcontrollers with ARM
cortex M4 based cores, this chapter is focused on ARM explained as the main stream processing unit.
The article covers generic architecture, programming models, operating modes and basic mechanism
of handling exceptions of ARM7 core. The instruction set and addressing modes have been discussed
with examples of instructions.
With an understanding of concepts such as the evolution of ARM core with the road map of different
core versions; ARM cortex M4 architecture, its floating point operations and generic view of the
instruction set; TIVA TM4C123X and TM4C129X and their features the reader is well placed to
understand subsequent chapters on microcontrollers, timers, mixed signal processing etc.
The previous chapter provided a detailed introduction to 32-bit microcontroller architecture and instruction
sets. It also covered the industry standard ARM based System on Chip architecture and its applications; the
TIVA C series microcontroller that has a wide range of applications in the field of security systems, IoT
gateway solutions.
Since most microcontrollers need to be programmed using assembly or high-level languages like C, C++,
and embedded JAVA to give more intelligence to overall system, this chapter provides an understanding of
how various components/peripherals of the microcontroller can be configured.
By the end of this chapter, readers will be equipped to understand basic C language, supported libraries
relevant to TIVA Architecture; learn how to program TIVA C Series using CC, and know more about low
power modes of TIVA microcontroller and peripheral and memory addressing in TIVA.
This chapter will also cover steps for GPIO programming and the working of watchdog timers and interrupts.'
Topic Page
2.1 Introduction.......................................................................................................................................... 56
2.2 Programming in Embedded Systems.................................................................................................. 56
2.3 Programming Tiva CSeries ................................................................................................................. 58
2.4 Peripheral and Memory Address......................................................................................................... 60
2.5 Programming GPIO in TivaTM Launchpad ......................................................................................... 65
2.6 Watchdog Timer .................................................................................................................................. 71
2.7 Interrupts ............................................................................................................................................. 72
2.8 Low Power Microcontroller .................................................................................................................. 78
2.9 Summary ............................................................................................................................................. 83
2.10 Review questions ............................................................................................................................... 84
2.1 Introduction
Typical embedded systems are designed using 8 to 32 bit microcontroller platforms. 32-bit controllers,
for example, find applications in consumer electronics, home automation, industrial automation,
automobile, security systems, IoT and healthcare segments. ARM based SoCs such as TIVA C Series
also find applications in the similar segments.
But microcontrollers can provide intelligence in the overall product design only if they are supported by
libraries and necessary software components. TIVA C series can be programed using Code Composer
Studio (CCS) and is well supported by libraries such as TIVAware, TI-RTOS etc. In this chapter, CCS
is the main tool for programming microcontrollers in C language.
To understand the controller capability we need to have knowledge about its memory and its
architecture and its peripherals. Memory addressing with respect to TIVA, including SRAM, flash
memory, internal memory, is important. A microcontroller has General-purpose input/output (GPIO),
which is used to take input and provide output from and to several devices such as sensors, switches
etc. In a fire alarm system, for example, the GPIO is interfaced with sensors. As sensors are analog in
nature, there needs to be an ADC to provide input to controller. The smoke sensor detects smoke in
the room and sends a signal (through GPIO) to switch on the buzzer, which warns users.
on same technical standards released C90. ISO further revised C90 in 1999 and 2011 and released
C99 and C11 respectively.
There is also a flavor of C especially committed to embedded application development called as
Embedded C. It is a collection of C extensions standardized by the C Standard Committee and
released in 2008. Embedded C is built in C language incorporating features like naming address
spaces, named-register storage classes, fixed-point arithmetic, and basic I/O hardware addressing.
By default, int is signed. It takes 4 bytes for 32 bit MPUs but 2 bytes for
int 4 bytes
16 bit MPUs.
long int 4 bytes For 16 bit MPUs as well as 32 bit MPUs, it takes 4 bytes.
Single-precision floating-point format. Unsigned type cannot be specified.
float 4 bytes
The precision is 6 decimal places
Double-precision floating-point format. The precision is 15 decimal
double 8 bytes
places
long Double 10 bytes The precision is 19 decimal places.
int16_t, uint16_t 2 bytes Can store integers in the range -(1 << x-1)+1 ~ (1 << x-1)-1, for all
int32_t, uint32_t 4 bytes intx_t.
Bitwise Shifting
There are two bit-wise shift operators in C. Shift Right (>> data >>) number of bit-positions to
be shifted right and Shift Left (<< data <<) number of bit-positions to be shifted left.
Debugger
The CCS debugger depends on a configuration file and a general extension language (GEL) file. The
debugger initializes and loads the software on a target device using information provided by these
files. A target configuration file specifies
(i) Connection type to the target device,
(ii) Target device, and
(iii) About a startup script
Table 2.4: Development Tools for Tiva C Series
In CCS, startup scripts are specified to setup the memory map for debugger. It is also used to setup
any initial target state that is necessary for connection to the debugger using memory or register
writes. These scripts are known as GEL script file. „OnStartup()‟ function in the GEL file runs when the
debugger is launched. After the target is connected, „OnTargetConnect()‟defined in the GEL file is
executed.
TivaWareTM
TivaWareTM for C series is a free collection of libraries in the form of source codes and static libraries.
TivaWareTM caters to all TI Cortex M devices. It includes
Peripheral driver library
USB stacks
Ethernet Stacks
Graphics library
Sensor library
And other features
TivaWareTM specializes in minimizing programming complexities with optimized drivers and OS
independent support. It provides a large set of libraries which reduces prototyping time. It also provides
a higher abstraction level for programmers to access the hardware peripherals of the board. In this
book, TivaWareTM has been extensively used for programming.
In MMIO, same address bus is used to address both memory and peripheral devices. The address bus
of the CPU is shared between the peripheral devices and memory devices attached to the CPU. Thus,
any address accessed by the CPU may denote an address in the memory or a register of attached
peripheral. In these architectures, same CPU instructions used for memory access can also be used
for I/O access.
In PMIO, peripheral devices possess a separate address bus from general memory devices. This is
accomplished in most architectures by providing a separate address bus dedicated to the peripheral
devices attached to the CPU. In these CPUs, the instruction set includes separate instructions to
perform I/O access.
A TM4C123GH6PM chip employs MMIO which implies that the peripherals are mapped into the 32-bit
address bus.
Flash Memory
Flash memory is structured into multiple blocks of single KB size which can be individually written to
and erased. Flash memory is used for store program code. Constant data used in a program can also
be stored in this memory. Lookup tables are used in many designs for performance improvement.
These lookup tables are stored in this memory.
Table 2.5: Memory Mapping in TM4C123GH6PM Chip
Bit-banded on-chip
32 KB 0x20000000 to 0x20007FFF
SRAM
Peripheral All the peripherals 0x40000000 to 0x400FFFFF
SRAM
The on-chip SRAM starts at address 0x2000.0000 of the device memory map. ARM provides a
technology to reduce occurrences of read-modify-write (RMW) operations called bit-banding. This
technology allows address aliasing of SRAM and peripheral to allow access of individual bits of the
same memory in single atomic operation. For SRAM, the bit-band base is located at address
0x2200.0000. Bit band alias are computed according to following formula.
bitband alias= bitband base + byte offset *32 + bit number *4 (2.1)
Note: Bit banding is the technique to access and modifying content of bits in a register. It is helpful to
finish the read-modify operation in single machine cycle.
The region of the memory which device consider for modification is known as bit band region and the
region of memory to which device maps the selected memory is known as bit band alias.
The SRAM is implemented using two 32-bit wide SRAM banks (separate SRAM arrays). The banks
are partitioned in a way that one bank contains all, even words (the even bank) and the other contains
all odd words (the odd bank). A write access that is followed immediately by a read access to the
same bank. This incurs a stall of a single clock cycle.
Internal ROM
The internal ROM of the TM4C123GH6PM device is located at address 0x0100.0000 of the device
memory map. The ROM contains:
TivaWare™ Boot Loader and vector table
TivaWareTM Peripheral Driver Library (DriverLib) release of product-specific peripherals and
interfaces
Advanced Encryption Standard (AES) cryptography tables
Cyclic Redundancy Check (CRC) error detection functionality
The boot loader is used as an initial program loader (when the Flash memory is empty) as well as an
application-initiated firmware upgrade mechanism (by calling back to the boot loader). The Peripheral
Driver Library, APIs in ROM can be called by applications, reducing flash memory requirements and
freeing the Flash memory to be used for other purposes (such as additional features in the
application). Advance Encryption Standard (AES) is a publicly defined encryption standard used by the
U.S. Government and Cyclic Redundancy Check (CRC) is a technique to validate if a block of data
has the same contents as when previously checked.
Peripheral
All Peripheral devices, timers, and ADCs are mapped as MMIO in address space 0x40000000 to
0x400FFFFF. Since the number of supported peripherals is different among ICs of ARM families, the
upper limit of 0x400FFFFF is variant.
Example:
is driven to the microcontroller pin. Similarly, when Direction register is configured as input, the
information on the microcontroller pin is written to the Data register.
Data Direction Operation: In Tiva C series Launchpad, the GPIO Direction (GPIODIR) register is
used to configure each individual pin as an input or output. When the data direction bit is cleared, the
GPIO is configured as an input, and the corresponding data register bit captures and stores the value
on the GPIO port. When the data direction bit is set, the GPIO is configured as an output, and the
corresponding data register bit is driven out on the GPIO port.
Data Register Operation: In Tiva C Series Launchpad, GPIODATA register is the data register in
which the values written in this register are transferred onto the GPIO port pins if the respective pins
have been configured as outputs through the GPIO Direction (GPIODIR) register. The GPIO ports
allow for the modification of individual bits in the GPIO Data (GPIODATA) register by using bits of the
address bus as a mask. In this manner, we can modify individual GPIO pins in a single instruction
without affecting the state of the other pins.
Used
for
Configuration
Table 2.7 Switches: RGB and GPIO pin connection to the microcontroller
In the following example, we will understand how to access a GPIO pin as an output. This code uses
TivaWareTM and can be downloaded for free from the Texas Instruments website. After TivaWareTM
is installed, for a project, it is essential to complete three steps to include TivaWareTM in the project.
Include TivaWareTM installation directory in path and build variables.
Add/link driverlib.lib file from “<install_directory>\driverlib\ccs\Debug” to the project.
Add startup_ccs.c file to the project. (If Applicable)
Example: In the line follower design there are servo motors employed for the movement, there is a IR
transmitter and receiver circuit in-built on the board. If the line follower is on the line then green led will
blink and it follow its path. If is turned then again it will try to follow it, but if there is no path or path is
damaged then it start blinking the red LED and the line follower stop at that point from which its path is
missing or damaged.
Code:
Start: Initialize peripherals
#DEFINE LED PIN1
#DEFINE LED PIN2
#DEFINE LED PIN3
#DEFINE IRin
#DEFINE IRout
Check the track
{
while (IR sense the darkness)
{
Turn on Green LED
Delay(nano secs)
}
while (IR sense the light)
{
Turn on Red LED
Delay (nano secs)
}
Run infinite
Table 2.8: Clock setup for TM4C123GH6PM
In this example, we have used the PLL which runs at 400 MHz (specified by SYSCTL_USE_PLL). It is
divided by a divisor 2.5 (specified by SYSCTL_SYSDIV_2_5). There is a divide by 2 in the clock tree
as mentioned in the datasheet. Thus, the effective clock can be calculated as
400MHz
80MHz
SYSCTL _ SYSDIV _ 2 _ 5 2
The clock is set to 80 MHz, to verify, SysCtlClockGet() function returns the value of the clock. In figure
3, we can observe that the clock frequency is 66MHz. This is because SYSCTL->DC1.MINSYSDIV,
which driverlib consults, insists that the minimum divider is 3, so it is not possible to operate at 80 MHz
Peripheral Setup
Then we need to enable the clk in the peripheral
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
SysCtlDelay(3);
Normally the clock is disabled in any peripheral to save power. Leave a delay after it. It is advised to
wait at least 3 clock cycles before configuring the peripheral you have just enabled.
SysCtlPeripheralEnable(uint32_t ui32Peripheral) is what you always use to turn on a peripheral. It's
what enables the clock for it. The parameter is the peripheral you want to enable. For GPIOs its
SYSCTL_PERIPH_GPIOx, being "x" the letter of the peripheral you want to enable.
SysCtlDelay(uint32_t ui32Count) specifies a delay of ui32Count cycles. This suggests that the
instruction pushes the microcontroller to enter an idle state for ui32Count cycles. Each value delays for
3 clock cycles, so in our case with the value 3, we delay 9 clock cycles.
The TM4C123GH6PM microcontroller has two Watchdog Timer modules, one module is clocked by
the system clock (Watchdog Timer 0) and the other (Watchdog Timer 1) is clocked by the PIOSC
therefore it requires synchronizers.
Features of Watchdog Timer in TM4C123GH6PM controller:
32-bit down counter with a programmable load register
Separate watchdog clock with an enable
Programmable interrupt generation logic with interrupt masking and optional NMI function
Lock register protection from runaway software
Reset generation logic with an enable/disable
User-enabled stalling when the microcontroller asserts the CPU halt flag during debug
2.7 Interrupts
The reader is aware that a microprocessor is connected to several input and output devices. It is
important at this point for us to know how a microprocessor manages these devices efficiently.
processing time from the presently executing task. This is a very inefficient way because I/O devices
do not always crave for attention from the microprocessor. But the microprocessor wastes valuable
processing time in unnecessarily polling of the devices.
Interrupts
However, in interrupt method, whenever a device requires the attention from the microprocessors, it
pings the microprocessor. This ping is called interrupt signal or sometimes interrupt request (IRQ).
Every IRQ is associated with a subroutine that needs to be executed within the microprocessor. This
subroutine is called interrupt service routine (ISR) or sometimes interrupt handler. The microprocessor
halts current program execution and attends to the IRQ by executing the ISR. Once execution of ISR
completes, the microprocessor resumes the halted task.
The current state of the microprocessor must be saved before it attends the IRQ in order to be able to
continue from where it was before the interrupt. To achieve this, the contents of all of its internal
registers, both general purpose and special registers, are required to be saved to a memory section
called the stack. On completion of the interrupt call, these register contents will be reinstated from the
stack. This allows the microprocessor to resume its originally halted task.
There are two types of interrupts namely software driven interrupts (SWI) and hardware driven
interrupts (HWI). SWIs are generated from within a currently executing program. They are triggered by
the interrupt opcode. A SWI will call a subroutine that allows a program to access certain lower level
service. HWIs are signals from a device to the microprocessor. The device sets an interrupt line in the
control bus high. Microprocessors have two types of hardware interrupts namely, non-maskable
interrupt (NMI) and interrupt request (INTR). An NMI has a very high priority and they demand
immediate execution. There is no option to ignore an NMI. NMI is exclusively used for events that are
regarded as having a higher priority or tragic consequences for the system operation. For example,
NMI can be initiated due to an interruption of power supply, a memory fault or pressing of the reset
button. An INTR may be generated by a number of different devices all of which are connected to the
single INTR control line. An INTR may or may not be attended by the microprocessor. If the
microprocessor is attending an interrupt, then no further interrupts, other than an NMI, will be
entertained until the current interrupt has been completed. A control signal is used by the
microprocessor to acknowledge an INTR. This control signal is called ACK or sometimes INTA.
1 -3 RESET 0x0000.0004
2 -2 NMI 0x0000.0008
13 - Reserved 0x0000.0034
Bus Fault
A bus fault is an exception that arises due to a memory-related fault for an instruction or data memory
transaction, such as a pre-fetch fault or a memory access fault. This fault can be enabled or disabled.
Usage Fault
Exception that occurs due to a fault associated with instruction execution. This includes undefined
instruction, illegal unaligned access, invalid state on instruction execution, or an error on exception
return may termed as usage fault. An unaligned address of a word or half-word memory access or
division by zero can cause a usage fault.
SVCall
A supervisor call (SVC) is an exception that is activated by the SVC instruction. In an operating
system, applications can use SVC instructions to contact OS kernel functions and device drivers. This
is a software interrupt since it was raised from software, and not from a Hardware or peripheral
exception.
PendSV
PendSV is pendable service call and interrupt-driven request for system-level service. PendSV is used
for framework switching when no other exception is active. The Interrupt Control and State (INTCTRL)
register is used to trigger PendSV. The PendSV is an interrupt and can wait until NVIC has time to
service it when other urgent higher priority interrupts are being taken care.
SysTick
A SysTick exception is generated by the system timer when it reaches zero and is enabled to generate
an interrupt. The software can also produce a SysTick exception using the Interrupt Control and State
(INTCTRL) register.
User Interrupts
This interrupt is an exception signaled either by a peripheral or by a software request and fed through
the NVIC based on their priority. All interrupts are asynchronous to instruction execution. In the
system, peripherals use interrupts to communicate with the processor. An ISR can be also propelled
as a result of an event at the peripheral devices. This may include timer timeout or completion of
analog-to-digital converter (ADC) conversion. Each peripheral device has a group of special function
registers that must be used to access the device for configuration. For a given peripheral interrupt to
take effect, the interrupt for that peripheral must be enabled.
/***************************************************************************
Aim: To understand how exceptions/interrupts work
***************************************************************************/
#include <stdint.h>
#include <stdbool.h>
#include "inc/tm4c123gh6pm.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/sysctl.h"
#include "driverlib/interrupt.h"
#include "driverlib/gpio.h"
#include "driverlib/timer.h"
int main(void)
uint32_t ui32Period;
SysCtlClockSet(SYSCTL_SYSDIV_5|SYSCTL_USE_PLL|SYSCTL_XTAL_16MHZ|SYSCTL_OSC_M
AIN);
// SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3);
SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);
TimerConfigure(TIMER0_BASE, TIMER_CFG_PERIODIC);
ui32Period = (SysCtlClockGet() / 10) / 2;
TimerLoadSet(TIMER0_BASE, TIMER_A, ui32Period -1);
IntEnable(INT_TIMER0A);
TimerIntEnable(TIMER0_BASE, TIMER_TIMA_TIMEOUT);
IntMasterEnable();
TimerEnable(TIMER0_BASE, TIMER_A);
while(1)
{
}
}
void Timer0IntHandler(void)
{
// Clear the timer interrupt
TimerIntClear(TIMER0_BASE, TIMER_TIMA_TIMEOUT);
// Read the current state of the GPIO pin and
// write back the opposite state
if(GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_2)) {
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3, 0);
}
Else {
GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_2, 4);
}
}
To achieve this, the Hibernation (HiB) Module is added with following features:
(i) A Real-Time Clock (RTC) to be used for wake events
(ii) A battery backed SRAM for storing and restoring processor state. The SRAM consists of 16 32-bit
word memory.
The RTC is a 32- bit seconds counter and 15- bit sub second counter. It also has an add-in trim
capability for precision control over time. The Microprocessor has a dedicated pin for waking using
external signal. The RTC and the SRAM are operational only if there is a valid battery voltage. There is
a VDD30N mode, which provides GPIO pin state during hibernation of the device.
Thus we are actually shutting the power off for the device or part at the lowest power mode. Under
such circumstances, it is safe to assume that in the wake up we are actually coming out of reset. But
this will allow the device to the keep the GPIO pins in their state without resetting them. A mechanism
for power control is used to shut down the part. In TM4C123GH6PM we have an on-chip power
controller which controls power for the CPU only. There is also a pin output from the microcontroller
which is used for system power control.
It should be duly noted that in TIVA Launchpad, the battery voltage is directly connected to the
processor voltage and it is always valid. But in a custom design with TM4C123GH6PM microcontroller
running on a battery, if the battery voltage is not valid, it will not go into hibernation mode.
The second mechanism controls the power to the microcontroller with a control signal (HIB)
that signals an external voltage regulator to turn on or off.
The Hibernation module power source is determined dynamically. The supply voltage of the
Hibernation module is the larger of the main voltage source (VDD) or the battery voltage source
(VBAT).
Hibernate mode can be entered through one of two ways:
The user initiates hibernation by setting the HIBREQ bit in the Hibernation Control (HIBCTL)
register.
Power is arbitrarily removed from VDD while a valid VBAT is applied
Power Modes
There are six power modes in which TM4C123GH6PM operates as shown in the below table. They are
Run, Sleep, Deep Sleep, Hibernate with VDD3ON, Hibernate with RTC, and Hibernate without RTC.
To understand all these modes and compare them, it is necessary to analyze them under a condition.
Let us consider that the device is operating at 40 MHz system clock with PLL.
Table 2.10: Power Modes of Tiva
sleep and the LED stops glowing. When SW2 (switch on the right hand bottom corner of the
Launchpad) is pressed, it triggers a wake event and the GREEN LED starts glowing again. Now, after
4s, the system goes to sleep again. This shows that, the wakeup process is the same as powering up.
When the code starts, we can determine that the processor woke from hibernation and restore the
processor state from the memory.
Flow chart:
#include <stdint.h>
#include <stdbool.h>
#include "utils/ustdlib.h"
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "driverlib/sysctl.h"
#include "driverlib/pin_map.h"
#include "driverlib/debug.h"
#include "driverlib/hibernate.h"
#include "driverlib/gpio.h"
int main(void)
{
SysCtlClockSet(SYSCTL_SYSDIV_5|SYSCTL_USE_PLL|SYSCTL_XTAL_16MHZ|SYSCTL_OSC_
MAIN); // System Clock set to 40 MHz
/***********************************************************************************
* Use the green LED (2=red=pin1, 4=blue=pin2 and 8=green=pin3) as an
* indicator that the device is in hibernation (off for hibernate and on for wake).
*
***********************************************************************************/
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3);
GPIOPinWrite(GPIO_PORTF_BASE,GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3, 0x08);
2.9 Summary
In this chapter the readers will be able to have an understanding of programming the TIVA
microcontroller using TIVAWare Peripheral driver library. The chapter describes the ARM architecture
as a programming model with the operating states and modes supported by the ARM architecture.
ARM and Thumb operating states of TM4C123x are also described rendering a detailed explanation of
the instruction set of ARM Cortex- M4 core. The chapter also discusses the interrupt and exception
handling mechanisms in TIVA microcontroller. An important difference between TM4C123x and
TM4C129x series of microcontrollers of TIVA family is also explained emphasizing the application
development from user‟s viewpoint.
2.10
Chapter 2 set the base for GPIO configurations according to application, interrupt handling and the role of
watchdog timer and low power mode of TIVA using hibernation module. This chapter covers applications
of timer/counters in home automation, traffic light control etc. The role of PWM in applications such as
speed control of DC motor is discussed in this chapter.
By the end of this chapter, readers can expect to have a good understanding of timers and their
importance in embedded systems. They will also acquire knowledge about DMA how they provide fast
access to memory; importance of ADC and how it works in different applications and configurations with
TIVA.
The chapter also covers PWM mode and its application area as well as Quadrature Encoder Interface and
its applications.
Topic Page
3.1 Introduction.......................................................................................................................................... 86
3.2 Timers ................................................................................................................................................. 86
3.3 Analog to Digital Converter (ADC) ...................................................................................................... 94
3.4 Analog Comparators ........................................................................................................................... 97
3.5 Analog Interfacing and Data Acquisition ........................................................................................... 100
3.6 Direct Memory Access (DMA) ........................................................................................................... 102
3.7 Pulse Width Modulation .................................................................................................................... 104
3.8 Quadrature Encoder Interface (QEI) ................................................................................................. 109
3.9 Summary ........................................................................................................................................... 114
3.10 Review Questions ............................................................................................................................. 115
3.1 Introduction
In our daily life, we have numerous applications of embedded systems in areas such as automobiles,
communication, home appliances etc. Consider an example of a washing machine, which uses various
modules such as temperature sensor, motor control, display systems and timer.
3.2 Timers
Timers are basic constituents of most microcontrollers. Today, just about every microcontroller comes
with one or more built-in timers. These are extremely useful to the embedded programmer - perhaps
second in usefulness only to GPIO. The timer can be described as the counter hardware and can
usually be constructed to count either regular or irregular clock pulses. Depending on the above
usage, it can be a timer or a counter respectively.
Sometimes, timers may also be termed as “hardware timers” to distinguish them from software timers.
Software timers can be described as a stream of bits of software that achieve some timing function.
The TM4C123GH6PM General-Purpose Timer Module (GPTM) contains six 16/32-bit GPTM blocks
and six 32/64-bit Wide GPTM blocks. These programmable timers can be used to count or time
external events that drive the Timer input pins. Timers can also be used to trigger μDMA transfers, to
trigger analog-to-digital conversions (ADC) when a time-out occurs in periodic and one-shot modes.
The GPT Module is one timing resource available on the Tiva™ C Series microcontrollers. Other timer
resources include the System Timer (SysTick) and the PWM timer in PWM modules.
The General-Purpose Timer Module (GPTM) blocks with the following functional options:
16/32-bit operating modes:
16- or 32-bit programmable one-shot timer
16- or 32-bit programmable periodic timer
16-bit general-purpose timer with an 8-bit prescaler
32-bit Real-Time Clock (RTC) when using an external 32.768-KHz clock as the input
16-bit input-edge count- or time-capture modes with an 8-bit prescaler
16-bit PWM mode with an 8-bit prescaler and software-programmable output inversion of
the PWM signal
32/64-bit operating modes:
32- or 64-bit programmable one-shot timer
32- or 64-bit programmable periodic timer
32-bit general-purpose timer with a 16-bit prescaler
64-bit Real-Time Clock (RTC) when using an external 32.768-KHz clock as the input
32-bit input-edge count- or time-capture modes with a16-bit prescaler
32-bit PWM mode with a 16-bit prescaler and software-programmable output inversion of
the PWM signal
Count up or down
Twelve 16/32-bit Capture Compare PWM pins (CCP)
Twelve 32/64-bit Capture Compare PWM pins (CCP)
Daisy chaining of timer modules to allow a single timer to initiate multiple timing events
Timer synchronization allows selected timers to start counting on the same clock cycle
ADC event trigger
User-enabled stalling when the microcontroller asserts CPU Halt flag during debug (excluding
RTC mode)
Ability to determine the elapsed time between the assertion of the timer interrupt and entry into
the interrupt service routine
Efficient transfers using Micro Direct Memory Access Controller (μDMA)
Dedicated channel for each timer
Burst request generated on timer interrupt
Timer Register
The timer register can be defined as hardware with an N-bit up-counter, which has accessibility of read
and write command rights for the current count value, and to stop or reset the counter. As discussed,
the timer is driven by the pre-scaler output. The regular pulses which drive the timer, irrespective of
their source are often called “ticks”. We may understand now that it is not necessary for a timer to time
in seconds or milliseconds, they do time in ticks. This enables us the elasticity to control the rate of
these ticks, depending upon the hardware and software configuration. We may construct our design to
some human-friendly value such as e.g. 1 millisecond or 1 microsecond, or any other design specified
units.
Capture Registers
A capture registers are those hardware which can be routinely loaded with the current counter value
upon the occurrence of some event, usually a change on an input pin. Therefore the capture register
is used to capture a “snapshot” of the timer at the instant when the event occurs. A capture event can
also be constructed to produce an interrupt, and the Interrupt Service Routines (ISR) can save or else
use the just-captured timer snapshot.
There is no latency problem in snapshot value as the capture occurs in hardware, which would be if
the capture was done in software. Capture registers can be used to time intervals between pulses or
input signals, to determine the high and low times of input signals.
Compare/Match Registers
Compare or match registers hold a value against which the current timer value is routinely compared
and shoots to trigger an event when the value in two registers matches.
If the timer/counter is configured as a timer, we can generate events at known and precise
times. Events can be like output pin changes and/or interrupts and/or timer resets.
If the timer/counter is configured as a counter, the compare registers can generate events
based on preset counts being achieved.
For instance, the compare registers can be used to generate a timer “tick”, a fixed timer interrupt used
for system software timing. For example, if a 2ms tick is desired, and the timer is configured with a
0.5us clock, setting a compare register to 4000 will cause a compare event after 2ms. If we set the
compare event to generate an interrupt as well as to reset the timer to 0, the result will be an endless
stream of 2ms interrupts.
Another notable use of a compare register can be to generate a pulse with variable width. Set an
output high/low when the timer is at 0, configure the compare register with value of pulse width, and on
the compare event set the output low/high. We may use a second compare register with a larger value,
to set the pulse interval by retuning the timer on compare.
Fig 3.5. (a) Period based input Read with free running counter
Fig 3.5. (b) Period based input Read with counter that increments only while gate input is HIGH
(Gate connected to Period Based Input)
Interrupts
The ADC module's interrupt signals are controlled by the state of the MASK bits in the ADC Interrupt
Mask (ADCIM) register. Interrupt status can be viewed at two locations: the ADC Raw Interrupt
Status (ADCRIS) register, which shows the raw status of the various interrupt signals; and the ADC
Interrupt Status and Clear (ADCISC) register, which shows active interrupts that are enabled by the
ADCIM register. Sequencer interrupts are cleared by writing a 1 to the corresponding IN bit in
ADCISC. Digital comparator interrupts are cleared by writing a 1 to the ADC Digital Comparator
Interrupt Status and Clear (ADCDCISC) register.
Fig 3.12. The Analog-Digital-Analog signal path with real time processing
DAQ cards mostly contain multiple components like ADC, DAC, multiplexer, TTL-IO, RAM, high speed
timers, etc. A controller is more flexible and inexpensive than a processor, so that it is allowable to
block it with simple polling loops. For example: received a trigger, starting the Analog to Digital
Conversion, matching up the time, waiting for the ADC to finish, storing values to RAM, switch
multiplexer, getting TTL input.
DAQ Device Drivers
In order to make the DAQ hardware work with a microcontroller unit, device drivers are needed. The
device driver executes low-level register reads and writes on the hardware, while exposing API for
developing user applications in a variety of programming environments. These drivers can be coded in
C or assembly language to let the MCU communicate with physical devices connected to it.
In bus master mode, the system bus is acquired by the DMA controller from the CPU to perform the
DMA transfers. This process is also referred to cycle stealing, as the CPU frees the system bus during
the transfer.
In bus slave mode, the CPU access DMA controller, to program its internal registers for DMA transfers.
The internal registers contain source and destination address registers along with transfer count
registers for each DMA channel. It also contains control and status registers.
This type of transfer is initiated under software control and is preferred for moving data from one region
of memory to another region.
Demand-mode transfer is analogous to standard mode apart from that the transfer is
controlled by an external device. This mode of transfer is used to move data between I/O and
memory or vice versa. The Input/output device requests and synchronizes the movement of
data.
Fly-by transfer is high-speed data movement system. Unlike conventional DMA transfers, this
mode moves data from source to destination in a single access (i.e., the data is not read into
the processor before reaching the destination). Here, memory and I/O are provided with
different bus control signals. For instance, memory is given a read request at the same time
that an I/O device is given a write request. Data moves from the memory device straight into
the I/O device.
Dead-band generator
o Produces two PWM signals with programmable dead-band delays suitable for driving a
half-H bridge.
o Can be bypassed, leaving input PWM signals unmodified.
Can initiate an ADC sample sequence
The control block determines the polarity of the PWM signals and which signals are passed through to
the pins. The output of the PWM generation blocks are managed by the output control block before
being passed to the device pins.
immediately followed by the load pulse. In the figures in this chapter, these signals are labelled "dir,"
"zero," and "load."
PWM Comparators
Each PWM generator has two comparators that monitor the value of the counter, when either
comparator matches the counter, they output a single-clock-cycle-width High pulse, labeled "cmpA"
and "cmpB" in the figures in this chapter. When in Count-Up/Down mode, these comparators match
both when counting up and when counting down, and thus are qualified by the counter direction signal.
These qualified pulses are used in the PWM generation process. If either comparator match value is
greater than the counter load value, then that comparator never outputs a High pulse.
o Velocity-timer expiration
o Direction change
o Quadrature error detection
Clock/direction mode, the encoder produces a clock signal to indicate steps and a
direction signal to indicate the direction of rotation. This mode is determined by the
SIGMODE bit of the QEICTL register.
When the QEI module is set to use the quadrature phase mode (SIGMODE bit is clear), the capture
mode for the position integrator can be set to update the position counter on every edge of the PhA
signal or to update on every edge of both PhA and PhB. Updating the position counter on every PhA
and PhB edge provides more positional resolution at the cost of less range in the positional counter.
When edges on PhA lead edges on PhB, the position counter is incremented. When edges on PhB
lead edges on PhA, the position counter is decremented. When a rising and falling edge pair is seen
on one of the phases without any edges on the other, the direction of rotation has changed.
The positional counter is automatically reset on one of two conditions:
Sensing the index pulse or
Reaching the maximum position value.
The reset mode is determined by the RESMODE bit of the QEICTL register.
When RESMODE is set, the positional counter is reset when the index pulse is sensed. This
mode limits the positional counter to the values [0: N-1], where N is the number of phase
edges in a full revolution of the encoder wheel. The QEI Maximum Position (QEIMAXPOS)
register must be programmed with N-1 so that the reverse direction from position 0 can move
the position counter to N-1. In this mode, the position register contains the absolute position of
the encoder relative to the index (or home) position once an index pulse has been seen.
When RESMODE is clear, the positional counter is constrained to the range [0: M], where M is
the programmable maximum value. The index pulse is ignored by the positional counter in this
mode. Velocity capture uses a configurable timer and a count register. The timer counts the
number of phase edges (using the same configuration as for the position integrator) in a given
time period.
The edge count from the previous time period is available to the controller via the QEI Velocity
(QEISPEED) register, while the edge count for the current time period is being accumulated in the QEI
Velocity Counter (QEICOUNT) register. As soon as the current time period is complete, the total
number of edges counted in that time period is made available in the QEISPEED register (overwriting
the previous value), the QEICOUNT register is cleared, and counting commences on a new time
period. The number of edges counted in a given time period is directly proportional to the velocity of
the encoder.
Case Study: TIVA based embedded system application using ADC & PWM
This case study is for the application of the PWM based speed control of DC motor using
Potentiometer. In this study all the sensors are initialized and then synchronized with the
synchronization clock pulse. Here the sensor used is potentiometer which is connected to the ADC of
the Tiva C Series Launchpad and the Motor is connected to the PWM pin of Launchpad as shown in
the below diagram. The value read from the potentiometer is used to vary the duty cycle of the PWM to
which the motor is connected, the value will change as per the rotation of the potentiometer. After
executing this we can control the speed of the motor by adjusting the rotation of the potentiometer.
3.9 Summary
External devices are principal components to bring a real time embedded systems into existence.
Interfacing modules in microcontrollers are required to provide connection to external components
such as sensors and actuators. Various in built interfacing modules such as Analog to Digital
converters, comparators and DMA are discussed. Quadrature Encoder Interface, a new module is
implemented in TIVA microcontroller to convert linear displacement into pulse signals. Pulse width
modulation, a method to create varying analog waveforms by altering the duty cycle is explained and
discussed with the help of a case study.
Chapter 3 covered the programming of PWM module, timers, QEI, ADC and their usage in applications
such as voltage regulator, speed control of motor etc. The present chapter will focus on serial
communication between the controller and various types of internal / external digital interfaces of any
microcontroller. The communication is achieved through interfaces and protocols such as UA RT, SPI, and
I2C etc.
By the end of this chapter, the reader will be able to understand and comprehend different types of
communication protocols and distinguish between synchronous and asynchronous protocols.
The chapter also covers serial communication protocols such as I2C, UART, SPI and different modes and
application area of these protocols, especially in reference to TIVA C Series. Readers will also learn how to
configure and interface these protocols with TIVA C Series.
Topic Page
4.1 Introduction........................................................................................................................................ 117
4.2 Synchronous and Asynchronous protocols ....................................................................................... 118
4.3 Universal Asynchronous Receiver-Transmitter ................................................................................. 118
4.4 Programming UART on Tiva Platform............................................................................................... 122
4.5 Inter IC (I2C) Communication Protocol ............................................................................................. 131
4.6 Serial Peripheral Interface (SPI) ....................................................................................................... 143
4.7 Summary ........................................................................................................................................... 153
4.8 Review Questions ............................................................................................................................. 154
4.1 Introduction
Microcontrollers or System on Chips (SoC) are important components of modern day electronic
systems. But microcontrollers alone can‟t make systems. For any system to work, it needs memory,
displays, real time clock, interfaces to the external world etc. This means that microcontrollers need to
communicate with other devices on the same PCB or with devices of other PCB from the same
system, to achieve the system functionality in applications such as digital audio, digital signal
processing, or telecommunications channels. Microcontroller is an intelligent component on the
system, which runs the software program to take decisions and control the other components of the
system. To take decisions, microcontroller needs data from various input sources and to execute the
decisions, it sends control signals to different devices/actuators interfaced on the system. For example,
several sensors (temperature, pressure, sound etc.) can be thought of as the components of input
system. These sensors gather data and communicate with the controller through a set of
communication interfaces. Consider a system shown in Fig 4.1, which highlight the various
components of weather monitoring systems. The weather monitoring systems usually monitor
atmospheric properties such as humidity, temperature, pressure etc. The various parameters are
gathered using sensors that are interfaced with microcontroller using popular serial interfaces such as
SPI, I2C, and UART etc. The same system can be used for upper atmospheric data gathering
missions by incorporating Wi-Fi and satellite connectivity with the ground station. Therefore,
communication between microcontroller and other devices on the system is very important to achieve
intended functionality.
connect microcontroller with other components parallel, because I/O‟s were not available. And also it
increases the physical dimensions of PCB board which will directly increase the cost of production of
electronic systems. In the mid 80‟s, Philips was facing similar problem with I/O‟s and cost of
production, motivated Philips to invented a serial communication protocol:- Inter-IC protocol (I2C). To
solve the same problem, Motorola came up with Serial Peripheral Interface (SPI). Several other serial
communication protocols are developed in last two decades for different applications in automotive,
industrial control and consumer electronics. Examples: Controller Area Network (Automotive), Inter-IC
sound (I2S) etc. The parallel communication is easy to understand and implement. To optimize the
I/O‟s and cost of production, most of the modern day electronic systems designs use different variety
of serial communication protocols. Similarly, modern microcontrollers support wireless communication
protocols like Bluetooth, ZigBee etc.
:
Fig 4.2. Frame for ASCII „A‟ (01000001)
Fig 4.2 shows the ASCII character “A,” binary 0100 0001, is framed between the start bit and two stop
bits. LSB will go out first. When there is no data transfer, the logic „1‟ is transmitted. This is known as
mark. The logic „0‟ is referred as space. Peripheral chips can be programmed to receive or transmit 5,
6, 7 or 8 bits of data. In the initial days, 2 stop bits were used to give sufficient time to organize the
received data or to make suitable arrangements to transmit next chunk of data. The modern day
microcontrollers and personal computers will use 1 stop bit. In modern UARTs, total 10-bits are used.
8-bits are for ASCII code, one for start bit and one for stop bit. 4.3.3 Parity Bit
A parity bit can be added into the frame in order to check integrity of data. The parity bit may be even
or odd. Odd parity means odd number of 1‟s in the data (parity = logic „1‟). Even parity means even
number of 1‟s in the data (parity = logic „0‟). Ex: The binary of ASCII „A‟ is 0100 0001. Parity bit is logic
„0‟ (Even parity). UART implementations in microcontrollers will allow programmer to decide whether to
include parity or not. The parity bit is transmitted as MSB followed by a stop bit.
Non-return to zero inverted (NRZI) is encoding method, in which binary signal is represented as
transitions in the signal. Binary information is encoded as the presence or absence of transition at the
clock boundary.
The interface logic chips like MAX232 will convert voltages between TTL/MOS/CMOS logic levels.
Where the SysClk is the working system clock connected to the UART and ClkDiv is the value
programmed into baud rate registers.
The baud-rate divisor (BRD) has the following relationship to the system clock, where BRDI is the
integer part of the BRD and BRDF is the fractional part, separated by a decimal place.
UARTSysClk is the system clock connected to the UART, and ClkDiv is 16 (if HSE in UARTCTL is
clear) or 8 (if HSE is set).
Alternatively, the UART may be clocked from the internal precision oscillator (PIOSC), independent of
the system clock selection. This will allow the UART clock to be programmed independently of the
system clock PLL settings.
TI Tiva Launchpad system clock is 16 MHz so desired Baud Rate can be calculated as:
The ClkDiv value includes both integer and fractional values loaded into UARTIBRD and UARTFBRD
registers. The integer part is easy to calculate and fraction part requires manipulations based on trial
and error.
Example:
System clock of TI Tiva Launchpad is16 MHz 16MHz is divided by 16 and it is fed into UART. So
UART operates at 1MHz frequency. So ClkDiv = 1MHz.
To generate a baud rate of 4800: 1MHz/4800 = 208.33
(a) 1MHz/4800 = 208.3333, UARTIBRD = 208 and UARTFBRD = (0.3333×64) +
0.5 = 21.8312 = 21
(b) 1MHz/9600 = 104.166666, UARTIBRD = 104 and UARTFBRD = (0.16666 × 64)
+0.5=11
(c) 1MHz/57600 = 17.361, UARTIBRD = 17 and UARTFBRD = (0.361 × 64) + 0.5
=23
(d) 1MHz/115200 = 8.680, UARTIBRD = 8 and UARTFBRD = (0.680 × 64) +0.5=44
FEN (FIFO Enable): UART has an internal 16-byte FIFO (first in first out) buffer to store data for
transmission to keep the CPU getting interrupted for the reception and transmission of every
byte. Enabling FEN bit, we can write up to16 bytes of data block into its transmission FIFO
buffer and let transfer happen one byte at a time. There is also a separate 16 byte FIFO for the
receiver to buffer the incoming data. Upon Reset, the default for FIFO buffer size is 1 byte.
WLEN (Word Length): The number of bits per character data in each frame can be 5, 6, 7, or 8.
we use 8 bits for each character data frame. Default world length mode is 5.
BRK (Send Break): A Low level is continually output on the UnTx signal, after completing
transmission of the current character. For the proper execution of the break command, software
must set this bit for at least two frames (character periods).
PEN (Parity Enable): Parity is enabled and parity bit is added to the data frame by making PEN
= 1. Parity checking is also enabled.
EPS (Even Parity Select): Odd parity is performed, which checks for an odd number of 1s when
EPS = 0. Even parity generation and checking is performed during transmission and reception,
which checks for an even number of 1s in data and parity bits when EPS = 1.
Set the bits in UARTLCRH register for 1 stop bit, no interrupt, no FIFO use, and for
8 -bit data size (for UART 0).
Program TxE and RxE in UARTCTL to enable transmitter and receiver.
Make PA0 and PA1 pins to use as digital pins.
Configure PA0 and PA1 pins for UART.
Loop the program for wait on TxD output. Monitor the TXFF flag bit and when it
goes low, write a data into data register.
Monitor the RXFE flag bit in UART Flag register and when it goes LOW read the received byte
from Data register and save before it gets overwrite.
UART0Tx('O');
}
}
/* UART0 Transmit */
void UART0Tx(char c)
{while((UART0->FR & 0x20) != 0); /* wait until Tx buffer not full */
UART0->DR = c; /* before giving it another byte */
}
Example 2 :
Program to receive data serially via UART0
#include <stdint.h>
#include "tm4c123gh6pm.h"
char UART0Rx(void);
void delayMs(int n);
int main(void)
{
char c;
SYSCTL->RCGCUART |= 1; /* enable clock supply to UART*/
SYSCTL->RCGCGPIO |= 1; /* enable clock supply to PORTA */
/* UART0 initialization */
UART0->CTL = 0; /* disable UART0 */
UART0->IBRD = 104; /* 9600 baud rate
UART0->FBRD = 11; /* fractional portion*/
UART0->CC = 0; /* configured to system clock */
UART0->LCRH = 0x60; /* 8-bit, no parity, 1-stop bit, no FIFO */
UART0->CTL = 0x301; /* configure UART0 and TXE, RXE */
/* UART0 TX0 and RX0 use PA0 and PA1. Set them up. */
GPIOA->DEN = 0x03; /* Make PA0 and PA1 as digital */
GPIOA->AFSEL = 0x03; /* Use PA0, PA1 alternate function */
GPIOA->PCTL = 0x11; /* configure PA0 and PA1 for UART */
for(;;)
{
c = UART0Rx(); /* get a character from UART */
}
}
/* UART0 Receive */
char UART0Rx(void)
{
char c;
while((UART0->FR & 0x10) != 0); /* wait until the buffer is not
empty */
c = UART0->DR; /* read the received data */
return c; /* and return it *
o Slave receive
Four transmission speeds:
o Standard (100 Kbps)
o Fast-mode (400 Kbps)
o Fast-mode plus (1 Mbps)
o High-speed mode (3.33 Mbps)
Clock low timeout interrupt
Dual slave address capability
Glitch suppression
Master and slave interrupt generation
Master generates interrupts when a transmit or receive operation completes (or aborts due to
an error)
Slave generates interrupts when data has been transferred or requested by a master or when
a START or STOP condition is detected
Master with arbitration and clock synchronization, multi-master support, and 7-bit addressing
mode.
To enable the clock SYSCTL ->RCGCI2C | = 0x0F will enable clock to all four modules.
Clock Speed: I2CMTPR (I2C Master Timer Period) register is programmed to set the clock frequency
for SCL.
TPR value to generate Standard, Fast and Fast mode plus SCL frequencies is given in below table:
Table 4.2. TPR Values for I2C modes
The HS bit in the I2CMTPR register needs to be set for the TPR value to be used in High-Speed
mode.
Table 4.3: TPR Values for High-Speed Mode
I2CMCR (I2C Master Configuration register) is used to configure microcontroller as master or slave.
The description of I2CMCR is below:
Slave Address:
In a master device, the slave address is stored in I2CMSA. Addresses in I2C communication is 7-bits.
I2CMSA stores D7 to D1 bits and LSB of D0 indicate master is receiver of transmitter.
Data Register:
In transmit mode, a byte of data will be placed in I2CMDR (I2C Master Data Register) for transmission.
(a) (b)
Fig 4.23. Data transmission using (a) Master Single Transmit, (b) Single Master receive
0 0 1 Hz
0 1 4.096 kHz
1 0 8.192 kHz
1 1 32.768 kHz
CPHA=0 means sample data on the leading (first) clock edge, while CPHA=1 means sample data on
the trailing (second) clock edge. The idle value of the clock is zero the leading clock edge is a positive
edge but if the idle value of the clock is one, the leading clock edge is a negative edge.
In SPI protocol both master and slaves use the same clock for communication When CPOL= 0 the idle
value of the clock is zero while at CPOL=1 the idle value of the clock is one.
CPHA=0 means sample data on the leading (first) clock edge, while CPHA=1 means sample data on
the trailing (second) clock edge. The idle value of the clock is zero the leading clock edge is a positive
edge but if the idle value of the clock is one, the leading clock edge is a negative edge.
Each data frame is between 4 and 16 bits long depending on the size of data programmed and is
transmitted starting with the MSB. There are three basic frame types that can be selected by
programming the FRF bit in the SSICR0 register:
Texas Instruments synchronous serial
Freescale SPI
Microwire
For all three formats, the serial clock (SSInClk) is held inactive while the SSI is idle, and SSInClk
transitions at the programmed frequency only during active transmission or reception of data. The idle
state of SSInClk is utilized to provide a receive timeout indication that occurs when the receive FIFO
still contains data after a timeout period.
For Freescale SPI and MICROWIRE frame formats, the serial frame (SSInFss) pin is active Low, and
is asserted (pulled down) during the entire transmission of the frame.
We focus on the SPI features of SSI module. This microcontroller supports four SSI modules. The SSI
modules are located at the following base addresses:
Table 4.9: SPI Modules base address
Module SSI0 SSI1 SSI2 SSI3
Base Address 0x40008000 0x40009000 0x4000A000 0x4000B000
Clock to SSI: RCGCSSI register is used to enable the clock to SSI modules. We need to write
RCGSSI = 0x0F to enable the clock to all SSI modules.
Fig 4.28. Synchronous Serial Interface Run Mode Clock Gating Control CRCG (SSI) Register
Example:
For a Bit Rate=50 KHz and SCR=03 in SSICR0 register.
The pre-scaler register value for a given system clock frequency of 16MHz, the BR can be calculated
using above formula as:
BR = SysClk / (CPSDVSR × (1 + SCR))
50 KHz = 16 MHz / (X × (1 + 3).
The pre-scaler value is 0x50 in Hex.
SPI module can act like slave or a master. The value in a MS bit in SSI control register 1 (SSICR1)
decide the microcontroller as master or slave. SSE bit in the SSICR1 register is used to enable/
disable the SPI.
Fig 4.36. Flowchart: Interfacing TIVA with Sensor Hub Booster Pack
4.7 Summary
The chapter discusses several serial communication protocols used for data transfer between
microcontroller and external devices. Serial communication protocols like UART, SPI and I2C are used
for connecting various analog sensors, actuators, external components such as memory, camera etc.
The TIVA microcontroller consists of serial modules such as UART, SPI, I2C and CAN protocol
embedded in a single Synchronous communication interface (SCI) module. The chapter discusses the
programming of serial communication modules where the reader will be able to configure and use the
communication protocol with the help of TIVAware peripheral driver library. The chapter concludes with
a case study involving SensorHub BoosterPack interfacing with TIVA microcontroller.
The previous chapter covered the process of communication between devices with wired medium using
different protocols such as UART, I2C, and SPI for sensor based and data logging applications.
As a next step, the current chapter covers IoT applications by configuring the CC3100 Wi-Fi module in
access point mode to achieve the applications like get weather, smart plug etc.
By the end of this chapter, readers can expect to have a better understanding of embedded networking and
know IoT fundamentals including its architecture and applications. This chapter also covers wireless
connectivity protocols and their application areas.
Readers will also acquire knowledge about CC3100 SimpleLink Wi-Fi module and its architecture and learn
how to interface CC3100 module with TIVA Launchpad
Topic Page
5.1 Introduction........................................................................................................................................ 156
5.2 Embedded Networking Fundamentals .............................................................................................. 156
5.3 TCP/IP Introduction IoT overview and architecture .......................................................................... 161
5.4 Wireless Sensor Networks ................................................................................................................ 166
5.5 Various Wireless Protocols and their Applications ............................................................................ 169
5.6 Adding Wi-fi to a Microcontroller-Based System using CC3100 Simplelink Wi-fi Module ............... 171
5.7 Case Studies with SimpleLink Wi-Fi CC3100 and TIVA Launchpad ................................................ 176
5.8 Summary ........................................................................................................................................... 183
5.9 Review Questions ............................................................................................................................. 184
5.1 Introduction
Embedded networking technologies such as ZigBee, NFC, Bluetooth, Wi-Fi etc. are key elements in
designing internet enabled applications. For example, in a residential set-up, these enable control of all
devices remotely, even if there is no one physically present in the house. Such a „Smart home’
allows the owner to monitor and control all smart equipment including power controls, security devices
such as surveillance camera, etc. remotely. That is possible by using Wi-Fi technology, gateway
solutions that provide connection to Cloud and of course the Internet to access the devices. Other
typical application areas are monitoring, smart Grid, Smart Transport, smart plug, wearable devices,
health monitoring etc.
that created it. If a socket has an IP address but not a port number, it is said to be 'unbound'. An
unbound socket cannot receive data because it does not have a complete address. When a socket
has both an IP address and a port number it is said to be 'bound to a port', or 'bound to an address'. A
bound socket can receive data because it has a complete address. The process of allocating a port
number to a socket is called 'binding'.
Client and Server
Servers are applications that wait for and then reply to incoming requests. Clients are applications that
send requests to servers. In this context, the requests and replies go over the network and clients need
to locate servers. Servers do not need to know the client's address in advance, they just send their
replies to the address from which the client's request originated and therefore clients can bind to nearly
any port number.
The sequence diagram below shows a socket being created and bound on both an echo client and an
echo server, and then a single echo transaction between the client and the server. Echo servers simply
echo back the data sent to them by clients.
boots up it contacts the DHCP server to request its IP address, removing the need for each node to be
statically configured.
Sub-netting / Netmask: A subnetwork, or subnet, is a logical, visible subdivision of an IP network. The
practice of dividing a network into two or more networks is called sub-netting. Sub-netting is a way of
determining whether a destination IP address exists on the local network or a remote network. Like the
IP address, the subnet mask can be configured either statically or dynamically from a DHCP server. If
a destination IP address bitwise ANDed with the subnet mask matches the local IP address bitwise
ANDed with the subnet mask then the two IP addresses exist on the same network.
Gateways and Routers: A gateway acts as a conversion from one protocol to another. A router works
by looking at the IP address in the data packet and decides if it is for internal use or if the packet
should move outside the network. If a destination IP address bitwise ANDed with the subnet mask
does not match the local IP address bitwise ANDed with the subnet mask then the two IP addresses
do not exist on the same network. In this case the packet being sent to the destination address cannot
be sent directly, and must instead be sent to a gateway for intelligent inter-network routing.
Domain Name System (DNS): The Domain Name System (DNS) is a hierarchical distributed naming
system for computers, services, or any resource connected to the Internet or a private network. It
associates various information with domain names assigned to each of the participating entities. Most
prominently, it translates domain names, which can be easily memorized by humans, to the numerical
IP addresses needed for the purpose of computer services and devices worldwide. The Domain Name
System is an essential component of the functionality of most Internet services because it is the
Internet's primary directory service. For example, entering "ping www.freertos.org" in the command
console of a desktop computer will show a ping request being sent to the IP address 195.8.66.1 (today
anyway) a DNS server resolved the string "www.freertos.org" to the IP address 195.8.66.1.
Address Resolution Protocol (ARP): The Address Resolution Protocol (ARP) is a telecommunication
protocol used for resolution of network layer addresses into link layer addresses, a critical function in
multiple-access networks.
Assuming a conventional wired network is used, UDP messages are sent in Ethernet frames. UDP
messages are sent between IP addresses, but Ethernet frames are sent between MAC (hardware)
addresses. Therefore, the MAC address of the destination IP address must be known before an
Ethernet frame can be created. The Address Resolution Protocol (ARP) is used to obtain MAC address
information.
In a smart home application, Ethernet can be used to monitor and control entry to the house by
enabling the door sensors of all the entry points. Fig. 5.5 shows the various components of an Ethernet-
based smart home. User can send a command to activate all the door sensors with the click of a
mouse. This message is sent from the user PC to the Gateway device over Ethernet connection. This
gateway device then delivers this message to the network of door sensors using wireless technology
like ZigBee.
Fig. 5.5 Smart Home Architecture with Ethernet interface to the sensor network
Fig. 5.6 Smart Home Architecture with TCP/IP connectivity to the Internet
Adoption: The Internet Protocol is a must and a requirement for any Internet connectivity. It is
the addressing scheme for any data transfer on the web.
Scalability: IPv6 offers a highly scalable address scheme. The present scheme of Internet
Governance provides at most 2 x 1019 unique, globally routable, addresses.
Solving the NAT barrier: Due to the limits of the IPv4 address space, the current Internet had
to adopt a stopgap solution to face its unplanned expansion: the Network Address Translation
(NAT). It enables several users and devices to share the same public IP address. The NAT
users are borrowing and sharing IP addresses with others. While this technique allows single
stakeholders to mount large applications, it becomes completely unmanageable if the same
end-points are to be used by many different stakeholders; this would occur in an IoT
deployment where the same sensors are to be used by multiple, independent, stakeholders.
Secondly the mechanism cannot be used to access specific end-points from the Internet.
Multi-Stakeholder Support: IPv6 provides for end devices to have multiple addresses and an
even more distributed routing mechanism than the IPv4 Internet. This allows different
stakeholders to assign IoT end-device addresses that are consistent with their own application
and network practices. Thus multiple stakeholders can deploy their own applications, sharing a
common sensor/actuation infrastructure, without impacting the technical operation or
governance of the Internet.
encounter wearable devices for entertainment and location tracking. For example, it can be a Bluetooth
headset or a GPS tracker. These devices facilitate the user to help enhance their health and wellness,
and to gather information around the user. At home we are surrounded with an ever-growing number of
appliances, multimedia devices and other consumer gadgets. In home automation systems,
IoT applications include monitoring and controlling the devices inside a home in an intelligent way.
They include lighting and temperature control among the connected appliances for effective use of
energy.
While on-the-go, we use private or public transportation vehicles and infrastructure to improve our
mobility time utilization. In industries, sensors might be introduced for production efficiency,
maintenance and failure management. And at a metropolitan level smart building management
systems include smart cities equipped with smart city lights, residential e-meters, surveillance cameras
for traffic control, pipeline leak detection etc. Healthcare IoT applications include remote monitoring of
patients for example heart rate, blood pressure level etc.
Users are human participants that use services and their own end equipments. They mostly
consume information and may inspire actions through profile settings and other decision-
making processes.
Things are physical or virtual endpoints representing either a data source, data sink or both.
They feed or consume information to and from the Internet.
Services are information aggregators and may provide tools for data analysis of different kinds.
In some cases can be used to carry out actions requested by clients, either users or things.
The different devices and environments needed in IoT can be layered as shown in the Figure 5.3. The
sensors and devices needed in the IoT environment are the bottom layer. The different types of
sensors can be temperature, pressure, moisture etc. The data captured by the sensors needs to be
processed using processors and enabling technologies. The technologies include RFID detection,
motion sensing etc. Some of the technologies that enable these devices are discussed further in the
Wireless Sensor networks section. Examples include Bluetooth, Wi-Fi etc. The processed data can be
stored using cloud infrastructures and thus in turn provide different IoT services. The different types of
IoT services include Home automation, healthcare services, energy management, emergency services
among others.
Connectivity: There is not one connectivity standard that “wins” over the others. There are a
wide variety of wired and wireless standards as well as proprietary implementations used to
connect the things in the IoT. The challenge is getting the connectivity standards to talk to one
another with one common worldwide data currency.
Power management: More things within the IoT need to be battery powered or use energy
harvesting to be more portable and self-sustaining. Line-powered equipment need to be more
energy efficient. The challenge is making it easy to add power management to these devices
and equipment. Wireless charging incorporates connectivity with charge management.
Complexity: Manufacturers are looking to add connectivity to devices and equipment that has
never been connected before to become part of the IoT. Ease of design and development is
essential to get more things connected especially when typical RF programming is complex.
Additionally, the average consumer needs to be able to set-up and use their devices without a
technical background
Rapid evolution: The IoT is constantly changing and evolving. More devices are being added
everyday and the industry is still in its naissance. The challenge facing the industry is the
unknown; unknown devices, unknown applications, unknown use cases. Given this, there
needs to be flexibility in all facets of development. Processors and microcontrollers4 that range
from 16–1500 MHz to address the full spectrum of applications from a microcontroller (MCU) in
a small, energy-harvested wireless sensor node to high-performance, multi-core processors for
IoT infrastructure. A wide variety of wired and wireless connectivity technologies are needed to
meet the various needs of the market. Last, a wide selection of sensors, mixed-signal and
power-management technologies are required to provide the user interface to the IoT and
energy-friendly designs.
There are several fundamental features that a “thing” has to encompass to be a good IoT
solution. Among these, the most important features are energy efficiency, security, data
handling and simplicity.
Energy Efficiency: As the number of devices grows, even small amounts of excessive power
are a noticeable waste. When it comes to power, the challenge is to ensure that adding
Internet connectivity does not impose a change to the power supply. In other words, ideally it
should fit within the existing power budget headroom. The TIVA Launchpad, being an ultra-low
power MCU ensures that the IoT application takes minimal power.
Security: Security is always a challenge in data networks. This challenge intensifies in the case
of the IoT simply because there are more entry points thereby creating more penetration
points. This increased system vulnerability makes the battle for security inevitable. In an IoT
solution, threats also take a new level of magnitude since it is not just data that is put at risk.
With IoT the damage potential is much higher (e.g., opening a door remotely, taking a burglar
alarm system offline). There will surely be a never-ending fight towards better security. This
provides inbuilt security features to address major security requirements.
Data handling: Massive deployment of endpoints results in higher node density. This requires
demand for higher capacity. Furthermore, large quantities of data that are generated create a
need for accessible storage. In addition, real network latency introduces a challenge to limited
resource systems. The TI wireless modules provide easy interfacing with the TIVA Launchpad
to provide connectivity that suits the need of the IoT application.
possible to develop low-power and low-cost sensor nodes that are small in size and communicate
using wireless medium over short distances. The sensor units in the nodes can sense any desired
parameter (like temperature, pressure humidity, movement etc.) in an area that is covered by the
network. The sensed data is then relayed through the network to the base station, where information
can be generated and acted upon to serve the purpose for which the network has been deployed.
WSNs are on the verge of being utilized for many challenging real-life applications like early
earthquake warning systems, battlefield surveillance, environment and habitat monitoring, healthcare,
smart homes and buildings etc... This involves deploying a large number of nodes in the area to be
sensed by the network. This large-scale deployment often requires the nodes to possess self-
organizing capability to form a network without any human intervention. A typical cluster-based sensor
network topology as shown in Fig. 5.10 consists of a base station, cluster-head nodes and sensor
nodes. The base station is normally connected to the outside world through internet link or a user
terminal.
6. Presentation Layer: This layer ensures that the data presented to the application layer is in proper
format and ready to be used. For example, data transmitted in EBCDIC-code by the sender may be
converted at the receiver end by presentation layer to ASCII code format used by the application layer.
7. Application layer: The protocols used in this layer define the user interface that finally displays the
information to the user.
The protocol stack of the OSI model is a valuable reference to understand the working and underlying
differences between many wireless technologies as discussed in the following text.
5.5.2 ZigBee
ZigBee is an industry-standard wireless networking technology that is suitable for applications that
require infrequent low-power data transfer at low data rates within a 100m range, such as inside a
home or a building. It is an IEEE 802.15.4 based specification for a suite of high-level communication
protocols used to create personal area networks (PAN’s) with small, low-power digital radios. ZigBee-
based PAN’s are suitable for applications like - home entertainment and control, building automation,
industrial control and implementing
wireless sensor networks. It operates in
the ISM radio bands with data rates that
can vary from 20 kbit/s to 250 kbit/s.
The protocol stack for ZigBee (Fig. 5.13)
builds on the physical layer and MAC
layer defined in IEEE standard 802.15.4
for low-rate wireless PAN’s (WPAN’s).
To this, ZigBee adds on specifications
for network layer and application layer.
The ZigBee network layer supports star,
tree and mesh network topologies. The
application layer provides an interface
between ZigBee system and the end-
user applications. A ZigBee network
Fig. 5.13 Zigbee Protocol Stack
may consist of the following three types of
devices:
ZigBee Coordinator (ZC): It is the most capable device in the network. Each ZigBee network
must have exactly one coordinator device, and it is responsible to build and maintain the network.
The ZC forms the root of the network and also connects to the other networks.
ZigBee Router (ZR): In addition to communicating with ZC, a ZR device can perform the
function of forwarding/routing data received from other devices.
ZigBee End Device (ZED): A ZED device can only talk to its parent node, a ZC or a ZR device.
5.5.3 Bluetooth
It is an important short-range communication technology that is widely used in smartphones and many
other fixed as well as mobile devices, for data transfer and building personal area networks. It operates
in the 2.4 GHz ISM frequency band and uses frequency hopping spread spectrum technique. Bluetooth
is a packet-based protocol with a master-slave structure. One master may communicate with upto 7
slaves in a piconet. Two or more piconets can be connected to form a bigger network, called a
scatternet. Bluetooth is widely used in applications like handsfree headset, smartphone-to-smartphone
data transfer, wireless communication between smartphone and car-stereo system, cable-free
connection between PC and I/O modules like mouse, keyboard, printer etc.
Bluetooth in its new avatar as Bluetooth Low Energy (BLE) or
Bluetooth Smart, is expected to be a key technology in near future
for wearable devices that will connect to the IoT, probably through
the smartphones and other such options. Bluetooth Smart is meant
to provide low-cost and low-power consumption while maintaining
the same range as Bluetooth.
Application development with Bluetooth Smart: Texas Instrument’s
CC2460 is a wireless MCU that can be used to design
Fig. 5.15 CC2640 Wireless MCU
Bluetooth Smart enabled applications. The CC2640 contains a
32-bit ARM Cortex-M3 processor running at 48-MHz as the
main processor and a rich peripheral feature set, including a unique ultra-low power sensor controller,
ideal for interfacing external sensors and/or collecting analog and digital data autonomously while the
rest of the system is in sleep mode. The Bluetooth Low Energy controller is embedded into ROM and
run partly on an ARM Cortex®-M0 processor. The Bluetooth Smart stack is available free of charge
from www.ti.com.
5.5.4 Wi-Fi
Wi-Fi is a wireless local area network (WLAN) technology that allows electronic devices to network
using the 2.4 GHz or 5 GHz ISM radio bands. It is based on the IEEE 802.11 MAC and physical layer
standards for WLAN and is the most pervasive choice for connectivity with the Internet, especially in
the home LAN environment. Wi-Fi supports very fast data transfer rates, but consumes a lot of power
which makes it unviable for low-power applications. Nevertheless, the embedded networks, wireless
sensor network applications and Internet-of-Things implementations explicitly make use of Wi-Fi as a
preferred choice for connectivity to the Internet.
5.6 Adding Wi-fi to a Microcontroller-Based System using CC3100 Simplelink Wi-fi Module
To illustrate the use of wireless connectivity in embedded networks, this section discusses the usage
of Wi-Fi technology with a microcontroller. Wi-Fi is very widely used to provide connectivity between
user and embedded systems. For example, a user can interact with utility systems (like AC, Garage
door, Coffee machine, etc.) in a smart-home using a smartphone, provided both (smart-home and
smartphone) are connected to the internet.
TI provides low-power and easy-to-use Wi-Fi solutions that include battery-operated Wi-Fi designs with
more than a year of battery life on two AA batteries. TI’s Simple Link Wi-Fi CC3100 module is
a wireless network processor with on-chip Wi-Fi, internet, and robust security protocols. It can be used
to connect any low-cost microcontroller (MCU). A functional block diagram of CC3100 module is shown
in Fig. 5.15
5.6.3 CC3100 SimpleLink Driver and its Application Programming Interface (API)
In order to simplify the development using the SimpleLink Wi-Fi devices, TI provides a simple and user
friendly host driver software. This driver software allows any MCU (like TIVA platform) to interact with a
SimpleLink device and performs the following functions:
Device API – Manages hardware-related functionality such as start, stop, set, and get device
configurations.
WLAN API – Manages WLAN, 802.11 protocol-related functionality such as device mode (station, AP,
or P2P), setting provisioning method, adding connection profiles, and setting connection policy.
Socket API – The most common API set for user applications, and adheres to BSD socket APIs.
NetApp API – Enables different networking services including the Hypertext Transfer Protocol (HTTP)
server service, DHCP server service, and MDNS client\server service.
NetCfg API – Configures different networking parameters, such as setting the MAC address, acquiring
the IP address by DHCP, and setting the static IP address.
File System API – Provides access to the serial flash component for read and write operations of
networking or user proprietary data.
5.6.4 Programmer’s model for CC3100 SimpleLink driver and its API
A programmer using a SimpleLink device needs to know about the different software blocks needed to
build a networking application. This topic describes the recommended flow for most applications.
However, program developers have complete flexibility on how to use the various software blocks.
Programs using the SimpleLink device consist of the following software blocks:
o Wi-Fi subsystem initialization – Wakes the Wi-Fi subsystem from the hibernate state.
o Configuration – WiFi sub-system. This phase refers to init time configuration that does not
happen very often. For instance, changing the WiFi sub-system from a WLAN STA to WLAN
soft AP, changing the MAC address and so forth.
o WLAN connection – The physical interface needs to be established. There are numerous
ways to do so, all of which will be explained in this document. The simplest way is to manually
connect to an AP as a wireless station.
DHCP – Although not an integral part of the WLAN connection, you need to wait for
the receiving
IP address before continuing to the next step of working with TCP\UDP sockets.
o Socket connection – At this point, it is up to the application to set up their TCP\IP layer.
Separate this phase into the following parts:
Creating the socket – Choosing to use TCP, UDP or RAW sockets, whether to use a
client or a server socket, defining socket characteristics such as blocking\non-
blocking, socket timeouts, and so forth.
Querying for the server IP address – In most occasions, when implementing a client
side communication, you will not know the remote server side IP address, which is
required for establishing the socket connection. This can be done by using DNS
protocol to query the server IP address by using the server name.
Creating socket connection – When using the TCP socket, it is required to establish
a proper socket connection before continuing to perform data transaction.
o Data transactions – Once the socket connection was established, it is possible to transmit
data both ways between the client and the server. Basically implementing the application logic.
o Socket disconnection – Upon finishing the required data transactions, it is recommended to
perform a graceful closure of the socket communication channel.
o Wi-Fi subsystem hibernate – When not working with the Wi-Fi subsystem for a long period of
time, it is recommended to put it into hibernate mode.
5.7 Case Studies with SimpleLink Wi-Fi CC3100 and TIVA Launchpad
Fig 5.22 Flowchart for configuring a static IP address for CC3100 module
In this case study the module CC3100 is configured as a Wireless Local Area Network (WLAN) Station
to connect to the internet and open weather.org as a server. A wireless local area network (WLAN) is a
wireless computer network that connects two or more devices without wires within a confined area for
example within a building. This facilitates the users to stay connected without physical wiring
constraints and also access Internet. Wi-Fi is based on IEEE 802.11 standards including IEEE 802.11a
and IEEE802.11b.
All nodes that connect over a wireless network are referred to as stations (STA). Wireless stations can
be categorized into Wireless Access Points (AP) or clients. Access Points (AP) work as the base station
for a wireless network. The Wireless clients could be any device such as computers, laptops, mobile
devices, smartphones etc. The flowchart for this case study is shown in fig. 5.23.
If we configure CC3100 as a server then it will be in Access Point (AP) mode with a pre-defined SSID-
NAME and uses the sample HTML pages stored in Flash which can be accessed by the clients. Clients
can connect to CC3100 and request for web-pages using the IP of device from any standard web
browser. There are pre-programmed html pages already residing on the flash and new HTML pages
can be downloaded on serial-flash of CC3100 using CCS_UniFlash utility using a separate tool EMU-
BOOST. The scope of this study will be to use the existing html pages already pre-programmed in the
flash by default. The flowchart for using CC3100 device as a HTTP server is given in fig. 5.24
5.8 Summary
The various connectivity protocols for realizing IoT applications are discussed. TI specific Wi-Fi
connectivity module and its interfacing with TIVA Launchpad is also implemented at the later stage of
the chapter. Various Wi-Fi connectivity concepts used to integrate microcontroller devices with cloud
Systems are also highlighted in the chapter. By understanding these technologies students are able to
implement Wi-Fi connectivity in microcontroller and able to design internet enabled IoT devices.\
Texas Instruments Incorporated (‘TI”) technical, application or other design advice, services or information, including, but not limited to,
reference designs and materials relating to evaluation modules, (collectively, “TI Resources”) are intended to assist designers who are
developing applications that incorporate TI products; by downloading, accessing or using any particular TI Resource in any way, you
(individually or, if you are acting on behalf of a company, your company) agree to use it solely for this purpose and subject to the terms of
this Notice.
TI’s provision of TI Resources does not expand or otherwise alter TI’s applicable published warranties or warranty disclaimers for TI
products, and no additional obligations or liabilities arise from TI providing such TI Resources. TI reserves the right to make corrections,
enhancements, improvements and other changes to its TI Resources.
You understand and agree that you remain responsible for using your independent analysis, evaluation and judgment in designing your
applications and that you have full and exclusive responsibility to assure the safety of your applications and compliance of your applications
(and of all TI products used in or for your applications) with all applicable regulations, laws and other applicable requirements. You
represent that, with respect to your applications, you have all the necessary expertise to create and implement safeguards that (1)
anticipate dangerous consequences of failures, (2) monitor failures and their consequences, and (3) lessen the likelihood of failures that
might cause harm and take appropriate actions. You agree that prior to using or distributing any applications that include TI products, you
will thoroughly test such applications and the functionality of such TI products as used in such applications. TI has not conducted any
testing other than that specifically described in the published documentation for a particular TI Resource.
You are authorized to use, copy and modify any individual TI Resource only in connection with the development of applications that include
the TI product(s) identified in such TI Resource. NO OTHER LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE TO
ANY OTHER TI INTELLECTUAL PROPERTY RIGHT, AND NO LICENSE TO ANY TECHNOLOGY OR INTELLECTUAL PROPERTY
RIGHT OF TI OR ANY THIRD PARTY IS GRANTED HEREIN, including but not limited to any patent right, copyright, mask work right, or
other intellectual property right relating to any combination, machine, or process in which TI products or services are used. Information
regarding or referencing third-party products or services does not constitute a license to use such products or services, or a warranty or
endorsement thereof. Use of TI Resources may require a license from a third party under the patents or other intellectual property of the
third party, or a license from TI under the patents or other intellectual property of TI.
TI RESOURCES ARE PROVIDED “AS IS” AND WITH ALL FAULTS. TI DISCLAIMS ALL OTHER WARRANTIES OR
REPRESENTATIONS, EXPRESS OR IMPLIED, REGARDING TI RESOURCES OR USE THEREOF, INCLUDING BUT NOT LIMITED TO
ACCURACY OR COMPLETENESS, TITLE, ANY EPIDEMIC FAILURE WARRANTY AND ANY IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF ANY THIRD PARTY INTELLECTUAL
PROPERTY RIGHTS.
TI SHALL NOT BE LIABLE FOR AND SHALL NOT DEFEND OR INDEMNIFY YOU AGAINST ANY CLAIM, INCLUDING BUT NOT
LIMITED TO ANY INFRINGEMENT CLAIM THAT RELATES TO OR IS BASED ON ANY COMBINATION OF PRODUCTS EVEN IF
DESCRIBED IN TI RESOURCES OR OTHERWISE. IN NO EVENT SHALL TI BE LIABLE FOR ANY ACTUAL, DIRECT, SPECIAL,
COLLATERAL, INDIRECT, PUNITIVE, INCIDENTAL, CONSEQUENTIAL OR EXEMPLARY DAMAGES IN CONNECTION WITH OR
ARISING OUT OF TI RESOURCES OR USE THEREOF, AND REGARDLESS OF WHETHER TI HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
You agree to fully indemnify TI and its representatives against any damages, costs, losses, and/or liabilities arising out of your non-
compliance with the terms and provisions of this Notice.
This Notice applies to TI Resources. Additional terms apply to the use and purchase of certain types of materials, TI products and services.
These include; without limitation, TI’s standard terms for semiconductor products http://www.ti.com/sc/docs/stdterms.htm), evaluation
modules, and samples (http://www.ti.com/sc/docs/sampterms.htm).
Mailing Address: Texas Instruments, Post Office Box 655303, Dallas, Texas 75265
Copyright © 2017, Texas Instruments Incorporated