Book DSP Frank Bormann PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 712

Introduction

Welcome to the F2833x - Tutorial


Welcome to the Texas Instruments TMS320F28335 Tutorial. This material is intended to be
used as a student guide for a series of lessons and lab exercises dedicated to the
TMS320F28335 Digital Signal Controller. The series of modules will guide you through the
various elements of this device, as well as train you in using Texas Instruments development
tools and additional resources from the Internet.
The material should be used for undergraduate classes at university. A basic knowledge of
microprocessor architecture and programming microprocessors in language C is necessary.
The material in Modules 1 to 10 shall be used in one semester, accompanied by lab exercises
in parallel. Each module includes a detailed lab procedure for self study and guidance during
the lab sessions.
The experimental lab sessions are based on the Texas Instruments “Peripheral Explorer
Board” (TI part number: TMDSPREX28335). A 32K code-size limited version of the
software design suite “Code Composer Studio” that is bundled with the Peripheral Explorer
Board is used for the development of code examples.
Modules 11 to 19 of the series go deeper into details of the TMS320F28335. They cover
more advanced subjects and can be seen as an optional series of lessons.

Module 1: Introduction

Digital Signal Controller


TMS320F28335
Texas Instruments Incorporated
European Customer Training Centre &
University of Applied Sciences Zwickau

1-1

DSP2833x - Introduction 1-1


Module Topics

Module Topics

Introduction ....................................................................................................................................... 1-1


Welcome to the F2833x - Tutorial ................................................................................................... 1-1
Module Topics ................................................................................................................................. 1-2
CD – ROM Structure ....................................................................................................................... 1-3
Installation and Laboratory Preparation ........................................................................................ 1-4
Piccolo F28027-USB stick .............................................................................................................. 1-5
Template Files for Laboratory Exercises ........................................................................................ 1-6
What is a Digital Signal Controller? .............................................................................................. 1-8
A typical microprocessor block diagram .................................................................................... 1-9
Arithmetic Logic Unit (“ALU”) of a microprocessor ............................................................... 1-11
The Desktop – PC: a Microcomputer ....................................................................................... 1-13
The Microcontroller: a single chip computer ............................................................................ 1-15
The MSP430 – a typical micro controller ................................................................................. 1-16
A Digital Signal Processor ........................................................................................................ 1-17
The “Sum of Product” – Equation ............................................................................................ 1-18
A SOP executed by a DSP ........................................................................................................ 1-20
A Digital Signal Controller ....................................................................................................... 1-21
DSP Competition ........................................................................................................................... 1-22
Texas Instruments DSP/DSC – Portfolio ...................................................................................... 1-23
TMS320F28x Roadmap ................................................................................................................. 1-25
TMS320F28x Application Areas ................................................................................................... 1-26
TMS320F28x Block Diagram........................................................................................................ 1-26

1-2 DSP2833x - Introduction


CD – ROM Structure

CD – ROM Structure

Chapter 1: Introduction to Microprocessor, MCU and DSP


Chapter 2: TMS320F28335 Architecture
Chapter 3: Software Development Tools
Chapter 4: Fixed Point, Floating Point or both?
Chapter 5: Digital Input/Output
Chapter 6: Understanding the F28335 Interrupt System
Chapter 7: Control Actuators and Power Electronics
Chapter 8: Sensor Interface - Analogue to Digital Converter
Chapter 9: Communication I: Serial Communication Interface
Chapter 10: Communication II: Serial Peripheral Interface
Chapter 11: Communication III: Controller Area Network (CAN)
Chapter 12: Communication IV: Inter Integrated Circuit®
Chapter 13: Communication V: Multi Channel Buffered SerialPort
Chapter 14: Internal FLASH Memory and stand alone control
Chapter 15: Boot – loader and Field update
Chapter 16: FLASH – Application Program Interface (API)
Chapter 17: IQ-Math and floating point hardware
Chapter 18: Digital Motor Control
Chapter 19: Digital Power Supply

DSP2833x - Introduction 1-3


Installation and Laboratory Preparation

Installation and Laboratory Preparation


This paragraph is for teachers / instructors only. If you read this textbook as a student, please
continue at Page 1-8.
The following preparations are necessary to use and run the laboratory exercises of this
tutorial:
1. A valid and working version of Code Composer Studio, Version 4.1 should be
installed. The default folder is “C:\Program Files\Texas Instruments\ccsv4”.
Some of the examples will refer to the subfolder “C:\Program Files\Texas
Instruments\ccsv4\C2000” to access C run-time support libraries and linker
command files. All laboratory procedures will reference this location. If your
installation was made to a different directory, you will have to inform your
students.
If you do not have a valid CCS4.1 installation, please use the CCS4.1 - DVD,
which comes with the Peripheral Explorer Board. To install and setup CCS4.1,
please follow the guidelines from the Texas Instruments wiki-page
(http://processors.wiki.ti.com/index.php/C2000_Getting_Started_with_Code_C
omposer_Studio_v4).
2 The Peripheral Explorer Board “Quick Start Guide” (sprugm2.pdf) describes the
hardware environment in detail. The file “sprugm2.pdf” can be found in folder
“C2833x_CCS4/hardware” of the C2000 teaching CD-ROM.
3. Install the Peripheral Register Header File support package. All laboratory
exercises expect to find the Header File package version 1.31 (sprc530.zip)
installed in folder “C:\tidcs\c28\DSP2833x\v131”. If it is not yet installed, you
can find the zip-file at the teaching CD-ROM under “C2833x_CCS4/libraries”.
4. For IQ-Math based exercises you have to install the IQ-Math library
(sprc087.zip). The default location is “C:\tidcs\c28\IQmath\v15a”. If this library
is not yet installed, you can find the zip-file at the teaching CD-ROM under
“C2833x_CCS4/libraries”.

1-4 DSP2833x - Introduction


Piccolo F28027-USB stick

Piccolo F28027-USB stick


This teaching CD-ROM and all Laboratory exercises are based on the TMS320F28335
processor and the Peripheral Explorer Board. For the TMS320F28027 Texas Instruments
offers an ultra low cost evaluation kit (TMDX28027USB):

For the most important peripheral unit, the Pulse Width Modulation Unit (PWM), the
teaching CD-ROM provides a dedicated chapter (Module 7A), which describes the
laboratory procedures and provides the laboratory templates and solutions for more than 10
exercises. These documents can be found in folder “C2833x_CCS4/Modules/Module7” of
the teaching CD-ROM (files “Module_07_A.pdf”and “Solution_07_A.zip”).
For other peripheral units of the F28027, you can easily start with the F28335 examples of
this CD-ROM. Just modify the source code of the F28335 examples and you can run the
examples also with a F28027. Of course, the USB-stick does not have all the additional
external devices of the Peripheral Explorer Board, which must be added manually to the
USB stick. For convenience, the corresponding Header File support package (sprc832.zip)
for the F28027 is also part of the teaching CD-ROM, as well as some additional support files
(sprc835.zip). Both files can be found in folder “C2833x_CCS3/libraries” of the teaching
CD-ROM.

DSP2833x - Introduction 1-5


Template Files for Laboratory Exercises

Template Files for Laboratory Exercises


All modules are accompanied by laboratory exercises. For some of the modules template
files are provided with the CD (“lab template files”), for other modules the students are
expected to develop their own project files out of previous laboratory sessions. In these cases
the lab description in the textbook chapter explains the procedure. A 2nd group of project
files (“solution files”) provides a full solution directory for all laboratory exercises. This
group is intended to be used by teachers only. Instead of a single zip-file for the whole CD-
ROM we decided to use separate archive files for the individual modules. This gives the
teacher the opportunity to select parts of the CD to be used in his classes.
The zip-files should be extracted to a working directory of your choice. However, the
textbook assumes that the files are located in: “C:\DSP2833x\Labs” for group #1 and
“C:\DSP2833x\solution” for group #2. When extracted, a subfolder named with the exercise
number will be added.

The laboratory exercises are:


Lab3: “Beginner’s project” - basic features of Code Composer Studio
Lab4_1: “Numbering Systems” - fixed-point multiply operation
Lab4_2: “Numbering Systems” - floating-point multiply (hardware and software)

Lab5_1: “Digital Output” - 4 LEDs binary counter-sequence


Lab5_2: “Digital Output” - 4 LEDs blinking “knight-rider”
Lab5_3: “Digital Input” - read 4 bit hexadecimal encoder and display value
Lab5_4: “Digital Input / Output” - speed control of binary counter by hex-encoder
Lab5_5: “Digital Input / Output” - additional start/stop push-buttons

Lab6: “CPU-Timer 0 and Interrupts” - add a hardware timer to Lab5_1 and use an
interrupt service routine (hardware time base
framework)

Lab7_1: “Pulse Width Modulation” - generate a single ePWM ( e = “enhanced”) output


signal
Lab7_2: “3 – Phase PWM” - generate a phase shifted set of 3 ePWM – signals
Lab7_3: “variable Pulse Width” - generate a 1 kHz – signal with variable pulse
width
Lab7_4: “dual complementary PWM” - generate a pair of complementary PWM signals
Lab7_5: “dual channel modulation” - independent modulation of pulse width at
ePWMA and ePWMB
Lab7_6: “Dead Band Generator” - generate a dead band delay at ePWMA and
ePWMB
Lab7_7: “Chopper Mode Unit” - split the active pulse phases in a series of high
frequency pulses
Lab7_8: “Trip Zone Protection” - switch off power lines in case of an over – current
Lab7_9: “Sinusoidal Signal” - use ePWM to generate sinusoidal signals (class D
audio amplifiers)
Lab7_10:”Capture Unit” - use a capture unit to measure a 1 kHz - signal
Lab7_11: “Radio Remote Control Unit” - use a capture unit to receive and decode an
infrared radio remote control unit (RC5-code)

1-6 DSP2833x - Introduction


Template Files for Laboratory Exercises

Lab8_1: “ADC dual conversion” - convert two analogue input voltages


Lab8_2: “ADC and control” - speed control of binary counter by ADCINA0

Lab9_1: “SCI - transmission” - send text message “F28335 UART is fine!”


Lab9_2: “SCI – transmit interrupts” - use of SCI – transmit interrupt services
Lab9_3: “SCI – transmit FIFO” - use of SCI – FIFO for transmission
Lab9_4: “SCI – receive and transmit” - wait for message “Texas” and answer with
“Instruments”
Lab9_5: “SCI – remote control” - control speed of binary counter by SCI – message

Lab11_1: “CAN – Transmission” - periodic transmission of a binary counter at 100


kbit/s and Identifier 0x1000 0000
Lab11_2: “CAN - Reception” - Receive Identifier 0x1000 0000 at 100 kbit/s and
display the message at 2 LED’s.
Lab11_3:“CAN – Transmit & Receive” - merger of Lab11_1 and Lab11_2
Lab11_4:”CAN – Interrupt” - use of CAN – interrupts to receive messages
Lab11_5:”CAN – Error – Handling” - use of CAN – error interrupts
Lab11_6:”CAN – Remote Transmit Request” – use of CAN transmit requests

Lab12_1:”I2C – Temperature Sensor” - use of TMP101 in 9 bit resolution mode


Lab12_2:”I2C – Temperature Sensor” - use of TMP101 in 12 bit resolution mode
Lab12_3:”I2C – Temperature Sensor” - use of I2C –FIFO – registers for TMP101
Lab12_4:”I2C – Temperature Sensor” - use of I2C – Interrupt System

Lab13_1:”McBSP and SPI” - use of audio codec AIC23B to generate a single


sinusoidal tone
Lab13_2:”McBSP and SPI” - use of audio codec AIC23B to generate a stereo
sinusoidal tone
Lab13_3:”McBSP - Interrupts” - Lab13_2 plus McBSP – interrupt system
Lab13_4:”McBSP – SPI – Emulation” - Write and Read to an SPI – EEPROM AT25256

Lab 14_1: “Standalone FLASH” - change Lab6 to run directly from FLASH after
power ON.
Lab 15_1: “SCI - Boot loader - download control code before start

Lab16_1: “FLASH – API” - update FLASH while the control code is running

Lab17: “IQ-MATH” - use of a digital low-pass filter in IQ-Math,


generate a 2 KHz square wave signal, sample the
signal with the Analogue to Digital Converter
and calculate the low-pass filter.
Lab18: “Digital Motor Control” - Labs are based on Texas Instruments “Digital
Motor Control Kit” (part number:
TMDS2MTRPFCKIT); see laboratory
descriptions, which are included in the software
part of this kit.
Lab19: “Digital Power Supply” - Labs are based on Texas Instruments “Digital
Power Experimenter’s Kit” (part number
“TMDSDCDC2KIT”); see laboratory
descriptions, which are included in the software
part of this kit.

DSP2833x - Introduction 1-7


What is a Digital Signal Controller?

What is a Digital Signal Controller?


First we have to discus some keywords that are quite often used when we speak about digital
control or computing in general. The TMS320F28335 belongs to a group of devices that is
called a “Digital Signal Controller (DSC)”. In computing, we use words like
“Microprocessor”, “Microcomputer” or “Microcontroller” to specify a given sort of
electronic device. When it comes to digital signal processing, the preferred name is “Digital
Signal Processors (DSP)”.
To begin with, let us introduce some terms:
• Microprocessor (µP)
• Micro Computer
• Microcontroller (µC)
• Digital Signal Processor (DSP)
• Digital Signal Controller (DSC)

1. what is a microprocessor?
microprocessor (µP, mp):
– Central Device of a multi chip Micro Computer System
– Two basic architectures:
» “von Neumann”- Architecture
» “Harvard” – Architecture

– “von Neumann” - Architecture:


» Shared memory space between code and data
» Shared memory busses between code and data
» Example: Intel‘s x86 Pentium Processor family

– “Harvard” – Architecture:
» Two independent memory spaces for code and data
» Two memory bus systems for code and data

– A µP needs additional external devices to operate properly

1-2

Microprocessors are based on a simple sequential procedural approach: Read next machine
code instruction from code memory, decode instruction, read optional operands from data
memory, execute instruction and write back result. This series of events runs in an endless
manner. To use a µP one has to add memory and additional external devices to the
Microprocessor.

1-8 DSP2833x - Introduction


What is a Digital Signal Controller?

A typical microprocessor block diagram

Microprocessor block diagram

code
memory

Control Unit

process
process

Central
input output –
Processing Unit
module CPU module

Microprocessor

data
memory

1-3

A typical microprocessor block diagram is shown above. As can be seen from slide 1-3, the
microprocessor consists of two parts – the control unit and the central processing unit (CPU).
It operates on input signals, reads operands from data memory, writes results back in data
memory, and updates output modules. All computing is based on machine code instructions,
which are sequentially stored in code memory. The microprocessor reads these instructions
one after each other into its control logic.
The execution flow of a piece of machine code instructions follows a certain sequence,
shown in the following slide. Life of a micro processor is quite boring; it never goes off the
beaten track unless it loses its power supply. The sequence is always:
1. Address the next entry in code memory
2. Read (or “fetch”) the next machine instruction from this very address
3. Look, what’s up (“decode” that instruction and prepare next activities)
4. Select one of five next steps:
• Read an input and compute it
• Read an entry from data memory and compute it
• Do an internal operation, which does not require an information exchange
• Write a result back in data memory
• Update an output channel with a result of a previous computation.

Note: Some processors are able to perform more than 1 step in parallel.
5. Calculate the next code memory address and return to step #1.

DSP2833x - Introduction 1-9


What is a Digital Signal Controller?

Microprocessor execution flow


program counter (PC) in control unit addresses
first (next) instruction in code memory

instruction read (“fetch”) from code memory


into microprocessors instruction register (IR)

decode instruction and 1 of the following actions:

read input read data memory internal update write data


& compute & compute operation output memory

increment or modify program counter

1-4

The heart of a micro processor is its Central Processing Unit (CPU). To keep it simple, we
just look at a very basic structure of a CPU. Today a microprocessor is really one of the most
complex integrated circuits.

CPU of a microprocessor
CPU = Central Processing Unit
• Consists of:
– few internal memory cells (“Register”) for operands
– calculation unit: “Arithmetic Logic Unit” (ALU)
– instruction register (IR) and instruction decoder
– address unit

• Address unit:
– read data and instruction from memory
– write data into memory
• Instruction decoder:
– analyses current instruction and controls subsequent actions of
other modules
• Register:
– store data for instantaneous instruction and computation

Note: today's microprocessors have a much finer granularity and


sometimes parallel units. However, the basics are still the very
same.

1-5

1 - 10 DSP2833x - Introduction
What is a Digital Signal Controller?

Arithmetic Logic Unit (“ALU”) of a microprocessor

ALU (Arithmetic Logic Unit) of a microprocessor


calculates arithmetical and / or logical functions:
At least:
arithmetical : Addition (ADD)
logical: Negation (NEG)
Conjunction (AND)
typical:
arithmetical: Subtraction (SUB)
Multiplication (MUL)
logical: Comparison (CMP)
Disjunction (OR)
Antivalence (EXOR)
miscellaneous: Right- and Left Shift (ASR,ASL)
Rotation (ROL, ROR)
Register-Bit-Manipulation (set, clear, toggle, test)

• a ALU is able to process two binary values with equal length (N)
 N-Bit ALU with N = 4,8,16,32 or 64
• most ALU’s process Fixed Point Numbers
• A few ALU’s, used especially in Digital Signal Processors and
desktop processors, are capable to operate on Floating Point
Numbers or on both formats.

1-6

An ALU performs the arithmetic and logic operations that the microprocessor is capable of.
A minimal requirement for an ALU is to perform ADD, NEG and AND. Other operations
shown in the slide above, improve the performance of a specific microprocessor. A virtual
ALU could look like this:

Example: a simple ALU structure

A, B, Y: Internal register
F: Functional code
C: Carry – Bit
N: Negative – Bit
Z: Zero - Bit

ALU’s are also available


Note : most ALU will generate a size of 2*n for register Y as standalone ICs:
in case of a multiply operation Y = A * B SN 74 LS 181

1-7

DSP2833x - Introduction 1 - 11
What is a Digital Signal Controller?

The Intel 80x86: the legacy microprocessor

History (1984): Microprocessor Intel 80x86

Address – Unit Bus - Unit address

control/
status
- Memory Manager - Bus Control
- logical / physical - Address & Data Bus – data
address Interface
- Instruction Queue

Execution - Unit Instruction – Unit

- CPU - Decode Instruction


- ALU - Operation Queue
- Register

1-8

The Intel 8086 can be considered to be the veteran of all 16-bit microprocessors. Inside this
processor four units take care of the sequence of states. The bus-unit is responsible for
addressing the external memory resources using a group of unidirectional digital address
signals, bi-directional data lines and control and status signals. Its purpose is to fill a first
pipeline, called the “instruction queue” with the next machine instructions to be processed. It
is controlled by the Execution unit and the Address-Unit.
The Instruction unit reads the next instruction out of the Instruction queue decodes it and fills
a second queue, the “Operation queue” with the next internal operations that must be
performed by the Execution Unit.
The Execution Unit does the ‘real’ work; it executes operations or calls the Bus Unit to read
an optional operand from memory.
Once an instruction is completed, the Execution Unit forces the Address Unit to generate the
address of the next instruction. If this instruction was already loaded into the Instruction
queue, the operational speed is increased. This principle is called a “cache”.
We could go much deeper into the secrets of a Microprocessor; eventually you can book
another class at your university that deals with this subject much more in detail, especially
into the pros and cons of Harvard versus Von-Neumann Machines, into RISC versus CISC,
versions of memory accesses etc.
For now, let us just keep in mind the basic operation of this type of device.

1 - 12 DSP2833x - Introduction
What is a Digital Signal Controller?

The Desktop – PC: a Microcomputer


When we add external devices to a microprocessor, we end up with the set-up for a computer
system. We need to add external memory both for instructions (“code”) and data to be
computed. We also have to use some sort of connections to the outside world to our system.
In general, they are grouped into digital input/outputs and analogue input/outputs.
The following Slide 1-9 is a simplified block diagram of a typical microcomputer. As you
can imagine, the latest designs of microcomputers are much more complex and are equipped
with a lot more hierarchical levels. To keep it simple, let us focus on such a simplified
architecture first.

2. our Desktop – PC is a?

2. Microcomputer
– Microcomputer = microprocessor (µP) + memory +
peripherals
– Example: your Desktop -PC

Code - Memory Data - Memory


Memory Bus

Clock Microprocessor Timer/Counter


Peripheral Bus

Digital In Digital Out Analogue In Analogue Out

1-9

In general, the microprocessor in a microcomputer is connected to the memory system via a


“memory” bus. In “von -Neumann” – microprocessor architectures this bus is a shared bus
between code and program memory. Whereas in “Harvard” – microprocessor architectures
this bus system is separated into two independent and parallel bus systems.
The “Peripheral” bus in the slide above connects the microprocessor to units, which allow
the processor to communicate with its environment (sensors, actuators, communication lines
etc.). Some microcomputers use a dedicated “Peripheral” bus, as shown in Slide 1-9,
whereas other devices integrate these peripheral functions into their data memory and call it
“Data Memory mapped Peripherals”.

DSP2833x - Introduction 1 - 13
What is a Digital Signal Controller?

Microcomputer Peripherals
The following slide (Slide 1-10) is a non-exclusive list of some of the peripheral functions of
a microcomputer. Peripherals are the interface of a microcomputer to the “real world”.
These units allow a microcomputer to communicate with sensors, actuators and to exchange
data and information with other nodes through network interface units.

microcomputer - peripherals
• Peripherals include:

– Digital Input / Output Lines


– Analogue to Digital Converter (ADC)
– Digital to Analogue Converter (DAC)
– Timer / Counter units
– Pulse Width Modulation (PWM) Digital Output Lines
– Digital Capture Input Lines
– Network Interface Units:
» Serial Communication Interface (SCI) - UART
» Serial Peripheral Interface (SPI)
» Inter Integrated Circuit ( I2C) – Bus
» Controller Area Network (CAN)
» Local Interconnect Network (LIN)
» Universal Serial Bus (USB)
» Local / Wide Area Networks (LAN, WAN)
– Graphical Output Devices
– and more …

1 - 10

Modern microcomputers are equipped with a lot of enhanced peripheral units. To keep it
simple, let us focus on basic peripheral unite here. If you are more familiar with
microcomputers and you like to work with such hardware units you can easily inspect all
those facinating peripheral units of a state of the art microcomputer.

1 - 14 DSP2833x - Introduction
What is a Digital Signal Controller?

The Microcontroller: a single chip computer


As technology advances, we want the silicon industry to build everything that is necessary
for a microcomputer into a single piece of silicon, and we end up with a microcontroller
(“µC”). Of course nobody will try to include every single peripheral that is available or
thinkable into a single chip – because nobody can afford to buy this “monster”-chip. On the
contrary, engineers demand a microcontroller that suits their applications best and – for
(almost) nothing. This leads to a huge number of dedicated microcontroller families with
totally different internal units, different instruction sets, different number of peripherals and
internal memory spaces. No customer will ask for a microcontroller with an internal code
memory size of 16 megabytes, if the application fits easily into 64 kilobytes.
Today, microcontrollers are built into almost every industrial product that is available on the
market. Try to guess, how many microcontrollers you possess at home! The problem is you
cannot see them from outside the product. That is the reason why they are also called
“embedded” computer or “embedded” controller. A sophisticated product such as the
modern car is equipped with up to 80 microcontrollers to execute all the new electronic
functions like antilock braking system (ABS), electronic stability program (ESP), adaptive
cruise control (ACC), central locking, electrical mirror and seat adjustments, etc. On the
other hand a simple device such as a vacuum cleaner is equipped with a microcontroller to
control the speed of the motor and the filling state of the cleaner. Not to speak of the latest
developments in vacuum cleaner electronics: the cleaning robot with lots of control and
sensor units to do the housework – with a much more powerful µC of course.
Microcontrollers are available as 4, 8, 16, 32 or even 64-bit devices, the number giving the
amount of bits of an operand that are processed in parallel. If a microcontroller is a 32-bit
type, the internal data memory is connected to the core unit with 32 internal signal lines.

3. System on Chip

3. Microcontroller (µC, MCU)

– Nothing more than a Microcomputer as a single


silicon chip!
– All computing power and input/output channels that
are required to design a real time control system are
“on chip”
– Guarantee cost efficient and powerful solutions for
embedded control applications
– Backbone for almost every type of modern product

– Over 200 independent families of µC


– Both µP – Architectures (“Von Neumann” and
“Harvard”) are used inside Microcontrollers

1 - 11

DSP2833x - Introduction 1 - 15
What is a Digital Signal Controller?

The MSP430 – a typical micro controller

3. Example: Microcontroller MSP430

Texas Instruments MSP430


von-Neumann architecture — all program, data memory
and peripherals share a common bus structure.
1 - 12

There are hundreds of types of micro controllers in the highly competitive market of
embedded systems. They all have their pro and cons. Depending on the application area,
budget limitations and on project requirements one has to decide, which one is the best suited
one. The slide above shows a block diagram of one of the most power effective micro
controllers in the market – the MSP430. It comes with integrated memory blocks – FLASH
for non - volatile storage of code sequences and RAM to store variables and results. It is
equipped with internal analog and digital peripherals, communication channels.

The MSP430 family contains much more enhanced versions as shown in the block diagram
at Slide 1-12. Some members of this family have integrated LCD display drivers, hardware
multipliers or direct memory access (DMA) units, just to name a few. If you are more
interested in that family, please use the corresponding Texas Instruments Teaching CD-ROM
for that family.

1 - 16 DSP2833x - Introduction
What is a Digital Signal Controller?

A Digital Signal Processor


A Digital Signal Processor is a specific device that is designed around the typical
mathematical operations to manipulate digital data that are measured by signal sensors. The
objective is to process the data as quickly as possible to be able to generate an output stream
of ‘new’ data in “real time”.

4. Digital Signal Processor

A Digital Signal Processor (“DSP”) is:

– Similar to a microprocessor (µP), e.g. core


of a computing system

– Additional Hardware Units to speed up


computing of sophisticated mathematical
operations:
» Additional Hardware Multiply Unit(s)
» Additional Pointer Arithmetic Unit(s)
» Additional Bus Systems for parallel access
» Additional Hardware Shifter for scaling
and/or multiply/divide by 2n

1 - 13

What are typical DSP algorithms?


An equation, called “Sum of Products” (SOP) is
the key element in most DSP algorithms:

Algorithm Equation

Finite Impulse Response Filter

Infinite Impulse Response Filter

Convolution

Discrete Fourier Transform

Discrete Cosine Transform

1 - 14

DSP2833x - Introduction 1 - 17
What is a Digital Signal Controller?

The “Sum of Product” – Equation


We won’t go into the details of the theory of Digital Signal Processing now. Again, look out
for additional classes at your university to learn more about the maths behind this amazing
part of modern technology. I highly recommend it. It is not the easiest topic, but it is worth it.
Consider a future world without anybody that understands how a mobile phone or an
autopilot of an airplane does work internally – a terrible thought.
To begin with, let us scale down the entire math’-s into one basic equation that is behind
almost all approaches of Digital Signal Processing. It is the “Sum of Products”- formula. A
new value ‘y’ is calculated as a sum of partial products. Two arrays “data” and “coeff” are
multiplied as pairs and the products are added together. Depending on the data type of the
input arrays we could solve this equation in floating point or integer mathematics. Integer is
most often also called “fixed - point” maths (see Chapter 2).
In contrast to its predecessor the TMS320F28335 is both a floating-point and also fixed-
point device, so we can use the best of both worlds. To keep it simple for now, let’s stay with
fixed - point mathematics first. In chapter 2 we will discuss the pros and cons of fixed point
versus floating point DSPs a little bit more in depth.
In a standard ANSI-C we can easily define two arrays of integer input data and the code lines
that are needed to calculate the output value ‘y’:

Doing a SOP with a µP


3
y = ∑ data[i ] * coeff [i ]
i =0

• Task : use a Desktop - PC and code the equation into


any common C-compiler system, e.g. Microsoft Visual
Studio 2008
• A C-Code Solution would probably look like:
#include <stdio.h>
int data[4]={1,2,3,4};
int coeff[4]={8,6,4,2};
int main(void)
{
int i;
int result =0;
for (i=0;i<4;i++)
result += data[i]*coeff[i];
printf("%i",result);
return 0;
}
1 - 15

1 - 18 DSP2833x - Introduction
What is a Digital Signal Controller?

If we look a little bit more in detail into the tasks that needs to be solved by a standard
processor we can distinguish 10 steps. Due to the sequential nature of this type of processor,
it can do only one of the 10 steps at one time. This will consume a considerable amount of
computing power of this processor. For our tiny example, the processor must loop between
step 3 and step 10 a total of four times. For real Digital Signal Processing the SOP –
procedure is going to much higher loop repetitions – forcing the standard processor to spend
even more computing power.

6 Basic Operations of a SOP


3
y = ∑ data[i ] * coeff [i ]
i =0

• What will a Pentium be forced to do?


1. Set a Pointer1 to point to data[0]
2. Set a second Pointer2 to point to coeff[0]
3. Read data[i] into core
4. Read coeff[i] into core
5. Multiply data[i]*coeff[i]
6. Add the latest product to the previous ones
7. Modify Pointer1
8. Modify Pointer2
9. Increment i;
10. If i<4 , then go back to step 3 and continue

• Steps 3 to 8 are called “6 Basic Operations of a DSP”


• A DSP is able to execute all 6 steps in one single machine
cycle!

1 - 16

SOP machine code of a µP


Address M-Code Assembly - Instruction
10: for (i=0;i<4;i++)
00411960 C7 45 FC 00 00 00 00 mov dword ptr [i],0
00411967 EB 09 jmp main+22h (411972h)
00411969 8B 45 FC mov eax,dword ptr [i]
0041196C 83 C0 01 add eax,1
0041196F 89 45 FC mov dword ptr [i],eax
00411972 83 7D FC 04 cmp dword ptr [i],4
00411976 7D 1F jge main+47h (411997h)

11: result += data[i]*coeff[i];


00411978 8B 45 FC mov eax,dword ptr [i]
0041197B 8B 4D FC mov ecx,dword ptr [i]
0041197E 8B 14 85 40 5B 42 00 mov edx,dword ptr[eax*4+425B40h]
00411985 0F AF 14 8D 50 5B 42 00 imul edx,dword ptr[ecx*4+425B50h]
0041198D 8B 45 F8 mov eax,dword ptr [result]
00411990 03 C2 add eax,edx
00411992 89 45 F8 mov dword ptr [result],eax
00411995 EB D2 jmp main+19h (411969h)

Note: The C-Compiler was used in basic setup mode using optimization level zero.

1 - 17

DSP2833x - Introduction 1 - 19
What is a Digital Signal Controller?

A SOP executed by a DSP


If we apply the SOP-task to a Digital Signal Processor of fixed-point type the ANSI-C code
looks identical to the standard processor one. The difference is the output of the compilation!
When you compare slide 19 with slide 17 you will notice the dramatic reduction in the
consumption of the memory space and number of execution cycles. A DSP is much more
appropriate to calculate a SOP in real time! Ask your professor about the details of the two
slides!

Doing a SOP with a DSP


3
y = ∑ data[i ] * coeff [i ]
i =0

• Now: use a DSP-Development System and code


the equation into a DSP C-compiler system, e.g.
Texas Instruments Code Composer Studio
• C-Code Solution is identical:

int data[4]={1,2,3,4};
int coeff[4]={8,6,4,2};
int main(void)
{
int i;
int result =0;
for (i=0;i<4;i++)
result += data[i]*coeff[i];
printf("%i",result);
return 0;
}
1 - 18

DSP-Translation into machine code

Address M-Code Assembly Instruction


0x8000 FF69 SPM 0
0x8001 8D04 0000R MOVL XAR1,#data
0x8003 76C0 0000R MOVL XAR7,#coeff
0x8005 5633 ZAPA
0x8006 F601 RPT #1
0x8007 564B 8781 || DMAC ACC:P,*XAR1++,*XAR7++
0x8009 10AC ADDL ACC,P<<PM
0x800A 8D04 0000R MOVL XAR1,#y
0x800B 1E81 MOVL *XAR1,ACC

Example: Texas Instruments TMS320F28335


Space : 12 Code Memory ; 9 Data Memory
Execution Cycles : 10 @ 150MHz = 66 ns

1 - 19

1 - 20 DSP2833x - Introduction
What is a Digital Signal Controller?

A Digital Signal Controller


Finally, a Digital Signal Controller (DSC) is a new type of microcontroller, where the
processing power is delivered by a DSP – a single chip device combining both the
computing power of a Digital Signal Processor and the embedded peripherals of a single chip
computing system.
For advanced real time control systems with a high amount of mathematical calculations, a
DSC is the first choice.
Today there are only a few manufacturers offering DSC’s. Due to the advantages of DSC’s
for many projects, a number of silicon manufacturers are developing this type of controller.
This tutorial is based on the Texas Instruments TMS320F28335, a 32-bit floating point
Digital Signal Controller (DSC).

5. Digital Signal Controller (DSC)


Digital Signal Controller (DSC)

– recall: a Microcontroller(MCU) is a single chip


Microcomputer with a Microprocessor(µP) as core
unit.

– Now: a Digital Signal Controller(DSC) is a single chip


Microcomputer with a Digital Signal Processor(DSP)
as core unit.

– By combining the computing power of a DSP with


memory and peripherals in one single device we
derive the most effective solution for embedded real
time control solutions that require lots of math
operations.

– DSC –Example: Texas Instruments C2000 DSC -


family.

1 - 20

Note: Some manufacturers, like Infineon and Renesas, still call their DSCs
microcontrollers. This is because most target applications are typically regarded as
‘microcontroller sockets’ and many engineers are unfamiliar with the term DSC.
TI also recently changed the naming of the C2000 line from DSC to microcontroller.”

DSP2833x - Introduction 1 - 21
DSP Competition

DSP Competition
There are only a few global players in the area of DSP and DSC. As you can see from the
next slide (for more details, go to: www.fwdconcepts.com ), Texas Instruments is the
absolute leader in this area. A working knowledge of TI-DSP will help you to master your
professional career.

DSP Market Share in 2006

6%
12%
9%

Agere
14% Analog Devices
Freescale
Texas Instruments
Other

59%

Total Revenue: 7635 Million US-$


Source: www.forwardconcepts.com

1 - 21

With such expertise in DSPs, it is only natural that the lessons TI has learned and
technologies developed for DSPs trickle down also to TI’s microcontrollers. As the leader in
DSP Texas Instruments microcontrollers will also challenge the market!

1 - 22 DSP2833x - Introduction
Texas Instruments DSP/DSC – Portfolio

DSP Market Areas in 2006

3,2 2,8
4,6

Wireless
Consumer
9,1 Multipurpose
Computer
Wireline
Automotive

72,3 Relative

Source: www.forwardconcepts.com

1 - 22

Texas Instruments DSP/DSC – Portfolio

Texas Instruments Portfolio

Microcontrollers Arm-Based DSP


16-bit 32-bit 32-bit
MCU ARM+ ARM + DSP DSP
Real-time ARM
MSP430 C2000™ Stellaris ARM9 C64x+ plus C647x, C64x+,
Cortex™ M3 Cortex A-8 ARM9/Cortex A-8 C55x
Ultra-Low Fixed & Industry Std Industry-Std Core, Industry-Std Core + Leadership DSP
Power Floating Point Low Power High-Perf GPP DSP for Signal Proc. Performance

Up to 25MHz Up to 150MHz Up to 100MHz Accelerators 4800 MMACs/ 24,000 MMACS


1.07 DMIPS/MHz
Flash Flash Flash MMU, Cache Up to 3MB
1KB to 256KB 32KB to 512KB 8KB to 256KB MMU L2 Cache

Analog I/O, ADC PWM, ADC, USB, ENET, USB, LCD, 1G EMAC, SRIO,
LCD, USB, RF CAN, SPI, I2C ADC, PWM, HMI MMC, EMAC VPSS, USB, DDR2, PCI-66
EMAC, MMC
Measurement, Motor Control, Host Control, Linux/WinCE Linux/Win + Comm, WiMAX,
Sensing, General Digital Power, general purpose, User Apps Video, Imaging, Industrial/
Purpose Lighting motor control Multimedia Medical Imaging

$0.49 to $9.00 $1.50 to $20.00 $2.00 to $8.00 $8.00 to $35.00 $12.00 to $65.00 $4.00 to $99.00+

1 - 23

The DSP / DSC – portfolio of Texas instruments is split into three major device families,
called “Microcontroller, ARM-based and DSP.
The C64x branch is the most powerful series of DSP in computing power. There are floating
– point as well as fixed – point devices in this family. The application fields are image
processing, audio, multimedia server, base stations for wireless communication etc.

DSP2833x - Introduction 1 - 23
Texas Instruments DSP/DSC – Portfolio

The C55x family is focused on mobile systems with very efficient power consumption per
MIPS. Its main application area is cell phone technology.
The C2000 – group is dedicated to Digital Signal Control (DSC), as you have learned from
the first slides and is a very powerful solution for real time control applications. This group
is accompanied at the two ends by a 16-bit Microcontroller group (MSP430) and 32-bit
series of ARM-core based microcontrollers (Cortex M3, Cortex A-8 or ARM9).
The next slide summarizes the main application areas for the 3 Texas Instruments families of
DSP.

Texas Instruments TMS320 DSP/DSC


Dedicated families and sub-families to
support different market needs

C2000 C5000 C6000

Lowest Cost Efficiency Performance &


Control Systems Best MIPS per Ease-of-Use
 Motor Control Watt / Dollar / Size
 Storage
 Multi Channel and
 Wireless phones
 Digital Control Systems
Multi Function App's
 Internet audio players
 Power Supply Control
 Communication Infrastructure
 Digital still cameras
 Wireless Base-stations
 Modems
 DSL
 Telephony
 Imaging
 VoIP
 Multi-media Servers
 Video
1 - 24

1 - 24 DSP2833x - Introduction
TMS320F28x Roadmap

TMS320F28x Roadmap
For the C2000 – family we can distinguish between two groups of devices: a 16-bit group,
called TMS320C24x and a 32-bit group, called TMS320C28x.

TMS320C2000™ DSC Family

1 - 25

The next Slide 1-26 illustrates the latest developments in the 32-bit real-time controller
family C28x:

C2000 32-bit Real-Time Controller


Next Gen
Production
C2834x
•Higher Performance
Sampling •Connectivity
F2833x •200-300MHz •Safety Enhancements
•196-516kB SRAM
Development
•100-150MHz •External ADC
•128-512kB Flash •Low Active Power
Future
•52-68kB SRAM

F2823x
PERFORMANCE

F281x

F280x
Next Gen
F2803x •Performance
•Memory
•Connectivity
Fixed Point F2802x
(100-176 Pins)
• 60 – 150 MHz
Next Gen
• 32 – 512kB Flash
• 3Ph PWM/QEP •60MHz •Low Power
•40-60MHz •Small Package
• 12-bit, 2 SH ADC •Control Law
•16-64kB Flash
(Up to 12.5 MSPS) Accelerator
• CAN, McBSP
•Analog Comp
•32-128kB Flash
• UART, SPI
•CAN, LIN

100+ Code Compatible Devices TIME

1 - 26

DSP2833x - Introduction 1 - 25
TMS320F28x Application Areas

TMS320F28x Application Areas

Versatile C2000 Application Areas


E-bike
Renewable Energy Digital Motor Control
Wind Power Inverters Power Tools

Solar Power Inverters


White Goods Industrial Drives &
Motion Control
Lighting
Digital Power
DC/DC LED Street Lighting
Converters C2000

Uninterruptable
Power Supplies LED TV
Auto HID Backlighting
Telecom / Server
AC/DC Rectifiers Radar / Collision
Avoidance Medical Oxygen
Laser Ranging Concentrators Optical
Power Line Networking
Hybrid Electric Vehicles
Communication

Electric Power Steering

RFID Readers

Automotive Precision Sensing & Control


1 - 27

TMS320F28x Block Diagram

TMS320C28x DSC Block Diagram

Code security TMS320F28335


512 KB 68 KB
Flash RAM Boot ROM
18 PWM
(6 HRPWM)
Memory Bus
6 CAP

DMA 2 QEP
Peripheral Bus

Interrupt Management 12-bit ADC

88 GPIO
C28xTM 32-bit DSC 16/32-bit
EMIF
32x32-bit RMW
Multiplier Atomic
ALU SPI
32-bit
Timers (3) 3 SCI
32-bit
Floating- 2 McBSP
Real-Time Point Unit
JTAG I²C
2 CAN

1 - 28

1 - 26 DSP2833x - Introduction
Architecture

Introduction
The TMS320F2833x Digital Signal Controller is capable of executing six basic operations in
a single instruction cycle, and therefore the architecture of the device must reflect this feature
in some way. Remember this key point when we look into the details of this Digital Signal
Controller (DSC). It will help you to understand the ‘philosophy’ behind the device with its
different hardware units. Doing six basic maths operations is no magic; we will find all the
hardware modules that are required to do so in this chapter.
In this and other modules, we will discuss the following parts of the architecture:
• Internal bus structure
• CPU
• Direct Memory Access Controller
• Floating-point Arithmetic Unit
• Fixed-point Hardware Multiplier, Arithmetic-Logic-Unit, Hardware-Shifter
• Pipeline Processing of Instructions
• Memory Map

Module 2: Architecture

Digital Signal Controller


TMS320F2833x
Texas Instruments Incorporated
European Customer Training Centre
University of Applied Sciences Zwickau

3-1

F2833x - Architecture 2-1


Module Topics

Module Topics

Architecture ....................................................................................................................................... 2-1


Introduction ..................................................................................................................................... 2-1
Module Topics ................................................................................................................................. 2-2
TMS320F2833x Block Diagram ...................................................................................................... 2-3
Bus System ................................................................................................................................. 2-3
Central Processing Unit (CPU) ................................................................................................... 2-4
Fixed-point Math Unit ................................................................................................................ 2-5
Floating-point Math Unit ............................................................................................................ 2-6
Data Memory Access .................................................................................................................. 2-7
Internal Bus Structure ................................................................................................................. 2-8
Direct Memory Access Controller (DMA) ................................................................................. 2-9
Atomic Arithmetic Logic Unit (ALU) ...................................................................................... 2-10
Instruction Pipeline ....................................................................................................................... 2-11
Memory Map ................................................................................................................................. 2-12
Code Security Module ................................................................................................................... 2-13
Interrupt Response ........................................................................................................................ 2-14
Operating Modes ........................................................................................................................... 2-15
Reset Behaviour ............................................................................................................................ 2-16
Summary of TMS320F2833x Architecture .................................................................................... 2-17

2-2 F2833x - Architecture


TMS320F2833x Block Diagram

TMS320F2833x Block Diagram


The TMS320F2833x Block Diagram can be divided into the following functional units:
• Internal and external Bus System
• Central Processing Unit (CPU)
• Internal Memory Sections
• Control Peripherals
• Communication Channels
• Direct Memory Access Controller (DMA)
• Interrupt Management Unit (PIE) and Core Time Unit
• Real - Time Emulation Interface

F2833x Block Diagram


Program Bus
ePWM

Boot DMA eCAP


Sectored RAM
A(19-0)
ROM 6 Ch.
Flash eQEP
XINTF

DMA Bus
12-bit ADC

D(31-0) Watchdog

PIE
32-bit R-M-W Interrupt CAN 2.0B
32x32 bit Manager
Auxiliary Atomic FPU
Multiplier I2C
Registers ALU
3
Real-Time SCI
32-bit
JTAG Register Bus Timers SPI
Emulation CPU
McBSP
Data Bus
GPIO
2-2

Bus System
Since the core of the TMS2833x Microcontroller is a DSP, it must be able to read at least
two operands from memory and transfer them to the central processing unit in a single clock
cycle. To do so, the F2833x features two independent bus systems, called the "Program Bus"
and the "Data Bus". This type of processor technology is called “Harvard-Architecture”. Due
to the ability of the F2833x to read operands not only from data memory but also from
program memory, Texas Instruments calls its technology a “modified Harvard-Architecture”.
The “bypass”-arrow in the bottom left corner of Slide 2-2 indicates this additional feature.
In addition, the F2833x connects all units inside the CPU core to a third bus system, called
the “Register Bus”, allowing a very fast exchange of data between its parallel mathematical

F2833x - Architecture 2-3


TMS320F2833x Block Diagram

units. Finally, because the DMA unit is able to operate on certain parts of the hardware units
independently of the CPU, a "Direct Memory Access Bus" has been added for this purpose.
On the left hand side of slide 2-2 you will notice a multiplexer block for data (D31-D0) and
address (A19-A0). This is an interface to connect external devices to the F2833x. Please note
that you cannot access the external program bus data and the data bus data simultaneously.
Compared to a single cycle for internal access to two 32-bit operands, it takes at least 2
cycles to do the same with external memory, not taking into account additional wait cycles
for slower external memories!

Central Processing Unit (CPU)


The F2833x - CPU is able to execute most of the instructions to perform register-to-register
operations and a range of instructions that are commonly used by microcontrollers, e.g. byte
packing and unpacking and bit manipulation in a single cycle. The architecture is also sup-
ported by powerful addressing modes, which allow the compiler as well as the assembly
programmer to generate compact code that almost corresponds one-to-one with the C code.

The F2833x is as efficient in typical math tasks for Digital Signal Processing as it is in the
system control tasks that are typically handled by microcontroller devices. This efficiency
removes the need for a second processor in many systems.

F2833x CPU
Program Bus

Data Read Bus

32-bit R-M-W
32x32 bit
Auxiliary Atomic FPU
Multiplier
Registers ALU 3 PIE
32-bit Interrupt
Register Bus Manager
Timers

CPU

Data Write Bus

 32-bit fixed and floating point DSP ; 32 x 32 bit fixed-point MAC


 Additional 32 x 32 bit hardware floating point unit
Real-Time
 Dual 16 x 16 single-cycle fixed-point MAC (DMAC)
JTAG
 32-/64-bit saturation Emulation
 Unique real-time debugging capabilities
2-3

Three 32-bit timers can be used for general timing purposes or to generate hardware driven
time periods for real-time operating systems. The Peripheral Interrupt Expansion Manager
(PIE) allows fast interrupt response to the various sources of external and internal signals and
events. The PIE-Manager processes individual interrupt vectors for all sources and reduces
the response time to an external event, called "Interrupt Latency", to an absolute minimum.

2-4 F2833x - Architecture


TMS320F2833x Block Diagram

A fixed-point 32-bit by 32-bit hardware multiplier and a 32-bit arithmetic logic unit (ALU)
can be used in parallel to simultaneously execute a multiply and an addition operation on
fixed-point numbers. The auxiliary register group is equipped with its own arithmetic unit
(ARAU)-also used in parallel to perform pointer arithmetic. In addition, a hardware floating-
point unit (FPU) for IEEE-754 single point precision numbers allows the direct usage of
floating-point numbers from C or MatLab-code.
The JTAG-interface is a very powerful tool to support real-time data exchange between the
DSC and a host during the debug phase of project development. A special operating mode
called "Real-time Debug" allows variables to be monitored while the code is running in real-
time, without a single clock cycle delay to the control code.

Fixed-point Math Unit


The 32-bit by 32-bit fixed-point “Multiply and Accumulate (MAC)” capabilities of the
F2833x and its internal 64-bit processing capabilities enable this DSC to efficiently handle
higher numerical resolution problems based on fixed-point numbers. In control applications,
a lot of algorithms are numerically based on a technique, called "Binary Fractions", some-
times also called "Integer-Quotient (IQ)"-numbers. The F2833x directly supports this ap-
proach. Furthermore, if the samples and coefficients are stored in a binary number of 16 bits
or less, which is quite often possible, this controller is able to perform two 16-bit by 16-bit
multiply and accumulate instructions simultaneously. The terminology for such an instruc-
tion is “Dual Multiply and Accumulate (DMAC)”.

F2833x Fixed Point Multiplier and ALU


Program Bus
32
Data Bus
XT (32) or T/TL 16/32
16 8/16/32
MULTIPLIER
32 32 x 32 or
Shift R/L (0-16) Dual 16 x 16
P (32) or PH/PL 8/16
32
32
32
32 Shift R/L (0-16)

32

ALU (32)
32
ACC (32)
AH (16) AL (16)
AH.MSB AH.LSB AL.MSB AL.LSB

• 32
Shift R/L (0-16)
32
Data Bus
2-4

Fixed-point multiplication uses the XT ("eXtended Temp") register to hold the first operand
and multiply it by a second operand, which is loaded from memory. If XT is loaded from a
data memory location and the second operand is fetched from a program memory location, a
single-cycle multiply operation can be performed. The result of a multiplication is shifted
into the P ("Product") register or directly into the Accumulator (ACC). Remember, if you

F2833x - Architecture 2-5


TMS320F2833x Block Diagram

multiply a 32-bit by a 32-bit number, what size is the result? Answer: 64-bits. The F2833x
instruction set includes two groups of multiply operations to store both 32-bit portions of the
result into P and ACC. In this way, we can say that the registers ACC and P are combined to
form a single 64-bit register.
Three hardware shifters can be used in parallel with other hardware units of the CPU.
Shifters are usually used to scale intermediate results in a real-time control loop or just to
multiply/divide by numbers of type 2n.
The Arithmetic Logic Unit (ALU) performs all other mathematical operations other than
multiplication. The first operand is always the content of the Accumulator (ACC) or a part of
it. The second operand for an operation is loaded from data memory, from program memory,
from the P register or directly from the multiply unit.

Floating-point Math Unit


To add more flexibility to the device by using single precision floating-point data types in C,
Texas Instruments have added a second hardware multiply unit to the F2833x family. The
right hand side of Slide 2-5 shows all the floating-point registers. The 8 general purpose
registers (R0H to R7H) are supported by a status register (STF) and a repeat block register
(RB). The latter is used to execute a block of machine code without the need for a software
loop. Such a technique allows the pipeline of the CPU to run at faster speeds.

F2833x Floating Point Unit FPU


Fixed Point Floating Point

32-bit C28 Register Set FPU Register Set


ACC
Accumulator, R0H
Product, P 32-bit
XT
Temporary and R1H
8 Auxiliary XAR0 8 FPU Result
XAR1 R2H Registers
Registers
XAR2
R3H
XAR3 FPU Status
XAR4 R4H Repeat Block
XAR5
22-bit R5H
XAR6
Program Counter
XAR7
Return PC R6H
PC
RPC R7H
DP
SP STF
16-bit
ST0
RB
Data Page Pointer ST1
IER
Stack Pointer
IFR
DBGIER R0H – R7H And STF Are Shadowed For Fast
2 Status Context Save And Restore
Interrupt Enable
Interrupt Flag
2-5

The left hand part of Slide 2-5 shows the fixed-point register set. It consists of the 3 CPU
registers, Accumulator (ACC), Product (P) and extended temp (XT), 8 general purpose
registers (XAR0…XAR7) and a set of control and status registers, such as "Program
Counter" (PC), "Data Page Pointer"(DP), "Stack Pointer" (SP), "Interrupt Enable" (IER),
"Interrupt Flag" (IFR) and "Debug Interrupt Enable" (DBGIER).

2-6 F2833x - Architecture


TMS320F2833x Block Diagram

Data Memory Access


Two basic methods are available to access data memory locations:
• Direct Addressing Mode
• Indirect Addressing Mode

F2833x Pointer, DP and Memory


Data Bus
Program Bus

6 LSB
XAR0 DP (16) from IR
XAR1
XAR2
32 22
XAR3
XAR4 MUX
XAR5
XAR6
XAR7
MUX

ARAU

Data Memory
XARn → 32-bits
ARn → 16-bits

2-6

Direct addressing mode generates the 22-bit address for a memory access from two sources -
a 16-bit register “Data Page (DP)” for the highest 16 bits plus another 6 bits taken from the
instruction. Advantage: Once DP is set, we can access any location of the selected page, in
any order. Disadvantage: If the code needs to access another page, DP must be changed first.
Indirect addressing mode uses one of eight 32-bit XARn registers to hold the 32-bit address
of the operand. Advantage: With the help of the ARAU, pointer arithmetic is available in the
same cycle in which an access to a data memory location is made. Disadvantage: A random
access to data memory needs the pointer register to be setup with a new value.
The auxiliary register arithmetic unit (ARAU) is able to perform pointer manipulations in the
same clock cycle as the access is made to a data memory location. The options for the
ARAU are: post-increment, pre-decrement, index addition and subtraction, stack relative
operation, circular addressing and bit-reverse addressing with additional options.

F2833x - Architecture 2-7


TMS320F2833x Block Diagram

Internal Bus Structure


A typical feature of Digital Signal Processors is their ability to increase the data throughput
based on multiple busses. Such busses are used to move data between memory locations,
peripheral units and the CPU. The F2833x memory bus architecture contains:

• A program read bus (22-bit address line and 32-bit data line)
• A data read bus (32-bit address line and 32-bit data line)
• A data write bus (32-bit address line and 32-bit data line)
• A register bus (32-bit data line and direct register addressing)

F2833x Internal Bus Structure

Program Program Address Bus (22)


PC
Program-read Data Bus (32) Program
Decoder
Memory
Data-read Address Bus (32)

Data-read Data Bus (32)


Data
Registers Execution Debug Memory
ARAU MPY32x32 FPU
SP Real-Time
ALU R-M-W
DP @X Atomic R0H JTAG
XAR0 XT to Emulation
P ALU Peripherals
to R7H
XAR7 ACC

Register Bus / Result Bus


External
Data/Program-write Data Bus (32) Interface

Data-write Address Bus (32)


2-7

The 32-bit wide data busses allow single cycle 32-bit operations. This multiple bus architec-
ture, known as a Harvard Bus Architecture enables the F2833x to (1) fetch an instruction, (2)
read a first data value and (3) write a second data value all within in a single clock cycle.

All registers to control peripheral units are mapped into specific locations in data memory
space and can be accessed with an ordinary data memory write or read instruction. For im-
portant peripheral registers, some security mechanisms are implemented to prevent a modifi-
cation by accident.

All internal memory sections are attached both to program and data memory (called "unified
memory model"). It allows the designer to select a certain part to be used as code or as a data
section.

2-8 F2833x - Architecture


TMS320F2833x Block Diagram

Direct Memory Access Controller (DMA)


A Direct Memory Access Controller has been introduced in the F2833x family. A DMA unit
allows a data transfer from a source to a destination unit without the need of an interaction of
the CPU. The strength of a digital signal controller (DSC) is not measured purely in proces-
sor speed, but also in total system capability. As a part of the equation, whenever the CPU
bandwidth for a given function can be reduced, the greater the system capability will be.
Very often applications spend a significant amount of their bandwidth moving data, whether
it is from off-chip memory to on-chip memory or from a peripheral such as an analog-to-
digital converter (ADC) to RAM, or even from one peripheral to another. Furthermore, there
are times when this data comes in a format that is not compatible with the optimum
processing powers of the CPU. The DMA module has the ability to free up CPU bandwidth
and rearrange the data into a pattern for more streamlined processing.

F2833x Direct Memory Access

PIE
DINTCH1-6
ADC XINTF
Result 0-15 Zone 0, 6, 7

DMA
L4 SARAM 6-channels
McBSP-A
Triggers
L5 SARAM McBSP-B
SEQ1INT / SEQ2INT
MXEVTA / MREVTA PWM1
L6 SARAM MXEVTB / MREVTB
XINT1-7 / 13 PWM2
TINT0 / 1 / 2 PWM3
L7 SARAM PWM4
PWM5
PWM6
SysCtrlRegs.MAPCNF.bit.MAPCNF
(re-maps PWM regs from PF1 to PF3)

2-8

The DMA module is an event-based machine, meaning it requires a peripheral interrupt trig-
ger to start a DMA transfer, such as:
• Analogue to Digital Converter Sequencer 1 (SEQ1INT) or Sequencer 2 (SEQ2INT)
• Multichannel Buffered Serial Port A and B (McBSP-A, McBSP-B) transmit/receive
• External Interrupt Input Signals XINT1-7 and XINT13
• CPU Timers 0, 1 and 2
• Pulse Width Module (PWM) signals ePWM1-6
• Software
As data sources and/or destinations that can be initialized:
• Internal SARAM sections L4 to L7
• All external memory zones XINTF
• ADC result registers (source only)
• McBSP-A and McBSP-B transmit and receive buffers
• PWM units 1-6 (destination only)

F2833x - Architecture 2-9


TMS320F2833x Block Diagram

Atomic Arithmetic Logic Unit (ALU)

F2833x Atomic Read/Modify/Write

 Atomic Instructions Benefits:


LOAD  Simpler programming
READ

 Smaller, faster code


Registers CPU ALU / MPY Mem
 Uninterruptible (Atomic)
WRITE

STORE  More efficient compiler

Standard Load/Store Atomic Read/Modify/Write


DINT
AND *XAR2,#1234h
MOV AL,*XAR2
AND AL,#1234h 2 words / 1 cycles
MOV *XAR2,AL
EINT
6 words / 6 cycles
2-9

Atomic instructions are common with embedded system controllers. Examples are logical
operations, such as AND, OR and EXOR directly performed in data memory locations.
Usually, these instructions must be executed without an interruption between read and write
accesses; they are called "non-interruptible" or "atomic" instructions. The F2833x atomic
Arithmetic Logic Unit (ALU) capability supports such types of instructions; as shown on the
right hand side of Slide 2-9.

By contrast, the traditional coding (left hand side of Slide 2-9) would execute several cycles
slower than atomic instructions.

2 - 10 F2833x - Architecture
Instruction Pipeline

Instruction Pipeline
Like almost all today's microprocessors that operate in speed regions above 50 MHz the
F2833x also uses a pipeline technique to maximize the code throughput. The F2833x fea-
tures an 8-stage protected pipeline. The adjective "protected" means that the pipeline unit
itself automatically prevents a "write to" and a "read from" the same location from occurring
out of sequence (see instructions E and G in Slide 2-10). This pipelining also enables the
F283xx to execute at high speeds without resorting to expensive high-speed memories. An
additional branch-look-ahead hardware minimizes the delay when jumping to another ad-
dress. Particular assembly instructions called "conditional store operations" avoid pipeline
stalls and further improve the overall system performance.

F2833x Pipeline
A F1 F2 D1 D2 R1 R2 E W 8-stage pipeline
B F1 F2 D1 D2 R1 R2 E W

C F1 F2 D1 D2 R1 R2 E W Instructions
F1 F2 D1 D2 R1 R2 E W
‘E’ and ‘G’
D access same
F1 F2 D1 D2 R1 R2 E W memory address
E
F1 F2 D1 D2 R1 R2 E W
F
G F1 F2 D1 D2 R11 R2 R
E2 E
W W
F1 F2 D1 D
D22 R1 RR21 R
E2 W
E W
H
F1: Instruction Address
F2: Instruction Content Protected Pipeline
D1: Decode Instruction  Order of results are as written in
D2: Resolve Operand Addr
R1: Operand Address
source code
R2: Get Operand  Programmer need not worry about
E: CPU doing “real” work
the pipeline
W: store content to memory
2 - 10

Each instruction passes through 8 stages until final completion. Once the pipeline is filled
with instructions, one instruction is executed per clock cycle. For a 150MHz device, this
equates to 6.67ns per instruction.
The stages are:

F1: Generate Instruction Address at program bus address lines.


F2: Read the instruction from program bus data lines.
D1: Decode Instruction
D2: Calculate Address information for operand(s) of the instruction
R1: Load operand(s) address to data and/or program bus address lines
R2: Read Operand
X: Execute the instruction
W: Write back result to data memory

F2833x - Architecture 2 - 11
Memory Map

Memory Map
The memory space of the F2833x is divided into program space and data space. There are
several different types of memory available that can be used as both as a program or a data
space member. These include independent sections of flash memory, single access RAM
(SARAM), one time programmable memory (OTP) and boot ROM. The latter is factory pro-
grammed with boot software routines and trigonometric lookup tables used in maths based
algorithms. Memory space width is always 16 bits.

TMS320F2833x Memory Map


Data Program
0x000000 0x010000
M0 SARAM (1Kw)
0x000400 reserved
M1 SARAM (1Kw) 0x100000
0x000800 XINTF Zone 6 (1Mw)
0x000D00 0x200000
PIE Vectors XINTF Zone 7 (1Mw)
(256 w) 0x300000
0x000E00 reserved
PF 0 (6Kw) FLASH (256Kw) Dual Mapped:
0x002000
L0, L1, L2, L3
0x004000 0x33FFF8 PASSWORDS (8w)
XINTF Zone 0 (4Kw) 0x340000
0x005000 reserved
PF 3 (4Kw) 0x380080
0x006000 ADC calibration data
PF 1 (4Kw) reserved 0x380090
0x007000 reserved CSM Protected:
PF 2 (4Kw) 0x380400 L0, L1, L2, L3,
0x008000 User OTP (1Kw) FLASH, ADC CAL,
L0 SARAM (4Kw) 0x380800
0x009000 reserved OTP
L1 SARAM (4Kw) 0x3F8000
0x00A000 L0 SARAM (4Kw)
L2 SARAM (4Kw) 0x3F9000
0x00B000 L1 SARAM (4Kw)
L3 SARAM (4Kw) 0x3FA000 DMA Accessible:
0x00C000 L2 SARAM (4Kw)
L4 SARAM (4Kw) 0x3FB000 L4, L5, L6, L7,
0x00D000 L3 SARAM (4Kw) XINTF Zone 0, 6, 7
L5 SARAM (4Kw) 0x3FC000
0x00E000 reserved
L6 SARAM (4Kw) 0x3FE000
0x00F000 Boot ROM (8Kw)
L7 SARAM (4Kw)
0x010000 0x3FFFC0 BROM Vectors (64w)
0x3FFFFF
Data Program
2 - 11

The F2833x can access memory both on and off the chip. The F2833x uses 32-bit data ad-
dresses and 22-bit program addresses. This allows for a total address reach of 4G words (1
word = 16 bits) in data space and 4M words in program space. Memory blocks on all F2833x
designs are uniformly mapped to both program and data space.

The memory map above shows the different blocks of memory available to the program and
data space.
The non-volatile internal memory consists of a group of FLASH-memory sections, a boot-
ROM for up to 12 reset-startup options and a one-time-programmable (OTP) area. FLASH
and OTP are usually used to store control code for the application and/or data that must be
present at reset. To load information into FLASH and OTP, a dedicated download program is
needed, which is also part of the Texas Instruments Code Composer Studio integrated design
environment.
Volatile Memory is split into 10 areas called M0, M1 and L0 to L7 that can be used both as
code memory and data memory.
PF0, PF1 and PF2 are Peripheral Frames that cover control and status registers of all
peripheral units (“Memory Mapped Registers”).

2 - 12 F2833x - Architecture
Code Security Module

Code Security Module


There is an internal security module available in all F2833x family members. It is based on a
128-bit password that is written by the software developer into the last 8 memory spaces of
the internal FLASH (0x3F 7FF8 to 0x3F 7FFF). Once a pattern is written into this area, all
further accesses to any of the memory areas covered by this Code Security Module (CSM)
are denied, as long as the user does not write an identical pattern into password registers of
frame PF0.
NOTE: If you write any pattern into the password area by accident, there is no way to get
access to this device anymore! Also, any attempt to re-flash a secured device will fail.
So please be careful and do not upset your laboratory technician!

Code Security Module

 Prevents reverse engineering and


protects valuable intellectual property

CSM Protected:
L0, L1, L2, L3,
FLASH, ADC CAL,
OTP

 128-bit user defined password is stored in Flash


 128-bits = 2128 = 3.4 x 1038 possible passwords
 To try 1 password every 2 cycles at 150 MHz, it
would take at least 1.4 x 1023 years to try all
possible combinations!
2 - 12

The purpose of a password secured device is to prevent reverse engineering of a control


system. The code security module will deny any unauthorized access attempts and will
protect your intellectual property (IP).

F2833x - Architecture 2 - 13
Interrupt Response

Interrupt Response
A key feature of a control system is its ability to respond to asynchronous external hardware
events as quickly as possible. The F2833x combines such fast interrupt responses with an
automatic “context” save of critical CPU registers, which allows the service of many asyn-
chronous events with minimal latency. Here “context” means all the registers that need to be
saved so that you can go away and carry out some other process, then come back to exactly
where you left. F2833x devices implement a zero cycle penalty to save and restore the 14
registers during an interrupt. This feature helps to reduce the interrupt service routine over-
heads.

F2833x Fast Interrupt Response Manager

 96 dedicated PIE
vectors
 No software decision
making required PIE module 28x CPU Interrupt logic
Peripheral Interrupts 12x8 = 96

For 96
 Direct access to RAM interrupts
vectors INT1 to
INT12 28x
 Auto flags update IFR IER INTM CPU
96
12 interrupts
 Concurrent auto PIE
Register
context save
Map

Auto Context Save


T ST0
AH AL
PH PL
AR1 (L) AR0 (L)
DP ST1
DBSTAT IER
PC(msw) PC(lsw)
2 - 13

We will look in detail into the F2833x interrupt system in Module 6 of this tutorial. The
Peripheral Interrupt Expansion (PIE) - Unit allows the user to specify individual interrupt
service routines for up to 96 internal and external interrupt events. All possible 96 interrupt
sources share 14 maskable interrupt lines (INT1 to INT14), 12 of them are controlled by the
PIE - module.
The auto context save loads 14 important CPU registers, as shown in Slide 2-13 above, into a
stack memory, which is pointed to by a stack pointer (SP) register. The stack is part of the
data memory and must reside in the lower 64K words of data memory.

2 - 14 F2833x - Architecture
Operating Modes

Operating Modes
The F2833x is a member of the TMS320C2000 family of Digital Signal Controllers (DSCs).
This family consists both of 32-bit fixed-point and floating-point devices and also of 16-bit
members. The Test Mode is used for fabrication test purposes only. The F2833x can be
switched from its native mode into an operating mode, that is source code compatible with
the 16-bit group C24x/C240x. Code, which has been previously written for a C24x device,
can be reassembled to run on a F2833x device. This allows for migration of existing code
onto the F2833x.

F2833x Operating Modes

Mode Type Mode Bits Compiler Option


OBJMODE AMODE

C28x Native Mode 1 0 -v28


C24x Compatible Mode 1 1 -v28 –m20
Test Mode (default) 0 0
Reserved 0 1

 Almost all uses will run in C28x Native Mode


 The bootloader will automatically select C28x Native Mode after reset
 C24x compatible mode is mostly for backwards compatibility with an
older processor family

2 - 14

In fact, the F2833x silicon is able to operate in three different modes:


• C28x - Mode - takes advantage of all 32-bit features of the F2833x device
• C24x - Mode - source code compatibility to the 16-bit family members
• Test - Mode - intermediate operating mode, test purposes only.
After RESET, the device is set into test mode. To take advantage of the full computing
power of an F2833x device, the control flag “OBJMODE” must be set to 1 to switch into
F2833x native mode. If you start the execution of your code from the boot code entry point,
the boot code will set that bit for you.

F2833x - Architecture 2 - 15
Reset Behaviour

Reset Behaviour
After a valid RESET-signal is applied to the F2833x, the following sequence depends on
some external pins on this DSC.
An active RESET signal will read the first address to be loaded into the Program Counter
register (PC) from address 0x3F FFC0, which is in boot memory. The value inside this
address is the address of the beginning of the boot code sequence. As a result, the F2833x
jumps directly to the internal boot code memory. This code has been developed by TI to be
able to distinguish between 12 different start options for the F2833x. The active option is
derived from the status of 4 general-purpose input pins (GPIO) at this very moment. For our
tutorial we use the volatile memory M0 as code memory and its first address as the execution
entry point.

Reset – Bootloader

Reset
OBJMODE = 0 AMODE = 0
ENPIE = 0 INTM = 1

Bootloader sets
OBJMODE = 1
AMODE = 0
Reset vector fetched
from boot ROM Boot determined by
state of GPIO pins
0x3F FFC0

Execution
Entry Point
Note: M0 SARAM
Details of the various boot options will be
discussed in the Reset and Interrupts module

2 - 15

2 - 16 F2833x - Architecture
Summary of TMS320F2833x Architecture

Summary of TMS320F2833x Architecture

Highlights of the F2833x


 High performance 32-bit DSP
 32x32 bit or dual 16x16 bit MAC
 IEEE single-precision floating point unit
 Atomic read-modify-write instructions
 Fast interrupt response manager
 256Kw on-chip flash memory
 Code security module (CSM)
 Control peripherals
 12-bit ADC module
 Up to 88 shared GPIO pins
 Watchdog timer
 DMA and external memory interface
 Communications peripherals
2 - 16

F2833x - Architecture 2 - 17
Summary of TMS320F2833x Architecture

This page has been intentionally left blank.

2 - 18 F2833x - Architecture
Program Development Tools

Introduction
The objective of this module is to understand the basic functions of the Code Composer Studio
(CCS) Integrated Design Environment (IDE) for the C2000 Family of Texas Instruments Digital
Signal Processors and Microcontrollers. This involves understanding the basic structure of a
project in C and Assembler coded source files, along with the basic operation of the C -
Compiler, Assembler and Linker.

Code Composer Studio IDE, Version 4


Note: This chapter explains the use of Code Composer Studio, Version 4 and later. This revision
is based on Eclipse and introduced a major change of the design environment compared to earlier
CCS versions. If you use an older version, please refer to the previous releases of this teaching
CD-ROM.
Code Composer Studio is the environment for project development and for all tools needed to
build an application for the C2000 family.

Code Composer Studio Version 4


Perspectives:
Menus or Icons Debug or C/C++
Help
Watch window

CPU
window

Source
code
window

Status
window

Full C/C++ & Assembly


Debug Graph Debugging:
Configuration Memory
window window C & ASM Source
 Break Points
3-2

F2833x - Program Development Tools 3-1


Module Topics

Module Topics
Program Development Tools .................................................................................................................... 3-1
Introduction ............................................................................................................................................. 3-1
Code Composer Studio IDE, Version 4 ................................................................................................... 3-1
Module Topics ......................................................................................................................................... 3-2
CCS 4: Eclipse Concepts......................................................................................................................... 3-3
Workbench .......................................................................................................................................... 3-3
Workspace .......................................................................................................................................... 3-4
Perspective .......................................................................................................................................... 3-4
Views .................................................................................................................................................. 3-5
Resources ............................................................................................................................................ 3-5
The Software Flow .................................................................................................................................. 3-6
Lab Hardware Setup ............................................................................................................................... 3-7
Code Composer Studio Version 4 - Step by Step ..................................................................................... 3-9
Start Code Composer Studio Version 4 ............................................................................................ 3-10
Create a project ................................................................................................................................. 3-11
Write C - code ................................................................................................................................... 3-14
Linker Command File ....................................................................................................................... 3-15
C - Compiler Sections ....................................................................................................................... 3-15
Linking Sections to Memory ............................................................................................................ 3-16
Build the active project ..................................................................................................................... 3-19
Create a new Target Configuaration ................................................................................................. 3-20
Download code into the controller .................................................................................................... 3-21
Debug Perspective ............................................................................................................................ 3-22
Test the Code .................................................................................................................................... 3-23
The Watch Window .......................................................................................................................... 3-24
Code Step Comands .......................................................................................................................... 3-25
Real - Time Debug Mode ................................................................................................................. 3-27
CPU Register Set .............................................................................................................................. 3-29
Watch Memory Contents .................................................................................................................. 3-30
Graphical View ................................................................................................................................. 3-31
Mixed Mode C and Assembly .......................................................................................................... 3-33
Assembly Single Step Mode ............................................................................................................. 3-34
GEL General Extension Language ................................................................................................... 3-35
Lab 3: beginner’s project ...................................................................................................................... 3-37
Objective ........................................................................................................................................... 3-37
Procedure .......................................................................................................................................... 3-37
Open Files, Create Project File ......................................................................................................... 3-37
Write C - code ................................................................................................................................... 3-40
Build and Load.................................................................................................................................. 3-40
Create a Target Configuration........................................................................................................... 3-40
Load Code into Target ...................................................................................................................... 3-41
Test ................................................................................................................................................... 3-41
Code Step Comands .......................................................................................................................... 3-42
Real Time Mode ............................................................................................................................... 3-43
Watch Memory Contents .................................................................................................................. 3-44
Graphical Views ............................................................................................................................... 3-45
Mixed Mode C and Assembly Language .......................................................................................... 3-48

3-2 F2833x - Program Development Tools


CCS 4: Eclipse Concepts

CCS 4: Eclipse Concepts


With CCS version 4 Texas instruments moved the Integrated Design Environment to an Eclipse
(www.eclipse.org) open source software framework. Hence understanding some of the basic
concepts of Eclipse will lead to a better understanding of CCSv4. Some of the more commonly
referenced concepts are described below.

CCS4 Eclipse Concepts

CCS 4 - based on Eclipse


• Open source framework (www.eclipse.org)

Commonly referenced categories:


• Workbenches
• Workspaces
• Perspectives
• Views
• Resources
• Projects
• Files
3-3

Workbench
A Workbench contains all the various views and resources used for development and debug.
Multiple CCSv4 Workbench windows can be opened ('Window->New Window'). While each
Workbench window can differ visually (arrangement of views, toolbars and such), all windows
refer to the same workspace and the same running instance of CCSv4 - if a project is opened from
one Workbench, that same project will be open in all the Workbench windows.

F2833x - Program Development Tools 3-3


CCS 4: Eclipse Concepts

Code Composer Studio Version 4


Perspectives:
Menus or Icons Debug or C/C++
Help
Watch window

CPU
window

Source
code
window

Status
window

Full C/C++ & Assembly


Debug Graph Debugging:
Configuration Memory
window window C & ASM Source
 Break Points
3-2

Workspace
The workspace is the main working folder for CCSv4 and where it stores project information to
manage all the projects that you define to it. This is the case even if the projects themselves do
not physically reside inside the workspace folder. CCSv4 Workspaces are not to be confused with
CCSv3 workspace files (*.wks), which have more in common with CCSv4 Perspectives than they
do with CCSv4 workspaces. The default location of any new projects created in CCSv4 will be
within the workspace folder. Once a project has been defined to the workspace, it will be visible
in the 'C/C++ Projects' view and can be opened and closed and such. To define an existing
CCSv4 project to the workspace, it will need to be imported into CCSv4.

CCSv4 will prompt the user for the workspace folder location when launching CCSv4. The
workspace folder is also used by CCSv4 to store other information such as user preferences,
custom perspectives, cached data for plug-ins, etc.
Multiple workspaces may be maintained (for example, one for each user), however only one can
be active within each CCSv4 instance. The 'File->Switch Workspace...' option can be used to
switch between the workspaces. Each workspace would have its own stored user preferences and
projects associated with it.

Perspective
A perspective (compare Slide 3-2) defines the initial set and layout of views in the Workbench
window. Each perspective provides a set of functionality aimed at accomplishing a specific type
of task. For example, the default 'C/C++' perspective displays views most commonly used during
code development, such as the 'C/C++ Projects' view, 'Outline' view and the Editor. When a de-
bug session is started, CCSv4 will automatically switch to the 'Debug' perspective, which (by de-

3-4 F2833x - Program Development Tools


CCS 4: Eclipse Concepts

fault) displays the 'Debug' view, 'Watch' view and 'Local' view. Also in the 'Debug' perspective,
menus and toolbars associated with debugging (such as target connect, load program, reset target,
etc) are now available. Users can also manually switch between perspectives. Any changes made
to a perspective will be preserved (but can be reset to the default arrangement via  Window
Reset Perspective). New perspectives can be created simply by saving the current perspective as a
new name ( Window Save Perspective As...).

Perspectives can be easily switched between perspectives by clicking on the perspective icons in
the upper right corner.

Views
Views are windows within the main Workbench window that provide visual representation of
some specific information. The Workbench window mainly consists of the editor and a collection
of views. Examples of some views are “C/C++ Projects”, “Debug”, “Outline”, “Memory”,
“Disassembly”, etc.
Most of the views in CCSv4 are available from the main “View” menu.

Resources
“Resources” is a collective term for the projects, folders, and files that exist in the Workbench.

Projects
“Projects” typically contain folders and files. Like the workspace, projects map to directories in
the file system.

Files
“Files” can either be added or linked to a project. When a file is added to a project, the file is
copied to the root location of the project directory. This differs from the concept of “adding” a
file to a CCSv3 project, where it would not make a local copy, but simply make a reference to
where the file is located (you were adding a reference to the file in your project). To achieve the
same functionality with CCSv4 projects, there is also the option to “link” a file to a project. This
will simply have the project create a reference to the file instead of copying the file into the
project directory.

F2833x - Program Development Tools 3-5


The Software Flow

The Software Flow


The following slide (Slide 3-4) illustrates the software design flow within Code Composer Studio.
The basic steps are: edit, compile and link, which are combined into “build”, then debug. If you
are familiar with other Eclipse based Integrated Design Environments, you will easily recognize
the typical steps used in a project design. If not, you will have to spend a little more time to
practice with the basic tools shown on this slide. The major difference to a PC design toolbox is
shown on the right-hand side - the connections to real-time hardware!

Code Composer Studio


Code
Build
lnk.cmd Simulator
Compile

eZdsp™
Asm Link Debug

Emulator
Editor Libraries Graphs,
(XDS100)
Profiling

MCU
Board
• Code Composer Studio includes:
– Integrated Edit/Debug Graphical User Interface
– Code Generation Tools
– Real – Time Operating System (DSP/BIOS)

3-4

You can use Code Composer Studio with a Simulator (running on the Host - PC) or you can
connect a microcontroller system and test the software on a real “target”. For this tutorial, we will
rely on the Peripheral Explorer Board and the TMS320F28335 Control Card as our “target”. Here
the word “target” means the physical processor we are using, in this case a TMS320F28335.

Before we inspect some basic features of Code Composer Studio Version 4 more in detail, we
will first discuss the hardware setup for lab exercises that follow.

3-6 F2833x - Program Development Tools


Lab Hardware Setup

Lab Hardware Setup


The following slides illustrate the hardware target that will be used during our lab exercises in the
chapters that follow. The core is the TMS320F2335 32-bit Digital Signal Controller on board of a
Texas Instruments “Peripheral Explorer Board”. All the major internal peripherals are available
through connectors. The JTAG interface connects the board to the PC via a USB link.

Slide 3-5 reveals all peripheral units, which are populated at the Peripheral Explorer Board
(Texas Instruments part number: TMDSPREX28335).

Peripheral Explorer Board

3-5

To be able to practice with all the peripheral units of the Digital Signal Controller and some ‘real’
process hardware, the Peripheral Explorer Board provides:

• 4 LEDs for digital output (GPIO9, GPIO11, GPIO34 and GPIO49)

• a 4 - bit hexadecimal input encoder (GPIO12…GPIO15) and 2 push buttons (GPIO 34


and GPIO17) for digital inputs

• 2 potentiometers (ADCINA0, ADCINA1) for analog inputs

F2833x - Program Development Tools 3-7


Lab Hardware Setup

• 1 stereo audio codec AIC23B for line -in and headphone -out (connected via McBSP and
SPI)

• 1 SPI 256k - Atmel AT25C256 EEPROM (connected via McBSP)

• 1 CAN Transceiver - Texas Instruments SN 65HVD230 (high speed)

• 1 I2C - Temperature Sensor Texas Instruments TMP100

• 1 SCI-A RS232 Transceiver - Texas Instruments MAX232D

• 1 Infrared Receiver TSOP32230 (connected to eCAP)

Slide 3-6 shows the F28335 Control Card, which we will use for our teaching course.
Teachers: Please note that the F28335ControlCard is already bundled with the Peripheral
Explorer Board. In case that you need additional spare modules of this control card, the part
number is TMDSCNCD28335.
Other versions of C2000 Control Cards are also available.

F28335 Control Card


• Low cost single-board controllers
• perfect for initial development and small
volume system builds.
• Small form factor with standard 100-pin
DIMM interface
• F28x analog I/O, digital I/O, and JTAG
signals available at DIMM interface
• Isolated RS-232 interface
• Single 5V power supply required
• Versions:
• “Piccolo” F28027 (TMDXCNCD28027)
• “Piccolo” F28035 (TMDXCNCD28035)
• F28044 (TMDSCNCD28044)
• F2808 (TMDSCNCD2808)
• “Delfino” F28335 (TMDSCNCD28335)
• “Delfino” C28343 (TMDXCNCD28343)

3-6

3-8 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Code Composer Studio Version 4 - Step by Step


Now let us start to look a little closer at the main parts of Code Composer Studio Version 4 that
we need to develop our first project. We will perform the following steps:

Learning by doing - Step by Step

Code Composer Studio V4 - The Basics


1. CCS workspace and welcome window
2. Create a F2833x - project, based on C language
3. Debug your program
4. Watch your variables
5. Perform a Single Step Debug
6. Use Breakpoints
7. Real – Time – Debug
8. CPU Register Set
9. Memory Window
10. Graph Window
11. Mixed Mode Display
12. Assembly Single Step
13. GEL - General Extension Language
3-7

The step-by-step approach for Lab3 will show how to do the following:

• Open Code Composer Studio

• Create a F2833x - Project, based on C

• Compile, Link, Download and Debug this test program

• Watch Variables

• Continuous run and single - step mode

• Use of Breakpoints

• Use of “Real - Time - Debug” - mode

• View registers

• Mixed Mode (C and Assembler Language)

• General Extension Language (GEL)

Before we start to go into the procedure for Lab3 at the end of this chapter, let us discuss the
individual steps using some additional slides.

F2833x - Program Development Tools 3-9


Code Composer Studio Version 4 - Step by Step

Start Code Composer Studio Version 4


Once you or your laboratory technician have installed the software tools and the correct Emulator
driver for CCS4.1, you can start Code Composer Studio by simply clicking on its desktop icon. If
you get an error message, check the correct USB connection of the target board. If everything
goes as expected, a message will pop up, asking you to select a “workspace”. Code Composer
Studio stores your projects in a folder called a workspace. Now you have to choose a workspace
folder for this session.
You might have to ask your teacher, which folder you should use in your classroom. For this
tutorial, I assume that we store the projects in “C:\DSP2833x_V4\labs”.

1. Start CCS Version 4


• Code Composer Studio stores your projects in a folder
called a workspace.
• Select a workspace folder for this session, e.g.:

C:\DSP2833x_V4\labs

3-8

Next, a “welcome” window will appear. As the name suggests, this window shows you essential
menus for CCS, such as “Getting Started”, “Examples”, “What’s new” and “Device Information”.
Although all these information might be very interesting, we will concentrate on our task to
generate our first project from scratch.
Later you can always return to this welcome page ( Help  Welcome).

3 - 10 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Create a project
Let us now create our first project. Click on File  New  CCS Project and enter “Lab3”:

2. Create a F2833x - Project

• File  New  CCS Project


give your project a name “Lab3” and select the default
location , as shown below:

3-9

This step is quite similar to most of today’s design environments with one exception. Because
CCS4 is also used for C6000, C5000, MSP430 and ARM processors, we have also to define the
project type, in our case “C2000”:

2. Create a F2833x - Project

• Select Type of Project: C2000

3 - 10

F2833x - Program Development Tools 3 - 11


Code Composer Studio Version 4 - Step by Step

We do not use any inter-project dependencies so far, so click “Next” twice.


Now we have to set the project properties according to the following Slide 3-11:

2. Create a F2833x - Project

Setup Properties:

Output Type :
Executable
Device Variant:
TMS320F28335
Code Generation Tools:
TI v 5.2.3
Linker Command File:
28335_RAM_lnk.cmd
Runtime Support Library:
rts2800_fpu32.lib
Target content:
None
3 - 11

Close the project setup by clicking on “Finish”. We are almost done. Cancel the “welcome”
window to show the project layout. All C code based programs need a system stack. We have to
define its size:

2. Create a F2833x - Project

Setup C- Stack Size:


• Right click at “Lab3” and select “Properties”

• Go to category:
• C/C++ Build, C2000 Linker, Basic Options
• Set C system stack size: 0x400
3 - 12

3 - 12 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

The following Slide 3-13 shows the setup for the stack size. The selected size of 0x400 is a first
“rule of thumb” number. Later we can be more specific about the stack usage of code examples.

2. Create a F2833x - Project

3 - 13

Do not change the remaining parts of this property window.


Close the window by clicking “OK”.

F2833x - Program Development Tools 3 - 13


Code Composer Studio Version 4 - Step by Step

Write C - code
Next, write the source code for your first application. The program from the slide below is one of
the simplest tasks for a processor.
unsigned int k;
unsigned int i;

void main(void)
{
while(1)
{
for(i=0; i<100; i++)
{
k = i*i;
}
}
}

The code example consists of an endless while(1) - loop, which contains a single for - loop -
instruction. In that for-loop we:

• increment variable i from 0 to 99,


• calculate the current product of i * i and
• store the product temporarily in variable k.
It seems to be an affront to bother a sophisticated Digital Signal Controller with such a simple
task! However, we want to gain hands-on experience of this DSC and our simple program is an
easy way for us to evaluate the basic commands of Code Composer Studio.

3. Write a C – code file

• Write a C-Source Code :


File New Source File

In „main.c“, enter this code:

3 - 14

3 - 14 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Linker Command File


Before we continue with our project, let us first discuss why we added the file
“28335_RAM_lnk.cmd” to our project (see Slide 3-11). This file is used to control the “Linker”.
The “Linker” puts together the various building blocks we need for a system. This is done with
the help of a so-called “Linker Command File”. Essentially, this file is used to connect physical
parts of the DSP’s memory with logical sections created by our software. We will discuss this
linker procedure later in detail. For now, we will use a predefined Linker Command File
“28335_RAM_lnk.cmd”. This file has been provided by Texas Instruments and is part of the CCS
Version 4 support package.

C - Compiler Sections
When we compile our tiny code from Lab3, the C - compiler will generate 4 so-called “sections”.
These sections cover different parts of the object module, which must be “linked” to physical
memory. Our four sections are:

• .text This section collects all assembly code instructions


• .ebss The section covers all global and static variables
• .cinit This section is used for initial values
• .stack The stack memory for local variables, return addresses, parameters

C – Compiler Sections

Global vars (.ebss) Init values (.cinit)

unsigned int k = 0;
unsigned int i;
void main(void)
{ Local variables,
while(1) System Context
{ (.stack)
for(i=0;i<100;i++)
{
k=i*i;
} Code (.text)
}
}
3 - 15

The linker will connect these sections to physical memory. For this task we pass information to
the linker with the help of “Linker - command - files” (extension *.cmd). But before we look at

F2833x - Program Development Tools 3 - 15


Code Composer Studio Version 4 - Step by Step

the details of this procedure, let us finish the C compiler sections. As you can probably guess,
when we use a slightly more complex program than Lab3, the C compiler will generate more
sections. The following slide will summarize all possible C sections:

Compiler Section Names


Initialized Sections
Name Description Link Location
.text code FLASH*
.cinit initialization values for global and static FLASH*
variables
.econst constant variables (e.g. const int m=3;) FLASH*
.switch tables for addresses in “switch – case” lines FLASH*
.pinit tables for global constructors (C++) FLASH*

Uninitialized Sections
Name Description Link Location
.ebss global and static variables RAM
.stack stack memory area RAM (lower 64K)
.esysmem heap memory for dynamic memory allocation. RAM

Note: (*)During development initialized sections could be linked to RAM


since the emulator can be used to load the RAM
3 - 16

Linking Sections to Memory


The following Slide (3-17) gives an example on how we could link the four sections from Lab3
into parts of physical memory. For a standalone embedded system, all constants, initialization
values and code must be stored in non-volatile memory, such as FLASH. Un-initialized data
(variables) are linked to RAM.
Note: Our lab “lab3” will be based on volatile memory usage only, so the following explanation
is a more generic one.

3 - 16 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Placing Sections in Memory

Memory
Sections
0x00 0000 M0SARAM
(0x400)
.ebss
0x00 0400 M1SARAM
(0x400)
.stack

0x30 0000 FLASH .cinit


(0x40000)

.text

3 - 17

Linking

 Memory description
 How to place Software
Sections into Memory

name.cmd

.obj Linker .out

.map

3 - 18

The procedure of linking connects one or more object files (*.obj) into an output file (*.out). This
output file contains not only the absolute machine code for the Digital Signal Controller, but also
information used to debug, to flash the controller and for more JTAG based tasks. NEVER take
the length of this output file as the length of your code! To extract the usage of resources we
always use the MAP file (*.map).

F2833x - Program Development Tools 3 - 17


Code Composer Studio Version 4 - Step by Step

Now let us inspect the linker command file “28335_RAM_lnk.cmd”. Basically the file consists of
two parts, “MEMORY” and “SECTIONS”.
“MEMORY” declares all available physical memory of the device. The declaration is split in
“PAGE 0” – for code memory and “PAGE 1” for data memory.
Please recall that the F28335 is a Digital Signal Controller and that one of the properties of DSPs
is to have a “Harvard”-Architecture, which has two memory spaces, one for code and one for
data.

Linker Command File

Memory:
physical spaces

Sections:
Connect
Logical blocks to
physical spaces

3 - 19

When you inspect the file, you will find that our sections are actually allocated in:

• .text is allocated in code address space 0x9000 (RAML1)

• .cinit is allocated in code address space 0x8000 (RAML0)

• .ebss is allocated in data address space 0x0C000 (RAML4)

• .stack is allocated in data address space 0x0400 (RAMM1)

Close the file “28335_RAM_lnk.cmd”, when you are done.

3 - 18 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Build the active project


Now let us resume or lab and build the machine code. This step includes the compilation of all
source code files (C and Assembler) and the linking of all modules and libraries, which are part of
the project, into a single output file. This file contains a lot of information, including the machine
code for all sections.
 Project  Rebuild Active Project
And watch the tools output in the console window:

4. Build the Active Project

•  Project  Rebuild Active Project


• Watch the tools running:

3 - 20

Hopefully you have the same console output as shown in Slide 3-20 above. If you have error
messages or warning, both in red colors, you will have to find out what went wrong. In most
cases, not always, the error comment gives you an indication about the cause of the
error/warning.
And, you still have the option to ask your teacher!
Please do NOT continue with the next steps in case of errors/warnings!

F2833x - Program Development Tools 3 - 19


Code Composer Studio Version 4 - Step by Step

Create a new Target Configuaration


Before we can download the machine code into the F28335, we have to define the “target
configuration”.
 Target  New Target Configuration
Type a name for the target configuration file in box “File name”. You can use any name here but
it makes sense to indicate the JTAG-emulation interface, which we will use for the download
later. In case of the Peripheral Explorer Board we use the XDS100V2, so let us call the file
“F28335_XDS100V2. The suffix “.ccxml” will be added automatically.

5. Create New Target Configuration

•  Target  New Target Configuration

3 - 21

In the window that appears, select the emulator “Texas Instruments XDS100v2 USB Emulator”
via the “Connection” pull-down list and select the “TMS320F28335” device checkbox.

3 - 20 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Download code into the controller


Now it is time to download the code into the F2833x.
 Target  Debug Active Project
This command is also available on the green bug:

This button combines the following “single action” commands:

• Rebuild Active Project

• Connect Target

• Load Program

6. Download and Debug

•  Target  Debug Active Project

3 - 22

A blue arrow should now point to the “for” – line in code file “main.c”. This is an indication that
the machine code has been downloaded properly into the F28335.

F2833x - Program Development Tools 3 - 21


Code Composer Studio Version 4 - Step by Step

Note: The automatic procedure of connecting the target, download code and run the code to the
entry point of main can be controlled by the project properties. Right click at the project “Lab3”
and select “Properties”. In the “CCS Debug” category, go to the “Target” properties and verify,
that “Run to main” on a program load is enabled. Next, close the property window.

6. Download and Debug

• Properties of Project “Lab3”:

Real time
Options

Auto Run
Options

3 - 23

Debug Perspective
Code Composer Studio Version 4 allows inspecting a project from different perspectives. All
available perspectives are show in the top right corner of CCS. You can always change your
perspective of looking into the project. There are at least two perspectives, “C/C++” and
“Debug”. For the following tests please make sure that you have selected perspective “Debug”:

3 - 22 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Test the Code


Now that we have successfully downloaded our code into the target, we can perform some basic
test commands.

RESET CPU
The most important hardware command for the target is “RESET”. This command will always
force the device to a default RESET condition, including all internal peripheral units.
 Target  Reset  Reset CPU

7. Test the code

• Hardware Reset:
 Target  Reset  Reset CPU

• Restart Code:
 Target  Restart

3 - 24

A new window, the “Disassembly Window” will open. This window shows the machine code that
will be executed in the next clock cycles. However, the JTAG – Emulator has frozen the
controller, so that we can take our time to inspect all parts of the CPU and the peripherals. The
blue arrow shows the current position of the Program Counter (PC), which is now loaded with the
hardware - reset address 0x3FF9CE in Boot-ROM. The purpose of register “PC” is to always
point the next machine code instruction to be executed.
We will not discuss the content of the Boot-ROM now; let us postpone its details for a later
chapter.

Restart CPU
Another important command is
 Target  Restart
This command is often used directly after a RESET command. Its purpose is to bypass the Boot –
code and to load the Program Counter (PC) directly with the “entry point address” for the code.

F2833x - Program Development Tools 3 - 23


Code Composer Studio Version 4 - Step by Step

This entry point address can be specified in the project options. For C-language based projects the
default address is the environment preparation function “_c_int00” (from library rts2800_fpu.lib”
However, because we have enabled the auto run option to “main()”, the restart command will run
through “_c_int00” and stop at the beginning of “main()”. If this auto run option would have been
disabled, we could use  Target  “Go to Main” as a 3rd command.

The Watch Window


To watch the program’s variables, we can use a dedicated window called the “Watch Window”.
This is probably the most used window during the test phase of a software project. It is good
engineering practice to carefully test parts and modules of a software project. For an embedded
system we need to ‘look’ into internal parts of the controller, such as variables and function
stacks and monitor their changes.
Here the Watch Window is of great use. Instead of hitting the ‘run’ - key F8 and hoping that the
software behaves as expected, it is much better to test it systematically. That means:

• Predict, what will happen in the next instruction

• Single step the critical code instruction

• Monitor the variables of that code snippet and compare the results with your
expectations.

• Proceed with the next line under test.

8. Watching variables
• If not already open, open a Watch Window:  View  Watch

• To inspect the global variables ‘i’ and ‘k’ we have to add this
variables manually. This can be done inside window ‘Watch(1)’. In
the column ‘name’ we just enter ‘k’ and in the second line ‘i’.
• Another convenient way is to mark the variables inside the source
code with the right mouse button and then select “Add Watch
expression”
• In column “Format” we can change the data format between
decimal, hexadecimal, binary, etc.

3 - 25

Note that the physical addresses for ‘i’ and ‘k’ in column “Address” are shown as 0xC009 and
0xC008 respectively. Can you explain why these two addresses have been used? (Answer: The
linker command file, which we inspected earlier, allocated section .ebss (global variables) to data
memory “RAML4” at address block 0x00C000.)

3 - 24 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Code Step Comands


Another useful part of a debug session is the ability to debug the code in larger portions and to
run the program for a few instructions. This can be done using other commands in the single-step
group. In the “Debug” perspective, perform:

9. Perform a Single Step Debug

• Perform a single step of the target - code:

 Target  Step Into (or use function key “F5”)

• Watch the current PC (blue arrow) and the values of


variables ‘i’ and ‘k’ in Watch Window while you single
step the code !

• More debug - commands are shown at the following


slide:

3 - 26

9. Perform Code Stepping

Run
Step Out

Halt

Source Single Step Assembly Step Over

Source Step Over Assembly Single Step

3 - 27

F2833x - Program Development Tools 3 - 25


Code Composer Studio Version 4 - Step by Step

When you would like to run the code through a portion of your program that you have already
tested before, a “Breakpoint” is very useful. After the “Run” command, the JTAG debugger stops
automatically when it hits a line that is marked by a breakpoint.

10. Set a Breakpoint

• Set a Breakpoint:
– Place the Cursor in Lab3.c at line: k = i * i;
– Click right mouse and select “Toggle Breakpoint”
– the left hand side of the line is marked with a blue dot to indicate an
active breakpoint.
– A 2nd option is to use a left mouse double click at the grey left hand side
of window “Lab3.c” to toggle the breakpoint.

• Reset the Program


 Target  Reset  Reset CPU
 Target  Restart

• Perform a real time run


 Target  Run (or F8)
The F2833x stops after hitting an active breakpoint
• repeat ‘Run’ and watch your variables
• remove the breakpoint (Toggle again) when you’re done.

3 - 28

10. Set a Breakpoint (cont. )

blue arrow:
blue and
current position
enabled dot:
of PC
active Breakpoint
3 - 29

3 - 26 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Real - Time Debug Mode


A critical part of a test session is any interference between the control code and the test functions.
Imagine, what would happen with PWM output lines for power inverters, if we would just place a
breakpoint in a certain point in our code. If the processor hits the breakpoint, the execution would
stop immediately, including all dynamic services of the PWM lines. The result would be: fatal,
because a permanent open switch will destroy the power circuits.
The best solution would be to have an operating mode, in which the control code is not disturbed
at all by any data exchange between Code Composer Studio and the running control code. This
test mode is called “Real - Time - Debug”. It is based on a large set of internal registers in the
JTAG - support module of the F2833x. At this stage we will not discuss the internal functionality;
we will just use its basic features.
It is important to delete or disable all breakpoints in a CCS - session, before you switch ON the
Real - Time - Debugger. So please make sure, that no breakpoints are left from previous tests!

11. Real – Time - Debug

Reset F2833x:
 Target  Reset  Reset CPU
Watchdog – Timer:
•always active after a Reset
•if not serviced, it will cause another Reset after 4.3
milliseconds.
• normally, watchdog is cleared by “key”-instructions
• for the first lab, let us just disable the watchdog:
 Scripts  Watchdog  Disable Watchdog

Start “Real – Time – Debug”:


 Scripts  Realtime Emulation Control 
Run_Realtime_with_Restart
3 - 30

To switch into Real - Time - Debug, it is good practice to first reset the device. This step ensures
that all previous core and peripheral initialization is cancelled.
We have not discussed so far the internal watchdog unit. This unit is nothing more than a free
running counter. If it is not serviced, it will cause a hardware reset. The purpose of this unit is to
monitor the correct flow of control code. There are two dedicated clear instructions, which are
normally executed from time to time, if the code is still running as expected. If not, because the
code hangs somewhere, the watchdog will bring the device back into a safe passive state. It
operates similar to a “dead man’s handle” in a railway locomotive.
We will discuss and use the watchdog in detail in chapter 5. However, the watchdog is active
after power on, so we cannot neglect it! For now, we can use a CCS script command to disable
the watchdog. We would never do that in a real project!

F2833x - Program Development Tools 3 - 27


Code Composer Studio Version 4 - Step by Step

To use “Real - Time - Debug” perform:


 Target  Reset  Reset CPU
 Scripts  Watchdog  Disable Watchdog
 Scripts  Real time Emulation Control  Run_Realtime_with_Restart
Now the code is running in real-time. The new feature is that we can interact with the device,
while the code is running. To practice this:

• In the upper right-hand corner of the watch window, click on the white down-arrow
and select “Customize Continuous Refresh Interval”. Change the “Continuous
Refresh Interval” to 1 second instead of the default 5 seconds.

• In the upper right-hand corner of the watch window, click on the yellow arrows
rotating in a circle over a pause sign to enable continuous refresh mode for the watch
window.
The content of the watch window is now updated frequently. The JTAG - controller uses cycles,
in which the core of the device does not access the variables to “steal” the information needed to
update the window. However, the USB-JTAG emulator is too slow to update the watch window
in the same frequency as our F2833x executes the for-loop. That is why we do not see each
increment of variables ‘i’ and ‘k’.

11. Real – Time – Debug (cont.)

In the Watch – Window:

Continuous
Menu
Refresh
• Enable Continuous Refresh
• In the “menu” open “Customize Continuous Refresh Interval”
and change the “Continuous Refresh Interval” to 1 second.
• The variables k and i are updated in the background, while
the code is running
• The execution speed of the control code is not delayed by
monitoring variables.
• Note: The USB – emulator is too slow to update the watch
window as fast as the F2833x executes the for-loop. That is
why you will not see each iteration of i and k.
Stop the real time - Debug:
 GEL  Realtime Emulation Control  Full_Halt
3 - 31

When you are done, you should stop the real - time test by:

 Scripts  Real time Emulation Control  Full_Halt

3 - 28 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Note: the test mode “Run_Realtime_with_Reset” will first perform a reset followed by a direct
start of the device from its reset address. The device will follow its hardware boot sequence (see
Chapter 15) to begin the code execution. Since the Peripheral Explorer Board sets the coding pins
to “Branch to FLASH” by default, it would start code stored in FLASH. The problem is, that so
far we have not stored anything in FLASH (we will do this in Chapter 14). By using
“Run_Realtime_with_Restart”, we force CCS to place the program counter at the start address
of our project in RAM (a function called “c_int00”) and to start from this position.

CPU Register Set


When you are more familiar with the F2833x and with the tools, you might want to verify the
efficiency of the C compiler or to optimize your code at the Assembly Language level. As a
beginner you are probably not in the mood to do this advanced step now, but a brief look would
not be amiss.
Open a register window:
 View  Registers

12. CPU Register Set


View  Registers

• Allows to monitor all internal


CPU registers
• Register ST0 combines math
status flags, such as:
• C (carry)
• Z (zero)
• N (negative)
• V (overflow)
• SXM (sign extension mode)
• OVM (overflow mode)
• TC (test control flag)
• PM (product mode shifter)
• OVC ( overflow counter)
• Register ST1 combines CPU
control flags.

3 - 32

When you expand the plus signs, for example for register ST0, you can inspect details of a
particular register more in detail. At this early stage of the tutorial it is not important to
understand the meaning of all the bit fields and registers, shown in this window. But you should
get the feeling, that with the help of such windows, you can obtain control information about all
internal activities of the device.
There are two core registers, ST0 and ST1, which combine all core control switches and flags of
the CPU, such as carry, zero, negative, overflow, sign extension mode, interrupt enable and so on.
An inspection of these flags and bits allows you to immediately monitor the status of the CPU in
a certain spot of code.

F2833x - Program Development Tools 3 - 29


Code Composer Studio Version 4 - Step by Step

The 32-bit registers ACC (“accumulator”), P (“Product”) and XT (“eXtended Temp”) are the core
math registers of the fixed - point arithmetic unit.
The 32-bit registers XAR0 to XAR7 are general purpose registers, often used as pointer registers
or auxiliary registers for temporary results.
The register PC (“Program Counter”) points always the address of the next machine code
instruction in code memory. The register RPC (“return program counter”) stores the return
address of a function, which has called a sub-routine.

Watch Memory Contents


Let us open another control window, the “Memory Window”. This window allows us to inspect
any physical memory locations of the device, including RAM, FLASH, OTP and Boot - ROM.
Since the core of this device is a Digital Signal Processor, we have always to remember that there
are two memory spaces, code and data. To inspect variables, we have to select “data space”. For
machine code instructions inspection we have to look into “code space”. The selection is made in
the center box at the bottom of this window.

13. Memory Window


View  Memory
– make sure to inspect data space (top right hand side selection box)
– enter address &i in the top left corner box:

• the current value in memory


location of variable i (and k) is
displayed

• change the display type from


“Hex – 16 bit” to “16 Bit
Unsigned Integer”

• change the display type into “16


Bit Binary”

3 - 33

The right-hand side selection box allows us to specify the display mode of the 16-bit memory
location in different form, such as:
• Hexadecimal
• Integer, signed and unsigned
• Binary
• Float
• Character
The number of memory windows is not limited, you can open as many as you like!

3 - 30 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Graphical View
A unique feature of Code Composer Studio (CCS) is the ability to display any region of memory
in a graphical form. This is very helpful for inspection of data, such as sampled analogue signals.
We can display such memory values as raw data on a time - axis or even better, we can display
the samples a frequency axis. In the 2nd option CCS is performing a FOURIER - transform,
before it displays the data.

Let us inspect this graph feature. The BOOT-ROM contains a sine - value lookup table of 512
samples for a unit circle of 360 degree. The data format is 32-bit signed integers in fractional
I2Q30 - format. The start address of this table is 0x3FE000.

Open a graph window and enter the properties from the left hand side of Slide 3 - 34:

14. Graph Window


Tools  Graph  Single Time
– View of sine-value look-up table
in BOOT-ROM (0x3FE000)
– 512 values (32-bit signed, I2Q30)

3 - 34

F2833x - Program Development Tools 3 - 31


Code Composer Studio Version 4 - Step by Step

Optionally, you can open a second window to show the fast FOURIER transform (FFT) of the
sinusoidal lookup table in Boot – ROM.

Open a graph window and enter the properties from the left hand side of Slide 3 - 35:

14. Graph Window


Tools  Graph  FFT Magnitude
– View of sine – value look – up table
in BOOT - ROM (0x3FE000)
– 512 values ( 32 – bit signed, I2Q30)

3 - 35

3 - 32 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

Mixed Mode C and Assembly


An important test method for inspecting both C and the resulting assembly code from the C -
compilation is called “Mixed Mode” - display. This option allows us not only to inspect and
verify the device steps both on C high-level language, but also on the device native environment
assembly language.

15. Mixed Mode Visualization

• To view both the C – source - code and the resulting


Assembler – Code:
– click right mouse inside window “Disassembly” and enable “Show
Source”
– Both the C-source code (bold) and the Assembler Instruction Code
generated by the C - Compiler (grey) are displayed

3 - 36

Although this test method is not always required, especially not at the beginning of a tutorial, it
allows us to benchmark the efficiency of the C compiler.
Also later, when we have to use assembly optimized libraries and to design time critical control
loops, it will be important to optimize programs. For high speed control loops, for example in
Digital Power Supply, where sometimes the control loop (e.g. sample measurement values,
compute new output values and adjust PWM - outputs) runs at 500 kHz or even at 1 MHz, we
deal with time intervals of 1/1MHz = 1µs. Assuming that the device runs at 150MHz (= 6.667
Nanoseconds clock period), we can execute just 150 machine code instructions in such a loop. In
such circumstances an option to monitor a code flow on assembly language level is very helpful.

F2833x - Program Development Tools 3 - 33


Code Composer Studio Version 4 - Step by Step

Assembly Single Step Mode


In mixed - mode visualization of C - modules we can perform test steps both on C and Assembly
Language level. Code Composer Studio supports the 2nd test mode by two more icons (green
arrows in the “Debug” and “Disassembly” windows):

• Assembly Single Step


• Assembly Step Over

16. Assembly Single Step


Current Current
C - line ASM -
Instruction

ASM – ASM –
single step step over

3 - 37

If you use “Assembly Single Step”, the code is executed machine code line by machine code line.
The dark blue arrow in the “Disassembly” window marks the next following assembly line. The
light blue arrow in the C-code window (“main.c”) remains at the corresponding C - line, as long
as we deal with the assembly results of that line.
At this point it is not important to understand what happens in this assembly code snippet. We
will deal later with assembly coding and optimization. However, it is never a fault to question
your teacher!

For Assembly Language freaks only:


Here is an explanation of the first C-line: for( i=0; i<100; i++)
MOVW DP ,#0x300 ; sets the direct address pointer DP to address 0xC000
; 0x300 left shifted 6 times gives 0xC000
MOV @8,#0 ; loads constant 0 into address 0xC008 (which is ‘i’)
MOV AL,@8 ; read value from address 0xC0008 into register AL
CMPB AL,#100 ; compares AL against constant 100
SB main, HIS ; short branch (SB) to the beginning of main, if AL was “HIgher
; or Same (HIS)”

3 - 34 F2833x - Program Development Tools


Code Composer Studio Version 4 - Step by Step

GEL General Extension Language


The General Extension Language (GEL) is a high-level script language. Based on a *.gel – file,
the user can expand the features of Code Composer Studio or perform recurrent steps
automatically.

17. GEL - “General Extension Language”


• GEL = high level language, similar to C
• Used to extend Code Composer Studio’s features
• to create GEL functions use the GEL syntax
• load GEL-files into Code Composer Studio
• With GEL, you can:
– access actual/simulated target memory locations
– add options to Code Composer’s GEL menu
• GEL is useful for automated testing and user workspace
adjustment .
• Startup GEL files defined in the target configuration file
will be automatically loaded when a debug session is
started
• Additional GEL files can be loaded in the CCS from the
'GEL Files' dialog (via 'Tools->GEL Files' menu)

3 - 38

By default, startup GEL – files defined in the target configuration file are automatically loaded
when a debug session is started.

To open and inspect the default GEL - file, select:


 Tools  GEL Files
Right click at file “F28335.gel” and select “Open”. Inspect the file to get a view of the syntax of
this GEL language.
For example search function “OnReset”. This function will be executed every time we perform a
command  Target  Reset  Reset CPU.

OnReset(int nErrorCode)
{
C28x_Mode();
Unlock_CSM();
ADC_Cal();
}

F2833x - Program Development Tools 3 - 35


Code Composer Studio Version 4 - Step by Step

This function itself calls 3 more functions to switch the device into C28x operating mode, to
unlock a code security module (CSM) and to calibrate the internal Analogue to Digital Converter
(ADC).

17. GEL - “General Extension Language”


Tools  GEL files

Right-click in the view and select ‘Open’ to inspect the


default GEL-File “F28335.gel”

Example Function: “OnReset”:

3 - 39

3 - 36 F2833x - Program Development Tools


Lab 3: beginner’s project

Lab 3: beginner’s project


The following procedure is a summary of the steps, which we discussed in the previous part of
this chapter. The following procedure will help you to build your first project for the F2833x
device under Code Composer Studio Version 4.1.

Objective
The objective of this lab is to practice and verify the basics of the Code Composer Studio
Integrated Design Environment. The following procedure will summarize all the steps discussed
in this chapter.

Procedure

Open Files, Create Project File


1. To open Code Composer Studio Version 4.1 click the corresponding desktop icon:

2. Next, select a workspace. Ask your teacher about the correct directory of the laboratory PC.
The example below uses the folder “C:\DSP2833x_V4\labs”

3. Create a new project “Lab3” ( File  New  CCS Project):

F2833x - Program Development Tools 3 - 37


Lab 3: beginner’s project

In the following window, select “C2000” for the project type.

In the next window, do not add any additional settings:

Fill in the project properties according to the following picture:

3 - 38 F2833x - Program Development Tools


Lab 3: beginner’s project

4. Define the size of the C system stack. In the project window, right click at “Lab3” and Select
properties:

In category “C/C++ Build”, “C2000 Linker”, “Basic Options” set the C stack size to 0x400:

Note: The stack memory is used by the compiler to store local variables, parameters and
the processors context in case of hardware interrupts. It is our task to specify a certain
amount of memory for this purpose and 0x400 is sufficient for this lab.

F2833x - Program Development Tools 3 - 39


Lab 3: beginner’s project

Write C - code
5. Write a new source code file by clicking: File  New  Source File. A new window will
open. Enter the file name “main.c”:

In the file “main.c” enter the following few lines:

Save this file by clicking File  Save as and type in: Lab3.c

Build and Load


6. Click the “Rebuild Active Project” button or perform: Project  Rebuild Active Project and
watch the tools run in the build window. Debug as necessary. To open up more space, close
any open files or windows that you do not need at this time.

Create a Target Configuration


7. Before we can download the machine code into the F28335, we have to define the “target
configuration”.
 Target  New Target Configuration

3 - 40 F2833x - Program Development Tools


Lab 3: beginner’s project

Type a name for the target configuration file in box “File name”. You can use any name here
but it makes sense to indicate the JTAG-emulation interface, which we will use for the
download later. In case of the Peripheral Explorer Board we use the XDS100V2, so let us call
the file “F28335_XDS100V2. The suffix “.ccxml” will be added automatically.
In the window that appears next, select the emulator “Texas Instruments XDS100v2 USB
Emulator” via the “Connection” pull-down list and select the “TMS320F28335” device
checkbox.

Load Code into Target


8. Load the machine code into the device. Click:
 Target  Debug Active Project

Or use the “Debug” icon:

A blue arrow should now point to the “for” – line in code file “main.c”. This is an indication
that the machine code has been downloaded properly into the F28335.

Test

F2833x - Program Development Tools 3 - 41


Lab 3: beginner’s project

9. Reset the DSP by clicking on  Target  Reset  Reset CPU

The blue arrow shows the current position of the Program Counter (PC), which is now loaded
with the hardware - reset address 0x3FF9CE in Boot-ROM.

10. Run the program until the first line of your C-code by clicking: Target  Restart.
This command is often used directly after a RESET command. Its purpose is to bypass the
Boot – code and to load the Program Counter (PC) directly with the “entry point address” for
the code. This entry point address can be specified in the project options. For C-language
based projects the default address is the environment preparation function “_c_int00” (from
library rts2800_fpu.lib”
However, because we have enabled the auto run option to “main()”, the restart command will
run through “_c_int00” and stop at the beginning of “main()”. If this auto run option would
have been disabled, we could use  Target  “Go to Main” as a 3rd command.

11. Open the Watch Window to watch your variables. Click: View  Watch. Add the two va-
riables ‘i’ and ‘k’ in the “name” column:

Code Step Comands


12. Perform a single-step through your program by clicking: Target  Step Into (or use function
Key F5). Repeat F5 and watch your variables.

13. Place a Breakpoint in the Lab3.c - window at line “k = i * i;”. Do this by placing the cursor
on this line, click right mouse and select: “Toggle Breakpoint”. The line is marked with a
blue dot to mark an active breakpoint. Perform a real- time run by Target  Run (or F8).
The program will stop execution when it reaches the active breakpoint. Remove the break-
point after this step (click right mouse and “Toggle Breakpoint”).

3 - 42 F2833x - Program Development Tools


Lab 3: beginner’s project

Real Time Mode


14. Now we will exercise with the real-time debug mode. Make sure that all breakpoints have
been deleted or disabled.

Next, reset the device:  Target  Reset  Reset CPU


This reset will set the device in its default state, including the watchdog unit, which is
enabled after reset. For this test we will have to disable the watchdog:

 Scripts Watchdog Disable Watchdog

Now start the real-time debug:

 Scripts  Real time Emulation Control  Run_Realtime_with_Restart


Now the code is running in real-time. The new feature is that we can interact with the device,
while the code is running. To practice using this:
 In the upper right-hand corner of the watch window, click on the white down-arrow
and select “Customize Continuous Refresh Interval”. Change the “Continuous Refresh
Interval” to 1 second instead of the default 5 seconds.
 In the upper right-hand corner of the watch window, click on the yellow arrows
rotating in a circle over a pause sign to enable continuous refresh mode for the watch
window.

The contents of the Watch Window are updated frequently. The JTAG - controller uses
cycles, in which the core of the device does not access the variables to “steal” the information
needed to update the window. However, the USB-JTAG emulator is too slow to update the
watch window at the same frequency as our F2833x executes the for-loop. That is why we do
not see each increment of ‘i’ and ‘k’.

When you are done, stop the real - time mode by:

 Scripts  Real time Emulation Control  Full_Halt

Note: the test mode “Run_Realtime_with_Reset” will first perform a reset followed by a di-
rect start of the device from its reset address. The device will follow its hardware boot se-
quence (see Chapter 15) to begin the code execution. Since the Peripheral Explorer Board
sets the coding pins to “Branch to FLASH” by default, it would start code stored in FLASH.
The problem is, that so far we have not stored anything in FLASH (we will do this in Chapter
14). By using “Run_Realtime_with_Restart” we force CCS to place the program counter at

F2833x - Program Development Tools 3 - 43


Lab 3: beginner’s project

the start address of our project in RAM (a function called “c_int00”) and to start from this po-
sition.

15. Inspect the internal device registers:

 View  Registers

When you expand the plus signs, for example for register ST0, you can inspect details of the
particular register more in detail. At this early stage of the tutorial it is not important to
understand the meaning of all the bit fields and registers, shown in this window. But you
should get the feeling, that with the help of such windows, you can obtain control information
about all internal activities of the device.
There are two core registers, ST0 and ST1, which combine all core control switches and flags
of the CPU, such as carry, zero, negative, overflow, sign extension mode, interrupt enable
and so on. An inspection of these flags and bits allows you to immediately monitor the status
of the CPU in a certain spot of code.
The 32-bit registers ACC (“accumulator”), P (“Product”) and XT (“eXtended Temp”) are the
core math registers of the fixed - point arithmetic unit.
The 32-bit registers XAR0 to XAR7 are general-purpose registers, often used as pointer
registers or auxiliary registers for temporary results.
The register PC (“Program Counter”) points always the address of the next machine code
instruction in code memory. The register RPC (“return program counter”) stores the return
address of a function, which has called a sub-routine.

Watch Memory Contents


16. Let us open another control window, the “Memory Window”:

 View  Memory

Enter the address for variable k (“&k”) in the address box (top left corner box).

3 - 44 F2833x - Program Development Tools


Lab 3: beginner’s project

This window allows us to inspect any physical memory location of the device, including
RAM, FLASH, OTP and Boot - ROM. Since the core of this device is a Digital Signal Pro-
cessor, we have always to remember that there are two memory spaces, code and data. To in-
spect variables, we have to select “data space”. For machine code instructions inspection we
have to look into “code space”. The selection is made in the top right corner box of this win-
dow.

The right center box allows us to specify the display mode of the 16-bit memory locations in
different form. Try using the different formats available: 16-bit hexadecimal, signed integer,
unsigned integer and binary.

Graphical Views
Time Domain Graph
17. A unique feature of Code Composer Studio (CCS) is the ability to display any region of
memory in graphical form. This is very helpful for inspection of data, such as sampled
analogue signals. We can display such memory values as raw data on a time - axis or even
better, we can display the samples a frequency axis. In the 2nd option CCS is performing a
FOURIER - transform, before it displays the data.
Let us inspect this graph feature:

 Tools  Graph  Single Time

The BOOT-ROM contains a sine value lookup table of 512 samples for a unit circle of 360
degree. The data format is 32-bit signed integers in fractional I2Q30 - format. The start ad-
dress of this table is 0x3FE000. Enter the following parameters:

F2833x - Program Development Tools 3 - 45


Lab 3: beginner’s project

As a result, the graph window should display a single sinusoidal signal:

3 - 46 F2833x - Program Development Tools


Lab 3: beginner’s project

Frequency Domain Graph


Now open a second graph:

 Tools  Graph  FFT Magnitude

Enter the following properties:

Close the graphical windows, when you are done.

F2833x - Program Development Tools 3 - 47


Lab 3: beginner’s project

Mixed Mode C and Assembly Language


An important test method for inspecting both C and the resulting assembly code from the C -
compilation is called “Mixed Mode” - display. This option allows us not only to inspect and
verify the device steps both on C high-level language, but also on the device native
environment assembly language.
18. To visualize C and Assembler:
Right mouse click into the “Disassembly Window” and enable “Show Source”

Optionally, use the green icon “Assembly Single Step” on the top window line.
If you use “Assembly Single Step”, the code is executed machine code line by machine code
line. The dark blue arrow marks the next following assembly line. The light blue arrow
remains at the corresponding line of C code, as long as we deal with the assembly results of
that line.
When you have finished the mixed mode tests, please switch back to “Source Mode” (right
mouse click).

End of Exercise Lab3

3 - 48 F2833x - Program Development Tools


Introduction

Numbering Systems
Introduction
One of the most important factors in embedded control is determining the computing time
for a given task. Because embedded control has to cope with its tasks in a given and fixed
amount of time, we call this “Real-Time Computing”. And, as you know, time goes very
quickly. If the device is also responsible for control actions, such as sampling sensor signals,
deviation control and adjusting actuator output signals then the term “Real-Time Control” is
used.
Therefore, one of the characteristics of a processor is its ability to do mathematical
calculations in an optimal and efficient way. In recent years, the size of mathematical
algorithms that have been implemented in embedded controller units has increased
dramatically. Just take the number of pages for the requirement specification for one of the
various electronic control modules for a passenger car:
• 1990: 50 pages,
• 2000: 3100 pages (Source: Volkswagen AG)
So, how does a processor operate with all these mathematical calculations? And, how does
the processor access and process data?
You probably know that the ‘native’ numbering scheme for a digital controller is binary
numbers. Unfortunately, all process values are either in the format of integer or real
numbers. Depending on how a processor deals with these numbers in its translation into
binary numbers, we distinguish between two basic types of processor core:
• Floating-Point Processors
• Fixed-Point Processors

This chapter will start with a brief comparison between the two types of processor.
After a brief discussion about binary numbers, we will then look into the different options to
use the Fixed-Point unit of the F2833x. It can perform various types of mathematical
operations in a very efficient way, using only a few machine clock cycles.
However, most of today’s numerical simulation systems, such as MATLAB and Simulink
from The Mathworks Corp., operate on Floating-Point numbers. If such a simulation project
is later implemented in a Fixed-Point microcontroller, a set of library functions is used to
operate on Floating-Point numbers. The result will be a noticeably slower performance of
such a system. But not so for the F2833x! This family of devices have an additional
Floating-Point hardware unit, which can directly operate on Floating-Point numbers!
A second option for the Fixed-Point part of the F2833x is called “IQ-Math”. Texas
Instruments provides a library that uses the internal hardware of the C28x in the most
efficient way to operate with 32bit Fixed-Point numbers. Taking into account that most
process data usually do not exceed a 16-bit resolution, the library gives enough headroom for
advanced numerical calculations. The latest version of Texas Instruments “IQ-Math”
Library can be found with literature number “SPRC087” at www.ti.com. We will discuss this
library in more detail in Chapter 17.

F2833x - Numerical Systems 4-1


Module Topics

Module Topics
Numbering Systems ........................................................................................................................... 4-1
Introduction ..................................................................................................................................... 4-1
Module Topics ................................................................................................................................. 4-2
Floating-Point, Integer and Fixed-Point......................................................................................... 4-3
Processor Types .......................................................................................................................... 4-4
IEEE-754 Floating-Point Format ................................................................................................... 4-5
Integer Number Basics .................................................................................................................... 4-8
Two’s Complement representation ............................................................................................. 4-8
Binary Multiplication .................................................................................................................. 4-8
Binary Fractions ........................................................................................................................... 4-10
Multiplying Binary Fractions .................................................................................................... 4-10
The “IQ”-Format .......................................................................................................................... 4-12
Fractional Data in C .................................................................................................................. 4-15
Lab4: Fixed-Point and Floating-Point......................................................................................... 4-16
Objective ................................................................................................................................... 4-16
Procedure .................................................................................................................................. 4-16
Open Files, Create Project File ................................................................................................. 4-16
Build and Load.......................................................................................................................... 4-19
Load Code into Target .............................................................................................................. 4-20
Test the Fixed-Point solution .................................................................................................... 4-20
Floating-Point Library .............................................................................................................. 4-22
Floating-Point Hardware ........................................................................................................... 4-24
Summary ................................................................................................................................... 4-26

4-2 F2833x - Numerical Systems


Floating-Point, Integer and Fixed-Point

Floating-Point, Integer and Fixed-Point


All processors can be divided into two groups, “Floating-Point” and “Fixed-Point”.
However, recent processor designs, such as the F2833x cover both numerical schemes. The
core of a Floating-Point processor is a hardware unit that supports Floating-Point operations
according to the international standard IEEE-754. Intel’s x86-family of Pentium processors
is probably the most popular example of this type. Floating-Point processors are very
efficient when operating with Floating-Point data and allow a high dynamic range for
numerical calculations. They are not so efficient when it comes to control tasks (bit
manipulations, input/output control, and interrupt response) and they are usually more
expensive than their Fixed-Point counter parts.

Floating-Point, Integer and Fixed-Point


 Two basic categories of processors:
 Floating-Point
 Integer/Fixed-Point
 What is the difference?
 What are advantages /
disadvantages ?
 Real-Time Control:
 Most microcontrollers are Fixed-Point!
 F2833x supports both worlds in
hardware!

4-2

Fixed-Point Processors are based on internal hardware that supports operations with integer
data. The Arithmetic Logic Unit (ALU) and in case of a Digital Signal Controller (DSC), the
hardware multiply unit expects data to be in one of the Fixed-Point format data types. There
are limitations in the dynamic range of a Fixed-Point processor, but they are inexpensive.
But what happens, when we write a program for a Fixed-Point processor in C and we declare
a Floating-Point data type ‘float’ or ‘double’? The answer is that library functions are
provided to support this data type on a Fixed-Point machine. However, these standard ANSI-
C functions consume a lot of computing power. If we take into account the time constrains in
a real time project, we just cannot afford to use these data types in most embedded control
applications.
But there is good news: the F2833x offer two solutions to reduce the computing time on
Floating-Point numbers: (1) an optimized library called “IQ-Math” and (2) an additional
Floating-Point hardware unit. The IQ-Math Library is a set of highly optimized and high
precision mathematical functions used to seamlessly port Floating-Point algorithms into
Fixed-Point code. In addition, by incorporating the ready to use high precision functions, the

F2833x - Numerical Systems 4-3


Floating-Point, Integer and Fixed-Point

IQ-Math library can significantly shorten an embedded control development time. We will
discuss this in more detail in Chapter 17.

Processor Types
Most of today’s microprocessors fall into the category of Fixed-Point types. There is a wide
range of semiconductor manufacturers that offer devices of this type. Just to name a few (the
list is in random order and not exhaustive):

• Atmel AVR, ARM7 and Cortex M3 based devices


• Freescale HCS12X, MC56F83x, MCF523x
• Renesas SH4
• Texas Instruments MSP430, TMS320F280xx, Stellaris M3
• Infineon XE166, XC878
• ST Microelectronics STM32
• NEC V850ES / IE2
• Fujitsu MB91480
• Microchip dsPIC 33FJxx
• NXP LPC2900
• Toshiba TMP370

Processor Types
 Floating-Point Processors
 Internal Hardware Unit to support Floating-
Point Operations
 Examples: Intel’s Pentium Series , Texas
Instruments C6000 DSP
 High dynamic range for numeric calculation
 Usually more expensive
 Integer / Fixed-Point Processors
 Fixed-Point Arithmetic Unit
 Almost all embedded controllers are fixed
point machines
 Examples: all microcontroller families, e.g.
Freescale S12X, Infineon C166, Texas
Instruments MSP430, Atmel AVR
 Lowest price per MIPS 4-3

The world of Floating-Point processors is not as widespread as the Fixed-Point group. The
most famous member is Intel’s Pentium family, but there are also others (again, the list is in
random order and not exhaustive):

• Intel x86 Pentium


• Freescale MPC556, PowerPC
• Texas Instruments C6000, DaVinci , TMS320F2833x

4-4 F2833x - Numerical Systems


IEEE-754 Floating-Point Format

IEEE-754 Floating-Point Format


The IEEE Standard for Floating-Point Arithmetic (IEEE-754) is the most widely-used
standard for Floating-Point computation, and is followed by many hardware and software
implementations. Many computer languages allow or require that some or all arithmetic be
carried out using IEEE-754 formats and operations. The current version is IEEE-754-2008,
which was published in August 2008; it includes nearly all of the original IEEE-754-1985
(which was published in 1985) and the IEEE Standard for Radix-Independent Floating-Point
Arithmetic (IEEE-854-1987).
The standard defines:

• arithmetic formats: sets of binary and decimal Floating-Point data, which consist of
finite numbers, (including signed zeros and subnormal numbers), infinities, and
special 'not a number' values (NaNs)
• interchange formats: encodings (bit strings) that may be used to exchange Floating-
Point data in an efficient and compact form
• rounding algorithms: methods to be used for rounding numbers during arithmetic
and conversions
• operations: arithmetic and other operations on arithmetic formats
• exception handling: indications of exceptional conditions (such as division by zero,
overflow, etc.)
The standard also includes extensive recommendations for advanced exception handling,
additional operations (such as trigonometric functions), expression evaluation, and for
achieving reproducible results.

Standard IEEE-754 Single Precision


Floating-Point
31 30 23 22 0
s eeeeeeee fffffffffffffffffffffff
1 bit sign 8 bit exponent 23 bit mantissa (fraction)

Case 1: if e = 255 and f =/ 0, then v = NaN


Case 2: if e = 255 and f = 0, then v = [(-1)s]*infinity

Case 3: if 0 < e < 255, then v = [(-1)s]*[2(e-127)]*(1.f)


Case 4: if e = 0 and f =/ 0, then v = [(-1)s]*[2(-126)]*(0.f)
Case 5: if e = 0 and f = 0, then v = [(-1)s]*0

Advantage ⇒ Exponent gives large dynamic range


Disadvantage ⇒ Precision of a number depends on its exponent

4-4

In the following slides we will focus on the arithmetic numbering formats only.

F2833x - Numerical Systems 4-5


IEEE-754 Floating-Point Format

32-bit Floating-Point format (C data type “float):


• Sign Bit (S):
 Negative: bit 31 = 1 / Positive: Bit 31 = 0

• Mantissa (M):
23
−1 −2
M = 1 + m1 ⋅ 2 + m2 ⋅ 2 + ... + m23 ⋅ 2 − 23
= 1 + ∑ mi ⋅ 2−i
i =1

 Mantissa is normalized to m0 = 1; m0 will not be stored in memory!

1≤ M < 2
• Exponent (E):
 8 Bit signed exponent, stored with offset, OFFSET = +127

• Summary:
E −OFFSET
Z = (− 1) ⋅ M ⋅ 2
S

Example 1:
0x 3FE0 0000 = 0011 1111 1110 0000 0000 0000 0000 0000 B
S=0
E = 0111 1111 = 127
M = (1).11000 = 1 + 0.5 + 0.25 = 1.75
Z = (-1)0 * 1.75 * 2127-127 = 1.75
Example 2:
0x BFB0 0000 = 1011 1111 1011 0000 0000 0000 0000 0000 B
S=1
E = 0111 1111 = 127
M = (1).011 = 1 + 0.25 + 0.125 = 1.375
Z = (-1)1 * 1.375 * 2127-127 = -1.375
Example 3:
Z = - 2.5 S=1
2.5 = 1.25 * 21
1 = E – OFFSET
E = 128
M = 1.25 = (1).01 = 1 + 0.25
Binary Result: 1100 0000 0010 0000 0000 0000 0000 0000 B = 0x C020 0000

4-6 F2833x - Numerical Systems


IEEE-754 Floating-Point Format

The advantage of Floating-Point is its huge dynamic range, which is given by the most
positive exponent (+127, base 2). This exponent plus the maximum mantissa leads to a range
of:

Z = ±(1 − 224 ) ∗ 2128 ≈ ± 3.403 ∗ 1038


The resolution of a single precision Floating-Point number is given by the smallest number
that can be represented in this format:

𝑍𝑍 = 2−23 ∗ 2−126 = 2−149 ≈ 1.401 ∗ 10−45

It seems that with this dynamic range and resolution we should be able to solve any
mathematical operation. However, when it comes to a simple add operation of a large
number and a very small number, even a Floating-Point device can fail! Look at the
following example for z = x + y:

Floating-Point does not solve


everything!
Example: x = 10.0 (0x41200000)
+ y = 0.000000240 (0x3480D959)

z = 10.000000240 WRONG!
RIGHT?
You cannot represent 10.000000240 with
single-precision floating-point

0x412000000 = 10.000000000
10.000000240 ⇐ can’t represent!
0x412000001 = 10.000001000

So z gets rounded down to 10.000000000


4-5

Such a rounding error can happen, when we have to add a compensation value (small) to a
larger set point value in a closed control loop! The result would be a somewhat sluggish
behavior of our digital controller.
In the second part of this chapter you will learn that Fixed-Point numbers do not show this
behavior, if we limit the dynamic range of the numbers to the expected area of a closed loop
control system. When we use the Texas Instruments IQ-Math Fixed-Point hardware, it will
add 10.0 and 0.00000024 to give the exact result of 10.00000024! This is a considerable
advantage of Fixed-Point numbers over Floating-Point numbers!

F2833x - Numerical Systems 4-7


Integer Number Basics

Integer Number Basics


Two’s Complement representation
The next slides summarize the basics of the two’s complement representation of signed
integer numbers. You should already be familiar with these schemes from basic lessons on
computer engineering or digital systems. If not, use Wikipedia to update yourself!

Integer Numbering System Basics

 Binary Numbers
01102 = (0*8)+(1*4)+(1*2)+(0*1) = 610
111102 = (1*16)+(1*8)+(1*4)+(1*2)+(0*1) = 3010

 Two’s Complement Numbers


01102 = (0*-8)+(1*4)+(1*2)+(0*1) = 610
111102 = (1*-16)+(1*8)+(1*4)+(1*2)+(0*1) = -210

4-6

In the signed integer format, the most significant bit (MSB) carries a negative weight of -1. If
the MSB is set, we have to multiply its coefficient representation by -1 (compare example in
the 2nd half of Slide 4-6).

Binary Multiplication
Now consider the process of multiplying two two's complement values, which is one of the
most often used operations in digital control. As with “long hand” decimal multiplication, we
can perform binary multiplication one “place” at a time, and sum the results together at the
end to obtain the total product.
Note: The method shown at the following slide is not the method the F22833x uses to
multiply integer numbers - it is merely a way of observing how binary numbers behave in
arithmetic processes.
The F2833x uses 32-bit operands and an internal 64-bit product register. For the sake of
clarity, consider the example below where we shall investigate the use of 4-bit values and an
8-bit accumulation:

4-8 F2833x - Numerical Systems


Integer Number Basics

Four-Bit Integer Multiplication


0100 4
x 1101 x -3
00000100
0000000
000100
+ 11100
11110100 -12
Accumulator 11110100

Data Memory ?
Is there another (superior) numbering system? 4-7

In this example, consider the following:


• 4 multiplied by (-3) gives (-12) in decimal.
• The size of the product is twice as long as the input values (4 bits * 4 bits = 8 bits).
• If this product is to be used in a next loop of a calculation, how can the result be
stored back to memory in the same length as the inputs?
 Store back upper 4 Bit of Accumulator?  -1
 Store back lower 4 Bit of Accumulator?  +4
 Store back all 8 Bit of Accumulator?  overflow of length
• As a result, scaling of intermediate results is needed!

From this analysis, it is clear that integers do not behave well when multiplied.
The question is: might some other type of integer number system behave better? Is there a
number system where the results of a multiplication have bounds?

The answer is: yes, there is.

F2833x - Numerical Systems 4-9


Binary Fractions

Binary Fractions
In order to represent both positive and negative values, the two's complement process will
again be used. However, in the case of fractions, we will not set the LSB to 1 (as was the
case for integers). When we consider that the range of fractions is from -1 to ~+1, and that
the only bit which conveys negative information is the MSB, it seems that the MSB must be
the “negative ones position”. Since the binary representation is based on powers of two, it
follows that the next bit would be the “one-half” position, and that each following bit would
have half the magnitude again.

Binary Fractions

1 0 1 1

-1
• 1/2 1/4 1/8

= -1 + 1/4 + 1/8 = -5/8

Fractions have the nice property that


fraction x fraction = fraction

4-8

Multiplying Binary Fractions


When the F2833x performs an integer multiplication, the process is identical for all oper-
ands, integers or fractions. Therefore, the user must determine how to interpret the results.
As before, consider the 4-bit multiply example:
The input numbers are now split into two parts - integer part (I-“integer”) and fractional part
(Q-“quotient”). These type of Fixed-Point numbers are often called “IQ”-numbers, or for
simplicity sometimes just Q-numbers.
The example below shows 2 input numbers in I1Q3-Format. When multiplied, the length of
the result will add both I and Q portions (see also next slide):

I1Q3 * I1Q3 = I2Q6

4 - 10 F2833x - Numerical Systems


Binary Fractions

Four-Bit IQ - Multiplication
0100
. 1/2
x 1101
. x - 3/8
00000100
0000000
000100
11100
11110100 -3/16
Accumulator 11110100

Data Memory 1110


. -1/4
4-9

If we store back the intermediate product with the four bits around the binary point we keep
the data format (I1Q3) in the same shape as the input values. There is no need to re-scale any
intermediate results!

Advantage: With Binary Fractions we will gain a lot of speed in closed loop
calculations.
Disadvantage: The result might not be the exact one. As you can see from the slide above
we will end up with (-4/16) stored back to data memory. Bits 2-4 to 2-6 are truncated. The
correct result would have been (-3/16).
Recall that the 4-bit input operand multiplication operation is not the real size for the
F2833x, which operates on 32-bit input values. In this case, the truncation will affect bits 2-32
to 2-64. Given the real size of process data with, let us say 12-bit ADC measurement values,
there is plenty of room left for truncation.
In most cases we will truncate noise only. However, in some feedback applications like
Infinite Impulse Response (IIR)-Filters the small errors can add and lead to a given degree of
instability. It is designer’s responsibility to recognize this potential source of failure when
using binary fractions.

F2833x - Numerical Systems 4 - 11


The “IQ”-Format

The “IQ”-Format
So far we have discussed only the option of using fractional numbers with the binary point at
the MSB-side of the number. In general, we can place this point anywhere in the binary
representation. This gives us the opportunity to trade off dynamic range against resolution.

Fractional Representation
31 0
S IIIIIIII fffffffffffffffffffffff
32 bit mantissa

.
-2I + 2I-1 + … + 21 + 20 2-1 + 2-2 + … + 2-Q

“IQ” – Format
“I” ⇒ INTEGER – Fraction
“Q” ⇒ QUOTIENT – Fraction

Advantage ⇒ Precision same for all numbers in an IQ format


Disadvantage ⇒ Limited dynamic range compared to Floating-Point

4 - 10

IQ - Examples
I1Q3 – Format:
3 0

S fff
Most negative decimal number: -1.0 = 1.000 B

Most positive decimal number: + 0.875 = 0.111 B

Smallest negative decimal number: -1*2-3 (-0.125) = 1.111 B

Smallest positive decimal number: 2-3 (+0.125) = 0.001 B

Range: -1.0 …. 0.875 (≈ + 1.0)


Resolution: 2-3

4 - 11

4 - 12 F2833x - Numerical Systems


The “IQ”-Format

IQ - Examples
I3Q1 – Format:
3 0
SII f
Most negative decimal number: -4.0 = 100.0 B

Most positive decimal number: + 3.5 = 011.1 B

Smallest negative decimal number: -1 * 2-1 (- 0.5) = 111.1 B

Smallest positive decimal number: 2-1 (+0.5) = 000.1 B

Range: -4.0 …. +3.5 (≈ + 4.0)


Resolution: 2-1

4 - 12

IQ - Examples
I1Q31 – Format:
31 0
S fff ffff ffff ffff ffff ffff ffff ffff
Most negative decimal number: -1.0
1.000 0000 0000 0000 0000 0000 0000 0000 B

Most positive decimal number: ≈ + 1.0


0.111 1111 1111 1111 1111 1111 1111 1111 B

Smallest negative decimal number: -1*2-31


1.111 1111 1111 1111 1111 1111 1111 1111 B

Smallest positive decimal number: 2-31


0.000 0000 0000 0000 0000 0000 0000 0001 B

Range: -1.0 …. (+1.0)


Resolution: 2-31

4 - 13

F2833x - Numerical Systems 4 - 13


The “IQ”-Format

IQ - Examples
I8Q24 – Format:
31 0
S III IIII ffff ffff ffff ffff ffff
Most negative decimal number: -128
1000 0000. 0000 0000 0000 0000 0000 0000 B

Most positive decimal number: ≈ + 128


0111 1111. 1111 1111 1111 1111 1111 1111 B

Smallest negative decimal number: -1*2-24


1111 1111. 1111 1111 1111 1111 1111 1111 B

Smallest positive decimal number: 2-24


0000 0000. 0000 0000 0000 0000 0000 0001 B

Range: -128 …. (+128)


Resolution: 2-24

4 - 14

Now let us resume the failing Floating-Point example from the beginning of this module; IQ-
Math can do much better:

IQ-Math can do better!

I8Q24 Example: x = 10.0 (0x0A000000)


+ y = 0.000000240 (0x00000004)

z = 10.000000240 (0x0A000004)

Exact Result (this example)

4 - 15

4 - 14 F2833x - Numerical Systems


The “IQ”-Format

Fractional Data in C
If by now you are convinced that fractional data has advantages over other number
representations, the next question is, how do we code fractions in an ANSI-C environment?
The ANSI-C standard does not define a dedicated data type, such as “fractional”. There is a
new ANSI-standard under development, called “embedded C”, which will eventually use
this type. For now we can use the following trick, as shown in Slide 4-16:

How is a fraction coded?


~1 ~ 32K 7FFF

½ 16K 4000

0
⇒ 0 0000
*32768
–½ –16K C000

–1 –32K 8000
Fractions Integers Hex
 Example: represent the fraction number 0.707

void main(void)
{
int coef = 32768 * 707 / 1000;
}
4 - 16

Fractional vs. Integer


 Range
 Integers have a maximum range
determined by the number of bits
 Fractions have a maximum range of ±1
 Precision
 Integers have a maximum precision of 1
 Fractional precision is determined by
the number of bits

4 - 17

F2833x - Numerical Systems 4 - 15


Lab4: Fixed-Point and Floating-Point

Lab4: Fixed-Point and Floating-Point


Objective
The objective of this lab is to practice and benchmark the different options for the F2833x in
terms of numerical systems. We have already discussed that the F2833x supports both Fixed-
Point and Floating-Point numbers in hardware. In the following lab we will use the simple
code example from Chapter 3 and compile it for the different numbering systems. To
benchmark the results, we will use a time measurement tool, called “Profiler”, which is part
of Code Composer Studio. The following procedure will summarize all steps discussed in
this chapter.

Lab4: Fixed-Point and Floating-Point


 Benchmark Multiply Operation
 k=i*i
 Test setup:
1. Integer multiply operation
2. Floating-Point multiply by Floating-Point Library
3. Floating-Point multiply by Floating-Point
Hardware unit
Benchmark result:
Fixed-point Floating-Point - Floating-Point-
Library Hardware
code size (words) 3 89 9
clock cycles (6.67 ns) 3 112 5
4 - 18

Procedure

Open Files, Create Project File


1. Using Code Composer Studio Version 4, create a new project, called Lab4.pjt in
C:\DSP2833x_V4\Labs (or another working directory used during your class, ask your
instructor for specific location!)

4 - 16 F2833x - Numerical Systems


Lab4: Fixed-Point and Floating-Point

Select a “C2000” project type:

Do not select any other additional project settings:

Finish the project design by adding the following parameters:

F2833x - Numerical Systems 4 - 17


Lab4: Fixed-Point and Floating-Point

• Define the size of the C system stack. In the project window, right click at project
“Lab4” and select “Properties”. In category “C/C++ Build”, “C2000 Linker”, “Basic
Options” set the C stack size to 0x400.
• In the category “C/C++ Build”, “C2000 Compiler”, “Runtime Model Options” scroll
down to “Specify Floating port support” and select “softlib”:

4 - 18 F2833x - Numerical Systems


Lab4: Fixed-Point and Floating-Point

2. Open the file “main.c” from project “Lab3” and save it as “lab4_1.c” in subfolder
“Lab4”:

 File  Open File…  “main.c”


 File  Save As…  “lab4_1.c”

Build and Load


3. Click the “Rebuild Active Project” button or perform: Project  Rebuild Active
Project (Alt +Shift + P) and watch the tools run in the build window. If you get errors,
debug as necessary before you continue.

Create a Target Configuration


4. Before we can download the machine code into the F28335, we have to define the
“target configuration”.
 Target  New Target Configuration

Type a name for the target configuration file in box “File name”. You can use any
name here but it makes sense to indicate the JTAG-emulation interface, which we will
use for the download later. In case of the Peripheral Explorer Board we use the
XDS100V2, so let us call the file “F28335_XDS100V2. The suffix “.ccxml” will be
added automatically.
This time mark “use shared location, because this will allow us to re-use this
configuration in all future projects.
In the window that appears next, select the emulator “Texas Instruments XDS100v2
USB Emulator” via the “Connection” pull-down list and select the “TMS320F28335”
device checkbox.
Save and close the Target Configuration File “F28335_XDS100V2.ccxml”.
In the “Target Configurations” window, right click at “F28335_XDS100V2.ccxml”
and select “Set as Default”:

F2833x - Numerical Systems 4 - 19


Lab4: Fixed-Point and Floating-Point

Load Code into Target


5. Load the machine code into the device. Click:
 Target  Debug Active Project

Or use the “Debug” icon:

At the top right corner of CCS, switch into the “Debug” perspective.

A blue arrow at the left hand side of window “lab4_1.c” should point to the “for” –
line. This is an indication that the machine code has been downloaded properly into
the F28335.

Test the Fixed-Point solution


6. Reset the DSP by clicking on  Target  Reset  Reset CPU, followed by  Tar-
get  Restart

7. Now, benchmark the results. In the “Disassembly” window, right click and enable
“Show Source”, Inspect the code-line, which we used to multiply (k = i * i;)

The C line “k = i*i” has been translated into a set of three assembly language
instructions.

• The first line moves a 16-bit value from data memory (to be exact: from offset
address 8) to internal register ‘T’. Obviously, offset 8 has been used for our
global variable ‘i’. The offset address 8 corresponds to a data page, which has
been initializes earlier (MOVW DP, # 0x0300). The hexadecimal number
0x0300 is used as upper 16 - bit part of the 22 - bit physical address, whereas
the offset 8 is the lower 6 bit part. If you do the math, you will get address
0xC008, the same address shown in the watch window for variable ‘i’.
• Line 2 multiplies the value in register T by the value from the same data
memory location (variable ‘i’). The 32-bit product is stored in register
“Accumulator (ACC)”.

4 - 20 F2833x - Numerical Systems


Lab4: Fixed-Point and Floating-Point

• Line 3 stores the lower 16-bits of the 32-bit product (register “Accumulator-
low”, AL) back into memory at address 9 of the active page. Obviously, address
9 at page 0x300 is the location of global variable ‘k’.
Benchmark #1 (code-size):
As you can see from the numbers at the left hand side, our code snippet “k = i * i”
occupies the code memory addresses 0x9080 to 0x9082, which gives a code size of 3
words. (Note: the absolute address numbers might be different on your CCS-session;
however the size should be identical).

Benchmark #2 (execution speed):

To measure the number of execution clock cycles, we can use the CCS “Clock Profi-
ler”:
 Target  Clock  Enable
 Target  Clock  View
A small yellow profiler clock will appear in the lower right corner of CCS.

This is our time measurement system. Using “Step Into” (F5), run the code until you
reach the line “k = i * i”. The number to the right of the clock gives the number of
elapsed clock cycles. To clear this number, double click on the yellow clock icon.
Now, with the yellow arrow still on line “k = i * i”, perform a single “Step Into” (F5).
The profiler clock should show a ‘3’, which indicates that one execution of the line “k
= i * i” took 3 clock cycles. This result corresponds to the three machine code
instructions, which we inspected above. Each instruction is executed in 1 CPU clock
cycle.

Result 1 (Fixed-Point math):


• Code size: 3 words
• Clock cycles: 3

F2833x - Numerical Systems 4 - 21


Lab4: Fixed-Point and Floating-Point

Floating-Point Library
8. Now let us change the code from Fixed-Point to Floating-Point. In the “C/C++
Perspective” of project “Lab4” in file “lab4_1.c”, change the data type of ‘k’ from
“unsigned int” to “float”.
Add a new global variable “float f = 1.0;”.
Change the code line “k = i * i;” into “k = f * f;”.

After this line but still inside the for-loop, add a new line “f = f + 1.0;”
Save the file as “Lab4_2.c”. Note: The file is added automatically to project “Lab4”.
Exclude “Lab4_1.c” from the build. In the project window, right click on “Lab4_1.c”
and select “Exclude from Build”. This technique allows us to keep more than one
source code file in the project tree and we can change between the different files. Note
the crossed out icon for “Lab4_1.c”, which indicates that this file has been excluded:

9. Rebuild the project and reload the new code:


 Target  Debug Active Project

10. Now, benchmark the results. Change into “Debug” perspective. In the “Disassembly
Window”, right click and enable “Show Source". Inspect the code-line, which we used
to multiply f by f:

The Floating-Point line “k = f * f” has been translated in a series of 6 assembly


language instructions. This is because the variables are now of Floating-Point type.

4 - 22 F2833x - Numerical Systems


Lab4: Fixed-Point and Floating-Point

• The 1st line reads a 32 bit value from data memory offset 2 into register ACC.
This is the Floating-Point variable ‘f’ as the first factor.
• Next and in preparation of the function call in line 4, this value is passed as an
input parameter back to stack memory [SP-2].
• Line 3 reads once more variable ‘f’ and stores it again in register ACC. Register
ACC is used to pass the 2nd multiply factor in the function call in line 4.
• Line 4 calls a Floating-Point multiply function “FS$$MPY”. The assembly
instruction “LCR-Long Call with Return” calls a function from library
“rts2800_ml.lib”, which performs a Floating-Point multiply on a Fixed-Point
device.
• The last two lines are used to store the result of the function call, which is
returned in register ACC, into memory address 4 of the active data page (address
of variable ‘k’).
Benchmark #3 (code-size, Floating-Point library function):
As you can see from the numbers at the left hand side, our code-snippet “k = f * f”
occupies the code memory addresses 0x911D to 0x9124, which gives a code size of 8
words. (Note: the absolute address numbers might be different on your CCS-session;
however the size should be identical). However, this result is not the full story! For
code size we have to add the size of function “FS$$MPY”. When you use “Assembly
Single Step Into” until you reach the instruction “LCR” and continue with another
assembly single step, CCS will open another disassembly window with the
instructions of function “FS$$MPY”. If you scroll down this window, you will find an
instruction “LRETR”, which is the return instruction of this function. The difference
between start- and end- address (0x90C9 - 0x9078) is the size of function
“FS$$MPY”.
Result for code size: 8 + 81 = 89 words.

Benchmark #4 (execution speed, Floating-Point library):


To measure the number of clock cycles for one Floating-Point multiplication, we can
use the same profiler steps as we did for the integer code:
From the beginning of “main()”, single step until you reach the line “k = f * f”. Clear
the profile clock counter (left double click) and perform another source single step
(F5). The result is: 112 clock cycles. Note: The numbers were measured with C
compiler - and library version 5.2.3. They might be different on your installation, but
they should be in the same sort of range.

Result for Floating-Point library:


• Code size: 89 words
• Clock cycles: 112

F2833x - Numerical Systems 4 - 23


Lab4: Fixed-Point and Floating-Point

Floating-Point Hardware
As a final step we will use the F2833x Floating-Point hardware unit and replace the Floating-
Point library function “FS$$MPY”(). This should reduce both the code size and the number
of clock cycles back to the integer results.
11. Add the Floating-Point support function to your project:
In the “C/C++” perspective and in the project window, right click at project “Lab4”
and select “Properties”. In the “Configuration Settings” select “Tool Settings” –
“C2000 Compiler” and “Runtime Model Options” scroll down to “Specify floating
point support” and select “fpu32”.

12. Rebuild the project and reload the new code:


 Target  Debug Active Project

13. Now, benchmark the results. Again, in the “Debug Perspective” and the “Disassem-
bly” window enable Show Source”. Inspect the code lines, which we use to multiply f
by f:

4 - 24 F2833x - Numerical Systems


Lab4: Fixed-Point and Floating-Point

The Floating-Point line “k = f * f” has been translated in a series of 5 assembly


instructions, which use the Floating-Point hardware unit:

• The 1st line moves a 32-bit value from data memory offset location 2 into Floating-
Point register R0H. This is float variable ‘f’ as the first multiplication factor.
• The 2nd line moves the same value into Floating-Point register R1H. This is our 2nd
factor.
• The next line is a Floating-Point multiply operation of R0H multiplied by R1H. The
product is stored in register R0H.
• Line 4 is a “no operation” instruction. It is used to compensate a clock difference
between the Floating-Point unit and the main unit.
• The last line stores the product (R0H) back in data memory at offset address 4 of the
active data page.
Benchmark #5 (code-size, Floating-Point hardware):
As you can see from the numbers at the left hand side, our code-snippet “k = f * f”
occupies the code memory addresses 0x904C to 0x9053, or 9 words.
Benchmark #6 (execution speed, Floating-Point hardware):
Using the profiler, measure the number of clock cycles for one Floating-Point
multiplication. From the beginning of “main()”, single step until you reach the line “k =
f * f”. Clear the clock counter and do another source single step. The result is 5!

F2833x - Numerical Systems 4 - 25


Lab4: Fixed-Point and Floating-Point

Summary
In Lab4 we benchmarked the 3 possible solutions that can be used to multiply two values.
For a Fixed-Point processor the native numbering scheme is integer. As you can see from the
numbers, both code size and clock cycles are minimal; we can generate an optimal solution
for real-time control, where speed always has the highest priority.

Fixed- Floating-Point- Floating-Point-


Point Library Hardware

code size (words) 3 89 9

clock cycles (6.67 ns) 3 112 5

However, if the software designer decides to use Floating-Point data types for variables k
and f, the library function will dramatically increase both code size and number of clock
cycles. Such a solution could lead to code, which could well be too slow for use in real-time
control. For most microcontrollers this is the end of the road…

Not so for the F2833x!

If we enable Floating-Point hardware support, we easily can use Floating-Point data types
with approximately the same speed factor as in Fixed-Point! The code size is a little bit
larger than for Fixed-Point numbers, but in most cases this does not matter.

To resume the discussion: With an F2833x device, the designer can use both worlds, Fixed-
and Floating-Point, with the same code performance!

4 - 26 F2833x - Numerical Systems


Digital Input / Output

Introduction
This module introduces the first integrated peripherals of the F2833x Digital Signal
Controller. The device has not only a 32-bit processor core, but also all of the peripheral
units needed to build a single chip control system (SOC-“System on Chip”). These integrated
peripherals give the F2833x an important advantage over other processors.
We will start with the simplest peripheral unit-Digital I/O. At the end of this chapter we will
exercise input lines (switches, buttons) and output lines (LEDs).

Data Memory Mapped Peripherals


All the peripheral units of the F2833x are memory mapped into the data memory space of its
Harvard Architecture Machine. This means that we control peripheral units by accessing
dedicated data memory addresses. The following slide shows these units:

F2833x Block Diagram


Program Bus
ePWM

Boot DMA eCAP


Sectored RAM
A(19-
ROM 6 Ch.
A(19-0) Flash eQEP
XINTF

DMA Bus
12-
12-bit ADC

D(31-
D(31-0) Watchdog

PIE
32-
32-bit R-M-W Interrupt CAN 2.0B
32x32 bit Manager
Auxiliary Atomic FPU
Multiplier I2C
Registers ALU
3
Real-
Real-Time SCI
32-
32-bit
JTAG Register Bus Timers SPI
Emulation CPU
McBSP
Data Bus
GPIO
5-2

F2833x - Digital I/O 5-1


Module Topics

Module Topics
Digital Input / Output ................................................................................................................................ 5-1
Introduction ............................................................................................................................................. 5-1
Data Memory Mapped Peripherals ......................................................................................................... 5-1
Module Topics ......................................................................................................................................... 5-2
The Peripheral Frames ........................................................................................................................... 5-3
Digital I/O Unit ....................................................................................................................................... 5-5
F2833x Pin Assignment ...................................................................................................................... 5-7
GPIO Input Qualification .................................................................................................................. 5-10
Summary GPIO-Registers ................................................................................................................ 5-11
F2833x Clock Module ........................................................................................................................... 5-12
Watchdog Timer .................................................................................................................................... 5-14
System Control and Status Register ...................................................................................................... 5-17
Low Power Mode .................................................................................................................................. 5-17
Lab 5_1: Digital Output at 4 LEDs ....................................................................................................... 5-20
Objective ........................................................................................................................................... 5-21
Procedure .......................................................................................................................................... 5-21
Create a Project File .......................................................................................................................... 5-21
Project Build Options ........................................................................................................................ 5-22
Modify the Source Code ................................................................................................................... 5-23
Setup the control loop ....................................................................................................................... 5-23
Build and Load.................................................................................................................................. 5-24
Test ................................................................................................................................................... 5-24
Enable Watchdog Timer ................................................................................................................... 5-24
Service the Watchdog Timer............................................................................................................. 5-25
Lab 5_2: Digital Output (modified) ...................................................................................................... 5-27
Procedure .......................................................................................................................................... 5-27
Modify Code and Project File ........................................................................................................... 5-27
Lab 5_3: Digital Input........................................................................................................................... 5-28
Objective ........................................................................................................................................... 5-28
Procedure .......................................................................................................................................... 5-28
Modify Code and Project File ........................................................................................................... 5-28
Build, Load and Test ......................................................................................................................... 5-29
Lab 5_4: Digital In- and Output ........................................................................................................... 5-30
Objective ........................................................................................................................................... 5-30
Modify Code and Project File ........................................................................................................... 5-30
Modify Lab5_4.C.............................................................................................................................. 5-30
Build, Load and Test ......................................................................................................................... 5-31
Lab 5_5: Digital In- and Output Start / Stop ........................................................................................ 5-32
Objective ........................................................................................................................................... 5-32
Modify Code and Project File ........................................................................................................... 5-32
Modify Lab5_5.c .............................................................................................................................. 5-32
Build, Load and Test ......................................................................................................................... 5-33

5-2 F2833x - Digital I/O


The Peripheral Frames

The Peripheral Frames


All peripheral registers are grouped together into what are known as “Peripheral Frames”-
PF0, PF1, PF2 and PF3. These frames are mapped in data memory only. Peripheral Frame
PF0 includes register sets to control the internal speed of the FLASH memory, as well as the
timing setup for external memory devices, direct memory access unit registers, core CPU
timer registers and the code security module control block. Flash is internal non-volatile
memory, usually used for code storage and for data that must be present at boot time.
Peripheral Frame PF1 contains most of the peripheral unit control registers, such as ePWM,
eCAP, Digital Input/Output control and the CAN register block. CAN-“Controller Area
Network” is a well-established network widely used inside motor vehicles to build a network
between electronic control units (ECU). Peripheral Frame PF2 combines the core system
control registers, the Analogue to Digital Converter and all other communication channels
other than McBSP, which has been allocated to PF3.

TMS320F2833x Memory Map


Data Program
0x000000 0x010000
M0 SARAM (1Kw)
0x000400 reserved
M1 SARAM (1Kw)
0x100000
0x000800 XINTF Zone 6 (1Mw)
0x000D00 0x200000
PIE Vectors XINTF Zone 7 (1Mw)
(256 w) 0x300000
0x000E00 reserved
PF 0 (6Kw) FLASH (256Kw) Dual Mapped:
0x002000
L0, L1, L2, L3
0x004000 0x33FFF8
PASSWORDS (8w)
XINTF Zone 0 (4Kw) 0x340000
0x005000 reserved
PF 3 (4Kw) 0x380080
0x006000 ADC calibration data
PF 1 (4Kw) reserved 0x380090
0x007000 reserved CSM Protected:
PF 2 (4Kw) 0x380400 L0, L1, L2, L3,
0x008000 User OTP (1Kw) FLASH, ADC CAL,
L0 SARAM (4Kw) 0x380800
0x009000 reserved OTP
L1 SARAM (4Kw) 0x3F8000
0x00A000 L0 SARAM (4Kw)
L2 SARAM (4Kw) 0x3F9000
0x00B000 L1 SARAM (4Kw)
L3 SARAM (4Kw) 0x3FA000 DMA Accessible:
0x00C000 L2 SARAM (4Kw)
L4 SARAM (4Kw) 0x3FB000 L4, L5, L6, L7,
0x00D000 L3 SARAM (4Kw) XINTF Zone 0, 6, 7
L5 SARAM (4Kw) 0x3FC000
0x00E000 reserved
L6 SARAM (4Kw) 0x3FE000
0x00F000 Boot ROM (8Kw)
L7 SARAM (4Kw)
0x010000 0x3FFFC0
BROM Vectors (64w)
0x3FFFFF
Data Program 5-3

F2833x - Digital I/O 5-3


The Peripheral Frames

The detailed mapping of peripherals into data memory is as follows:

PF0: PIE: PIE Interrupt Enable and Control Registers plus PIE Vector Table
Flash: Flash Wait state Registers
XINTF: External Interface Registers
DMA: DMA Registers
Timers: CPU-Timers 0, 1, 2 Registers
CSM: Code Security Module KEY Registers
ADC: ADC Result registers (dual-mapped)

PF1: eCAN: eCAN Mailbox and Control Registers


GPIO: GPIO MUX Configuration and Control Registers
ePWM: Enhanced Pulse Width Modulator Module and Registers (dual
mapped)
eCAP: Enhanced Capture Module and Registers
eQEP: Enhanced Quadrature Encoder Pulse Module and Registers

PF2: SYS: System Control Registers


SCI: Serial Communications Interface (SCI) Control and RX/TX Regis-
ters
SPI: Serial Port Interface (SPI) Control and RX/TX Registers
ADC: ADC Status, Control, and Result Register
I2C: Inter-Integrated Circuit Module and Registers
XINT: External Interrupt Registers

PF3: McBSP: Multichannel Buffered Serial Port Registers


ePWM: Enhanced Pulse Width Modulator Module and Registers (dual
mapped)

Some of the memory areas are password protected by the “Code Security Module” (check
patterned areas of the slide above). This is a feature to prevent reverse engineering. Once the
password area is programmed, any access to the secured areas is only granted when the
correct password is entered into a special area of PF0.
Now let us start with a discussion of the Digital Input/Output unit.

5-4 F2833x - Digital I/O


Digital I/O Unit

Digital I/O Unit


All digital I/O’s are grouped together into “Ports”, called GPIO-A, B and C. Here GPIO
means “general purpose input output”. The F2833x features a total of 88 I/O-pins, called
GPIO0 to GPIO87. But there’s more. The device comes with so many additional internal
units, that not all features could be connected to dedicated pins of the device package at any
one time. The solution is: multiplex. This means, one single physical pin of the device can be
used for up to 4 different functions and it is up to the programmer to decide which function is
selected. The next slide shows a block diagram of one physical pin of the device:

F2833x GPIO Pin Block Diagram

Peripheral Peripheral Peripheral


I/O DIR Bit 1 2 3
GPxSET 0 = Input
GPxCLEAR 1 = Output
GPxTOGGLE
GPxDIR
GPxDAT
Out
01• • 10 GPxMUX1
00• •11 GPxMUX2
I/O DAT
Bit (R/W) MUX Control Bits
In
00 = GPIO
01 = Peripheral 1
10 = Peripheral 2
11 = Peripheral 3
Input
Qualification
GPxPUD
• (GPIO 0-
0-63 only)
GPxQSEL1
GPxQSEL2
Internal Pull-
Pull-Up GPxCTRL
0 = enable (default GPIO 12-
12-31)
1 = disable (default GPIO 0-
0-11)
Pin

5-4

The term “Input Qualification” refers to an additional option for digital input signals at
GPIO0-63. When this feature is used, an input pulse must be longer than the specified
number of clock cycles to be recognized as a valid input signal. This is useful for removing
input noise.
Register Group “GPxPUD” can be used to disable internal pull-up resistors to leave the
voltage level floating or high-impedance.
When a digital I/O function is selected, then register group GPxDIR defines the direction of
the Input or Output. Clearing a bit position to zero configures the line as an input, setting the
bit position to 1 configures the line as an output.
A data read from an input line is performed with a set of GPxDAT registers.
A data write to an output line can also be performed with registers GPxDAT. Additionally,
there are 3 more groups of registers:
• GPxSET
• GPxCLEAR
• GPxTOGGLE

F2833x - Digital I/O 5-5


Digital I/O Unit

The objective of these registers is to use a mask technique to set, clear or toggle those output
lines, which correspond to a bit set to 1 in the mask in use. For example, to clear line GPIO5
to 0, one can use the instruction:
• GpioDataRegs.GPACLEAR.bit.GPIO5 = 1;

The following slide summarizes the I/O control register set:

F2833x GPIO Grouping Overview

GPIO Port A Mux1


Input

GPIO Port A
Register (GPAMUX1)
[GPIO 0 to 15] GPIO Port A
Direction Register Qual
(GPADIR)
GPIO Port A Mux2 [GPIO 0 to 31]
Register (GPAMUX2)
[GPIO 16 to 31]

GPIO Port B Mux1


Input
Internal Bus

GPIO Port B
Register (GPBMUX1)
[GPIO 32 to 47] GPIO Port B
Direction Register Qual
(GPBDIR)
GPIO Port B Mux2 [GPIO 32 to 63]
Register (GPBMUX2)
[GPIO 48 to 63]

GPIO Port C Mux1

GPIO Port C
Register (GPCMUX1)
[GPIO 64 to 79] GPIO Port C
Direction Register
(GPCDIR)
GPIO Port C Mux2 [GPIO 64 to 87]
Register (GPCMUX2)
[GPIO 80 to 87]

5-5

5-6 F2833x - Digital I/O


Digital I/O Unit

F2833x Pin Assignment


The next five slides show the multiplex assignment for all 88 I/O-lines:

F2833x GPIO Pin Assignment

GPIO - A Multiplex Register GPAMUX1


GPAMUX1 - Bits 00 01 10 11
1,0 GPIO0 EPWM1A - -
3,2 GPIO1 EPWM1B ECAP6 MFSRB
5,4 GPIO2 EPWM2A - -
7,6 GPIO3 EPWM2B ECAP5 MCLKRB
9,8 GPIO4 EPWM3A - -
11,10 GPIO5 EPWM3B MFSRA ECAP1
13,12 GPIO6 EPWM4A EPWMSYNCI EPWMSYNC0
15,14 GPIO7 EPWM4B MCLKRA ECAP2
17,16 GPIO8 EPWM5A CANTXB /ADCSOCA0
19,18 GPIO9 EPWM5B SCITXDB ECAP3
21,20 GPIO10 EPWM6A CANRXB /ADCSOCB0
23,22 GPIO11 EPWM6B SCIRXDB ECAP4
25,24 GPIO12 /TZ1 CANTXB SPISIMOB
27,26 GPIO13 /TZ2 CANRXB SPISOMIB
29,28 GPIO14 /TZ3_/XHOLD SCITXDB SPICLKB
31,30 GPIO15 /TZ4_/XHOLDA SCIRXDB /SPISTEB

5-6

F2833x GPIO Pin Assignment

GPIO - A Multiplex Register GPAMUX2


GPAMUX2 - Bits 00 01 10 11
1,0 GPIO16 SPISIMOA CANTXB /TZ5
3,2 GPIO17 SPISOMIA CANRXB /TZ6
5,4 GPIO18 SPICLKA SCITXDB CANRXA
7,6 GPIO19 /SPISTEA SCIRXDB CANTXA
9,8 GPIO20 EQEP1A MDXA CANTXB
11,10 GPIO21 EQEP1B MDRA CANRXB
13,12 GPIO22 EQEP1S MCLKXA SCITXDB
15,14 GPIO23 EQEP1I MFSXA SCIRXDB
17,16 GPIO24 ECAP1 EQEP2A MDXB
19,18 GPIO25 ECAP2 EQEP2B MDRB
21,20 GPIO26 ECAP3 EQEP2I MCLKXB
23,22 GPIO27 ECAP4 EQEP2S MFSXB
25,24 GPIO28 SCIRXDA /XZCS6 /XZCS6
27,26 GPIO29 SCITXDA XA19 XA19
29,28 GPIO30 CANRXA XA18 XA18
31,30 GPIO31 CANTXA XA17 XA17

5-7

F2833x - Digital I/O 5-7


Digital I/O Unit

F2833x GPIO Pin Assignment

GPIO - B Multiplex Register GPBMUX1


GPBMUX1 - Bits 00 01 10 11
1,0 GPIO32 SDAA EPWMSYNCI /ADCSOCA0
3,2 GPIO33 SCLA EPWMSYNCO /ADCSOCB0
5,4 GPIO34 ECAP1 XREADY XREADY
7,6 GPIO35 SCITXDA XR/W XR/W
9,8 GPIO36 SCIRXDA /XZCS0 /XZCS0
11,10 GPIO37 ECAP2 /XZCS7 /XZCS7
13,12 GPIO38 - /XWE0 /XWE0
15,14 GPIO39 - XA16 XA16
17,16 GPIO40 - XA0/XWE1 XA0/XWE1
19,18 GPIO41 - XA1 XA1
21,20 GPIO42 - XA2 XA2
23,22 GPIO43 - XA3 XA3
25,24 GPIO44 - XA4 XA4
27,26 GPIO45 - XA5 XA6
29,28 GPIO46 - XA6 XA6
31,30 GPIO47 - XA7 XA7

5-8

F2833x GPIO Pin Assignment

GPIO - B Multiplex Register GPBMUX2


GPBMUX2 - Bits 00 01 10 11
1,0 GPIO48 ECAP5 XD31 XD31
3,2 GPIO49 ECAP6 XD30 XD30
5,4 GPIO50 EQEP1A XD29 XD29
7,6 GPIO51 EQEP1B XD28 XD28
9,8 GPIO52 EQEP1S XD27 XD27
11,10 GPIO53 EQEP1I XD26 XD26
13,12 GPIO54 SPISIMOA XD25 XD25
15,14 GPIO55 SPISOMIA XD24 XD24
17,16 GPIO56 SPICLKA XD23 XD23
19,18 GPIO57 /SPISTEA XD22 XD22
21,20 GPIO58 MCLKRA XD21 XD21
23,22 GPIO59 MFSRA XD20 XD20
25,24 GPIO60 MCLKRB XD19 XD19
27,26 GPIO61 MFSRB XD18 XD18
29,28 GPIO62 SCIRXDC XD17 XD17
31,30 GPIO63 SCITXDC XD16 XD16

5-9

5-8 F2833x - Digital I/O


Digital I/O Unit

F2833x GPIO Pin Assignment


GPIO - C Multiplex Register

GPCMUX1 - 00 or 01 10 or 11 GPCMUX2 - 00 or 01 10 or 11
Bits Bits
1,0 GPIO64 XD15 1,0 GPIO80 XA8
3,2 GPIO65 XD14 3,2 GPIO81 XA9
5,4 GPIO66 XD13 5,4 GPIO82 XA10
7,6 GPIO67 XD12 7,6 GPIO83 XA11
9,8 GPIO68 XD11 9,8 GPIO84 XA12
11,10 GPIO69 XD10 11,10 GPIO85 XA13
13,12 GPIO70 XD9 13,12 GPIO86 XA14
15,14 GPIO71 XD8 15,14 GPIO87 XA15
17,16 GPIO72 XD7 17,16 - -
19,18 GPIO73 XD6 19,18 - -
21,20 GPIO74 XD5 21,20 - -
23,22 GPIO75 XD4 23,22 - -
25,24 GPIO76 XD3 25,24 - -
27,26 GPIO77 XD2 27,26 - -
29,28 GPIO78 XD1 29,28 - -
31,30 GPIO79 XD0 31,30 - -

5 - 10

F2833x - Digital I/O 5-9


Digital I/O Unit

GPIO Input Qualification


As has already been stated, this feature on GPIO0-63 behaves like a low-pass input filter on
noisy input signals. It is controlled by a pair of additional registers.

F2833x GPIO Input Qualification

Input to GPIO and


pin peripheral
Qualification modules

SYSCLKOUT

 Qualification available on ports A & B (GPIO 0 - 63) only


 Individually selectable per pin samples taken
 no qualification (peripherals only)
 sync to SYCLKOUT only
 qualify 3 samples
 qualify 6 samples
 Port C pins are fixed as T T T
‘sync to SYSCLKOUT’ T = qualification period
5 - 11

F2833x GPIO Input Qualification Registers

GPAQSEL1 / GPAQSEL2 / GPBQSEL1 / GPBQSEL2


31 0
16 pins configured per register

00 = sync to SYSCLKOUT only


01 = qual to 3 samples
10 = qual to 6 samples
11 = no sync or qual (for peripheral only; GPIO same as 00)

GPACTRL / GPBCTRL
31 24 16 8 0
QUALPRD3 QUALPRD2 QUALPRD1 QUALPRD0
B: GPIO63-56 GPIO55-48 GPIO47-40 GPIO39-32
A: GPIO31-24 GPIO23-16 GPIO15-8 GPIO7-0

0x00 no qualification (SYNC to SYSCLKOUT)


0x01 QUALPRD = TSYSCLKOUT * 2
0x02 QUALPRD = TSYSCLKOUT * 4
… … …
0xFF QUALPRD = TSYSCLKOUT * 510
5 - 12

5 - 10 F2833x - Digital I/O


Digital I/O Unit

Summary GPIO-Registers
The next two slides will summarize all registers of the GPIO-unit.

C2833x GPIO Control Registers

Register Description
GPACTRL GPIO A Control Register [GPIO 0 – 31]
GPAQSEL1 GPIO A Qualifier Select 1 Register [GPIO 0 – 15]
GPAQSEL2 GPIO A Qualifier Select 2 Register [GPIO 16 – 31]
GPAMUX1 GPIO A Mux1 Register [GPIO 0 – 15]
GPAMUX2 GPIO A Mux2 Register [GPIO 16 – 31]
GPADIR GPIO A Direction Register [GPIO 0 – 31]
GPAPUD GPIO A Pull-
Pull-Up Disable Register [GPIO 0 – 31]
GPBCTRL GPIO B Control Register [GPIO 32 – 63]
GPBQSEL1 GPIO B Qualifier Select 1 Register [GPIO 32 – 47]
GPBQSEL2 GPIO B Qualifier Select 2 Register [GPIO 48 – 63]
GPBMUX1 GPIO B Mux1 Register [GPIO 32 – 47]
GPBMUX2 GPIO B Mux2 Register [GPIO 48 – 63]
GPBDIR GPIO B Direction Register [GPIO 32 – 63]
GPBPUD GPIO B Pull-
Pull-Up Disable Register [GPIO 32 – 63]
GPCMUX1 GPIO C Mux1 Register [GPIO 64 – 79]
GPCMUX2 GPIO C Mux2 Register [GPIO 80 – 87]
GPCDIR GPIO C Direction Register [GPIO 64 – 87]
GPCPUD GPIO C Pull-
Pull-Up Disable Register [GPIO 64 – 87]
5 - 13

C2833x GPIO Data Registers

Register Description
GPADAT GPIO A Data Register [GPIO 0 – 31]
GPASET GPIO A Data Set Register [GPIO 0 – 31]
GPACLEAR GPIO A Data Clear Register [GPIO 0 – 31]
GPATOGGLE GPIO A Data Toggle [GPIO 0 – 31]
GPBDAT GPIO B Data Register [GPIO 32 – 63]
GPBSET GPIO B Data Set Register [GPIO 32 – 63]
GPBCLEAR GPIO B Data Clear Register [GPIO 32 – 63]
GPBTOGGLE GPIO B Data Toggle [GPIO 32 – 63]
GPCDAT GPIO C Data Register [GPIO 64 – 87]
GPCSET GPIO C Data Set Register [GPIO 64 – 87]
GPCCLEAR GPIO C Data Clear Register [GPIO 64 – 87]
GPCTOGGLE GPIO C Data Toggle [GPIO 64 – 87]

5 - 14

F2833x - Digital I/O 5 - 11


F2833x Clock Module

F2833x Clock Module


Before we can start using the digital I/Os, we need to setup the F2833x Clock Module. Like
all modern processors, the F2833x is driven externally by a much slower clock generator or
oscillator to reduce electromagnetic interference. An internal PLL circuit generates the
internal speed. The F28335 ControlCard in our Labs is running at 20MHz externally. To
achieve the internal frequency of 100 MHz, we have to use the multiply by a factor of 10,
followed by a divide by 2. This is implemented by programming the PLL control register
(PLLCR).

F2833x Clock Module

Watchdog
Module CLKIN C28x
XCLKIN
Core
OSCCLK
X1
• • (PLL bypass) MUX SYSCLKOUT
• •
XTAL OSC

1/n
crystal VCOCLK
PLL HISPCP LOSPCP
X2
HSPCLK LSPCLK
SysCtrlRegs.PLLCR.bit.DIV ADC SCI, SPI, I2C,
SysCtrlRegs.PLLSTS.bit.DIVSEL McBSP

DIV CLKIN All other peripherals


DIVSEL n clocked by SYSCLKOUT
0x /4 * 0000 OSCCLK / n * (PLL bypass)
10 /2 0001 OSCCLK x 1 / n
0010 OSCCLK x 2 / n Input Clock Fail Detect Circuitry
11 /1
0011 OSCCLK x 3 / n
* default 0100 OSCCLK x 4 / n PLL will issue a “limp mode”
mode”
Note: /1 mode can 0101 OSCCLK x 5 / n clock (1-
(1-4 MHz) if input clock is
only be used when removed after PLL has locked.
PLL is bypassed 0110 OSCCLK x 6 / n
0111 OSCCLK x 7 / n An internal device reset will also
1000 OSCCLK x 8 / n be issued (XRSn
(XRSn pin not driven).
1001 OSCCLK x 9 / n
1010 OSCCLK x 10 / n
5 - 15

High-speed Clock Pre-scaler (HISPCP) and Low speed Clock Pre-scaler (LOSPCP) are used
as additional clock dividers. The outputs of the two pre-scalers are used as the clock source
for the peripheral units. We can set up the two pre-scalers individually and independently.
Note that:
(1) the signal “CLKIN” is of the same frequency as the core output signal “SYSCLKOUT”,
which is used for the external memory interface, for clocking the ePWMs and the CAN-unit.
(2) the Watchdog Unit is clocked directly by the external oscillator.
(3) the maximum frequency for the external oscillator is 35MHz.

5 - 12 F2833x - Digital I/O


F2833x Clock Module

F2833x Clock Scaling

SysCtrlRegs.HISPCP
15 - 3 2-0
reserved HSPCLK

ADC
SysCtrlRegs.LOSPCP
15 - 3 2-0
reserved LSPCLK

SCI / SPI /
H/LSPCLK Peripheral Clock Frequency I2C / McBSP
000 SYSCLKOUT / 1
001 SYSCLKOUT / 2 (default HISPCP)
NOTE:
NOTE:
010 SYSCLKOUT / 4 (default LOSPCP)
011 SYSCLKOUT / 6 All Other
100 SYSCLKOUT / 8 Peripherals
101 SYSCLKOUT / 10 Clocked By
110 SYSCLKOUT / 12 SYSCLKOUT
111 SYSCLKOUT / 14

5 - 16

To use a peripheral unit, we have to enable its clock distribution by setting individual bit
fields of the PCLKCRx register. Bit field “GPIOIN_ENCLK” enables the clock signal for
the input qualification filter. If input qualification is not used, then it is not necessary to
enable this bit.

F2833x Clock Control Unit

SysCtrlRegs.PCLKCR0
15 14 13 12 11 10 9 8
ECANB ECANA MA MB SCIB SCIA reserved SPIA
ENCLK ENCLK ENCLK ENCLK ENCLK ENCLK ENCLK
7 6 5 4 3 2 1 0
SCIC I2CA ADC TBCLK reserved reserved
reserved reserved ENCLK ENCLK ENCLK SYNC

SysCtrlRegs.PCLKCR1
15 14 13 12 11 10 9 8
EQEP2 EQEP1 ECAP6 ECAP5 ECAP4 ECAP3 ECAP2 ECAP1
ENCLK ENCLK ENCLK ENCLK ENCLK ENCLK ENCLK ENCLK
7 6 5 4 3 2 1 0

reserved EPWM6 EPWM5 EPWM4 EPWM3 EPWM2 EPWM1


reserved ENCLK ENCLK ENCLK
ENCLK ENCLK ENCLK

SysCtrlRegs.PCLKCR3
15 - 14 13 12 11 10 9 8 7-0

reserved GPIOIN XINTF DMA CPUTIMER2 CPUTIMER1 CPUTIMER0 reserved


ENCLK ENCLK ENCLK ENCLK ENCLK ENCLK

Module Enable Clock Bit


0 = disable (default) 1 = enable
5 - 17

F2833x - Digital I/O 5 - 13


Watchdog Timer

Watchdog Timer
A “Watchdog Timer” is a free running counter unit that triggers a reset if it is not cleared
periodically by a specific instruction sequence. It is used to recognize events where the
program leaves its designated sequence of execution, for example, if the program crashes.

Watchdog Timer

 Resets the F2833x if the CPU crashes


 Watchdog counter runs independent of CPU
 If counter overflows, a reset or interrupt is
triggered (user selectable)
 CPU must write correct data key sequence to
reset the counter before overflow
 Watchdog must be serviced or disabled
within 4.37ms after reset (assuming a 30
MHz OSCCLK)
 This time period translates into 645000
instructions, if CPU runs at 150MHz!

5 - 18

Watchdog Timer Module


SCSR . 0
OSCCLK
/64 111
6 - Bit /32 110 WDOVERRIDE
Free - /16 101 WDPS
WDCR . 2 - 0
/512 • Running /8 100
Counter /4 011 • • •
/2 010 WDCR . 6
CLR 001
WDDIS
000


WDCNTR . 7 - 0
System
Reset • 8 - Bit Watchdog
WDFLAG
One-
One-Cycle WDCR . 7
Counter
Delay
CLR
WDRST
Output •
Pulse
WDCR . 5 - 3 WDCHK 2-
2-0 WDINT
55 + AA SCSR .1
Detector Good Key 3 WDENINT
•• /
•• 3
3
/ Bad WDCR Key
Watchdog 1 0 1
Reset Key WDKEY . 7 - 0
Register
5 - 19

5 - 14 F2833x - Digital I/O


Watchdog Timer

The Watchdog is always alive when the DSP is powered up! When we do not take care of
the Watchdog periodically, it will trigger a RESET. One of the simplest methods to deal with
the Watchdog is to disable it. This is done by setting bit 6 of register WDCR to 1. Of course
this is not a wise decision, because a Watchdog is a security feature and a real project should
always include as much security as possible or available.
The Watchdog Pre-scaler can be used to increase the Watchdog’s overflow period. The
Logic Check Bits (WDCHK) is another security bit field. All write accesses to the register
WDCR must include the bit combination “101” for this 3 bit field, otherwise the access is
denied and a RESET is triggered immediately.
The Watchdog Flag Bit (WDFLAG) can be used to distinguish between a normal power on
RESET (WDFLAG = 0) and a Watchdog RESET (WDFLAG = 1). NOTE: To clear this flag
by software, we have to write a ‘1’ into this bit!

Watchdog Timer Control Register


Register: SysCtrlRegs.WDCR

WD Flag Bit
Gets set when the WD causes a reset
• Writing a 1 clears this bit
• Writing a 0 has no effect

15 - 8 7 6 5-3 2-0

reserved WDFLAG WDDIS WDCHK WDPS

Logic Check Bits WD Prescale


Write as 101 or reset Selection Bits
Watchdog Disable Bit immediately triggered
Write 1 to disable
(Functions only if WD OVERRIDE
bit in SCSR is equal to 1)

5 - 20

Note: if for some reason the external oscillator clock fails, the Watchdog stops incrementing.
In an application we can catch this condition by reading the Watchdog counter register
periodically. In the case of a lost external clock, this register will not increment any longer.
The F2833x itself will still execute if in PLL mode, since the PLL will output a clock
between 1 and 4 MHz in a so-called “limp”-mode.

F2833x - Digital I/O 5 - 15


Watchdog Timer

How do we clear the Watchdog counter register, before it overflows? Answer: By writing a
“valid key” or “good key” sequence into register WDKEY:

Resetting the Watchdog

15 - 8 7-0

reserved WDKEY

 WDKEY write values:


0x55 - counter enabled for reset on next 0xAA write
0xAA - counter set to zero if reset enabled
 Writing any other value has no effect
 Watchdog should not be serviced solely in
an ISR
 If main code crashes, but interrupt continues to
execute, the watchdog will not catch the crash
 Could put the 0x55 WDKEY in the main code, and
the 0xAA WDKEY in an ISR; this catches main
code crashes and also ISR crashes

5 - 21

WDKEY Write Results

Sequential Value Written


Step to WDKEY Result

1 AAh No action
2 AAh No action
3 55h WD counter enabled for reset on next AAh write
4 55h WD counter enabled for reset on next AAh write
5 55h WD counter enabled for reset on next AAh write
6 AAh WD counter is reset
7 AAh No action
8 55h WD counter enabled for reset on next AAh write
9 AAh WD counter is reset
10 55h WD counter enabled for reset on next AAh write
11 23h No effect; WD counter not reset on next AAh write
12 AAh No action due to previous invalid value
13 55h WD counter enabled for reset on next AAh write
14 AAh WD counter is reset

5 - 22

5 - 16 F2833x - Digital I/O


System Control and Status Register

System Control and Status Register


Register SCSR controls whether the Watchdog causes a RESET (WDENINT = 0) or an
Interrupt Service Request (WDENINT = 1). The default state after RESET is to trigger a
RESET.
The WDOVERRIDE bit is a “clear only” bit, that means, once we have closed this switch by
writing a 1 into the bit, we cannot re-open this switch again (see block diagram of the
Watchdog). At this point the WD-disable bit is ineffectual, so there is no way to disable the
Watchdog!
Bit 2 (WDINTS) is a read only bit that flags the status of the Watchdog Interrupt.

System Control and Status Register

Register: SysCtrlRegs.SCSR

WD Override (protect bit)


Protects WD from being disabled
0 = WDDIS bit in WDCR has no effect (WD cannot be disabled)
1 = WDDIS bit in WDCR can disable the watchdog
• This bit is a clear-
clear-only bit (write 1 to clear)
• The reset default of this bit is a 1

15 - 3 2 1 0

reserved WDINTS WDENINT WDOVERRIDE

WD Interrupt Status WD Enable Interrupt


(read only) 0 = WD generates a DSP reset
0 = active 1 = WD generates a WDINT interrupt
1 = not active

5 - 23

Low Power Mode


To reduce power consumption, the F2833x is able to switch into 3 different low-power
operating modes. We will not use this feature in this chapter; therefore we can treat the Low
Power Mode control bits as “don’t care”. The Low Power Mode is entered by execution of
the dedicated Assembler Instruction “IDLE”. As long as we do not execute this instruction,
the initialization of the LPMCR0 register has no effect.
The next four slides explain the Low Power Modes in detail.

F2833x - Digital I/O 5 - 17


Low Power Mode

Low Power Modes

Low Power CPU Logic Peripheral Watchdog PLL /


Mode Clock Logic Clock Clock OSC
Normal Run on on on on

IDLE off on on on

STANDBY off off on on

HALT off off off off

See device datasheet for power consumption in each mode

5 - 24

Low Power Mode Control Register 0


Register: SysCtrlRegs.LPMCR0
Watchdog Interrupt 000000 = 2 OSCCLKs
wake device from 000001 = 3 OSCCLKs
STANDBY Wake from STANDBY
GPIO signal qualification *
.. .. ..
0 = disable (default) . . .
1 = enable 111111 = 65 OSCCLKS (default)

15 14 - 8 7-2 1-0
WDINTE reserved QUALSTDBY LPM0

Low Power Mode Selection


Low Power Mode Entering 00 = Idle (default)
1. Set LPM bits 01 = Standby
2. Enable desired exit interrupt(s) 1x = Halt
3. Execute IDLE instruction
4. The Power down sequence of the hardware
depends on LP mode

* QUALSTDBY will qualify the GPIO wakeup signal in series with the GPIO port qualification.
This is useful when GPIO port qualification is not available or insufficient for wake-up purposes.
5 - 25

5 - 18 F2833x - Digital I/O


Low Power Mode

Low Power Mode Exit

Exit
Interrupt RESET GPIO Watchdog Any
or Port A Interrupt Enabled
Low Power XNMI Signal Interrupt
Mode

IDLE yes yes yes yes

STANDBY yes yes yes no

HALT yes yes no no

5 - 26

GPIO Low Power Wakeup Select

Register: SysCtrlRegs.GPIOLPMSEL
31 30 29 28 27 26 25 24

GPIO31 GPIO30 GPIO29 GPIO28 GPIO27 GPIO26 GPIO25 GPIO24

23 22 21 20 19 18 17 16
GPIO23 GPIO22 GPIO21 GPIO20 GPIO19 GPIO18 GPIO17 GPIO16

15 14 13 12 11 10 9 8

GPIO15 GPIO14 GPIO13 GPIO12 GPIO11 GPIO10 GPIO9 GPIO8

7 6 5 4 3 2 1 0
GPIO7 GPIO6 GPIO5 GPIO4 GPIO3 GPIO2 GPIO1 GPIO0

Wake device from


HALT and STANDBY mode
(GPIO Port A)
0 = disable (default)
1 = enable
5 - 27

F2833x - Digital I/O 5 - 19


Lab 5_1: Digital Output at 4 LEDs

Lab 5_1: Digital Output at 4 LEDs


Lab 5_1: “Binary Counter” at 4 LEDs

Objective:
• Display the 4 least significant bits of a counter variable at
LED LD1(GPIO9), LD2(GPIO11), LD3(GPIO34) and
LD4(GPIO49) of the Peripheral Explorer Board.
• Increment variable “counter” every 100 milliseconds
• Use a software delay loop to generate the interval of 100
milliseconds
0000 Project - Files :
1. C - source file “Lab5_1.c”
0001 2. Start assembly code file:
“DSP2833x_CodeStartBranch.asm”
0010 2. Register Variable Definition File:
… “DSP2833x_GlobalVariableDefs.c”
3. Linker Command File:
1111 “28335_RAM_lnk.cmd”
“DSP2833x_Headers_nonBIOS.cmd”
4. Runtime Library “rts2800_fpu32.lib”
5 - 28

“DSP2833x_GlobalVariableDefs.c”

• Definition of global variables for all memory mapped


peripheral registers based on predefined structures
• Master Header File is “DSP2833x_Device.h”
• Example GpioDataRegs:
volatile struct GPIO_DATA_REGS GpioDataRegs;
• This structure variable combines all registers, which
belong to this peripheral group, e.g.:
GpioDataRegs.GPADAT
• Each register is declared as a union to allow 32-bit-
(“all”) and single bit field -accesses (“bit”), e.g.:
GpioDataRegs.GPADAT.bit.GPIO9 = 1;
GpioDataRegs.GPADAT.all = 0x0000FFFF;

• Steps to be done are:


1. Add “DSP2833x_GlobalVariableDefs.c” to project
2. Include “DSP2833x_Device.h” into your C-code
5 - 29

5 - 20 F2833x - Digital I/O


Lab 5_1: Digital Output at 4 LEDs

“Lab 5_1 Register usage”

Registers involved in LAB 5_1:


• Core Initialisation:
• Watchdog - Timer - Control : WDCR
• PLL Clock Register : PLLCR
• High Speed Clock Pre-scaler: HISPCP
• Low Speed Clock Pre-scaler : LOSPCP
• Peripheral Clock Control : PCLKCRx
• System Control and Status : SCSR
• Access to LED‘s (GPIO9, GPIO11,GPIO34,GPIO49):
• GPA and GPB Multiplex Register:
• GPAMUX1, GPAMUX2, GPBMUX1, GPBMUX2
• GPA and GPB Direction Register:
• GPADIR and GPBDIR
• GPA and GPB Data Register:
• GPASET, GPACLEAR, GPBSET, GPBCLEAR
5 - 31

Objective
The objective of this lab is to practice using basic digital I/O-operations. GPIO9, GPIO11,
GPIO34 and GPIO49 are connected to 4 Leds (LD1-4) at the Peripheral Explorer Board; a
digital output value of ‘1’ will switch on a light, a digital ‘0’ will switch it off. Lab5_1 will
use register GPAMUX1, GPBMUX1, GPADIR, GPBDIR and the data registers GPADAT,
GPBDAT, GPASET, GPACLEAR, GPBSET and GPBCLEAR.
The code of Lab5_1 will continuously increment an integer variable "counter" and display
the current value of its 4 least significant bits on LD1 to LD4. For this first hardware based
lab we will not use any interrupts. The Watchdog-Timer unit and the core registers to set up
the controller speed are also used in this exercise.

Procedure

Create a Project File


1. Using Code Composer Studio, create a new project, called Lab5.pjt in
C:\DSP2833x_V4\Labs (or in another path that is accessible by you; ask your teacher
or a technician for an appropriate location!).
2. Define the size of the C system stack. In the project window, right click at project
“Lab5” and select “Properties”. In category “C/C++ Build”, “C2000 Linker”, “Basic
Options” set the C stack size to 0x400.
3. Copy the provided source code file “Lab5_1.c” in the project folder
“C:\DSP2833x_V4\Labs\Lab5”. This step will automatically include the file in
project “Lab5”.

F2833x - Digital I/O 5 - 21


Lab 5_1: Digital Output at 4 LEDs

Next, we will take advantage of some useful files, which have been created and provided by
Texas Instruments and should be already available on your hard disk drive C as part of the
so-called "Header File" package (sprc530.zip). If not, ask a technician to install that package
for you!
3. In the C/C++ perspective, right click at project “Lab5” and select “Link Files to Project”.
Go to folder “C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\source” and link:

• DSP2833x_GlobalVariableDefs.c
This file defines all global variable names to access memory mapped peripheral
registers.
4. Repeat the “Link Files to Project” step. From C:\tidcs\c28\dsp2833x\v131\
DSP2833x_common\source add:

• DSP2833x_CodeStartBranch.asm
This file contains a single Long Branch assembly instruction and must be placed into
the code entry point section "BEGIN" in code space. The Linker will that do for us,
based on the file that is added in the next step.
5. From C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\cmd link to project “Lab5”:

• DSP2833x_Headers_nonBIOS.cmd
This linker command file will connect all global register variables to their
corresponding physical addresses.

Project Build Options


6. We also have to extent the search path of the C-Compiler for include files. Right click at
project “Lab5” and select “Properties”. Select “C/C++ Build”, “C2000 Compiler”,
“Include Options”. In the box "Add dir to #include search path”, add the following line:

C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include

Note: Use the “Add” Icon to add the new path:

Close the Property Window by Clicking <OK>.

5 - 22 F2833x - Digital I/O


Lab 5_1: Digital Output at 4 LEDs

Modify the Source Code


After we have prepared our project, it is time to inspect and change the provided C-source
code file "Lab5_1.c". To find the correct setup for the registers, use the information from the
PowerPoint slides in the presentation of this chapter!
7. Open Lab5_1.c and search for the local function “InitSystem()”. You will find several
question marks in this code. Your task is to replace all the question marks to complete
the code.
• Set up the Watchdog-Timer (WDCR): disable the Watchdog and clear the
WD Flag bit.
• Set up the SCSR to generate a RESET out of a Watchdog event
(WDENINT)
• Setup the Clock-PLL (PLLCR)-multiply by 10/2. Assuming we use an
external 30 MHz oscillator this will set the DSP to 150 MHz internal
frequency. Set bit field "DIV" in PLLCR to 10 and field DIVSEL in
register PLLSTS to 2!
• Initialize the High speed Clock Pre-scaler (HISPCP) to “divide by 2“, the
Low speed Clock Pre-scaler (LOSPCP) to “divide by 4”.
• Enable the GPIO-Clock bit "GPIOINENCLK" in register PCLKCR3.
Disable all other peripheral clock units in register: PCLKCR0, PCLKCR1
and PCLKCR3.
8. Search for the local function “Gpio_select()” and modify the code in it to:
• Set up all multiplex register to digital I/O.
• Set up GPADIR: lines GPIO9 and GPIO11 to output and all other lines to input.
• Set up GPBDIR: lines GPIO34 and GPIO49 to output and all other lines to
input.
• Set up GPCDIR: all lines to digital input.

Setup the control loop


9. In “Lab5_1.c” look for the endless “while(1)” loop. After the increment of the variable
"counter" add some instructions to analyze the current value in "counter":

• If bit 0 of counter is 1, set GPIO9 to 1, otherwise clear GPIO9 to 0


• If bit 1 of counter is 1, set GPIO11 to 1, otherwise clear GPIO11 to 0
• If bit 2 of counter is 1, set GPIO34 to 1, otherwise clear GPIO34 to 0
• If bit 3 of counter is 1, set GPIO49 to 1, otherwise clear GPIO49 to 0
Note: The GPIO data registers are accessible using a set of 4 registers (‘x’ stands
for A, B or C):
• GpioDataRegs.GPxDAT - access to data register
• GpioDataRegs.GPxSET - set those lines, which are marked with a 1
• GpioDataRegs.GPxCLEAR - clear the lines, which are marked with a 1

F2833x - Digital I/O 5 - 23


Lab 5_1: Digital Output at 4 LEDs

• GpioDataRegs.GPxTOGGLE - invert the level at lines, which are marked


as 1

Example to set pin GPIO5 to 1:


GpioDataRegs.GPASET.bit.GPIO5 = 1;

Build and Load


10. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

and watch the tools run in the build window. If you get errors or warnings debug as ne-
cessary.

11. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

Test
12. Verify that in the debug perspective the window of the source code “Lab5_1.c” is hig-
hlighted and that the blue arrow for the current Program Counter position is placed under
the line “void main(void)”.

13. Perform a real time run.

Target  Run

14. Verify that the LEDs behave as expected. In this case you have successfully finished the
first part of Lab5_1. Halt the Device ( Target  Halt).

Enable Watchdog Timer


15. Now let us improve our Lab5_1 towards a more realistic scenario. Although it was very
easy to disable the watchdog for the first part of this exercise, it is not a good practice for
a ‘real’ hardware project. The watchdog timer is a security hardware unit; it is an internal
part of the F2833x and it should be used in all projects. So let us modify our code:
16. Switch back to the “C/C++” perspective. In file “Lab5_1.c” search the function
“InitSystem()” and modify the WDCR - register initialization
• Now do NOT disable the watchdog.
17. What will be the result?
• Answer: If the watchdog is enabled, our program will stop operations after a few
milliseconds somewhere in our while(1) loop. Depending on the preselected boot-

5 - 24 F2833x - Digital I/O


Lab 5_1: Digital Output at 4 LEDs

mode, the watchdog will force the controller into the hardware start sequence,
usually into the FLASH entry point. Since our program has been loaded in RAM
rather than in FLASH, it will not start again. As a result, our LED program will not
run any more!
• Note: The BOOT - Mode sequence of F2833x is selected with 4 GPIOs (GPIO87,
86, 85 and 84), which are sampled during startup. In case of the F28335ControlCard
all 4 pins are resistor pulled up to 3.3V, thus the "Jump to FLASH entry point"
option is selected by default. At the Peripheral Explorer Board pin GPI084 can be
forced to GND by closing jumper J3 (“Boot-2”) at the XDS100 module (“M1”) of
the Peripheral Explorer Board; this will select the option "SCI-A boot loader". All
remaining boot start options are not available for the combination
F28335ControlCard + Peripheral Explorer Board.

18. Click the “Rebuild All” button or perform:

Project  Rebuild Active Project

19. Load the output file in the debugger session:

Target  Debug Active Project

and switch back into the “Debug” perspective.

20. Perform a real time run.

Target  Run

Our LED code should not work any more! This is a sign that the F2833x has been RESET by
a watchdog overflow.

Service the Watchdog Timer


21. To enable the watchdog timer was only half of the task to use it properly. Now we have
to deal with it in our code. This means that if our control loop runs as expected, the
watchdog, although it is enabled, should never trigger a RESET. How can we achieve
this? Answer: We have to execute the watchdog reset key sequence somewhere in our
control loop. The key sequence consists of two write instructions into the WDKEY-
register, a 0x55 followed by a 0xAA.
• Switch back to “C/C++” perspective and inspect file “Lab5_1.c”. Look for function
“delay_loop()” and uncomment the four lines:
EALLOW;
SysCtrlRegs.WDKEY = 0x55;
SysCtrlRegs.WDKEY = 0xAA;
EDIS;

Note: The C-Macro “EALLOW” will open the access to certain CPU core registers,
including the Watchdog-Registers. The Macro “EDIS” will disable this access.

F2833x - Digital I/O 5 - 25


Lab 5_1: Digital Output at 4 LEDs

22. Click the “Rebuild All” button or perform:

Project  Rebuild Active Project


23. Load the output file in the debugger session:

Target  Debug Active Project

and switch back into the “Debug” perspective.

24. Perform a real time run.

Target  Run
25. Now our LED control code should run again as expected. The watchdog is still active
but due to our key sequence it will not trigger a RESET unless the F2833x code crashes.
Hopefully this will never happen!

END of Lab 5_1

5 - 26 F2833x - Digital I/O


Lab 5_2: Digital Output (modified)

Lab 5_2: Digital Output (modified)


Let’s modify the code of Lab5_1. Instead of showing the four least significant bits of
variable "counter" as in Lab5_1, let us now produce a “running” LED from left to
right and vice versa (known as a “Knight Rider”):

Lab Exercise 5_2

Modify the C -source – code to:

• switch 4 LEDs at GPIO9, GPIO11, GPIO34


and GPIO49 sequentially on and off
• use a software time delay from Lab5_1
GPIO9 GPIO11 GPIO34 GPIO49

Step 1

Step 2 Step 6

Step 3 Step 5
Step 4
5 - 32

Procedure

Modify Code and Project File


1. Open the source code “Lab5_1.c” from project Lab5.pjt in C:\DSP2833x_V4\Labs\Lab5
and save it as “Lab5_2.c”.

2. Exclude file “Lab5_1.c” from build. Right click at Lab5_1.c in the project window
and enable “Exclude File(s) from Build". Add the new source code file to your
project:

3. Modify the code inside the “Lab5_2.c” according to the new objective. Variable
“counter” is no longer needed, so remove it.

4. Rebuild and test as you have done in Lab5_1.

END of Lab 5_2

F2833x - Digital I/O 5 - 27


Lab 5_3: Digital Input

Lab 5_3: Digital Input


Objective
Now let us add some digital input function to our code. On the Peripheral Explorer Board,
the digital lines GPIO12 to GPIO15 are inputs from a 4-bit hexadecimal encoder device
(SW2). This device generates a 4-bit number between binary “0000” and “1111”, depending
on its position.
The objective of Lab5_3 is to read the status of this hexadecimal encoder and display it at
LEDs LD1 (GPIO9), LD2 (GPIO11), LD3 (GPIO34) and LD4 (GPIO49) of the Peripheral
Explorer Board.

Lab 5_3: Digital Input (GPIO 15...12)


Objective:
• a 4 bit hex encoder connected to GPIO15…GPIO12
• 4 LED‘s connected to GPIO9, GPIO11, GPIO34 and
GPIO49
• read the status of encoder and display it at the LEDs

Project - Files :
1. C - source file: “Lab5_3.c”
2. Register Definition File:
“DSP2833x_GlobalVariableDefs.c”
3. Linker Command File:
“28335_RAM_lnk.cmd”
4. Runtime Library: “rts2800_fpu32.lib”

5 - 33

Procedure

Modify Code and Project File


1. Open the source code “Lab5_1.c” from project “Lab5” in
C:\DSP2833x_V4\Labs\Lab5 and save it as “Lab5_3.c”.

2. Exclude file “Lab5_2.c” from build. Right click at Lab5_2.c in the project
window and select “Exclude File(s) from Build”.
3. Modify Lab5_3.c. Remove variable "counter". Keep the function calls to
“InitSystem()” and “Gpio_select()”. Inside the endless while(1)-loop, modify the
control loop as needed. Just copy the current value from input GPIO12 (encoder
bit 0) to output GPIO9 (LED1) and so on.

5 - 28 F2833x - Digital I/O


Lab 5_3: Digital Input

4. What about the watchdog? Recall that we serviced the watchdog inside
“delay_function()” - it would be unwise to remove this function call from our
control loop!

Build, Load and Test


5. Build, Load and Test as you have done in previous exercises.
When the code is running, turn the hex-encoder switch at the Peripheral Explorer
Board. Each clockwise turn should increment the binary pattern at the 4 LEDs,
an anti clockwise turn should decrement the pattern.

END of Lab 5_3

F2833x - Digital I/O 5 - 29


Lab 5_4: Digital In- and Output

Lab 5_4: Digital In- and Output


Objective
Now let us combine Lab5_1 and Lab5_3! That means your task is to control the speed of
your “LED”- counter code (Lab5_1) by the current status of the 4-bit hex encoder. It inputs a
value between 0 and 15. For example, we can use this number to change the input parameter
for function “delay_loop()” to generate a time interval between 100 milliseconds (hex-
encoder = 0) and 1.6 seconds (hex-encoder = 15).

Lab 5_4: Digital In- and Output

• Mix between Lab5_1 and LAB5_3:

• change the loop – speed of Lab5_1 depending of


the status of the hex – encoder.
• If hex – encoder reads “0000”, set the time period
for the LED update to approximately 100 ms.
• If hex - encoder reads “1111”, set the time period for
the LED update to approximately 1.6 seconds.
• Adjust the period for all other encoder values
accordingly.

5 - 33

Modify Code and Project File


1. Open the source code “Lab5_1.c” from project Lab5.pjt in
C:\DSP2833x_V4\Labs\Lab5 and save it as “Lab5_4.c”.

2. Exclude file “Lab5_3.c” from build. Right click at Lab5_3.c in the project
window and select “Exclude File(s) from Build".

Modify Lab5_4.C
4. In “main()”, modify the input parameter of the function “delay_loop()”. This
parameter defines the number of iterations of the for-loop. All you have to do is
to change the current parameter using the GPIO-inputs GPIO15…GPIO12.
5. The best position to update the parameter for the delay loop time is inside the
endless loop of “main()”, between two steps of the LED-sequence. Recall, that
the 4-bit encoder will give you a number between 0 and 15. The task is to

5 - 30 F2833x - Digital I/O


generate a delay period between 100 milliseconds and 1.6 seconds. You need to
do a little bit of maths here. Assuming your DSP runs at 100 MHz, one loop of
the “for()” loop -instruction in function “delay_loop()” takes approximately 173
nanoseconds, so you need to scale the value accordingly.

Build, Load and Test


6. Build, Load and Test as you have done in previous exercises.

END of Lab 5_4

F2833x - Digital I/O 5 - 31


Lab 5_5: Digital In- and Output Start / Stop

Lab 5_5: Digital In- and Output Start / Stop


Objective
As a final exercise in this chapter, let us add some start/stop functionality to our project. The
Peripheral Explorer Board is equipped with two push-buttons PB1 and PB2. If pushed, the
corresponding input line reads ‘0’; if not, it reads as ‘1’. Button PB1 is wired to GPIO17 and
PB2 to GPIO48.
The Task is:
(1) to start the LED counting sequence from Lab5_4, if PB1 has been pushed.
(2) to suspend the LED counting sequence, if PB2 has been pushed.
(3) to resume the LED counting, if PB1 has been pushed again

Lab 5_5: Start - /Stop Control

• Add a start/stop function to Lab5_4:

• Peripheral Explorer Board Pushbuttons:


• PB1 (GPIO17) to start/restart control code
• PB2 (GPIO48) to stop/suspend control code

• If PB1 is pushed, LED counting should start / resume


• If PB2 is pushed, LED counting should stop.

5 - 35

Modify Code and Project File


1. Open the source code “Lab5_4.c” from project Lab5.pjt in
C:\DSP2833x_V4\Labs\Lab5 and save it as “Lab5_5.c”.

2. Exclude file “Lab5_4.c” from build. Right click at Lab5_4.c in the project
window and select “Exclude File(s) from Build".

Modify Lab5_5.c
4. Inspect function “Gpio_select()” and make sure that GPIO17 and GPIO48 are
initialized as input lines.

5 - 32 F2833x - Digital I/O


Lab 5_5: Digital In- and Output Start / Stop

5. At the beginning of Lab5_5.c add two definitions:


#define START GpioDataRegs.GPADAT.bit.GPIO17

#define STOP GpioDataRegs.GPBDAT.bit.GPIO48


Now we can use the symbols “START” and “STOP” instead of the long bit
variable names.
6. At the beginning of function “delay_loop()”, add a definition for a static variable
“run” and initialize it with 0:
static unsigned int run = 0;
This variable will later be used as a control switch. If run = 0, the control code
loop execution is stopped; If run = 1, the control code loop is enabled.
7. Inside the for()-loop of function “delay_loop()”, add a code sequence to
postpone the loop-execution as long as PB1 has not been pushed. One option is
to use a do-while construction:
do
{
EALLOW;
SysCtrlRegs.WDKEY = 0x55;
SysCtrlRegs.WDKEY = 0xAA; // service watchdog
EDIS;
if (START == 0 && STOP == 1) run = 1; // run control code if PB1=0
} while (!run);

Note: You will have to adjust the calculation of the input parameter for the
function “delay_loop()”!
8. After leaving this do-while loop, we need to check, if PB2 has been pushed. If
so, all we have to do is to set variable run = 0.
if(STOP == 0) run = 0; // suspend
With the next repetition of the for() -loop the processor will re-enter the do-
while construction and wait for a second START command.
Procedure step 7 and 8 are only one option to solve the task. You might find
other solutions even better suited.

Build, Load and Test


9. Build, Load and Test as you have done in previous exercises.

END of Lab 5_5

F2833x - Digital I/O 5 - 33


Lab 5_5: Digital In- and Output Start / Stop

Blank Page

5 - 34 F2833x - Digital I/O


Interrupt System

Introduction
This module is used to explain the interrupt system of the F2833x Digital Signal Controller.
So what is an interrupt?
Before we go into the technical terms, let us start with an analogy: Think of a nice evening
and you are working at your desk, preparing the laboratory experiments for the next day.
Suddenly the phone rings, you answer it and then you get back to work (after the
interruption). The shorter the phone call, the better! Of course, if the call comes from your
girlfriend you might have to re-think your next step due to the “priority” of the
interruption… Anyway, sooner or later you will have to get back to the preparation of the
task for the next day; otherwise you might not pass the next exam.
This analogy touches some basic definitions for interrupts;
• interrupts appear “suddenly”: in technical terms, this is called “asynchronous”
• interrupts might be more or less important: they have a “priority”
• they must be dealt with before the phone stops ringing: “immediately”
• the laboratory preparation should be continued after the call - the “interrupted task is
resumed”
• the time spent to search the phone should be as small as possible – “interrupt
latency”.
• after the call, you should continue your work from the exact place where you left it -
“context save” and “context restore”
To summarize the technical terms:
Interrupts are defined as asynchronous events, generated by an external or internal hardware
unit. An event causes the controller to interrupt the execution of the current program and to
start a service routine, which is dedicated to this event. After the execution of this interrupt
service routine, the program that was interrupted will be resumed.
The quicker a CPU performs this “task-switch”, the more this controller is suited for real-
time control. After going through this chapter, you will be able to understand the F2833x
interrupt system.
At the end of this chapter, we will perform an exercise with a program controlled by
interrupts that uses one of the 3 core timers of the CPU. The core timer’s period interrupt
will be used to perform a periodic task.

F2833x - Interrupts 6-1


Module Topics

Module Topics
Interrupt System ........................................................................................................................................ 6-1
Introduction ............................................................................................................................................. 6-1
Module Topics ......................................................................................................................................... 6-2
F2833x Core Interrupt Lines................................................................................................................... 6-3
The F2833x RESET ................................................................................................................................. 6-4
Reset Bootloader ..................................................................................................................................... 6-5
Interrupt Sources ..................................................................................................................................... 6-9
Maskable Interrupt Processing ............................................................................................................. 6-10
Peripheral Interrupt Expansion ............................................................................................................ 6-12
Hardware Interrupt Response ............................................................................................................... 6-15
F2833x CPU Timers.............................................................................................................................. 6-16
Summary: .............................................................................................................................................. 6-18
Lab 6: CPU Timer 0 Interrupt and 4 LEDs .......................................................................................... 6-19
Objective ........................................................................................................................................... 6-19
Procedure .......................................................................................................................................... 6-19
Create a Project File .......................................................................................................................... 6-19
Project Build Options ........................................................................................................................ 6-20
Modify the Source Code ................................................................................................................... 6-20
Build, Load and Test ......................................................................................................................... 6-21
Modify Source Code - Part 2 ............................................................................................................ 6-21
Build, Load and Test ......................................................................................................................... 6-24

6-2 F2833x - Interrupts


F2833x Core Interrupt Lines

F2833x Core Interrupt Lines


The core interrupt system of the F2833x consists of 16 interrupt lines; two of them are called
“Non-Maskable” (RESET, NMI). The other 14 lines are ‘maskable’ - this means the
programmer can allow or disable interrupts from these 14 lines.
What does the phrase “mask” stand for?
A “mask” is a binary combination of ‘1’ and ‘0’. A ‘1’ stands for an enabled interrupt line, a
‘0’ for a disabled one. By loading the mask into register “IER” we can select, which interrupt
lines will be enabled to request an interrupt service from the CPU.
For a “non-maskable” interrupt, we cannot disable an interrupt request. Once the signal line
goes active, the running program will be suspended and the dedicated interrupt service
routine will start. Generally, “non-maskable” interrupts are used for high priority and safety
based events e.g. emergency stop.

F2833x Core Interrupt Lines


RS
NMI
INT1
INT2
 2 non-
non-maskable
INT3
INT4
interrupts (RS,
INT5 “selectable”
selectable” NMI)
F2833x INT6
CORE  14 maskable interrupts
INT7 (INT1 – INT14)
INT8
INT9
INT10
INT11
INT12
INT13
INT14
6-2

All 16 lines are connected to a table of ‘interrupt vectors’, which consists of 32 bit memory
locations per interrupt. It is the responsibility of the programmer to fill this table with the
start addresses of dedicated interrupt service routines. However, in case of the F2833x, this
table is in ROM and filled with addresses, defined by Texas Instruments in such a way, that
“RESET (RS ¯¯ )” points to address 0x00 0040, NMI to address 0x00 0042 an so on. All these
addresses are in RAM, so the programmer has to fit a single 32-bit instruction into these
memory locations.

F2833x - Interrupts 6-3


The F2833x RESET

The F2833x RESET


A high to low transition at the external “RESET (RS
¯¯ )” pin will cause a reset of the Digital
Signal Controller. The next rising edge of RS¯¯ will force the CPU to read the code start
address from address 0x3F FFC0 in code memory. This event is not an ‘interrupt’ in the
sense that the old program will be resumed. A reset is generated during powering up the
device.
Another source for a reset is the overflow of the watchdog timer. To inform all other external
devices that the CPU has acknowledged a reset, the device itself drives the reset pin active
low. This means that the reset pin must be bi-directional!

F2833x Reset Sources

F2833x Core
Watchdog Timer
RS
RS pin active

To RS pin

6-3

Reset will force the controller not only to start from address 0x3F FFC0, but it will also clear
all internal operation registers, reset a group of CPU-Flags to initial states and disable all 16
interrupt lines. We will not go into details about all the flags and registers for now, please
refer to the data sheet for the F2833x.

6-4 F2833x - Interrupts


Reset Bootloader

Reset Bootloader
After a RESET signal has been released, the CPU starts the execution of a first code section
in ROM, called “boot loader”. This function determines the next step, depending on the
status of four GPIO -pins (GPIO87, 86, 85 and 84).

Reset – Bootloader

Reset
OBJMODE = 0 AMODE = 0
ENPIE = 0 INTM = 1

Bootloader sets
OBJMODE = 1
AMODE = 0
Reset vector fetched
from boot ROM Boot determined by
state of GPIO pins
0x3F FFC0

Execution Bootloading
Entry Point Routines
FLASH SCI-
SCI-A / SPI-
SPI-A
M0 SARAM I2C
OTP eCAN-
eCAN-A
XINTF McBSP-
McBSP-A
GPIO / XINTF
6-4

Bootloader Options
GPIO pins
87 / 86 / 85 / 84 /
XA15 XA14 XA13 XA12
1 1 1 1 jump to FLASH address 0x33 FFF6
1 1 1 0 bootload code to on-
on-chip memory via SCI-
SCI-A
1 1 0 1 bootload external EEPROM to on-
on-chip memory via SPI-
SPI-A
1 1 0 0 bootload external EEPROM to on-
on-chip memory via I2C
1 0 1 1 Call CAN_Boot to load from eCAN-
eCAN-A mailbox 1
1 0 1 0 bootload code to on-
on-chip memory via McBSP-
McBSP-A
1 0 0 1 jump to XINTF Zone 6 address 0x10 0000 for 16-
16-bit data
1 0 0 0 jump to XINTF Zone 6 address 0x10 0000 for 32-
32-bit data
0 1 1 1 jump to OTP address 0x38 0400
0 1 1 0 bootload code to on-
on-chip memory via GPIO port A (parallel)
0 1 0 1 bootload code to on-
on-chip memory via XINTF (parallel)
0 1 0 0 jump to M0 SARAM address 0x00 0000
0 0 1 1 branch to check boot mode
0 0 1 0 branch to Flash without ADC calibration (TI debug only)
0 0 0 1 branch to M0 SARAM without ADC calibration (TI debug only)
0 0 0 0 branch to SCI-A without ADC calibration (TI debug only)
6-5

F2833x - Interrupts 6-5


Reset Bootloader

The F28335ControlCard pulls all four GPIO - input lines to ‘1’, so by default the start option
“jump to FLASH address 0x3F FFF6” is selected. This will force the controller to continue
the code sequence in FLASH memory. However, we do not currently have anything
programmed into FLASH memory. So why did all of our previous labs work? The answer is:
we over-ruled the hardware - sequence and forced the DSC into our own code entry point by
using three of Code Composer Studio Debug commands:

• Reset CPU - force the DSC to Reset Address 0x3F FFC0

• Restart - force the DSC directly to code entry point


“c_int00”, bypassing the hardware start sequence

• Go Main - finish the “c_int00”, call “main()” and stop at the


first instruction of “main()”.
With the help of jumper J18 (SCI - Boot) on the Peripheral Explorer Board, we could change
the hardware sequence. If this jumper is closed, GPIO84 will be ‘0’ and the start sequence is:
“boot load code to on-chip memory via SCI-A”. In this operation mode, the chip would wait
for a serial communication stream from a host, which is of no use for us for now. This mode
will be used in chapter 15.
The next flowchart summarises the reset code flow for all start options of the F2833x.

Reset Code Flow - Summary


0x00 0000 0x00 0000
M0 SARAM (1Kw)

0x38 0400 XINTF Zone 6


OTP (1Kw) (x16 / x32)
0x10 0000
0x30 0000
FLASH (256Kw)
0x33 FFF6

Execution Entry
0x3F E000 Boot ROM (8Kw) Point Determined
Boot Code By GPIO Pins
0x3F F9CE
• •
• •

BROM vector (64w)


RESET 0x3F FFC0 0x3F F9CE Bootloading
Routines
(SCI-A, SPI-A, I2C,
eCAN-A, McBSP-A
GPIO, XINTF)
6-6

The option ‘Flash Entry’ is usually used at the end of a project development phase when the
software flow is bug free. To load a program into the flash you will need to use a specific
program, available either as Code Composer Studio plug in or as a stand-alone tool. For our
current lab exercises we will refrain from loading (or ‘burning’) the flash memory.
The boot loader options via serial interface (SPI / SCI / I2C / eCAN / McBSP) or parallel
port (GPIO / XINTF) are usually used to download the executable code from an external

6-6 F2833x - Interrupts


Reset Bootloader

host or to update the contents of the flash memory. For these modes, please refer to chapters
15 and 16.
OTP-memory is a ‘one time programmable’ memory; there is no second chance to fit code
into this non-volatile memory. This option is usually used for company specific startup
procedures only. Again, to program this portion of memory you would need to use a Code
Composer Studio plug in. You might assess your experimental code to be worth storing
forever, but for sure your teacher will not. So, PLEASE do not upset your supervisor by
using this option, he want to use the boards for future classes!

The next two slides show the status of important core registers and status bits after a reset.

Register Bits Initialized at Reset

Register bits defined by reset


PC 0x3F FFC0 PC loaded with reset vector
ACC 0x0000 0000 Accumulator cleared
XAR0 - XAR7 0x0000 0000 Auxiliary Registers
DP 0x0000 Data Page pointer points to page 0
P 0x0000 0000 P register cleared
XT 0x0000 0000 XT register cleared
SP 0x0400 Stack Pointer to address 0400
RPC 0x00 0000 Return Program Counter cleared
IFR 0x0000 no pending interrupts
IER 0x0000 maskable interrupts disabled
DBGIER 0x0000 debug interrupts disabled

6-7

All internal math registers (ACC, P, XT) and auxiliary registers (XAR0 to XAR7) are
cleared, interrupts are disabled (IER) and pending interrupts, which have been requested
before RESET, are cancelled (IFR). The stack pointer (SP) is initialized to address 0x400
and the program counter (PC) points to hardware start address 0x3F FFC0.

F2833x - Interrupts 6-7


Reset Bootloader

The two registers ST0 and ST1 combine all control and status flags of the CPU. Slide 6-8
explains the reset status of all the bits. ST0 contains all math bits such as zero (Z), carry (C)
and negative (N), whereas ST1 covers some more general operating mode bits.
We will postpone the discussion of the individual meaning of the bits until later chapters.

Control Bits Initialized at Reset


Status Register 0 (ST0)
SXM = 0 Sign extension off
OVM = 0 Overflow mode off N=0 negative flag
TC = 0 test/control flag V=0 overflow bit
C=0 carry bit PM = 000 set to left-
left-shift-
shift-by-
by-1
Z=0 zero flag OVC = 00 0000 overflow counter
Status Register 1 (ST1)
INTM = 1 Disable all maskable interrupts - global
DBGM = 1 Emulation access/events disabled
PAGE0 = 0 Stack addressing mode enabled/Direct addressing disabled
VMAP = 1 Interrupt vectors mapped to PM 0x3F FFC0 – 0x3F FFFF
SPA = 0 stack pointer even address alignment status bit
LOOP = 0 Loop instruction status bit
EALLOW = 0 emulation access enable bit
IDLESTAT = 0 Idle instruction status bit
AMODE = 0 C27x/C28x addressing mode
OBJMODE = 0 C27x object mode
M0M1MAP = 1 mapping mode bit
XF = 0 XF status bit
ARP = 0 ARP points to AR0
6-8

6-8 F2833x - Interrupts


Interrupt Sources

Interrupt Sources
As you can see from the next slide the F2833x has a large number of interrupt sources (96 at
the moment) but only 14 maskable interrupt inputs. The question is: How do we handle this
‘bottleneck’?
Obviously we have to use a single INT-line for multiple sources. Each interrupt line is
connected to its interrupt vector, a 32-bit memory space inside the vector table. This memory
space holds the address for the interrupt service routine. In case of multiple interrupts this
service routine must be used for all incoming interrupt requests. This technique forces the
programmer to use a software based separation method on entry of this service routine. This
method will cost additional time that is often not available in real time applications. So how
can we speed up this interrupt service?

Interrupt Sources
Internal Sources
TINT2
TINT1 F2833x CORE
TINT0 XRS

ePWM, eCAP, NMI


PIE INT1
eQEP,
eQEP, ADC, SCI,
(Peripheral
SPI, I2C, eCAN, INT2
Interrupt
McBSP, DMA, WD
Expansion) INT3



External Sources
INT12
INT13
XINT1 – XINT7
INT14
TZx
XRS
XNMI_XINT13
6-9

The answer from Texas Instruments is sweet, they simply used a pie. PIE stands for
Peripheral Interrupt Expansion unit.
This unit ‘expands’ the vector address table into a larger scale, reserving individual 32 bit
entries for each of the 96 possible interrupt sources. An interrupt response with the help of
this unit is much faster than without it. To use the PIE we will have to re-map the location of
the interrupt vector table to address 0x 00 0D00. This is in volatile memory! Before we can
use this memory we will have to initialise it.
Do not worry about the PIE-procedure for the moment, we will exercise all this during Lab6.

F2833x - Interrupts 6-9


Maskable Interrupt Processing

Maskable Interrupt Processing


Before we dive into the PIE-registers, we have to discuss the remaining path from an
interrupt request to its acknowledgement by the DSC. As you can see from the next slide, we
have to close two more switches to allow an interrupt request.

Maskable Interrupt Processing


Conceptual Core Overview
Core (IFR)
IFR) (IER)
IER) (INTM)
INTM)
Interrupt “Latch”
Latch” “Switch”
Switch ” “ Global Switch”
Switch”

INT1 1

INT2 0 F2833x
Core

INT14 1

 A valid signal on a specific interrupt line causes the latch


to display a “1” in the appropriate bit

 If the individual and global switches are turned “on”


on” the
interrupt reaches the core
6 - 10

Interrupt Flag Register (IFR)


15 14 13 12 11 10 9 8
RTOSINT DLOGINT INT14 INT13 INT12 INT11 INT10 INT9

7 6 5 4 3 2 1 0
INT8 INT7 INT6 INT5 INT4 INT3 INT2 INT1

Pending : IFR Bit = 1


Absent : IFR Bit = 0

/*** Manual setting/clearing IFR ***/


extern cregister volatile unsigned int IFR;
IFR |= 0x0008; //set INT4 in IFR
IFR &= 0xFFF7; //clear INT4 in IFR

 Compiler generates atomic instructions (non-


(non-interruptible) for setting/clearing IFR
 If interrupt occurs when writing IFR, interrupt has priority
 IFR(bit) cleared when interrupt is acknowledged by CPU
 Register cleared on reset
6 - 11

6 - 10 F2833x - Interrupts
Maskable Interrupt Processing

Interrupt Enable Register (IER)


15 14 13 12 11 10 9 8
RTOSINT DLOGINT INT14 INT13 INT12 INT11 INT10 INT9

7 6 5 4 3 2 1 0
INT8 INT7 INT6 INT5 INT4 INT3 INT2 INT1

Enable: Set IER Bit = 1


Disable: Clear IER Bit = 0

/*** Interrupt Enable Register ***/


extern cregister volatile unsigned int IER;
IER |= 0x0008; //enable INT4 in IER
IER &= 0xFFF7; //disable INT4 in IER

 Compiler generates atomic instructions (non-


(non-interruptible)
for setting/clearing IER
 Register cleared on reset
6 - 12

Interrupt Global Mask Bit


Bit 0
ST1 INTM

 INTM used to globally enable/disable interrupts:


 Enable:INTM
Enable:INTM = 0
 Disable: INTM = 1 (reset value)
 INTM modified from assembly code only:

/*** Global Interrupts ***/


asm(“
asm(“ CLRC INTM”
INTM”); //enable global interrupts
asm(“
asm(“ SETC INTM”
INTM”); //disable global interrupts

6 - 13

F2833x - Interrupts 6 - 11
Peripheral Interrupt Expansion

Peripheral Interrupt Expansion


All 96 possible sources are grouped into 12 PIE-lines, 8 sources per line. To enable/disable
individual sources we have to program another group of registers: ‘PIEIFRx’ and ‘PIEIERx’.

Peripheral Interrupt Expansion - PIE


Interrupt Group 1
PIE module for 96 Interrupts
PIEIFR1 PIEIER1
Peripheral Interrupts 12x8 = 96

INT1.x interrupt group INT1.1 1


INT2.x interrupt group
INT1.2 0
INT3.x interrupt group INT1
• •
INT4.x interrupt group • •
INT5.x interrupt group
• •
INT1.8 1
INT6.x interrupt group
96
INT7.x interrupt group
28x Core Interrupt logic
INT8.x interrupt group
INT9.x interrupt group INT1 – INT 12

INTM
INT10.x interrupt group 28x

IER
IFR
12 Interrupts
INT11.x interrupt group Core

INT12.x interrupt group

INT13 (TINT1 / XINT13)


INT14 (TINT2)
NMI
6 - 14

PIE Registers
PIEIFRx register (x = 1 to 12)
15 - 8 7 6 5 4 3 2 1 0
reserved INTx.8 INTx.7 INTx.6 INTx.5 INTx.4 INTx.3 INTx.2 INTx.1

PIEIERx register (x = 1 to 12)


15 - 8 7 6 5 4 3 2 1 0
reserved INTx.8 INTx.7 INTx.6 INTx.5 INTx.4 INTx.3 INTx.2 INTx.1

PIE Interrupt Acknowledge Register (PIEACK)


15 - 12 11 10 9 8 7 6 5 4 3 2 1 0
reserved PIEACKx

PIECTRL register 15 - 1 0
PIEVECT ENPIE

#include “DSP2833_Device.h”
PieCtrlRegs.PIEIFR1.bit.INTx4 = 1; //manually set IFR for XINT1 in PIE group 1
PieCtrlRegs.PIEIER3.bit.INTx5 = 1; //enable CAPINT1 in PIE group 3
PieCtrlRegs.PIEACK.all = 0x0004; //acknowledge the PIE group 3
PieCtrlRegs.PIECTRL.bit.ENPIE = 1; //enable the PIE
6 - 15

All interrupt sources are connected to interrupt lines according to this assignment table:

6 - 12 F2833x - Interrupts
Peripheral Interrupt Expansion

F2833x PIE Interrupt Assignment Table


INTx.8 INTx.7 INTx.6 INTx.5 INTx.4 INTx.3 INTx.2 INTx.1

INT1 WAKEINT TINT0 ADCINT XINT2 XINT1 SEQ2INT SEQ1INT

EPWM6 EPWM5 EPWM4 EPWM3 EPWM2 EPWM1


INT2 _TZINT _TZINT _TZINT _TZINT _TZINT _TZINT
EPWM6 EPWM5 EPWM4 EPWM3 EPWM2 EPWM1
INT3 _INT _INT _INT _INT _INT _INT
ECAP6 ECAP5 ECAP4 ECAP3 ECAP2 ECAP1
INT4 _INT _INT _INT _INT _INT _INT
EQEP2 EQEP1
INT5 _INT _INT

INT6 MXINTA MRINTA MXINTB MRINTB SPITXINTA SPIRXINTA

INT7 DINTCH6 DINTCH5 DINTCH4 DINTCH3 DINTCH2 DINTCH1

INT8 SCITXINTC SCIRXINTC I2CINT2A I2CINT1A


ECAN1 ECAN0 ECAN1 ECAN0
INT9 _INTB _INTB _INTA _INTA
SCITXINTB SCIRXINTB SCITXINTA SCIRXINTA

INT10

INT11

INT12 LUF LVF XINT7 XINT6 XINT5 XINT4 XINT3

6 - 16

Examples: ADCINT = INT1.6; T2PINT = INT3.1; SCITXINTA = INT9.2


The vector table location at reset is:

Default Interrupt Vector Table at Reset


Vector Offset
RESET 00 Default Vector Table
INT1 02 Re-
Re-mapped when
INT2 04 ENPIE = 1
INT3 06 Memory
INT4 08 0
INT5 0A
INT6 0C
INT7 0E
INT8 10
INT9 0x00 0D00
12
INT10 14
PIE Vectors
256w
INT11 16
INT12 18
INT13 1A
INT14 1C BROM Vectors 0x3F FFC0
DATALOG 1E 64w
RTOSINT 20 ENPIE = 0
0x3F FFFF
EMUINT 22
NMI 24
PieVectTableInit{
PieVectTableInit{ }
ILLEGAL 26
Used to initialize PIE vectors
USER 1-1-12 28-
28-3E 6 - 17

The PIE re-maps the location like this:

F2833x - Interrupts 6 - 13
Peripheral Interrupt Expansion

PIE Vector Mapping (ENPIE = 1)


Vector name PIE vector address PIE vector Description
not used 0x00 0D00 Reset vector (never fetched here)
INT1 0x00 0D02 INT1 re-
re-mapped to PIE group below
…… …… …… re-re-mapped to PIE group below
INT12 0x00 0D18 INT12 re-
re-mapped to PIE group below
INT13 0x00 0D1A XINT13 Interrupt or CPU Timer 1 (RTOS)
INT14 0x00 0D1C CPU Timer 2 (RTOS)
DATALOG 0x00 0D1D CPU Data logging Interrupt
…… …… ……
USER12 0x00 0D3E User-
User-defined Trap
INT1.1 0x00 0D40 PIEINT1.1 Interrupt Vector
…… …… ……
INT1.8 0x00 0D4E PIEINT1.8 Interrupt Vector
…… …… ……
INT12.1 0x00 0DF0 PIEINT12.1 Interrupt Vector
…… …… ……
INT12.8 0x00 0DFE PIEINT12.8 Interrupt Vector
 PIE vector location – 0x00 0D00 – 256 words in data memory
 RESET and INT1-INT12 vector locations are re-mapped
 CPU vectors are re-mapped to 0x00 0D00 in data memory 6 - 18

As you can see from Slide 6-18, the addresses 0x00 0D40 to 0x00 0DFF are used as the
expansion area. Now we do have 32 bits for each individual interrupt vector PIEINT1.1 to
PIEINT12.8.

Device Vector Mapping - Summary


RESET
<0x3F FFC0>

Reset Vector <0x3F F9A9> = Boot Code


Flash Entry Point <0x33 FFF6 > = LB _c_int00
User Code Start < _c_int00 >

_c_int00:
. . .
CALL main()
Initialization()
{
Load PIE Vectors PIE Vector Table
main() Enable the PIE
{ initialization(); Enable PIEIER 256 Word RAM
. . . Enable Core IER 0x00 0D00 – 0DFF
} Enable INTM
}

6 - 19

6 - 14 F2833x - Interrupts
Hardware Interrupt Response

Hardware Interrupt Response


After an interrupt has been acknowledged by the CPU, an automatic hardware context switch
sequence is started. It includes an auto-save of 14 internal registers with the all-important
internal control and status bits, and loads the program counter (PC) with the address of the
ISR.

Interrupt Response - Hardware Sequence


CPU Action Description
Registers → stack 14 Register words auto saved
0 → IFR (bit) Clear corresponding IFR bit
0 → IER (bit) Clear corresponding IER bit
1 → INTM/DBGM Disable global ints/debug events
Vector → PC Loads PC with int vector address
Clear other status bits Clear LOOP, EALLOW, IDLESTAT

Note: some actions occur simultaneously, none are interruptible


T ST0
AH AL
PH PL
AR1 AR0
DP ST1
DBSTAT IER
PC(msw) PC(lsw)
6 - 20

Interrupt Latency
Latency
ext. Internal
interrupt interrupt Assumes ISR in
occurs occurs internal RAM
here here

cycles
2 4 3 3 1 3
Recognition Get vector ISR
Sync ext. PF1/PF2/D1 Save D2/R1/R2 of instruction
signal delay (3) and (3 reg. of ISR return ISR executed
SP alignment pairs instruction address instruction
(ext. (1) saved) on next
(3 reg. pairs cycle
interrupt saved)
only)

Above is for PIE enabled or disabled

 Minimum latency (to when real work occurs in the ISR):


 Internal interrupts: 14 cycles
 External interrupts: 16 cycles

 Maximum latency: Depends on wait states, ready, INTM, etc.


6 - 21

F2833x - Interrupts 6 - 15
F2833x CPU Timers

F2833x CPU Timers


The F2833x features 3 independent 32-bit core timers. The block diagram for one timer is
shown below in Slide 6-22:

F2833x CPU Timers


RESET

Timer Reload

16 - Bit divide down 32 - Bit period


TDDRH:TDDR PRDH:PRD

SYSCLKOUT
16 - Bit prescaler 32 - Bit counter
PSCH:PSC TIMH:TIM
TCR.4

BORROW

INT

6 - 22

As you can see, the clock source is the internal clock “SYSCLKOUT”, which is usually
150MHz, assuming an external oscillator of 30MHz and a PLL-ratio of 10/2. Once the timer
is enabled (TCR-bit 4 = 0), the incoming clock counts down a 16-bit prescaler (PSCH: PSC).
On underflow, its borrow signal is used to count down the 32-bit counter (TIMH: TIM). At
the end, when this timer underflows, an interrupt request is transferred to the CPU.
The 16-bit divide down register (TDDRH: TDDR) is used as a reload register for the
prescaler. Each times the prescaler underflows, the value from the divide down-register is
reloaded into the prescaler. A similar reload function for the counter is performed by the 32-
bit period register (PRDH_PRD).
Timer 1 and Timer 2 are usually used by Texas Instruments for the real time operation
system “DSP/BIOS”, whereas Timer 0 is generally free for general usage. Lab 6 will use
Timer 0. This will not only preserve Timer 1 and 2 for later use together with DSP/BIOS, but
also help us to understand the PIE-unit, because Timer 0 is the only timer of the CPU that
goes through the PIE, as can be seen in the following slide, Slide 6-23:

6 - 16 F2833x - Interrupts
F2833x CPU Timers

F2833x Timer Interrupt System

PIE unit
TINT0
INT1.7 interrupt
28x Core Interrupt logic
INT1

TINT1 / XINT13 INT13

INTM
28x

IER
IFR
Core
INT14
TINT2

6 - 23

A timer unit is usually initialized by a set of registers. In Lab6, we will perform an exercise
with the registers of CPU Timer 0. However, instead of setting every single bit by ourselves,
we will use a hardware abstraction function, for which we only have to specify the desired
timer period and the clock speed of our processor. This function is provided by Texas
Instruments as part of a set of such functions.

F2833x Timer Registers


Address Register Name
0x0000 0C00 TIMER0TIM Timer 0, Counter Register Low
0x0000 0C01 TIMER0TIMH Timer 0, Counter Register High
0x0000 0C02 TIMER0PRD Timer 0, Period Register Low
0x0000 0C03 TIMER0PRDH Timer 0, Period Register High
0x0000 0C04 TIMER0TCR Timer 0, Control Register
0x0000 0C06 TIMER0TPR Timer 0, Prescaler Register
0x0000 0C07 TIMER0TPRH Timer 0, Prescaler Register High
0x0000 0C08 TIMER1TIM Timer 1, Counter Register Low
0x0000 0C09 TIMER1TIMH Timer 1, Counter Register High
0x0000 0C0A TIMER1PRD Timer 1, Period Register Low
0x0000 0C0B TIMER1PRDH Timer 1, Period Register High
0x0000 0C0C TIMER1TCR Timer 1, Control Register
0x0000 0C0D TIMER1TPR Timer 1, Prescaler Register
0x0000 0C0F TIMER1TPRH Timer 1, Prescaler Register High

0x0000 0C10 to 0C17 Timer 2 Registers ; same layout as above

6 - 24

F2833x - Interrupts 6 - 17
It is worthwhile to inspect the control register, as this is the most important register of a timer
unit.

F2833x Timer Control Registers


TIMERxTCR
Emulator Interaction
Timer Interrupt Flag Timer Interrupt Enable 1x = run free
Write 1 clear bit Write 1 to enable INT

15 14 13 12 11 10 9 8
TIF TIE reserved reserved FREE SOFT reserved reserved

7 6 5 4 3 2 1 0
reserved reserved TRB TSS reserved reserved reserved reserved

Timer Reload Bit Timer Stop Status


1 = reload 0 = start / 1 = stop
6 - 25

Summary:
Sounds pretty complicated, doesn’t it? Well, nothing is better suited to understand the PIE
unit than a lab exercise. In Lab 6 you will add the initialization of the PIE vector table to re-
map the vector table to address 0x00 0D00. You will also use CPU Timer 0 as a clock time
base for the source code of Lab 5_1 (“4 bit LED-counter”).
Remember, so far we generated time periods with a software-loop in function
“delay_loop()”. This was quite a waste of processor time, not very precise and poor
programming technique.
The procedure on the next page will guide you through the necessary steps to modify the
source code step by step.
Take your time, no pain no gain!
We will use functions, pre-defined by Texas Instruments as often as we can. This principle
will save us a lot of development time; we do not have to re-invent the wheel again and
again!

6 - 18 F2833x - Interrupts
Lab 6: CPU Timer 0 Interrupt and 4 LEDs

Lab 6: CPU Timer 0 Interrupt and 4 LEDs


Objective
The objective of this lab is to include a basic example of the interrupt system in the “LED-
counter” project of Lab5_1. Instead of using a software delay loop to generate the time
interval between the output steps, which is a poor use of processor time, we will now use one
of the 3 core CPU timers to do the job. One of the simplest tasks for a timer is to generate a
periodic interrupt request. We can use its interrupt service routine to perform periodic
activities OR to increment a global variable. This variable will then contain the number of
periods that are elapsed from the start of the program.
CPU Timer 0 is using the Peripheral Interrupt Expansion (PIE) Unit. This gives us the
opportunity to exercise this unit as well. Timer 1 and 2 bypass the PIE-unit and they are
usually reserved for Texas Instruments real-time operating system, called “DSP/BIOS”.
Therefore we implement Timer 0 as the core clock for this exercise.

Procedure

Create a Project File


1. Using Code Composer Studio, create a new project, called Lab6.pjt in
C:\DSP2833x_V4\Labs (or in another path that is accessible by you; ask your teacher
or a technician for an appropriate location!).
2. Define the size of the C system stack. In the project window, right click at project
“Lab6” and select “Properties”. In category “C/C++ Build”, “C2000 Linker”, “Basic
Options” set the C stack size to 0x400.
3. Open the file Lab5_1.c from C:\DSP2833x_V4\Labs\Lab5 and save it as Lab6.c in
C:\DSP2833x_V4\Labs\Lab6.
Next, we will take advantage of some useful files, which have been created and provided by
Texas Instruments and should be already available on your hard disk drive C as part of the
so-called "Header File" package (sprc530.zip). If not, ask a technician to install that package
for you!
4. In the C/C++ perspective, right click at project “Lab6” and select “Link Files to
Project”. Go to folder “C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\source” and
link:

• DSP2833x_GlobalVariableDefs.c
This file defines all global variable names to access memory mapped peripheral
registers.
5. Repeat the “Link Files to Project” step. From C:\tidcs\c28\dsp2833x\v131\
DSP2833x_common\source add:

• DSP2833x_CodeStartBranch.asm
• DSP2833x_SysCtrl.c

F2833x - Interrupts 6 - 19
Lab 6: CPU Timer 0 Interrupt and 4 LEDs

• DSP2833x_ADC_cal.asm
• DSP2833x_usDelay.asm
6. From C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\cmd link to project “Lab6”:

• DSP2833x_Headers_nonBIOS.cmd
This linker command file will connect all global register variables to their
corresponding physical addresses.

Project Build Options


7. We also have to extent the search path of the C-Compiler for include files. Right click at
project “Lab6” and select “Properties”. Select “C/C++ Build”, “C2000 Compiler”,
“Include Options”. In the box: “Add dir to #include search path”, add the following
lines:

C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include

Note: Use the “Add” Icon to add the new paths:

Close the Property Window by Clicking <OK>.

Modify the Source Code


8. Open Lab6.c to edit: double click on “Lab6.c” inside the project window. At the start of
your code, add the function prototype statement for the external function "InitSysCtrl()":
extern void InitSysCtrl(void);
9. Remove the function prototype for the local function "InitSystem()" at the beginning and
the whole function definition at the end of Lab6.c
10. In main replace the function call "InitSystem()" by "InitSysCtrl()".
11. Since "InitSysCtrl()" disables the watchdog, but we would like the watchdog to be
active, we have to re-enable the watchdog. Add the following lines just after the call of
function "InitSysCtrl()":
EALLOW;
SysCtrlRegs.WDCR = 0x00AF;
EDIS;

6 - 20 F2833x - Interrupts
Lab 6: CPU Timer 0 Interrupt and 4 LEDs

Build, Load and Test


12. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

and watch the tools run in the build window. If you get errors or warnings debug as ne-
cessary.

13. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

14. Verify that in the debug perspective the window of the source code “Lab6.c” is high-
lighted and that the blue arrow for the current Program Counter position is placed under
the line “void main(void)”.

15. Perform a real time run.

Target  Run

16. Verify that the LEDs behave as expected. In this case you have successfully finished the
first part of Lab6. Halt the Device (Target  Halt). Switch back into the “C/C++” –
Perspective.

Modify Source Code - Part 2


17. At the beginning of “Lab6.c” add a function prototype for a new interrupt service func-
tion for CPU Timer 0:
interrupt void cpu_timer0_isr(void);

18. In “main()”, directly after the function call "Gpio_select()", add a function call to:
InitPieCtrl();
This is a function that is provided by TI’s header file examples. We use this function “as it
is”. The purpose of this function is to clear all pending PIE-Interrupts and to disable all PIE
interrupt lines. This is a useful step when we would like to initialize the PIE-unit. Function
“InitPieCtrl ()” is defined in the source code file “DSP2833x_PieCtrl.c”; we have to link this
file to our project:
19. From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\source link to project:
DSP2833x_PieCtrl.c
Also, add an external function prototype at the beginning of Lab6.c:
extern void InitPieCtrl(void);

F2833x - Interrupts 6 - 21
Lab 6: CPU Timer 0 Interrupt and 4 LEDs

20. Inside “main()”, directly after the function call “InitPieCtrl();”, add a function call to:
InitPieVectTable();
This function will initialize the PIE-memory to an initial state. It uses a predefined
interrupt table “PieVectTableInit()” - defined in source code file “DSP2833x_PieVect.c”
and copies this table to the global variable “PieVectTable” - defined in
“DSP2833x_GlobalVariableDefs.c”. Variable “PieVectTable” is linked to the physical
memory of the PIE area.
Also, add an external function prototype at the beginning of Lab6.c:
extern void InitPieVectTable(void);
To be able to use “InitPieVectTable()”, we need to link two more code files to our
project:
21. From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\source, link to project:
DSP2833x_PieVect.c and
DSP2833x_DefaultIsr.c
The code file “DSP2833x_DefaultIsr.c” will add a set of interrupt service routines to our
project. When you open and inspect this file, you will find that all ISRs consist of an
endless for-loop and a specific assembler instruction “ESTOP0”. This instruction
behaves like a software breakpoint. This is a security measure. Remember, at this point
we have disabled all PIE interrupts. If we were to now run the program, we should never
see an interrupt request. If, for some reason, for example a power supply glitch, noise
interference or just a software bug, the DSP calls an interrupt service routine, then we
can catch this event by the “ESTOP0” break.
22. Now we have to re-map the entry for CPU-Timer0 Interrupt Service from the
“ESTOP0” operation to a real interrupt service. Editing the source code of TI’s code
“DSP2833x_DefaultIsr.c” would be one way to do this. Of course this would not be
a wise decision, because we would modify the original code for this single Lab
exercise. SO DO NOT DO THAT! A much better way is to modify the entry for
CPU-Timer0 Interrupt Service directly inside the PIE-memory. This is done in main
by adding the next 3 lines after the function call of “InitPieVectTable();”:
EALLOW;
PieVectTable.TINT0 = &cpu_timer0_isr;
EDIS;
EALLOW and EDIS are two macros to enable and disable the access to a group of
protected registers; the PIE is part of this area. The name of our own interrupt service
routine for Timer0 is “cpu_timer0_isr()”. We created the prototype statement earlier in
the procedure for this Lab. Please be sure to use the same name as you used in the
prototype statement!
23. Inside “main()”, directly after the re-mapping instructions from above, add the
function call “InitCpuTimers();”. This function will set the core Timer0 to a known
state and it will stop this timer.
InitCpuTimers();

6 - 22 F2833x - Interrupts
Lab 6: CPU Timer 0 Interrupt and 4 LEDs

Also, add an external function prototype at the beginning of Lab6.c:


extern void InitCpuTimers(void);
Again, we use a predefined function. To do so, we have to link the source code file
“DSP2833x_CpuTimers.c” to our project.
24. From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\source link to project:
DSP2833x_CpuTimers.c
25. Now we have to initialize Timer0 to generate a period of 100ms. TI has provided a
function “ConfigCpuTimer()”. All we have to do is to pass 3 arguments to this function.
Parameter 1 is the address of the core timer structure, e.g. “CpuTimer0”; Parameter 2 is
the internal speed of the DSP in MHz, e.g. 150 for 150MHz; Parameter 3 is the period
time for the timer overflow in microseconds, e.g. 100000 for 100 milliseconds. The
following function call will setup Timer0 to a 100ms period:
ConfigCpuTimer(&CpuTimer0, 150, 100000);
Add this function call in “main()” directly after the line “InitCpuTimers();”
Again, add an external function prototype at the beginning of Lab6.c:
extern void ConfigCpuTimer(struct CPUTIMER_VARS *, float, float);
26. Before we can start timer0 we have to enable its interrupt masks. We have to take care
of 3 levels to enable an individual interrupt source. Level 1 is the PIE unit. To enable it,
we have to set bit 7 of PIEIER1 to 1. Why? Because the Timer0 interrupt is directly
connected to group INT1, Bit7. Add the following line to your code after the call of
“ConfigCpuTimer()” in step 25:
PieCtrlRegs.PIEIER1.bit.INTx7 = 1;
27. Next, enable interrupt core line 1 (INT1). Modify the register IER accordingly.
IER |= 1;
28. Next, enable control – interrupts (EINT) and debug – interrupts (ERTM) globally. This
is done by adding the two code macros:
EINT; and
ERTM;
29. Finally, we have to start Timer 0. The bit TSS inside register TCR will do the job. Add:
CpuTimer0Regs.TCR.bit.TSS = 0;
30. After the end of “main()”, we have to add our new interrupt service routine
“cpu_timer0_isr()”. Remember, we have prototyped this function at the beginning of our
modifications. Now we have to add its body. Inside this function we have to perform two
activities:
1st - increment the interrupt counter “CpuTimer0.InterruptCount”. This way we
will have global information about how often this 100 milliseconds task was called.

F2833x - Interrupts 6 - 23
Lab 6: CPU Timer 0 Interrupt and 4 LEDs

2nd - acknowledge the interrupt service as the last line before return. This step is
necessary to re-enable the next Timer 0 interrupt service. It is done by:
PieCtrlRegs.PIEACK.all = PIEACK_GROUP1;
31. Now we are almost done. Inside the endless while(1) loop of “main()” we have to delete
the function call: “delay_loop(1000000);”. We do not need this function any longer; we
can also delete its prototype at the top of our code and its function body, which is still
present after the code of “main()”.
32. Inside the endless loop “while(1)“, after the “if-else”-construct, we have to implement a
statement to wait until the global variable “CpuTimer0.InterruptCount” has been
incremented to 1, which corresponds to the interval of 100 milliseconds. Remember to
reset the variable “CpuTimer0.InterruptCount” to zero when you continue after the wait
statement. Note: The global variable “CpuTimer0.InterruptCount” has been defined in
the file “DSP2833x_CpuTimers.c” as a global and volatile variable, which also has been
initialized to zero when we called the function “ConfigCpuTimer()”.
33. Done?
34. No, not quite! We forgot the watchdog! It is still alive and we removed the service
instructions together with the function “delay_loop()”. So we have to add the watchdog
reset sequence somewhere into our modified source code. Where? A good strategy is to
service the watchdog not in a single portion of our code. Our code now consists of two
independent tasks: the while-loop of main and the interrupt service routine of timer 0.
Place one of the two reset instructions for WDKEY into the ISR and the other one into
the while(1)-loop of main.
If you are a little bit fearful about being bitten by the watchdog, then disable it first; try
to get your code running without it. Later, when the code works as expected, you can re-
think the watchdog service part again.

Build, Load and Test


35. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

If you get errors or warnings debug as necessary.

36. Load the output file in the debugger session:

Target  Debug Active Project and switch into the “Debug” perspective.

37. Perform a real time run.

Target  Run

38. Verify that the LEDs behave as expected. You have successfully finished Lab6. Halt the
Device (Target  Halt). Switch back into the “C/C++” – Perspective.
End of Lab6.

6 - 24 F2833x - Interrupts
F2833x PWM, Capture and QEP
Introduction
Today’s electronic systems are described using terms such as “direct digital control”, “digital
power supply”, “digital power converters” and so on. A core feature of all these applications
is the ability to generate different series of digital pulse patterns to control power electronic
switches based on the results of sophisticated numerical calculations. The F283xx family
provides such hardware units; several pulse width modulation (PWM) output signals, along
with time measurements units (“Capture Units”).
In Chapter 6 we have already implemented a time base unit, using the CPU core timers 0 to
2. Although these units are also hardware based time units, they are only able to 'signal' the
end of a pre-defined period. On such an event, an interrupt service routine could be requested
to start and perform desired activities by a software sequence. While this scenario is
sufficient for most time-based software activities, it is not suitable for hardware related
actions, such as switching the control line of an output stage from passive to active. In this
case we need much more precise and automatic response to the actuator control lines, based
on different events on the timeline. This is where PWM - lines come into the play.
The main applications of PWM are:

• Digital Motor Control (DMC)

• Control of switching pulses for Digital Power Supply (DPS) systems

• Analogue Voltage Generators


Later we will discuss these main application areas in more detail. The F2833x is equipped
with different and independent numbers of PWM channels; a F28335, for example, has 6
PWMs.
The F2833x is also able to perform time measurements using hardware signals. With the
help of independent edge detector state machines, called ‘Capture Units’ we can measure the
time difference between edges to determine the speed of a rotating shaft in revolutions per
minute or the active duty cycle of a feedback signal.
A third hardware part of the Control System is called a ‘Quadrature Encoder Pulse’ -unit
(QEP). This is a unit that is used to derive the speed and direction information of a rotating
shaft directly from hardware signals from incremental encoders or resolvers.
Our lab series Lab 7-1 to Lab 7-9 will include the most important operating modes of a
PWM signal. A typical requirement in control loop calculations is the operation using
complex numbers, which are translated according to Euler's law into sine and cosine
components. Instead of calculating a new sine-value each time we need one, we can access a
look-up table, which is already available inside the F283xx! This is exactly what we will do
in Lab 7- 9 (“Generate a pulse width modulated sine wave signal”) to implement a practical
example.

F2833x - PWM and Capture Units 7-1


Module Topics

Module Topics
F2833x PWM, Capture and QEP ..................................................................................................... 7-1
Introduction ..................................................................................................................................... 7-1
Module Topics ................................................................................................................................. 7-2
ePWM Block Diagram .................................................................................................................... 7-3
ePWM Time Base Unit .................................................................................................................... 7-4
ePWM Phase Synchronisation ........................................................................................................ 7-5
Timer Operating Modes .................................................................................................................. 7-6
Time Base Registers ........................................................................................................................ 7-7
Lab 7_1: Generate an ePWM signal ............................................................................................. 7-11
Lab 7_2: Generate a 3 - phase signal system................................................................................ 7-16
Purpose of Pulse Width Modulation ............................................................................................. 7-19
ePWM Compare Unit .................................................................................................................... 7-21
ePWM Action Qualifier Unit ......................................................................................................... 7-24
Lab 7_3: A 1 kHz with variable pulse width ................................................................................. 7-30
Lab 7_4: a pair of complementary 1 kHz-Signals ......................................................................... 7-32
Lab 7_5: Independent Modulation on ePWM1A / 1B ................................................................... 7-34
ePWM Dead Band Module ............................................................................................................ 7-38
Lab 7_6: Dead Band Unit on ePWM1A / 1B ................................................................................ 7-43
ePWM Chopper Module ................................................................................................................ 7-46
Lab 7_7: Chopped Signals at ePWM1A / 1B ................................................................................ 7-50
ePWM Over Current Protection.................................................................................................... 7-52
Lab 7_8: Trip Zone protection with TZ6 ....................................................................................... 7-56
ePWM Interrupt Sources ............................................................................................................... 7-61
Lab7_9: ePWM Sine Wave Modulation ........................................................................................ 7-65
eCAP Capture Module .................................................................................................................. 7-71
Capture Units Registers ................................................................................................................ 7-74
Lab7_10: ePWM1A 1 kHz captured by eCAP1 ............................................................................. 7-79
Enhanced QEP module ................................................................................................................. 7-82
Infrared Remote Control ............................................................................................................... 7-84
Lab7_11: eCAP4 to receive a RC5 IR-signal................................................................................ 7-87

7-2 F2833x - PWM and Capture Units


ePWM Block Diagram

ePWM Block Diagram


Each enhanced Pulse Width Modulation (ePWM) unit is controlled by its own logic block, as
shown in Slide 7_2 below. This logic is able both to automatically generate signals on
different time events and also to request various interrupt services from the F2833x PIE
interrupt system, to support its operational modes.

ePWM Block Diagram


CMPA . 15 - 0 CMPB . 15 - 0
TBCTL . 12 - 7
Shadowed Shadowed
Clock Compare Compare
Prescaler Register Register
AQCTLA . 11 - 0
TBCTR . 15 - 0
AQCTLB . 11 - 0 DBCTL . 4 - 0
16-
16-Bit
Compare Action Dead
Time-
Time-Base
TBCLK Logic Qualifier Band
Counter

EPWMxSYNCI EPWMxSYNCO
Period
Register EPWMxA
PWM Trip
Shadowed
Chopper Zone
SYSCLKOUT TBPRD . 15 - 0 EPWMxB
PCCTL . 10 - 0
TZy
TZSEL . 15 - 0

7-2

A unique feature of an ePWM - module is its ability to start the Analogue to Digital
Converter (ADC) without software interaction, directly from an internal hardware event. A
common microcontroller would have to request an interrupt service to do the same - the
F2833x does this automatically. We will use this feature in the next module!
Note: There are two basic operating modes of the ePWM system: (1) standard ePWM 16-bit
mode and (2) 24-bit High Resolution PWM mode (HRPWM). For now we will discuss the
16-bit mode.
The purpose of an ePWM unit is to generate a single ended signal or a pair of output signals,
called EPWMxA and EPWMxB, which are related to each other. The lower case letter x is a
placeholder for the number of the ePWM unit, e.g. 1…6.
Note: to generate a physical output signal on the F2833x we have to set the multiplex
registers for the I/O ports accordingly - please refer to Chapter 5!
As you can see from Slide 7-2, to generate a physical output signal we will have to setup a
few units: time base, compare logic, action qualifier, dead band unit, chopper and trip zone.
On first glance this looks cumbersome. However, it does allow us to setup a range of
different operating modes, all of which can be used in modern digital control. So, let us
make use of it!

F2833x - PWM and Capture Units 7-3


ePWM Time Base Unit

ePWM Time Base Unit


The central block of an ePWM unit is a 16-bit timer (register "TBCTR"), with signal
SYSCLKOUT as its time-base. In Chapter 5 we initialized the core to run at 100 MHz or 150
MHz, depending on the external clock of the F2833x. This frequency sets the time-base for
all ePWM units.

ePWM Time-Base Module


CMPA . 15 - 0 CMPB . 15 - 0
TBCTL . 12 - 7
Shadowed Shadowed
Clock Compare Compare
Prescaler Register Register
AQCTLA . 11 - 0
TBCTR . 15 - 0
AQCTLB . 11 - 0 DBCTL . 4 - 0
16-
16-Bit
Compare Action Dead
Time-
Time-Base
TBCLK Logic Qualifier Band
Counter

EPWMxSYNCI EPWMxSYNCO
Period
Register EPWMxA
PWM Trip
Shadowed
Chopper Zone
SYSCLKOUT TBPRD . 15 - 0 EPWMxB
PCCTL . 10 - 0
TZy
TZSEL . 15 - 0

7-3

A clock prescaler (register TBCTL, bits 12 to 7) can be used to reduce the input counting
frequency by a selectable factor between 1 and 1792.
Register TBPRD defines the length of a period of an output signal, in multiples of the time-
period of the input signal.
Another unique feature of the F2833x is its “shadow” functionality of operating registers, in
the case of ePWM units available for compare register A, B and period register. For some
applications it is necessary to modify the values inside a compare or period register, every
period. The advantage of the background registers is that we can prepare the values for the
next period in the current one. Without a background function we would have to wait for the
end of the current period, and then trigger a high prioritized interrupt. Sometimes this form
of scheduling will miss its deadline…

7-4 F2833x - PWM and Capture Units


ePWM Phase Synchronisation

ePWM Phase Synchronisation


Two hardware signals "SYNCI" (synch in) and "SYNCO" (synch out) can be used to
synchronize ePWM units to each other. For example, we could define one ePWM unit as a
"master" to generate an output signal "SYNCO" each time the counter equals period. Two
more ePWM units could be initialized to recognize this signal as "SYNCI" and start
immediately counting, each time they receive this signal. In such way we have established a
synchronous set of 3 ePWM channels. But we can do even better. By using another register
called "TBPHS" we can introduce a phase shift between master, slave 1 and slave 2, an
absolute necessity for three-phase control systems.

ePWM Phase Synchronization


Ext. SyncIn
(optional)

Phase
φ=0°
=0°
En
o o .
SyncIn
EPWM1A
o
CTR=zero o
CTR=CMPB o o EPWM1B
X o
SyncOut
To eCAP1
SyncIn
Phase
φ=120°
=120°
En
o o .
SyncIn
EPWM2A φ=120°
=120°
o
CTR=zero o
CTR=CMPB o o EPWM2B
X o
SyncOut

Phase
φ=240°
=240°
En
o o .
SyncIn
EPWM3A
φ=120°
=120°

o
CTR=zero o
CTR=CMPB o o EPWM3B
X o
SyncOut φ=240°
=240°

7-4

Slide 7-4 shows such an example, where register TBCNT of ePWM2 and ePWM3 are
preloaded with a start value that corresponds to 120° and 240° respectively. In this example
ePWM1 has been initialized as master to generate SYNCO each time the counter register
equals zero. With the enabled phase input feature for ePWM2 and ePWM3 the two channels
operate as slave 1 and slave 2 and will load their counter registers TBCNT with numbers
stored in the corresponding phase registers TBPHS.
Example:
• ePWM1 counts from 0 to 6000. TBPRD = 6000
• ePWM2 register TBPHS = 2000
• ePWM3 register TBPHS = 4000

F2833x - PWM and Capture Units 7-5


Timer Operating Modes

Timer Operating Modes


Each ePWM module is able to operate in one of 3 different counting modes, selected by bits
1 and 0 of register TBCTL:
• count up mode
• count down mode
• count up and down mode

ePWM Time-Base Count Modes


TBCTR

TBPRD
Asymmetrical
Waveform

Count Up Mode
TBCTR

TBPRD
Asymmetrical
Waveform

Count Down Mode


TBCTR

TBPRD
Symmetrical
Waveform

Count Up and Down Mode


7-5

Which of the three modes is used is mostly determined by the application. The first two
operating modes are called "Asymmetrical" because in of the shape of the counting pattern
from 0 to TBPRD (count up) or from TBPRD to 0 (count down). Also, in a three phase
system, one could define three different timing events between 0 and TBPRD to switch a
phase output signal to "ON" and to use the match between TBCNT and TBPRD to switch
"OFF" all three phases simultaneously, thus generating an asymmetrical shape of the switch
signals.
In "Symmetrical" waveform mode, the register TBCNT starts from zero to count up until it
equals TBPRD. Then TBCNT turns direction to count down back to zero to finish a counting
period.

7-6 F2833x - PWM and Capture Units


Time Base Registers

Time Base Registers


To initialize the time base for one of the ePWM units it is necessary to initialize a first group
of registers, shown in slide 7-6:

ePWM Time-Base Module Registers

Name Description Structure


TBCTL Time-
Time-Base Control EPwmxRegs.TBCTL.all
EPwm Regs.TBCTL.all =
TBSTS Time-
Time-Base Status EPwmxRegs.TBSTS.all
EPwm Regs.TBSTS.all =
TBPHS Time-
Time-Base Phase EPwmxRegs.TBPHS
EPwm Regs.TBPHS =
TBCTR Time-
Time-Base Counter EPwmxRegs.TBCTR
EPwm Regs.TBCTR =
TBPRD Time-
Time-Base Period EPwmxRegs.TBPRD
EPwm Regs.TBPRD =

7-6

To access these registers using the C programming language, we can take advantage of the
source code file "DSP2833x_GlobalVariableDefs.c", which defines all memory mapped
hardware registers as global variables. All variables are based on structure and union data
types, also already defined by Texas Instruments and included with a master header file
"DSP2833x_headers.h".
For the purpose of ePWMs this file defines 6 structures "EPwm1Regs" to "EPwm6Regs",
which include all registers that belong to one of these hardware units.
Time related registers such as the period register can be accessed directly, e.g. to define a
period of 6000 count pulses we can use:
EPwm1Regs.TBPRD = 6000;
For control registers, such as TBCTL, the structure members have been defined as unions.
This technique allows us to access the register en bloc (union member "all") or just
individual bit groups (union member "bit"). For example, a line to write the full register
TBCTL would look like this:
EPwm1Regs.TBCTL.all = 0x1234;
A bit field access to fields "CLKDIV" only would look like:
EPwm1Regs.TBCTL.bit.CLKDIV = 7;

F2833x - PWM and Capture Units 7-7


Time Base Registers

Time Base Control Register TBCTL


The master control register for an ePWM unit is register TBCTL.

ePWM Register TBCTL


Upper Register:

Phase Direction
0 = count down after sync
1 = count up after sync TBCLK = SYSCLKOUT / (HSPCLKDIV * CLKDIV)

15 - 14 13 12 - 10 9-7
FREE_SOFT PHSDIR CLKDIV HSPCLKDIV

Emulation Halt Behavior TB Clock Prescale High Speed TB


00 = stop after next CTR inc/dec
inc/dec 000 = /1 (default) Clock Prescale
01 = stop when: 001 = /2 000 = /1
Up Mode; CTR = PRD 010 = /4 001 = /2 (default)
Down Mode; CTR = 0 011 = /8 010 = /4
Up/Down Mode; CTR = 0 100 = /16 011 = /6
1x = free run (do not stop) 101 = /32 100 = /8
110 = /64 101 = /10
111 = /128 110 = /12
111 = /14
(HSPCLKDIV is for legacy compatibility)
7-7

FREE_SOFT:
• controls the interaction between the DSC and the JTAG - Emulator.
• if the execution sequence of the code hits a breakpoint, we can specify what
should happen with to this ePWM unit.
PHSDIR:
• specifies if this ePWM unit starts counting up or down after a SYNCIN pulse
has been seen.
• In case of a single ePWM setup with a disabled sync in feature, this bit is a
"don't care"
CLKDIV and HSPCLKDIV:
• Prescaler Bit fields to reduce the input frequency "SYSCLKOUT"
• For a 100MHz-System each pulse translates into 10 ns, for a 150MHz - System
into 6.667 ns.

7-8 F2833x - PWM and Capture Units


Time Base Registers

ePWM Register TBCTL


Lower Register:
Counter Mode
00 = count up
Software Force Sync Pulse 01 = count down
0 = no action 10 = count up and down
1 = force one-
one-time sync 11 = stop – freeze (default)

6 5-4 3 2 1-0
SWFSYNC SYNCOSEL PRDLD PHSEN CTRMODE

Sync Output Select Period Shadow Load Phase Reg. Enable


(source of EPWMxSYNC0 signal) 0 = load on CTR = 0 0 = disable
00 = EPWMxSYNCI 1 = load immediately 1 = CTR = TBPHS on
01 = CTR = 0 EPWMxSYNCI signal
10 = CTR = CMPB
11 = disable SyncOut

7-8

SWFSYNC:
• An instruction that sets this bit will immediately produce a "SYNCO" pulse from
this ePWM unit
SYNCOSEL:
• Selection of the source for the SYNCO signal.
• If no channel synchronization is used, switch off this feature
PRDLD:
• Enables (0) or disables (1) the shadow register function of TBPRD. If disabled,
all write instructions to TBPRD will directly change the period register. If
enabled, a write instruction will store a new value in shadow. With the next
event CTR = 0 the shadow value will be loaded into TBPRD automatically.
PHSEN:
• Enables (1) the preload of register TBCTR from TBPHS by a "SYNCIN"
trigger
CTRMODE:
• Defines the operating mode of this ePWM unit

F2833x - PWM and Capture Units 7-9


Time Base Registers

Time Base Status Register TBSTS


This register flags the current status of the ePWM unit

ePWM Register TBSTS

Counter Max Latched Counter Direction


0 = max value not reached 0 = CTR counting down
1 = CTR = 0xFFFF (write 1 to clear) 1 = CTR counting up

15 - 3 2 1 0
reserved CTRMAX SYNCI CTRDIR

External Input Sync Latched


0 = no sync event occurred
1 = sync has occurred (write 1 to clear)

7-9

CTRDIR:
• Indicates, if ePWM counts up (1) or down(0)
SYNCI:
• If an SYNCI event has been seen by this ePWM unit, this bit is 1, if not, it is 0.
• Note: To clear this bit, one must write a 1 into it!
CTRMAX:
• If for some reason the 16-bit counter register TBCTR overflows, bit
"CTRMAX" will be set to 1. Under normal circumstances this should not
happen, so we can treat this bit as a security alert signal.
• Note: To clear this bit, one must write a 1 into it!

7 - 10 F2833x - PWM and Capture Units


Lab 7_1: Generate an ePWM signal

Lab 7_1: Generate an ePWM signal


Although we have not discussed all the remaining modules inside the ePWM units,
let us start an exercise to generate a single ended ePWM output signal. We will
resume the discussion of additional modules in an ePWM unit later. The following
procedure will guide you through the task of the exercise and will give you all
necessary information.

Lab 7_1: Generate a 1 KHz Signal at ePWM1A


Objective:
• Generate a 1 KHz square wave signal at ePWM1A with a
duty cycle of 50 %
• Measure it with an oscilloscope or
• Connect the signal to an external buzzer or loudspeaker

• Registers involved:
• TBPRD: define signal frequency
• TBCTL: setup operating mode and time prescale
• AQCTLA: define signal shape for ePWM1A

1 TPWM
TBPRD = ∗
2 TSYSCLKOUT ∗ CLKDIV ∗ HSPCLKDIV

7 - 10

Objective
The objective of this lab is to generate a square wave signal of 1 kHz at line
ePWM1A. With the help of an oscilloscope connected to header J6-1 of the
Peripheral Explorer Board, we can monitor the signal. A small external circuit
featuring a buzzer would allow us to make the signal audible. A possible schematic
is given at the end of this exercise.

Procedure

Create a new Project File


1. Using Code Composer Studio, create a new CCS project, called Lab7.pjt in
C:\DSP2833x_V4\Labs (or in another path that is accessible by you; ask your teacher
or a technician for an appropriate location!).
2. Open the file Lab6.c from C:\DSP2833x_V4\Labs\Lab6 and save it as Lab7_1.c in
C:\DSP2833x_V4\Labs\Lab7.

F2833x - PWM and Capture Units 7 - 11


Lab 7_1: Generate an ePWM signal

3. Define the size of the C system stack. In the project window, right click at project
“Lab6” and select “Properties”. In category “C/C++ Build”, “C2000 Linker”, “Basic
Options” set the C stack size to 0x400.
As we did in previous labs, let us add some of the files, provided by Texas Instruments, to
the project:
4. In the C/C++ perspective, right click at project “Lab7” and select “Link Files to
Project”. Go to folder “C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\source”
and link:

• DSP2833x_GlobalVariableDefs.c
5. Repeat the “Link Files to Project” step. From C:\tidcs\c28\dsp2833x\v131\
DSP2833x_common\source add:
• DSP2833x_CodeStartBranch.asm
• DSP2833x_SysCtrl.c
• DSP2833x_ADC_cal.asm
• DSP2833x_usDelay.asm
• DSP2833x_CpuTimers.c
• DSP2833x_PieCtrl.c
• DSP2833x_PieVect.c
• DSP2833x_DefaultIsr.c
6. From C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\cmd link to project “Lab7”:

• DSP2833x_Headers_nonBIOS.cmd

Project Build Options


7. We also have to extent the search path of the C-Compiler for include files. Right
click at project “Lab7” and select “Properties”. Select “C/C++ Build”, “C2000
Compiler”, “Include Options”. In the box: “Add dir to #include search path”, add the
following lines:

C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include

Note: Use the “Add” Icon to add the new paths:

Close the Property Window by Clicking <OK>.

7 - 12 F2833x - PWM and Capture Units


Lab 7_1: Generate an ePWM signal

Build, Load and Test


8. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

and watch the tools run in the build window. If you get errors or warnings debug as
necessary.

9. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

10. Verify that in the debug perspective the window of the source code “Lab7_1.c” is
high-lighted and that the blue arrow for the current Program Counter position is
placed under the line “void main(void)”.

11. Perform a real time run.

Target  Run
If the code does not work as it did in Lab6, do not continue with the next steps! Go back and
try to find out which step of the procedure you missed.

Modify Source Code


12. In CCS, switch to the “C/C++” perspective. In function "Gpio_select()", set multip-
lex register line GPIO0 to enable ePWM1A as output signal.

13. In “main()”, just after the call to the function "Gpio_select()", call a new function
"Setup_ePWM1A()". Also, add a new function prototype at the beginning of
“Lab7_1.c”:
void Setup_ePWM1A(void);

14. At the end of Lab7_1.c, add the definition of the new function "Setup_ePWM1A()".
We will use this function to initialize ePWM1 to generate a 1 kHz square wave sig-
nal. We have to initialize the following registers:

• EPwm1Regs.TBCTL
• EPwm1Regs.TBPRD
• EPwm1Regs.AQCTLA

To setup the registers we can use either the "all"-member of the register union or the individ-
ual bit field member "bit". An instruction to "all" would require us to calculate a hexadecim-
al number for all 16 bits. By using the "bit" - structure we can leave the task to calculate the
correct logical and/or -instruction to set or clear individual bit fields with the C-compiler. As

F2833x - PWM and Capture Units 7 - 13


Lab 7_1: Generate an ePWM signal

an example, an instruction to setup the operating mode to "up/down"-mode would look like
this:

• EPwm1Regs.TBCTL.bit.CTRMODE = 2;

Furthermore, we have to calculate the value for register TBPRD. If we use the "up/down" -
counting operating mode for ePWM1A, the formula is:

1 f SYSCLKOUT
TBPRD = ∗
2 f PWM ∗ CLKDIV ∗ HSPCLKDIV

The factor 1/2 must be used in "up/down operating mode. Remember that TBPRD is a 16-
bit register, therefore the maximum number for TBPRD is (216 -1) or 65535.
Now, recall the objective is to generate a PWM signal of 1 kHz with the F28335ControlCard
running at 150 MHz. Your task is to calculate appropriate numbers for CLKDIV,
HSPCLKDIV and TBPRD.
In function "Setup_ePWM1A()" initialize:
EPwm1Regs.TBCTL.bit.CLKDIV = ?
EPwm1Regs.TBCTL.bit.HSPCLKDIV = ?
EPwm1Regs.TBCTL.bit.CTRMODE = 2; // up-down mode
EPwm1Regs.TBPRD = ?
EPwm1Regs.AQCTLA.all = 0x0006; // zero = set; period = clear

Re-Build, Load and Test


15. Now rebuild, load and test the new project. The program should still show the binary
counter from Lab6 at LEDs LD1…LD4. The new addition is a 1 kHz - signal at
output ePWM1A (header J6-1 at the Peripheral Explorer Board).
16. Use a scope to inspect this signal. It should look like:

7 - 14 F2833x - PWM and Capture Units


Lab 7_1: Generate an ePWM signal

17. Optional exercise: experiment with different frequencies by changing the value for
register TBPRD!
18. Optional Hardware: Make your frequency audible! By adding the following
circuitry to your Peripheral Explorer Board, we can do it!

ePWM1A

Device B1 (“Beeper”) can be a Digisound F/SMD8585JSLF (Mouser Part # 847 -


FSMD8585JS) or a Digisound F/PCW04A.

END of LAB 7_1

F2833x - PWM and Capture Units 7 - 15


Lab 7_2: Generate a 3 - phase signal system

Lab 7_2: Generate a 3 - phase signal system


Now let us experiment with a 3-phase system with a phase shift of 120° and 240°
between the signals. We will use ePWM1A, ePWM2A and ePWM3A for this
exercise. Signal ePWM1A will be the master phase and ePWM2A and 3A will trail
at 120° and 240° respectively.

Lab 7_2: Generate a 3 phase system


Objective:
• Generate three 1 KHz square wave signals at ePWM1A, 2A
and 3A with duty cycles of 50 % and a phase shift of 120°
and 240° between the signals
• Measure all three signals with an oscilloscope

• Registers involved:
• TBPRD: define signal frequency
• TBCTL: setup operating mode and time prescale
• AQCTLA: define signal shape for ePWM1A
• TBPHS: definition of the phase shift for 2A and 3A
1 TPWM
TBPRD = ∗
2 TSYSCLKOUT ∗ CLKDIV ∗ HSPCLKDIV

7 - 11

Objective
The objective of this lab is to generate a set of 3 square wave signals of 1 kHz each at lines
ePWM1A, ePWM2A and ePWM3A. With the help of a 4 channel oscilloscope connected to
header J6-1, 2 and 3 of the Peripheral Explorer Board, we can visualize the signal.

Procedure

Open Project File


1. If not still open from Lab7_1, re-open project Lab7.pjt in “C/C++” - perspective.
2. Open file “Lab7_1.c” and save it as “Lab7_2.c”
3. Exclude file “Lab7_1.c” from build. Use a right mouse click at file “Lab7_1.c”, and
enable “Exclude File(s) from Build”.

7 - 16 F2833x - PWM and Capture Units


Lab 7_2: Generate a 3 - phase signal system

Modify Source Code


4. In file “Lab7_2.c” change the function name “Setup_ePWM1A”. Since we will also
initialize ePWM2A and ePWM3A with this function, the function name is now
somewhat misleading. Change the name into “Setup_ePWM”, including the function
prototype and the calling line in the “main()” - loop.
5. In local function “Gpio_select()”, add instructions to initialize the pin functions of
GPIO2 and GPIO4 to ePWM2A and ePWM3A respectively.
6. In function “Setup_ePWM()”, repeat the initialization for ePWM1A with the same
instructions for ePWM2A and ePWM3A. Apply identical values as for ePWM1A to
the following registers:
• EPwm2Regs.TBCTL
• EPwm2Regs.TBPRD
• EPwm2Regs.AQCTLA
• EPwm3Regs.TBCTL
• EPwm3Regs.TBPRD
• EPwm3Regs.AQCTLA
If you now recompile, load and test your new code, you should get 3 identical 1 kHz -
signals with zero phase-shift between the 3 ePWM lines:

7. Now let us add the phase shift commands between ePWM1A, ePWM2A and
ePWM3A. To do so, we will have to program the phase registers of ePWM2A and
ePWM3A. Also, we must define ePWM1A as the master phase to generate a
SYNCOUT pulse each time its counter register TBCNT equals zero. For ePWM2,
we must enable a SYNCIN - pulse and also define SYNCIN as SYNCOUT to drive
it into ePWM3 unit. Recall that the period register TBPRD of ePWM1A has been
initialized with a value that corresponds to a time period of 1 millisecond. Now for
ePWM2 and ePWM3 we need a phase shift of 1/3rd and 2/3rd of that value preloaded
in register TBPHS.

F2833x - PWM and Capture Units 7 - 17


Lab 7_2: Generate a 3 - phase signal system

Summary: In function “Setup_ePWM()” add the following instructions:


EPwm1Regs.TBCTL:

• Sync Out Select: generate a signal if CTR = 0


EPwm2Regs.TBCTL:

• Set phase enable

• Sync Out Select: SYNCIN = SYNCOUT


EPwm2Regs.TBPHS:

• Load it with 1/3rd of TBPRD

• Since TBPHS is a union type, a valid access is made like this:


EPwm2Regs.TBPHS.half.TBPHS = ????? ;
Epwm3Regs.TBCTL:

• Set phase enable


EPwm3Regs.TBPHS:

• Load TBPHS with 2/3rd of TBPRD

Build, Load and Test


8. Now build, load and test the modified project. Using an oscilloscope you should see
3 time shifted signals on ePWM1A, ePWM2A and ePWM3A:

END OF LAB 7_2

7 - 18 F2833x - PWM and Capture Units


Purpose of Pulse Width Modulation

Purpose of Pulse Width Modulation


In Lab7_1 and Lab7_2 we created square wave signals with a pulse duty cycle of 50% low
and 50% high. We are also able to produce a sequence of time-shifted signals on a group of
output signals. But so far, we are still not able to change or “to modulate” the width of the
pulses - even though this hardware unit is called “Pulse Width Modulation”. This modulation
is based on another set of control registers of a unit called “Compare Module”.
Before we discuss the compare module, let us look into the technical background and
purpose of PWM.

What is Pulse Width Modulation?


 PWM is a scheme to represent a
signal as a sequence of pulses
 fixed carrier frequency
 fixed pulse amplitude
 pulse width proportional to
instantaneous signal amplitude
 PWM energy ≈ original signal energy

t t
T
Original Signal PWM representation
7 - 12

PWM is nothing more than a digital output signal with binary amplitude, 0 or 1. In technical
terms, the voltage at this output pin is either 0V or 3.3V. However, we can setup a point
within a period, at which we switch the output from 0 to 3.3V and vice versa. By changing
this set-point between 0 and 100% of the period, we can adjust the duty cycle of the output
signal.
With a PWM signal we can represent any analogue output signal as a series of digital pulses!
All we need to do with this pulse series is to integrate it (with a simple low pass filter) to
imitate the desired signal. This way we can build a sine wave shaped output signal. The more
pulses we use for one period of the desired signal, the more precisely we can imitate it. We
speak very often of two different frequencies, the PWM-frequency (or sometimes “carrier
frequency”) and the desired signal frequency.
A lot of practical applications have an internal integrator. For example the windings of an
electrical motor are perfectly suited to behave as a low-pass filter.

F2833x - PWM and Capture Units 7 - 19


Purpose of Pulse Width Modulation

Why use PWM with Power Switching


Devices?
 Desired output currents or voltages are known
 Power switching devices are transistors
 Difficult to control in proportional region
 Easy to control in saturated region
 PWM is a digital signal  easy for DSP to output

DC Supply DC Supply

? PWM
Desired PWM approx.
signal to of desired
system signal
Unknown Base Signal Base Signal known with PWM
7 - 13

One of the most used applications of PWM is (A) Digital Motor Control (DMC) and (B)
Digital Power Supply (DPS) - sometimes also called “Switched Power Supply”.
Why is that? Answer: The overall goal is to control electrical drives by inducing harmonic
voltages and currents into the windings of the motor. This is done to avoid electromagnetic
distortions of the environment and to achieve a high power factor. To induce a sine wave
shaped signal into the windings of a motor we would have to use an amplifier to achieve
high currents. The simplest amplifier is a standard NPN or PNP transistor that proportionally
amplifies the base current into the collector current. The problem is, for high currents we
cannot force the transistor into its linear region; this would generate a lot of thermal losses
and likely to exceed its maximum power dissipation.
The solution is to use this transistor in its static switch states only (On: Ice = Icesat, Off: Ice =
0). In these states, a transistor has its minimum power dissipation. AND: by adapting the
switch pattern of a PWM (recall: amplitude is 1 or 0 only) we can induce a sine wave shaped
current!
Environmentally friendly power supply units use switching technologies to increase the
efficiency factor of traditional power supply units. Instead of converting a lot of primary
energy just in pure thermal energy, these techniques, known as “Buck”- or “Boost” -
converters, allow customers to build reduce the package of their goods and more important
to help save our environment.

7 - 20 F2833x - PWM and Capture Units


ePWM Compare Unit

ePWM Compare Unit


The module to control the active phase of a pulse pattern and the position of the switching
points in a PWM is called the “Compare Unit”, highlighted in the next slide:

ePWM Compare Module


CMPA . 15 - 0 CMPB . 15 - 0
TBCTL . 12 - 7
Shadowed Shadowed
Clock Compare Compare
Prescaler Register Register
AQCTLA . 11 - 0
TBCTR . 15 - 0
AQCTLB . 11 - 0 DBCTL . 4 - 0
16-
16-Bit
Compare Action Dead
Time-
Time-Base
TBCLK Logic Qualifier Band
Counter

EPWMxSYNCI EPWMxSYNCI
Period
Register EPWMxA
PWM Trip
Shadowed
Chopper Zone
SYSCLKOUT TBPRD . 15 - 0 EPWMxB
PCCTL . 10 - 0
TZy
TZSEL . 15 - 0

7 - 14

Its functionality is based on a pair of registers, called “Compare Register A and B” (CMPA
and CMPB). Note that there is no relationship between the letters A and B in these registers
and the naming of the two output signals in the lower right corner, EPWMxA and EPWMxB.
This naming convention is a little bit misleading, it would have been better to use different
names such as CMP1 and CMP2, but the decision was made by Texas Instruments.
Depending on the pre-selected operating mode of the ePWM unit, it is possible to define 2 or
4 events within a period of the PWM - frequency, by choosing the appropriate values in
CMPA and/or CMPB.
Have you kept in mind these operating modes? If not, please review Slide 7-5. Here is a
summary:
• count up mode
• count down mode
• count up and down mode
In Lab7_1 and Lab7_2 we used the up/down mode to generate the 1 kHz signal. We have
used two events to change the voltage level on the output line:
• counter register is zero (TBCNT = 0)
• counter register is equal to period register (TBCNT = TBPRD)
Now we can use 2 or 4 more events:

F2833x - PWM and Capture Units 7 - 21


ePWM Compare Unit

ePWM Compare Event Waveforms


TBCTR . = compare events are fed to the Action Qualifier Module

.. .. ..
TBPRD
CMPA Asymmetrical
CMPB Waveform

Count Up Mode
TBCTR

TBPRD
CMPA
CMPB
.. .. .. Asymmetrical
Waveform

Count Down Mode


TBCTR

.. .. .. ..
TBPRD
CMPA Symmetrical
CMPB Waveform

Count Up and Down Mode


7 - 15

Instead of using 0 or TBPRD we now can use up to 4 more points per period to trigger an
action. What action? Well, the type of action will be defined in another module, coming
next. For now let us summarize the Compare Unit registers:

ePWM Compare Module Registers

Name Description Structure


CMPCTL Compare Control EPwmxRegs.CMPCTL.all
EPwm Regs.CMPCTL.all =
CMPA Compare A EPwmxRegs.CMPA
EPwm Regs.CMPA =
CMPB Compare B EPwmxRegs.CMPB
EPwm Regs.CMPB =

7 - 16

While CMPA and CMPB are just number registers to specify the point of action relatively to
the counter register, CMPCTL controls the operation of the shadow registers behind CMPA
and CMPB. Do you recall the purpose of “Shadow” registers? Shadows or Background

7 - 22 F2833x - PWM and Capture Units


ePWM Compare Unit

registers can be used to prepare a new value for the next coming period while the current
period is still running an may still rely on the value in the foreground.

ePWM Compare Control Register


EPwmxRegs.CMPCTL
EPwm Regs.CMPCTL

CMPA and CMPB Shadow Full Flag


(bit automatically clears on load)
0 = shadow not full
1 = shadow full

15 - 10 9 8 7
reserved SHDWBFULL SHDWAFULL reserved

6 5 4 3-2 1-0
SHDWBMODE reserved SHDWAMODE LOADBMODE LOADAMODE

CMPA and CMPB Operating Mode CMPA and CMPB Shadow Load Mode
0 = shadow mode; 00 = load on CTR = 0
double buffer w/ shadow register 01 = load on CTR = PRD
1 = immediate mode; 10 = load on CTR = 0 or PRD
shadow register not used 11 = freeze (no load possible)
7 - 17

LOADxMODE:

• define the hardware event, which will copy a value from background into
the active foreground register
SHDWxMODE:

• enable (0) or disable (1) the background update mode. If disabled, all write
instructions will immediately change the value in register CMPA or CMPB
SHDWxFULL:

• read only status field. If shadow is full (1) and the hardware copies the value
into foreground, the bit is cleared automatically
For most applications it is highly recommended to use this shadow feature, since it eases the
urgency of accesses to the CMP registers, when we change these values on a cycle-by-cycle
base, sometimes called “on the fly”.
After a hardware reset, or by default, shadow mode is enabled and LOADxMODE is set to
“load on CTR=0”; If we don’t initialize CMPCTL at all, the default mode will be active.

F2833x - PWM and Capture Units 7 - 23


ePWM Action Qualifier Unit

ePWM Action Qualifier Unit


Now let us inspect another unit, which we need to generate a series of pulses at EPWMxA
and EPWMxB - the Action Qualifier Module.

ePWM Action Qualifier Module


CMPA . 15 - 0 CMPB . 15 - 0
TBCTL . 12 - 7
Shadowed Shadowed
Clock Compare Compare
Prescaler Register Register
AQCTLA . 11 - 0
TBCTR . 15 - 0
AQCTLB . 11 - 0 DBCTL . 4 - 0
16-
16-Bit
Compare Action Dead
Time-Base
Time-
TBCLK Logic Qualifier Band
Counter

EPWMxSYNCI EPWMxSYNCO
Period
Register EPWMxA
PWM Trip
Shadowed
Chopper Zone
SYSCLKOUT TBPRD . 15 - 0 EPWMxB
PCCTL . 10 - 0
TZy
TZSEL . 15 - 0

7 - 18

We can initialize this unit by a set of two control registers, AQCTLA for output line A and
AQCTLB for line B. For each of the 6 events on a timescale (Zero-match; CMPA-up, CMPB
- up, Period, CMPA - down and CMPB - down) we can specify a certain action at the
corresponding signal line:

• set line to high (rising edge)

• clear line to low (falling edge)

• toggle the line (low to high OR high to low)

• do nothing (ignore this event)


Furthermore we can also force the corresponding line to a certain level by executing a
software instruction in one of two software force registers. In most cases, the latter option is
not used, because it cannot be synchronized with other hardware activities of the PWM unit.
Sometimes however, especially for emergency routines, it is welcome to have such a force
option.
The next slide summarizes the available options for the Action Qualifier Unit. The icons
used in this slide will also be used in the following slides to highlight some popular control
patterns for PWM systems.

7 - 24 F2833x - PWM and Capture Units


ePWM Action Qualifier Unit

ePWM Action Qualifier Actions

Time-
Time-Base Counter equals: EPWM
S/W Output
Force Actions
Zero CMPA CMPB TBPRD

SW Z CA CB P Do Nothing
X X X X X

SW Z CA CB P Clear Low
↓ ↓ ↓ ↓ ↓

SW Z CA CB P Set High
↑ ↑ ↑ ↑ ↑

SW Z CA CB P
Toggle
T T T T T
7 - 19

Independent Duty Cycle on line A and B


The first example uses the lines A and B in count-up mode. The duty cycles are
independently controlled by CMPA for line A and CMPB for line B.

Independent Modulation on EPWMA / B

TBCTR

TBPRD
. .
. .
Z P CB CA Z P CB CA Z P
↑ X X ↓ ↑ X X ↓ ↑ X

EPWMA

Z P CB CA Z P CB CA Z P
↑ X ↓ X ↑ X ↓ X ↑ X

EPWMB

7 - 20

F2833x - PWM and Capture Units 7 - 25


ePWM Action Qualifier Unit

Moving Pulse on EPWMA


This example uses EPWMB just to indicate half of the period of the PWM - frequency.
CMPA and CMPB are both used to control
(1) the position and
(2) the size of the pulse on line EPWMxA

Moving Pulse on EPWMA

TBCTR

TBPRD
. .
. .
CA CB CA CB
↑ ↓ ↑ ↓

EPWMA

Z Z Z
T T T

EPWMB

7 - 21

7 - 26 F2833x - PWM and Capture Units


ePWM Action Qualifier Unit

Independent modulation of two pulses


Here both lines EPWMA and EPWMB carry a control signal. EPWMA is solely controlled
by CMPA and is always centered on the period match event. By reducing the difference
between CMPA and TBPRD we can reduce the size of the pulse, by extending the difference
the pulse will grow towards 100%.
Register CMPB is used to control the pulse size of EPWMB independently of EPWMA. In
this example output pulse EPWMB is also center aligned on the period match event.

Independent Modulation on EPWMA / B

TBCTR

. . . . . . . .
TBPRD

CA CA CA CA
↑ ↓ ↑ ↓

EPWMA

CB CB CB CB
↑ ↓ ↑ ↓

EPWMB

7 - 22

There are many more application examples and operating modes than those, which we
discussed in the previous slides, especially when you recall typical 3-phase systems with
their well known complementary switching patterns.
Let us postpone these industrial applications for now and focus on what we have learned so
far. To perform an exercise with the basic pulse sequences shown above, we will have to
include the Action Qualifier Unit (AQU) into our exercises.
We have not discussed the layout of the control registers for the AQU. The group of registers
is shown on the next slide.

F2833x - PWM and Capture Units 7 - 27


ePWM Action Qualifier Unit

Action Qualifier Registers

ePWM Action Qualifier Module Registers

Name Description Structure


AQCTLA AQ Control Output A EPwmxRegs.AQCTLA.all
EPwm Regs.AQCTLA.all =
AQCTLB AQ Control Output B EPwmxRegs.AQCTLB.all
EPwm Regs.AQCTLB.all =
AQSFRC AQ S/W Force EPwmxRegs.AQSFRC.all
EPwm Regs.AQSFRC.all =
AQCSFRC AQ Cont. S/W Force EPwmxRegs.AQCSFRC.all
EPwm Regs.AQCSFRC.all =

7 - 23

Action Control Register A and B


Action Qualifier Control Register
EPwmxRegs.AQCTL
EPwm Regs.AQCTLy (y = A or B)

Action when Action when


CTR = CMPB CTR = CMPA Action when
on UP Count on UP Count CTR = 0

15 - 12 11 - 10 9-8 7-6 5-4 3-2 1-0


reserved CBD CBU CAD CAU PRD ZRO

Action when Action when Action when


CTR = CMPB CTR = CMPA CTR = PRD
on DOWN Count on DOWN Count

00 = do nothing (action disabled)


01 = clear (low)
10 = set (high)
11 = toggle (low → high; high → low)
7 - 24

7 - 28 F2833x - PWM and Capture Units


ePWM Action Qualifier Unit

Software Forcing Registers


This register allows forcing an output line into a defined state. “One-Time” stands for the
duration of the current period of the PWM - frequency.

Action Qualifier SW Force Register


EPwmxRegs.AQSFRC
EPwm Regs.AQSFRC

One-
One-Time S/W Force on Output B / A
0 = no action
1 = single s/w force event

15 - 8 7-6 5 4-3 2 1-0


reserved RLDCSF OTSFB ACTSFB OTSFA ACTSFA

AQSFRC Shadow Reload Options Action on One-


One-Time S/W Force B / A
00 = load on event CTR = 0 00 = do nothing (action disabled)
01 = load on event CTR = PRD 01 = clear (low)
10 = load on event CTR = 0 or CTR = PRD 10 = set (high)
11 = load immediately (from active reg.) 11 = toggle (low → high; high → low)

7 - 25

“Continuous Force” will hold the line permanently in the selected state.

Continuous SW Force Register


EPwmxRegs.AQCSFRC

15 - 4 3-2 1-0
reserved CSFB CSFA

Continuous S/W Force on Output B / A


00 = forcing disabled
01 = force continuous low on output
10 = force continuous high on output
11 = forcing disabled

7 - 26

F2833x - PWM and Capture Units 7 - 29


Lab 7_3: A 1 kHz with variable pulse width

Lab 7_3: A 1 kHz with variable pulse width


Now let us experiment with a variable pulse width signal. The starting point is again Lab7_1.
We will now use CpuTimer0 as a time-base to change the pulse width of the 1 kHz signal
once every 100 milliseconds between 0 and 100 %.

Lab 7_3: 1 KHz Signal with variable pulse


width at ePWM1A
Objective:
• Generate a 1 KHz square wave signal at ePWM1A with a
variable duty cycle between 0 and 100%
• Measure the pulse with an oscilloscope

• Registers involved:
• TBPRD: define signal frequency
• TBCTL: setup operating mode and time prescale
• CMPA: setup the pulse width for ePWM1A
• AQCTLA: define signal shape for ePWM1A
1 TPWM
TBPRD = ∗
2 TSYSCLKOUT ∗ CLKDIV ∗ HSPCLKDIV

7 - 27

Objective
The objective of this lab is to generate a square wave signal of 1 kHz at line ePWM1A. With
the help of an oscilloscope connected to header J6-1 of the Peripheral Explorer Board, we
can monitor the signal. Using CPU - Timer 0, we will change CMPA between 0 and TBPRD
to generate a pulse width between 100 and 0%.

Procedure

Open Project File


1. In the “C/C++” perspective of CCS open or re-open project Lab7.pjt.
2. Open file “Lab7_1.c” and save it as “Lab7_3.c”
3. Exclude file “Lab7_2.c” from build. Use a right mouse click at file “Lab7_2.c”, and
enable “Exclude File(s) from Build”.

7 - 30 F2833x - PWM and Capture Units


Lab 7_3: A 1 kHz with variable pulse width

4. In file “Lab7_3.c”, edit the function “Setup_ePWM1A()”. We will again use count
up/down mode, so we can keep the existing setup for bit field TBCTL.CTRMODE.
However, now we would like to set ePWM1A to 1 on “CMPA - up match” and to
clear ePWM1A on event “CMPA - down match”. Change the setup for register
AQCTLA accordingly!
5. In the function “Setup_ePWM1A()” add a line to initialize CMPA to 0, which will
define a pulse width of 100%:
EPwm1Regs.CMPA.half.CMPA = 0;
6. In “main()”, change the function call “ConfigCpuTimer()” to define a period of 100
microseconds for timer 0:
ConfigCpuTimer(&CpuTimer0, 150, 100);
7. CpuTimer0 is still active from Lab exercise Lab6. It has been initialized to request
an interrupt service once every 100 microseconds. Now we can use its interrupt
service routine “cpu_timer0_isr()” to increment the value in register CMPA until it
reaches the value in TBPRD - thus we will change the pulse width gradually from
100% to 0%. If you like, you can add a second sequence to increase the pulse width
of ePWM1A again back to 100%.
Note: All registers of ePWM1 are read- and writable. To compare the current value
of CMPA against TBPRD you can use:
if (EPwm1Regs.CMPA.half.CMPA < EPwm1Regs.TBPRD) …

Build, Load and Test


8. Now build, load and test the modified project. A screenshot of signal ePWM1A
could look like this:

Result: The pulse width of your signal should change gradually between 100% and 0 %.
END of LAB 7_3

F2833x - PWM and Capture Units 7 - 31


Lab 7_4: a pair of complementary 1 kHz-Signals

Lab 7_4: a pair of complementary 1 kHz-Signals


Most power electronic systems require pairs of PWM pulse series to control two power
switches in such a way, that if one switch is on (conducting), the other switch is off (open-
circuit). In the following exercise you will modify Lab7_3 to generate such a pair of output
pulses at ePWM1A and ePWM1B. Again we will use CpuTimer0 as a time-base to change
the pulse width of the 1 kHz signal every 100 milliseconds between 0 and 100 %.

Lab 7_4: a pair of complementary 1 KHz


signals at ePWM1A and ePWM1B
Objective:
• Generate a 1 KHz square wave signal at ePWM1A with a
variable duty cycle between 0 and 100%
• Generate a complementary signal at ePWM1B
• Measure the pulses with an oscilloscope

• Registers involved:

• TBPRD: define signal frequency


• TBCTL: setup operating mode and time prescale
• CMPA: setup the pulse width for ePWM1A / 1B
• AQCTLB: define signal shape for ePWM1B
• AQCTLA: define signal shape for ePWM1A

7 - 28

Objective
The objective of this lab is to generate a square wave signal of 1 kHz at line ePWM1A and a
second signal at ePWM1B with opposite voltage levels. With the help of an oscilloscope
connected to header J6-1 of the Peripheral Explorer Board, we can monitor the signal. Based
on CPU - Timer 0, we will change CMPA between 0 and TBPRD to generate a pulse width
between 100 and 0%.

Procedure

Open Project File


1. If not still open from Lab7_3, re-open project Lab7.pjt in the “C/C++” perspective
of Code Composer Studio.
2. Open file “Lab7_3.c” and save it as “Lab7_4.c”
3. Exclude file “Lab7_3.c” from build. Use a right mouse click at file “Lab7_3.c”, and
enable “Exclude File(s) from Build”.

7 - 32 F2833x - PWM and Capture Units


Lab 7_4: a pair of complementary 1 kHz-Signals

4. In file “Lab7_4.c” edit function “Gpio_select()”. In the multiplex block enable line
GPIO1 to drive ePWM1B.
5. Rename function “Setup_ePWM1A()” to “Setup_ePWM1()”, because we will now
initialize both line A and B with this function. Also, rename the function prototype at
the beginning of “Lab7_4.c” and the function call in “main()”.
6. In “Setup_ePWM1()”, add a line to initialize register EPwm1Regs.AQCTLB. Recall
that we initialized EPwm1Regs.AQCTLA to set ePWM1A on CMPA - up and to
clear ePWM1A on CMPA - down match. For register EPwm1Regs.AQCTLB we
will have to modify that setup to generate a complementary signal at ePWM1B.

Build, Load and Test


7. Now build, load and test the modified project. A oscilloscope screenshot of signal
ePWM1A and ePWM1B should look like the following graph:

Result: The pulse width of your pair of signals should change gradually between 100%
and 0 %.

END of LAB 7_4

F2833x - PWM and Capture Units 7 - 33


Lab 7_5: Independent Modulation on ePWM1A / 1B

Lab 7_5: Independent Modulation on ePWM1A / 1B


Before we continue to discuss other modules of the ePWM - units we will perform an
exercise to produce the exact pulse pattern, as shown in Slide 7-29:

Lab 7_5: Independent Modulation of


ePWM1A and ePWM1B
TBCTR

TBPRD

. . . . . . . .
CA CA CA CA
↑ ↓ ↑ ↓

EPWMA

CB CB CB CB
↑ ↓ ↑ ↓

EPWMB

7 - 29

Objective
The objective of this lab is to generate a square wave signal of 1 kHz at line ePWM1A and a
second signal at ePWM1B with independent modulation of the pulse widths. Signal
ePWM1A will be controlled by register CMPA and ePWM1B by register CMPB. This time
we will also use a real-time operating mode to change the values of CMPA and CMPB in a
variable watch window while the program is running.

Procedure

Open Project File


1. If not still open from Lab7_3, re-open project Lab7.pjt in the “C/C++” perspective
of Code Composer Studio.
2. Open file “Lab7_4.c” and save it as “Lab7_5.c”
3. Exclude file “Lab7_4.c” from build. Use a right mouse click at file “Lab7_4.c”, and
enable “Exclude File(s) from Build”.
4. In the function “Setup_ePWM1()”, change the line to initialize register
EPwm1Regs.AQCTLB. The new setup for AQCTLB should be to set ePWM1B on
CMPB - up and to clear ePWM1B on CMPB - down match.

7 - 34 F2833x - PWM and Capture Units


Lab 7_5: Independent Modulation on ePWM1A / 1B

5. After the line to initialize register TBPRD, add two lines to set register CMPA and
CMPB to initially generate a pulse width of 50%.
EPwm1Regs.CMPA.half.CMPA = EPwm1Regs.TBPRD / 2;
EPwm1Regs.CMPB = EPwm1Regs.TBPRD / 2;
Note the difference between the structure data types of the two registers. This
difference is caused by a second operating mode, called “High Resolution PWM”
(HRPWM), which is available only for the signal line(s) ePWMxA. To support this
mode, TI has enhanced the structure type for register CMPA.
6. In the function “cpu_timer0_isr()”, remove all instructions to change the pulse width
by register CMPA. We will use a fixed pulse width for this exercise, initially 50%
for both ePWM1A and ePWM1B.

Build, Load and Test


7. Now build, load and test the modified project. A oscilloscope screenshot of signal
ePWM1A and ePWM1B should look like the following graph:

8. Stop the code execution:


Target  Halt, followed by
Target  Reset  Reset CPU
9. Now open a Watch Window:
View  Watch
In window “Watch 1” add the two variables:
EPwm1Regs.CMPA.half.CMPA and
EPwm1Regs.CMPB

F2833x - PWM and Capture Units 7 - 35


Lab 7_5: Independent Modulation on ePWM1A / 1B

10. Enable Real Time Debug Mode:


Target  Advanced  Enable Silicon Realtime Mode
A warning might pop up on your screen to inform you, that you will enter a real time
data exchange debug mode now. Answer this window with “Yes”:

In the Watch window, enable the icon “Continuous Refresh”:

11. Restart your Test, this time with a new sequence:


Scripts  Realtime Emulation Control  Run_Realtime_with_Restart
Your Watch window should display the current values for CMPA and CMPB:

7 - 36 F2833x - PWM and Capture Units


Lab 7_5: Independent Modulation on ePWM1A / 1B

Now, while the code is still running, change the values in CMPA and CMPB to 9375
and 28125 respectively.
The result should look like this:

Try other combinations of CMPA and CMPB and verify the changes with your
scope!
12. If you are done with this exercise, it is important to fully halt the DSC. Since we are
currently running in real time mode, we have to apply a different command
sequence:
Scripts  Realtime Emulation Control  Full_Halt_with_Reset

END of LAB 7_5

F2833x - PWM and Capture Units 7 - 37


ePWM Dead Band Module

ePWM Dead Band Module


Motivation for Dead - Band
In switched mode power electronics, a typical configuration to drive a 3-phase system is
shown in the next slide (Slide 7-30). A typical system consists of a 3-phase current or
voltage injection circuit, in which a pair of power switches per phase is controlled by a
sequence of PWM - pulses. A phase current flows either from a DC bus voltage through a
top switch into the winding of a motor or via a bottom switch from the motor winding back
to ground. Of course, we have to prevent both switches from conducting at the same time.

Voltage source inverter components


Upper & lower
devices can not
be turned on
simultaneously
(dead band)
PWM signal is
applied between
gate and source + + +

DC bus
Three phase
capacitor − − −
outputs to drive
the motor
terminals

Power
Switching
Devices

7 - 30

A minor problem arises from the fact that power switches usually turn on faster than they
turn off. If we would apply an identical but complementary pulse pattern to the top and
bottom switch of a phase, we would end up in a short period in time with a shoot-through
situation.
Dead-band control provides a convenient means of combating current “shoot-through”
problems in a power converter. “Shoot-through” occurs when both the upper and lower
transistors in the same phase of a power converter are on simultaneously. This condition
shorts the power supply and results in a large current draw. Shoot-through problems occur
because transistors (especially FET’s) turn on faster than they turn off and also because high-
side and low-side power converter transistors are typically switched in a complimentary
fashion. Although the duration of the shoot-through current path is finite during PWM
cycling, (i.e. the transistor will eventually turn off), even brief periods of a short circuit
condition can produce excessive heating and stress the power converter and power supply.

7 - 38 F2833x - PWM and Capture Units


ePWM Dead Band Module

Two basic approaches exist for controlling shoot-through: modify the transistors, or modify
the PWM gate signals controlling the transistors. In the first case, the switch-on time of the
transistor gate must be increased so that it (slightly) exceeds the switch-off time.
The hard way to accomplish this is by adding a cluster of passive components such as
resistors and diodes in series with the transistor gate to act as low-pass filter to implement the
delay.
The second approach to shoot-through control separates transitions on complimentary PWM
signals with a fixed period of time. This is called dead-band. While it is possible to perform
software implementation of dead-band, the F2833x offers on-chip hardware for this purpose
that requires no additional CPU overhead. Compared to the passive approach, dead-band
offers more precise control of gate timing requirements.

Motivation for Dead-Band

supply rail

gate signals are to power


complementary PWM switching
device

♦ Transistor gates turn on faster than they shut off


♦ Short circuit if both gates are on at same time!

7 - 31

F2833x - PWM and Capture Units 7 - 39


ePWM Dead Band Module

Hardware Dead Band Unit


All ePWM modules of the F2833x feature a hardware dead band unit.

ePWM Dead-Band Module


CMPA . 15 - 0 CMPB . 15 - 0
TBCTL . 12 - 7
Shadowed Shadowed
Clock Compare Compare
Prescaler Register Register
AQCTLA . 11 - 0
TBCTR . 15 - 0
AQCTLB . 11 - 0 DBCTL . 4 - 0
16-
16-Bit
Compare Action Dead
Time-
Time-Base
TBCLK Logic Qualifier Band
Counter

EPWMxSYNCI EPWMxSYNCO
Period
Register EPWMxA
PWM Trip
Shadowed
Chopper Zone
SYSCLKOUT TBPRD . 15 - 0 EPWMxB
PCCTL . 10 - 0
TZy
TZSEL . 15 - 0

7 - 32

The block diagram shows the different options available for this module:

ePWM Dead-Band Module Block Diagram

PWMxA - IN

Rising

.
0

.
Edge 0
° S1° PWMxA
0 Delay ° ° S2 RED
°1
° °
S4

°1
In
(10-
(10-bit
Out
° °1
counter)

Falling

.
Edge 0

. ° S3°
0 Delay FED 1
° ° S5
° S0° PWMxB

°1
In
(10-
(10-bit
Out
° °1 °0
counter)
IN-
IN-MODE POLSEL OUT-
OUT-MODE

PWMxB - IN

7 - 33

7 - 40 F2833x - PWM and Capture Units


ePWM Dead Band Module

The setup of the dead-band unit is based on six switches, S0 to S5.


Although all combinations are supported, not all modes would be used in practice. The more
classical modes assume that S4=0 and S5=0 [IN_MODE] is configured such that
“EPWMxA-IN” is the source for both the falling-edge and rising-edge delay. Enhanced or
non-traditional modes can be achieved by changing the input signal source.

The corresponding pulse sequences are:

Operating mode “Active High Complementary” (AHC) is the desired one for a pair of power
switches in one phase of a 3-phase motor control system.

F2833x - PWM and Capture Units 7 - 41


ePWM Dead Band Module

Dead Band Unit Registers

ePWM Dead-Band Module Registers

Name Description Structure


DBCTL Dead-
Dead-Band Control EPwmxRegs.DBCTL.all
EPwm Regs.DBCTL.all =
DBRED 10-
10-bit Rising Edge Delay EPwmxRegs.DBRED
EPwm Regs.DBRED =
DBFED 10-
10-bit Falling Edge Delay EPwmxRegs.DBFED
EPwm Regs.DBFED =

Rising Edge Delay = TTBCLK x DBRED


Falling Edge Delay = TTBCLK x DBFED

7 - 34

The Dead Band Control Register combines the bit fields for switches S0 to S5:

ePWM Dead Band Control Register

Polarity Select
00 = active high
01 = active low complementary (RED)
10 = active high complementary (FED)
11 = active low

15 - 6 5-4 3-2 1-0


reserved IN_MODE POLSEL OUT_MODE

In-
In-Mode Control Out-
Out-Mode Control
00 = PWMxA is source for RED and FED 00 = disabled (DBM bypass)
01 = PWMxA is source for FED 01 = PWMxA = no delay
PWMxB is source for RED PWMxB = FED
10 = PWMxA is source for RED 10 = PWMxA = RED
PWMxB is source for FED PWMxB = no delay
11 = PWMxB is source for RED and FED 11 = RED & FED (DBM fully enabled)

7 - 35

7 - 42 F2833x - PWM and Capture Units


Lab 7_6: Dead Band Unit on ePWM1A / 1B

Lab 7_6: Dead Band Unit on ePWM1A / 1B


Objective
The objective of this lab is to introduce a delay time for rising edges in a pair of
complementary PWM signals at ePWM1A and ePWM1B. The desired operating mode is
“Active High Complementary” (AHC) and the two output signals are generated from input
signal ePWM1A - in from the action qualifier unit.

Lab 7_6: Dead Band Unit for


ePWM1A and ePWM1B
Objective:
• Add a delay time for rising edges on a pair of
complementary signals ePWM1A and ePWM1B
• Active High Complementary (AHC) Mode
• Input signal to Dead-Band Unit is ePWM1A
• Dead Band Unit will generate ePWM1A and ePWM1B
• Use Lab7_4 as starting point

• New Registers involved:

• DBRED: Dead Band Unit Rising Edge Delay


• DBFED: Dead Band Unit Falling Edge Delay
• DBCTL: Dead Band Unit Control Register

7 - 36

Procedure

Open Project File


1. If not still open from Lab7_5, re-open project Lab7.pjt in the “C/C++” perspective
of Code Composer Studio.
2. Open file “Lab7_4.c” and save it as “Lab7_6.c”
3. Exclude file “Lab7_5.c” from build. Use a right mouse click at file “Lab7_5.c”, and
enable “Exclude File(s) from Build”.
4. In file “Lab7_6.c” edit the function “cpu_timer0_isr()”. Remove all instructions to
change the pulse width by register CMPA. We will use a fixed pulse width of 50% for
this exercise, both for ePWM1A and ePWM1B.
5. In the function “Setup_ePWM1()”, initialize the pulse width to 50% of TBPRD:

F2833x - PWM and Capture Units 7 - 43


Lab 7_6: Dead Band Unit on ePWM1A / 1B

EPwm1Regs.CMPA.half.CMPA = EPwm1Regs.TBPRD / 2;
6. Next, in the function “Setup_ePWM1()”, remove the instruction to initialize register
AQCTLB. When using the dead band unit, both output pulse sequences ePWM1A and
ePWM1B are normally derived from a single input signal, usually from internal signal
ePWM1A of the action qualifier module.
7. In the function “Setup_ePWM1()”, add lines to initialize the dead band unit. Delay
times are calculated in multiples of TBCLK, which we calculated at the beginning of
Lab7_1 directly from SYSCLKOUT with CLKDIV set to 1 and HSPCLKDIV set to
2. In case of the F28335ControlCard running at 150MHz, TBCLK equals to 13.33334
ns. In our example we will setup a delay time of 10 microseconds, just as an example.
EPwm1Regs.DBRED = 750;
EPwm1Regs.DBFED = 750;
To initialize register DBCTL, we have to take into account switches S0 to S5 in Slide 7-
33:

• Set S4 and S5 to 0: this way we will solely use input signal ePWM1A from
unit AQCTL to generate the two output signals ePWM1A and ePWM1B.

• Set S2 = 0 and S3=1 to invert the polarity of signal ePWM1B against input
ePWM1A.

• Set S0 = 1 and S1 = 1 to include a time delay for both switching points.

Build, Load and Test


8. Now build, load and test the modified project. A oscilloscope screenshot of signal
ePWM1A and ePWM1B should look like this, when you trigger at the rising edge of
channel 1 (ePWM1A):

If you trigger at the falling edge of channel 1 (ePWM1A, yellow), again you should
see a delayed rising edge, now at signal ePWM1B (blue):

7 - 44 F2833x - PWM and Capture Units


Lab 7_6: Dead Band Unit on ePWM1A / 1B

END of LAB 7_6

F2833x - PWM and Capture Units 7 - 45


ePWM Chopper Module

ePWM Chopper Module


The PWM-chopper sub module allows a high-frequency carrier signal to modulate the PWM
waveform generated by the action-qualifier and dead-band sub modules. This capability is
important if you need pulse transformer-based gate drivers to control the power switching
elements.

ePWM Chopper Module


CMPA . 15 - 0 CMPB . 15 - 0
TBCTL . 12 - 7
Shadowed Shadowed
Clock Compare Compare
Prescaler Register Register
AQCTLA . 11 - 0
TBCTR . 15 - 0
AQCTLB . 11 - 0 DBCTL . 4 - 0
16-
16-Bit
Compare Action Dead
Time-
Time-Base
TBCLK Logic Qualifier Band
Counter

EPWMxSYNCI EPWMxSYNCO
Period
Register EPWMxA
PWM Trip
Shadowed
Chopper Zone
SYSCLKOUT TBPRD . 15 - 0 EPWMxB
PCCTL . 10 - 0
TZy
TZSEL . 15 - 0

7 - 37

The key functions of the PWM-chopper sub module are:


• Programmable chopping (carrier) frequency
• Programmable pulse width of first pulse
• Programmable duty cycle of second and subsequent pulses
• Can be fully bypassed if not required

7 - 46 F2833x - PWM and Capture Units


ePWM Chopper Module

Purpose of Chopping

Purpose of the PWM Chopper Module

 Allows a high frequency carrier


signal to modulate the PWM
waveform generated by the Action
Qualifier and Dead-Band modules
 Used with pulse transformer-based
gate drivers to control power
switching elements

7 - 38

The carrier clock of the ePWM Chopper Module is derived from SYSCLKOUT. The
frequency and duty cycle of the chopper unit are controlled via the CHPFREQ and
CHPDUTY bits in the PCCTL register.
The one-shot block is a feature that provides a high-energy first pulse to ensure hard and fast
power switch turn on, while the subsequent pulses sustain pulses, ensuring the power switch
remains on. The one-shot width is programmed via the OSHTWTH bits.
The PWM-chopper sub module can be fully disabled (bypassed) via the CHPEN bit.

F2833x - PWM and Capture Units 7 - 47


ePWM Chopper Module

Waveform Diagram of Chopped Signals


The top half of the following slide (Slide 7-39) shows the simplified waveforms of the
chopping module action.
The bottom part of this slide shows a diagram of the special "one shot" mode, in which the
duration of the first pulse can be programmed independently of all sustaining pulses of the
chopper sequence.
Note: The duty-cycle control mode of the chopper module is not shown in the slide. This
additional mode allows the setup of a different pulse width other than 50%.

ePWM Chopper Waveform


EPWMxA

EPWMxB

CHPFREQ

EPWMxA

EPWMxB

Programmable
Pulse Width
OSHT (OSHTWTH)

Sustaining
EPWMxA Pulses

With One-Shot Pulse on EPWMxA and/or EPWMxB 7 - 39

The width of the first pulse can be programmed to any of 16 possible pulse width values. The
width or period of the first pulse is given by:

T1stPULSE = TSYSCLKOUT ∗ 8 ∗ OSHTWTH

Where TSYSCLKOUT is the period of the system clock (SYSCLKOUT) and OSHTWTH is set
by four control bits to a value between 1 and 16.

7 - 48 F2833x - PWM and Capture Units


ePWM Chopper Module

Chopper Mode Control Registers

ePWM Chopper Module Registers

Name Description Structure


PCCTL PWM-
PWM-Chopper Control EPwmxRegs.PCCTL.all
EPwm Regs.PCCTL.all =

7 - 40

ePWM Chopper Control Register


EPwmxRegs.PCCTL
EPwm Regs.PCCTL

Chopper Clk Duty Cycle Chopper Clk Freq.


000 = 1/8 (12.5%) 000 = SYSCLKOUT/8 ÷ 1
001 = 2/8 (25.0%) 001 = SYSCLKOUT/8 ÷ 2
010 = 3/8 (37.5%) 010 = SYSCLKOUT/8 ÷ 3
011 = 4/8 (50.0%) 011 = SYSCLKOUT/8 ÷ 4
100 = 5/8 (62.5%) 100 = SYSCLKOUT/8 ÷ 5 Chopper Enable
101 = 6/8 (75.0%) 101 = SYSCLKOUT/8 ÷ 6 0 = disable (bypass)
110 = 7/8 (87.5%) 110 = SYSCLKOUT/8 ÷ 7 1 = enable
111 = reserved 111 = SYSCLKOUT/8 ÷ 8

15 - 11 10 - 8 7-5 4-1 0
reserved CHPDUTY CHPFREQ OSHTWTH CHPEN

One-
One-Shot Pulse Width
0000 = 8 / SYSCLKOUT 1000 = 72 / SYSCLKOUT
0001 = 16 / SYSCLKOUT 1001 = 80 / SYSCLKOUT
0010 = 24 / SYSCLKOUT 1010 = 88 / SYSCLKOUT
0011 = 32 / SYSCLKOUT 1011 = 96 / SYSCLKOUT
0100 = 40 / SYSCLKOUT 1100 = 104 / SYSCLKOUT
0101 = 48 / SYSCLKOUT 1101 = 112 / SYSCLKOUT
0110 = 56 / SYSCLKOUT 1110 = 120 / SYSCLKOUT
0111 = 64 / SYSCLKOUT 1111 = 128 / SYSCLKOUT 7 - 41

F2833x - PWM and Capture Units 7 - 49


Lab 7_7: Chopped Signals at ePWM1A / 1B

Lab 7_7: Chopped Signals at ePWM1A / 1B


Objective
We will add a chopper frequency modulation to the software developed in Chapter 7. In
Lab7_5 we controlled the pulse width of ePWM1A by register CMPA independently of
ePWM1B, which was controlled by CMPB. The objective now is to chop the active phase of
the pulses at ePWM1A and ePWM1B with a higher frequency.

Lab 7_7: Chopper Mode Signals


add ePWM1A and ePWM1B
Objective:
• The pair of complementary signals ePWM1A and ePWM1B
will be modulated by a chopper frequency of 2.344 MHz
• Chopper Mode Duty Cycle = 50%
• One shot pulse width = 800 ns
• Use Lab7_5 as starting point

7 - 42

Procedure

Open Project File


1. In project "Lab7" open file “Lab7_5.c” and save it as “Lab7_7.c”
2. Exclude “Lab7_6.c” from build.
3. In the function “Setup_ePWM1()”, initialize the chopper module. Remember that
SYSCLKOUT has been set to 150 MHz (assuming an external clock of 30 MHz at the
F28335ControlCard). In register "EPwm1Regs.PCCTL":
• Set chopper frequency to 2.34375 MHz (SYSCLKOUT / 64).
• Set chopper duty cycle to 50%
• Set one shot pulse to 800 ns
• Enable the chopper unit.

7 - 50 F2833x - PWM and Capture Units


Lab 7_7: Chopped Signals at ePWM1A / 1B

Build, Load and Test

4. Build, load and test the modified project. A oscilloscope screenshot of signal
ePWM1A and ePWM1B should look like the following graph, when you trigger at the
rising edge of channel 1 (ePWM1A):

F2833x - PWM and Capture Units 7 - 51


ePWM Over Current Protection

ePWM Over Current Protection


Each ePWM module is connected to six Trip - Zone signals (TZ1 to TZ6) that are sourced
from the GPIO MUX. These signals indicate external fault or trip conditions, and the ePWM
outputs can be programmed to respond accordingly when faults occur.

ePWM Trip-Zone Module


CMPA . 15 - 0 CMPB . 15 - 0
TBCTL . 12 - 7
Shadowed Shadowed
Clock Compare Compare
Prescaler Register Register
AQCTLA . 11 - 0
TBCTR . 15 - 0
AQCTLB . 11 - 0 DBCTL . 4 - 0
16-
16-Bit
Compare Action Dead
Time-
Time-Base
TBCLK Logic Qualifier Band
Counter

EPWMxSYNCI EPWMxSYNCO
Period
Register EPWMxA
PWM Trip
Shadowed
Chopper Zone
SYSCLKOUT TBPRD . 15 - 0 EPWMxB
PCCTL . 10 - 0
TZy
TZSEL . 15 - 0

7 - 43

Purpose of the Trip-Zone Submodule


Trip Zone signals are usually generated by over-current sensors, which set a signal if a
threshold is passed. The key functions of the Trip-Zone sub module are:
• Trip inputs TZ1 to TZ6 can be flexibly mapped to any ePWM module.
• Upon a fault condition, outputs EPWMxA and EPWMxB can be forced to one
of the following:
 High
 Low
 High-impedance
 No action taken
• One-shot trip (OSHT) mode to support major short circuits or over-current
conditions.
• Support for cycle-by-cycle tripping (CBC) for current limiting operation.
• Each trip-zone input pin can be allocated to either one-shot or cycle-by-cycle
operation.
• Interrupt generation is possible on any trip-zone pin.
• Software-forced tripping is also supported.

7 - 52 F2833x - PWM and Capture Units


ePWM Over Current Protection

• The trip-zone sub module can be fully bypassed if it is not required.

Trip-Zone Module Features


♦ Trip-
Trip-Zone has a fast, clock independent logic path to high-
high-impedance
the EPWMxA/B
EPWMxA/B output pins
♦ Interrupt latency may not protect hardware when responding to over
over
current conditions or short-
short-circuits through ISR software
♦ Supports: #1) one-
one-shot trip for major short circuits or over
current conditions
#2) cycle-
cycle-by-
by-cycle trip for current limiting operation
EPWM1A
Over
Current DSP EPWM1B
EPWM2A
P
Sensors core W
EPWM2B M
EPWM3A
TZ1 EPWMxTZINT EPWM3B O
TZ2 Cycle-by-Cycle U
EPWM4A
TZ3 Mode EPWM4B T
P
TZ4 EPWM5A U
TZ5 One-Shot EPWM5B T
TZ6 Mode EPWM6A S
EPWM6B
7 - 44

ePWM Trip - Zone Registers

ePWM Trip-Zone Module Registers

Name Description Structure


TZCTL Trip-
Trip-Zone Control EPwmxRegs.TZCTL.all
EPwm Regs.TZCTL.all =
TZSEL Trip-
Trip-Zone Select EPwmxRegs.TZSEL.all
EPwm Regs.TZSEL.all =
TZEINT Enable Interrupt EPwmxRegs.TZEINT.all
EPwm Regs.TZEINT.all =
TZFLG Trip-
Trip-Zone Flag EPwmxRegs.TZFLG.all
EPwm Regs.TZFLG.all =
TZCLR Trip-
Trip-Zone Clear EPwmxRegs.TZCLR.all
EPwm Regs.TZCLR.all =
TZFRC Trip-
Trip-Zone Force EPwmxRegs.TZFRC.all
EPwm Regs.TZFRC.all =

7 - 45

F2833x - PWM and Capture Units 7 - 53


ePWM Over Current Protection

Note: Trip Zone Registers are protected! When you initialize these registers, you must
EALLOW the access, before you can change the values. After you are done, close the
protection again with an EDIS instruction!

ePWM Trip-Zone Control Register


EPwmxRegs.TZCTL
EPwm Regs.TZCTL

15 - 4 3-2 1-0
reserved TZB TZA

TZ1 to TZ6 Action on EPWMxB / EPWMxA


00 = high impedance
01 = force high
10 = force low
11 = do nothing (disable)

7 - 46

Register TZCTL is used to define the state of line ePWMxA and ePWMxB in case of an
over current signal.

ePWM Trip-Zone Select Register


EPwmxRegs.TZSEL
EPwm Regs.TZSEL

One-
One-Shot Trip Zone
(event only cleared under S/W
control; remains latched)
0 = disable as trip source
1 = enable as trip source

15 - 14 13 12 11 10 9 8
reserved OSHT6 OSHT5 OSHT4 OSHT3 OSHT2 OSHT1

7-6 5 4 3 2 1 0
reserved CBC6 CBC5 CBC4 CBC3 CBC2 CBC1

Cycle-
Cycle-by-
by-Cycle Trip Zone
(event cleared when CTR = 0;
i.e. cleared every PWM cycle)
0 = disable as trip source
1 = enable as trip source
7 - 47

7 - 54 F2833x - PWM and Capture Units


ePWM Over Current Protection

With register TZSEL, we can specify which input signal TZx should be used as a cycle-by-
cycle or as a permanent (one shot) switch off signal.

ePWM Trip-Zone Enable Interrupt Register


EPwmxRegs.TZEINT
EPwm Regs.TZEINT

15 - 3 2 1 0
reserved OST CBC reserved

One-
One-Shot Cycle-
Cycle-by-
by-Cycle
Interrupt Enable Interrupt Enable
0 = disable 0 = disable
1 = enable 1 = enable

7 - 48

Register TZEINT can be used to request an interrupt service request in case of an over
current situation in a closed loop control system. We can use either a cycle - by-cycle or a
one-shot over current interrupt request, depending on the selection in register TZSEL.
What should be done in such an interrupt event? Well, this depends on the application and on
the seriousness of the fault.

F2833x - PWM and Capture Units 7 - 55


Lab 7_8: Trip Zone protection with TZ6

Lab 7_8: Trip Zone protection with TZ6


Objective
Again we will start with file "lab7_5.c". Trip Zone signal “/TZ6” is multiplexed with input
signal GPIO17, which on the Peripheral Explorer Board is connected to push button PB1. So
a very simple setup is to use this button to "simulate" an over current signal. When we push
this button, we can produce an active signal TZ6. The objective is to force both ePWM1A
and ePWM1B permanently to low in case of this button is pushed.

Lab 7_8: Over Current Protection


with Trip Zone Signals TZx
Objective:
• Trip Zone Signal TZ6 is connected to GPIO17, push –
button PB1at Peripheral Explorer Board
• Active Signal PB1 will force ePWM1A and ePWM1B to low
• Use Lab7_5 as starting point

• New registers in this lab:


• TZCTL: Trip Zone Control
• TZSEL: Trip Zone Select
• TZEINT: Trip Zone Enable Interrupt
• TZCLR: Trip Zone Clear Interrupt Flags

7 - 49

Procedure

Open Project File


1. In project "Lab7", open file “Lab7_5.c” and save it as “Lab7_8.c”
2. Exclude the file “Lab7_7.c” from build.
3. In the function "Gpio_select()", set multiplex register GPAMUX2 to use /TZ6 for
GPIO17.
4. The in the function “Setup_ePWM1()”, initialize the trip zone registers.

7 - 56 F2833x - PWM and Capture Units


Lab 7_8: Trip Zone protection with TZ6

• In the register "EPwm1Regs.TZCTL", set TZA and TZB to force ePWM1A and
ePWM1B to zero in case of an active TZ6.
• In the register "EPwm1Regs.TZSEL", select TZ6 as source for a one shot over
current signal. In the event of an active TZ6 (when we push button PB1), both lines
ePWM1A and ePWM1B will be switched off permanently.
• Remember that both registers are EALLOW - protected, so please do not forget to
open / close the access to these registers.

Build, Load and Test


5. Build, load and test the modified project. A oscilloscope screenshot of signal
ePWM1A and ePWM1B should show the desired pattern at ePWM1A an ePWM1B:

6. Now push button PB1. Both ePWM1A and ePWM1B should be switched off (0V)
permanently.

One Shot Mode


7. Now let us modify the code in such a way, that an active button PB1 (our trip zone
TZ6) will request a cycle-by-cycle switch off of the two signals ePWM1A and
ePWM1B.
• In the function "Setup_ePWM1()", change register "EPwm1Regs.TZSEL" so that
TZ6 will now be the source for a cycle-by-cycle over current signal, and no longer
for a one-shot procedure.

Re-Build, Load and Test


8. Build, load and test the modified project. Please do not forget to reset the DSC before
you perform a new test. This is always a good practice, since the chip will always start
from a known state! Here once more is the required sequence:
• Debug  Reset CPU
• Debug  Restart
• Debug  Go Main

F2833x - PWM and Capture Units 7 - 57


Lab 7_8: Trip Zone protection with TZ6

• Debug  Run
The scope should again show the pulse sequences at ePWM1A and ePWM1B.
When you push PB1, the signals should fade out to ground and keep this ground
voltage, as long as you keep your finger on PB1 to hold it down. But, when you
release PB1, the pulse pattern at ePWM1A and ePWM1B should reappear again.
That's why we this time initialized the F2833x to resume the PWM operation on a
cycle-by-cycle basis!

Add an Interrupt Service


Although we do not have a real power stage system and just the Peripheral Explorer Board, it
still allows us also to perform an exercise with an interrupt service in the event of an over
current situation.
9. At the beginning of "Lab7_8.c", add a prototype for an interrupt service routine:
interrupt void ePWM1_TZ_isr(void);
10. In “main()”, look for the line, in which we change the entry in PieVectTable for
TINT0. After this line, add a new line to replace the entry for EPWM1_TZINT:
PieVectTable.EPWM1_TZINT = &ePWM1_TZ_isr;
11. Interrupt EPWM1_TZINT is wired to PIE - interrupt line INT2 bit 1. We have to
enable this line. In “main()”, search for the line, where we enabled
PIEIER1.bit.INTx7. Add a new line to also enable interrupt 2.1:
PieCtrlRegs.PIEIER2.bit.INTx1 = 1;
12. Change the line "IER |= 1;" so that the two lines INT1 and INT2 are enabled:
IER |= 3;
13. In the function "Setup_ePWM1()", add a line to enable cycle-by-cycle interrupts in
register EPwm1Regs.TZEINT. Include this new instruction in the EALLOW - EDIS
block!
14. At the end of "Lab7_8.c", add the definition for function "ePWM1_TZ_isr()". In this
function include the following actions:
• Clear the two flags "CBC" and "INT" in register "EPwm1Regs.TZCLR" to re-
enable TZ6 for the next interrupt service:
EPwm1Regs.TZCLR.bit.CBC = 1;
EPwm1Regs.TZCLR.bit.INT = 1;
Recall that this register is EALLOW - protected!
• Now, because we "simulate" our over current signal TZ6 using a push button, the
duration of the "over-current" signal depends on how fast we can take our finger
off the button. So what happens, if we push it too long? Answer: TZ6 will trigger
a next interrupt immediately after we return from interrupt function
"ePWM1_TZ_isr()".

7 - 58 F2833x - PWM and Capture Units


Lab 7_8: Trip Zone protection with TZ6

Remember that we have three different software activities in Lab7_8:


• “main()” - loop, where we execute the watchdog service #1;
• interrupt service "cpu_timer0_isr()", where we execute the watchdog service
#2;
• new interrupt service "ePWM1_TZ_isr()".
Because the interrupt service "cpu_timer0_isr()" has a higher priority than
"ePWM1_TZ_isr()", it will interleave with our finger triggered series of interrupt
requests. The problem is, that the “main()”-loop, and consequently our watchdog
service #1, will be locked out - as long as we keep pushing button PB1.
Solution: push quickly! Or, if you like to push slowly, include the watchdog service
#1 into the new interrupt service function "ePWM1_TZ_isr()":

SysCtrlRegs.WDKEY = 0x55;
Remember that this register is also EALLOW - protected!
• To indicate, that we are executing code from the new interrupt service routine
"ePWM1_TZ_isr", add a line to toggle LED GPIO9:
GpioDataRegs.GPATOGGLE.bit.GPIO9 = 1;
• To acknowledge that we are done with the interrupt service, in PIE group 2, add:
PieCtrlRegs.PIEACK.all = 2;
15. In the while(1) - loop of “main()”, remove the code for the binary counter at GPIO9,
GPIO11, GPIO34 and GPIO49. Because we will use GPIO9 as an indicator for the
new interrupt service function "ePWM1_TZ_isr()", we cannot use that old block of
code any more. Optionally, you can add a toggle instruction for GPIO11 to the second
interrupt service function "cpu_timer0_isr()".
16. In “main()”, change the line to setup CPU - Timer 0 back to a period of 100
milliseconds:
ConfigCpuTimer(&CpuTimer0,100,100000);

Re-Build, Load and Test


17. Build, load and test the modified project. Please do not forget to reset the device
before you perform a new test. This is always a good practice, since the chip will
always start from a known state! Here's ones more the sequence:
• Debug  Reset CPU
• Debug  Restart
• Debug  Go Main
• Debug  Run

The scope should again show the pulse sequences at ePWM1A and ePWM1B.

F2833x - PWM and Capture Units 7 - 59


Lab 7_8: Trip Zone protection with TZ6

When you push PB1 the signals should fade out to ground and keep this ground
voltage, as long as you keep your finger on PB1 to hold it down. When you release
PB1, the pulse pattern at ePWM1A and ePWM1B should reappear again.
LED LD2 (GPIO11) should toggle with a period of 100 milliseconds.
Each time you push PB1, LED LD1 (GPIO9) should toggle, as an indication of the
execution of the over current interrupt service routine "ePWM1_TZ_isr()". Please note
that button PB1 is a switch with bouncing contacts, so it might request more than one
interrupt, when you press it down.
Of course, in a real-world application, an over-current signal will never be generated
by a push button; we would use a real sensor unit to measure the current in a power
stage! Nevertheless, this exercise with the limited features of the Peripheral Explorer
Board includes all the software features of such a real-world application.

END of Lab7_8

7 - 60 F2833x - PWM and Capture Units


ePWM Interrupt Sources

ePWM Interrupt Sources


ePWM Event-Trigger Module
CMPA . 15 - 0 CMPB . 15 - 0
TBCTL . 12 - 7
Shadowed Shadowed
Clock Compare Compare
Prescaler Register Register
AQCTLA . 11 - 0
TBCTR . 15 - 0
AQCTLB . 11 - 0 DBCTL . 4 - 0
16-
16-Bit
Compare Action Dead
Time-
Time-Base
TBCLK Logic Qualifier Band
Counter

EPWMxSYNCI EPWMxSYNCO
Period
Register EPWMxA
PWM Trip
Shadowed
Chopper Zone
SYSCLKOUT TBPRD . 15 - 0 EPWMxB
PCCTL . 10 - 0
TZy
TZSEL . 15 - 0

7 - 50

We still have left one module of the ePWM unit: the event trigger sub module. It
monitors various event conditions, such as
 Counter value TBCTR = zero
 Counter value TBCTR = TBPRD
 Counter value TBCTR = CMPA
 Counter value TBCTR = CMPB
and can be configured to prescale these events before issuing an Interrupt request or an ADC
start of conversion. The event-trigger prescaling logic can issue Interrupt requests and ADC
start of conversion at:
 Every event
 Every second event
 Every third event
The next slide is an example for symmetrical PWM operation mode and shows available
point of actions for interrupt service requests or to start an analogue to digital conversion:

F2833x - PWM and Capture Units 7 - 61


ePWM Interrupt Sources

ePWM Event-Trigger Interrupts and SOC


TBCTR

TBPRD
CMPB
. . . . . . . .
CMPA

EPWMA

EPWMB

CTR = 0

CTR = PRD
CTRU = CMPA

CTRD = CMPA
CTRU = CMPB

CTRD = CMPB 7 - 51

The Event-Trigger- Sub module is initialized by a set of registers:


 ETSEL - This register selects which of the possible events will trigger
an interrupt or start an ADC conversion
 ETPS - This register programs the event prescaling options
mentioned above.
 ETFLG - Register with flag bits to indicate the status of the selected
and prescaled events.
 ETCLR - These bits allow you to clear the flag bits in the ETFLG
register via software.
 ETFRC - These bits allow software forcing of an event. Useful for
debugging or s/w intervention.

We will use one of the interrupts of the event trigger module in the next lab exercise Lab7_9
to request a change of the pulse width on a cycle by cycle base (or "on the fly") to generate a
sine wave modulated signal at ePWM1A.

7 - 62 F2833x - PWM and Capture Units


ePWM Interrupt Sources

ePWM Event-Trigger Module Registers

Name Description Structure


ETSEL Event-
Event-Trigger Selection EPwmxRegs.ETSEL.all
EPwm Regs.ETSEL.all =
ETPS Event-
Event-Trigger Pre-
Pre-Scale EPwmxRegs.ETPS.all
EPwm Regs.ETPS.all =
ETFLG Event-
Event-Trigger Flag EPwmxRegs.ETFLG.all
EPwm Regs.ETFLG.all =
ETCLR Event-
Event-Trigger Clear EPwmxRegs.ETCLR.all
EPwm Regs.ETCLR.all =
ETFRC Event-
Event-Trigger Force EPwmxRegs.ETFRC.all
EPwm Regs.ETFRC.all =

7 - 52

ePWM Event-Trigger Selection Register


EPwmxRegs.ETSEL
EPwm Regs.ETSEL

Enable SOCB / A Enable EPWMxINT


0 = disable 0 = disable
1 = enable 1 = enable

15 14 - 12 11 10 - 8 7-4 3 2-0
SOCBEN SOCBSEL SOCAEN SOCASEL reserved INTEN INTSEL

EPWMxSOCB / A Select EPWMxINT Select


000 = reserved 000 = reserved
001 = CTR = 0 001 = CTR = 0
010 = CTR = PRD 010 = CTR = PRD
011 = reserved 011 = reserved
100 = CTRU = CMPA 100 = CTRU = CMPA
101 = CTRD = CMPA 101 = CTRD = CMPA
110 = CTRU = CMPB 110 = CTRU = CMPB
111 = CTRD = CMPB 111 = CTRD = CMPB
7 - 53

F2833x - PWM and Capture Units 7 - 63


ePWM Interrupt Sources

ePWM Event-Trigger Prescale Register


EPwmxRegs.ETPS
EPwm Regs.ETPS

EPWMxSOCB / A Counter EPWMxINT Counter


(number of events have occurred) (number of events have occurred)
00 = no events 00 = no events
01 = 1 event 01 = 1 event
10 = 2 events 10 = 2 events
11 = 3 events 11 = 3 events

15 - 14 13 - 12 11 - 10 9-8 7-4 2-3 1-0


SOCBCNT SOCBPRD SOCACNT SOCAPRD reserved INTCNT INTPRD

EPWMxSOCB / A Period EPWMxINT Period


(number of events before SOC) (number of events before INT)
00 = disabled 00 = disabled
01 = SOC on first event 01 = INT on first event
10 = SOC on second event 10 = INT on second event
11 = SOC on third event 11 = INT on third event

7 - 54

7 - 64 F2833x - PWM and Capture Units


Lab7_9: ePWM Sine Wave Modulation

Lab7_9: ePWM Sine Wave Modulation


Objective
The F28335ControlCARD is used in combination with the Peripheral Explorer Board to
output a sine wave signal at ePWM1A. Channel ePWM1A is set up in standard 16-bit
resolution. The generated signal is connected to a second order low pass filter with a cut-off
frequency of 105 kHz. The filter output signal can be monitored at header J11-1 (“DAC-1”)
of the Peripheral Explorer Board.

Lab 7_9: Sine Wave PWM signal at ePWM1A

Objective:
• Generate a sine wave modulated pulse sequence at
ePWM1A
• ePWM1A carrier frequency is 500 KHz
• Sine wave frequency is 976 Hz

7 - 55

Channel ePWM1A is set up for a 500 kHz PWM frequency, ePWM1 compare down event
triggers an interrupt service routine (ISR), according to the frequency the trigger appears
every 2000 ns.

F2833x - PWM and Capture Units 7 - 65


Lab7_9: ePWM Sine Wave Modulation

The ISR with a code execution time of 630ns takes advantage of the Boot-ROM sine wave
lookup-table to calculate the next compare value for the next ePWM1A period. The lookup-
table consists of 512 values in I2Q30-format and is located at address 0x3FE000. Every ISR
call is used to read the next entry of this table, thus a full period of the resulting sine wave
takes 512 * 2000 ns = 1024 µs. The synthesized sine wave signal has a frequency of
1/1024µs = 976 Hz. Due to the type of look-up values in I2Q30-format, functions of a
library called “IQmath” are used to calculate the next value for the duty cycle.
Although we have not discussed the background of fixed-point binary mathematics and
especially of Texas Instruments IQMath yet, we will use this library in a 'black box' method.
We will resume the discussion of this mathematical approach in a later chapter of this
teaching course.

Procedure

Install IQMath
If not already installed on your PC, you will have to install the IQMath library now. The
standard installation path is "C:\tidcs\c28\IQmath":

If this library isn't available on your PC, you will have to install it first. If you are in a
classroom and you do not have administrator installation rights, ask your teacher for
assistance. You can find the installation file under number "sprc087.zip" in the utility part of
this CD-ROM or at the Texas Instruments Website (www.ti.com).

7 - 66 F2833x - PWM and Capture Units


Lab7_9: ePWM Sine Wave Modulation

Open Project File


1. In project "Lab7" open the file “Lab7_8.c” and save it as “Lab7_9.c”
2. Exclude the file “Lab7_8.c” from build.
3. Change the Build options.
We have to extend the preprocessors include search path. In the “C/C++” perspective,
in the project window right click at project “Lab7” and open “Properties”. In the
“C/C++ Build” category, open “Include Options:” and add a new entry:
C:\tidcs\c28\IQmath\v15a\include

Close the “C/C++ Build” options menu with <OK>


4. Link the IQmath library to your project. Right click at project “Lab7” and select
function “Link Files to Project. Link:
C:\tidcs\c28\IQmath\v15a\lib\IQmath_fpu32.lib
5. At the beginning of "Lab7_9.c" include the header file for IQmath:
#include "IQmathLib.h"
Also at the beginning of "Lab7_9.c", add a new global variable "sine_table[512]" of
data type "_iq30" to "Lab7_9.c":
#pragma DATA_SECTION(sine_table, "IQmathTables");
_iq30 sine_table[512];
The pragma statement is a directive for the compiler to generate a new data section for
"sine_table". The linker command file "28335_RAM_lnk.cmd", which is already part
of our project, will connect the section "IQmathTables" to physical address 0x3FE000,
which is where our lookup table is stored in ROM.
6. In "Lab7_9.c" remove everything that is related to CpuTimer0, including external
function prototypes, the call to functions "InitCpuTimers()", "ConfigCpuTimer()" and
Interrupt Service Routine "cpu_timer0_isr()", including its prototype and definition. In
the while(1) loop of main, also remove all instruction related to variable
"CpuTimer0.InterruptCount".
Also remove everything that is related to variable "counter". We do not need this
variable any more.
7. Also at the beginning of "Lab7_9.c", replace the function prototype of ISR
"ePWM1_TZ_isr()" by a new interrupt service function prototype:
interrupt void ePWM1A_compare_isr(void);

F2833x - PWM and Capture Units 7 - 67


Lab7_9: ePWM Sine Wave Modulation

8. In “main()”, remove the entry instruction to write into


"PieVectTable.EPWM1_TZINT" and add a new instruction:
PieVectTable.EPWM1_INT = &ePWM1A_compare_isr;
PWM1 interrupts are connected to PIE group 3, bit 1. Therefore change the line to
enable PIE interrupts into:
PieCtrlRegs.PIEIER3.bit.INTx1 = 1;
Change register IER to allow interrupts at line 3:
IER |= 4;
9. In the while(1) - loop of main keep just the instruction to service the watchdog
instruction #1 (value 0x55) to register WDKEY. Remember that the register WDKEY
is EALLOW protected!
10. Next, in the function "Gpio_select()", just keep ePWM1A as PWM output signal.
Remove the instructions to enable lines ePWM1B and TZ6.
11. In the function "Setup_ePWM1()", change the period of ePWM1 to 500 kHz. In
up/down mode the value for TBPRD is calculated by:

1 f SYSCLKOUT
TBPRD = ∗
2 f PWM * CLKDIV * HSPCLKDIV

with CLKDIV and HSPCLKDIV both set to "divide by 1" and fSYSCLKOUT = 150MHz,
TBPRD should be initialized to 150.
12. Then in the function "Setup_ePWM1()", remove the initialization lines for registers
CMPB an AQCTLB, since we will not generate a signal at ePWM1B.
13. At the end of the function "Setup_ePWM1()", remove the code to initialize the trip
zone unit, including all instructions for registers TZCTL, TZSEL and TZEINT.
14. At the end of the function "Setup_ePWM1()", add code to initialize the Event Trigger
module. In the register "ETSEL", enable bit "INTEN" and set the bit field "INTSEL"
to select an interrupt request, if CTRD = CMPA (counter down matches CMPA). In
the register "ETPS", set bit field "INTPRD" to request an interrupt on first event.
15. At the end of "Lab7_9.c" add the definition of function "ePWM1A_compare_isr()":
interrupt void ePWM1A_compare_isr(void)
{
First define a static variable "index" and initialize it to zero. This variable will be used
as an index into lookup-table "sine_table[512]:
static unsigned int index = 0;
Next we have to service the second half of the watchdog - key sequence to register
WDKEY (value 0xAA). Remember that this register is EALLOW protected!
Now we have to calculate a new value for register CMPA. Here is the line:

7 - 68 F2833x - PWM and Capture Units


Lab7_9: ePWM Sine Wave Modulation

EPwm1Regs.CMPA.half.CMPA =
EPwm1Regs.TBPRD -_IQsat(
_IQ30mpy((sine_table[index]+_IQ30(0.9999))/2, EPwm1Regs.TBPRD),
EPwm1Regs.TBPRD,0);
Confusing, isn't it?
Here is an attempt to explain it, should you be interested in the details:
 Recall, the difference between TBPRD and CMPA defines the pulse width of the
PWM signal. The bigger the difference, the bigger the pulse. It means that we
have to subtract a percentage value from TBPRD to define the next pulse width
and store this percent value in CMPA.
 To find that next value to be subtracted from TBPRD we have to access the sine
table. Variable "index" points to this table, which consists of 512 entries for a
unit circle of 360 degrees. The value taken from this table is in I2Q30-Format
and between 0 for sin(0), 1 for sin(90°), 0 for sin(180°), -1 for sin(270°) and
again 0 for sin(360°).
 So, we read a number between +1 and -1, which corresponds to the current
amplitude of the sine. However, we cannot use a negative number for the
calculation of a result between 0 and 100% of TBPRD. What we do is we add an
offset of +1 in the form of an IQ-number (_IQ30(0.9999)) to obtain numbers
between 0 and +2. Next we divide the result by 2 to scale it into a range between
0 and 1 (or 0% and 100%).
 Now we multiply this relative number (0 to 1) by TBPRD with a call of function
"_IQ30mpy( )" . If TBPRD has been set to 100, the result will be a number
between 0 and 100.
 The function "_IQsat()" is a saturation function that will limit the first parameter
(our result) between maximum (parameter 2, TBPRD) and minimum (parameter
3, zero). To call this function is just a precaution to avoid any calculation
overflows, which could result in catastrophic output signals, where a large
positive number suddenly becomes a large negative number.
After this calculation, still inside "ePWM1A_compare_isr()", we have to increment
variable "index" and to reset it, if we are at the end of the sine_table:
index +=1;
if( index > 511) index = 0;
Finally, we have to clear the interrupt flags of the event trigger module and the PIE-
unit:
EPwm1Regs.ETCLR.bit.INT = 1;
PieCtrlRegs.PIEACK.all = 4;
Close function "ePWM1A_compare_isr()" with a closing curly brace ( }).

F2833x - PWM and Capture Units 7 - 69


Build, Load and Test
16. Build, load and test the modified project. Please do not forget to reset the DSC before
you perform a new test. This is always a good practice, since the chip will always start
from a known state! Here's the sequence:
• Trace  Reset  Reset CPU
• Trace  Restart
• Trace  Run

17. A scope should show the 500 kHz-pulse sequence at ePWM1A (Peripheral Explorer
Board Jumper J6-1) and a sine wave signal of 976 Hz at DAC1 (Peripheral Explorer
Board Jumper J11-1).

End of Lab7_9

7 - 70 F2833x - PWM and Capture Units


eCAP Capture Module

eCAP Capture Module


The enhanced Capture (eCAP) module provides measurement units, which are useful for
accurate time stamps of external events, such as rising or falling edges of digital signals.

Capture Operating Mode

eCAP Block Diagram – Capture Mode


CAP1POL
CAP1 . 31 - 0 ECCTL . 0

Capture 1 Polarity
Register Select 1
CAP2POL
CAP2 . 31 - 0 ECCTL . 2

TSCTR . 31 - 0 Capture 2 Polarity PRESCALE

Event Logic
Register Select 2 ECCTL . 13 - 9
32-
32-Bit CAP3POL Event
Time-
Time-Stamp CAP3 . 31 - 0 ECCTL . 4 Prescale
Counter ECAPx
Capture 3 Polarity pin
Register Select 3
SYSCLKOUT CAP4POL
CAP4 . 31 - 0 ECCTL . 6

Capture 4 Polarity
Register Select 4
7 - 56

The capture units allow time-based logging of external logic level signal transitions on the
capture input pins.
Devices in the F2833x family have four independent capture units; one of them is shown in
Slide 7-56 above. Each capture unit is associated with a capture input pin. An event prescaler
can be initialized to reduce the input frequency. Four polarity select bit fields define rising or
falling edges as the trigger events for capture events 1 to 4. The measurement time-base is
derived from the frequency SYSCLKOUT, in the case of the F28335ControlCard, this is 100
MHz. This signal will increment a 32-bit Time-Stamp Counter. In the event of a capture
trigger signal the current value of this counter is captured and stored in the corresponding
capture register.
Multiple identical eCAP modules can be contained in a 2833x system as shown in Slide 7-
56. The number of modules is device-dependent and is based on target application needs.

F2833x - PWM and Capture Units 7 - 71


eCAP Capture Module

Capture Units (eCAP)

Timer
Trigger
pin
Timestamp
Values

 The eCAP module timestamps transitions on a


capture input pin

7 - 57

Typical uses for the Capture Units are:

• Period and duty cycle measurements of pulse train signals

• Low speed measurement of a rotating machinery (e.g., toothed sprockets sensed via
Hall sensors). A potential advantage for low speed estimation is given when we use
“time capture” (32-bit resolution) instead of position pulse counting, which has a
poor resolution at slow operating speeds.

• Elapsed time measurements between position sensor pulses.

• Decoding current or voltage amplitude derived from duty cycle encoded


current/voltage sensors

Additionally, if the capture operation is not used in an application, an ePWM channel can be
used as another single ended ePWM - output channel, with 32-bit resolution for frequency
and duty cycle register setup. Since this operation mode is not the primary purpose of this
unit, it is called "Auxiliary PWM" mode.

7 - 72 F2833x - PWM and Capture Units


eCAP Capture Module

Some Uses for the Capture Units

 Measure the time width of a pulse


 Low speed velocity estimation from incr. encoder:
Problem: At low speeds, calculation of speed
xk - xk-1
based on a measured position change at vk ≈
fixed time intervals produces large estimate ∆t
errors

Alternative: Estimate the speed using a measured time interval


at fixed position intervals
Signal from one
∆x
vk ≈ quadrature
tk - tk-1 encoder channel
∆x

 Auxiliary PWM generation


7 - 58

Auxilliary PWM Operating Mode


As a second operating mode of a capture unit, auxiliary PWM mode can be used. In this case
a single ended output PWM signal can be generated. Register CAP1 features as period
register and register CAP2 as compare register.

eCAP Block Diagram – APWM Mode

Shadowed
Period CAP3 . 31 - 0
CAP1 . 31 - 0 Period Register shadow
immediate Register (CAP3) mode
mode (CAP1)

TSCTR . 31 - 0

32-
32-Bit PWM
Time-
Time-Stamp Compare
Counter Logic ECAP
pin
SYSCLKOUT
CAP2 . 31 - 0 Compare
immediate Register Compare CAP4 . 31 - 0
mode (CAP2) Register shadow
Shadowed (CAP4) mode

7 - 59

F2833x - PWM and Capture Units 7 - 73


Capture Units Registers

Capture Units Registers


Each of the four capture units is controlled by a set of individual registers.

eCAP Module Registers


Name Description Structure
ECCTL1 Capture Control 1 ECapxRegs.ECCTL1.all
ECap Regs.ECCTL1.all =
ECCTL2 Capture Control 2 ECapxRegs.ECCTL2.all
ECap Regs.ECCTL2.all =
TSCTR Time-
Time-Stamp Counter ECapxRegs.TSCTR
ECap Regs.TSCTR =
CTRPHS Counter Phase Offset ECapxRegs.CTRPHS
ECap Regs.CTRPHS =
CAP1 Capture 1 ECapxRegs.CAP1
ECap Regs.CAP1 =
CAP2 Capture 2 ECapxRegs.CAP2
ECap Regs.CAP2 =
CAP3 Capture 3 ECapxRegs.CAP3
ECap Regs.CAP3 =
CAP4 Capture 4 ECapxRegs.CAP4
ECap Regs.CAP4 =
ECEINT Enable Interrupt ECapxRegs.ECEINT.all
ECap Regs.ECEINT.all =
ECFLG Interrupt Flag ECapxRegs.ECFLG.all
ECap Regs.ECFLG.all =
ECCLR Interrupt Clear ECapxRegs.ECCLR.all
ECap Regs.ECCLR.all =
ECFRC Interrupt Force ECapxRegs.ECFRC.all
ECap Regs.ECFRC.all =

7 - 60

eCAP Control Register 1

eCAP Control Register 1


ECapxRegs.ECCTL1
ECap Regs.ECCTL1

Upper Register:
CAP1 – 4 Load
on Capture Event
0 = disable
1 = enable

15 - 14 13 - 9 8
FREE_SOFT PRESCALE CAPLDEN

Emulation Control Event Filter Prescale Counter


00 = TSCTR stops immediately 00000 = divide by 1 (bypass)
01 = TSCTR runs until equals 0 00001 = divide by 2
1X = free run (do not stop) 00010 = divide by 4
00011 = divide by 6
00100 = divide by 8

11110 = divide by 60
11111 = divide by 62
7 - 61

7 - 74 F2833x - PWM and Capture Units


Capture Units Registers

ECCTL1 [15-14] specify the interaction between the DSC and the JTAG emulation unit. If a
running code hits a breakpoint, these two bits define how the capture unit behaves in this
situation.
The prescaler counter in ECCTL1 [13-9] is used as an input filter of the capture signal. If set
to "00001", every other edge is used to trigger the capture unit.
ECCTL [8] is the global enable switch for the particular capture unit.
ECCTL1 [6, 4, 2, 0] define rising (0) or falling (1) edge as trigger signal for capture event 1
to 4
ECCTL1 [7, 5, 3, 1] specify absolute (0) or relative (1) time stamp mode. Absolute mode
will never clear the timestamp - counter, after the capture unit has been started. Relative
mode will clear the timestamp - counter simultaneously with the trigger event. For example,
if bits 0 and 1 are initialized to 1, the first falling edge after enabling the capture unit will
zero the timestamp-counter.

eCAP Control Register 1


ECapxRegs.ECCTL1
ECap Regs.ECCTL1

Lower Register:
Counter Reset on Capture Event
0 = no reset (absolute time stamp mode)
1 = reset after capture (difference mode)

7 6 5 4 3 2 1 0
CTRRST4 CAP4POL CTRRST3 CAP3POL CTRRST2 CAP2POL CTRRST1 CAP1POL

Capture Event Polarity


0 = trigger on rising edge
1 = trigger on falling edge

7 - 62

F2833x - PWM and Capture Units 7 - 75


Capture Units Registers

eCAP Control Register 2

ECCTL2 [10] defines the shape of an ePWM - output signal in auxiliary PWM operation
mode to be active high (0) or active low (1). In capture operating mode, this bit is don't care.
ECTTL2 [9] selects either capture operating mode (0) or auxiliary PWM mode (1).

eCAP Control Register 2


ECapxRegs.ECCTL2
ECap Regs.ECCTL2

Upper Register:
Capture / APWM mode
0 = capture mode
1 = APWM mode

15 - 11 10 9 8
reserved APWMPOL CAP_APWM SWSYNC

APWM Output Polarity Software Force


(valid only in APWM mode) Counter Synchronization
0 = active high output 0 = no effect
1 = active low output 1 = TSCTR load of current
module and other modules
if SYNCO_SEL bits = 00

7 - 63

ECTTL2 [8] can be used in APWM-Mode to synchronize different capture units with each
other. In case of an active sync input signal, register TSCTR is loaded with a start value.

7 - 76 F2833x - PWM and Capture Units


Capture Units Registers

eCAP Control Register 2


ECapxRegs.ECCTL2
ECap Regs.ECCTL2

Lower Register:
Re-
Re-arm Continuous/One-
Continuous/One-Shot
Counter Sync-
Sync-In (capture mode only) (capture mode only)
0 = disable 0 = no effect 0 = continuous mode
1 = enable 1 = arm sequence 1 = one-
one-shot mode

7-6 5 4 3 2-1 0
SYNCO_SEL SYNCI_EN TSCTRSTOP REARM STOP_WRAP CONT_ONESHT

Sync-
Sync-Out Select Time Stamp Stop Value for One-
One-Shot Mode/
00 = sync-
sync-in to sync-
sync-out Counter Stop Wrap Value for Continuous Mode
01 = CTR = PRD event 0 = stop (capture mode only)
generates sync-
sync-out 1 = run 00 = stop/wrap after capture event 1
1X = disable 01 = stop/wrap after capture event 2
10 = stop/wrap after capture event 3
11 = stop/wrap after capture event 4

7 - 64

ECTTL2 [7-6] are used to specify the source of the sync output signal (to achieve
synchronized APWM channels). The code 00 will directly drive a sync input signal to the
sync output. Code 01 will sent a sync output signal to other capture channels, if TBCTR =
TBPRD.
ECTTL2 [5] allows the APWM sync input feature.
ECTTL2 [4] is the master switch to enable the capture counter unit.
ECTTL2 [3-0]: The continuous/one-shot block controls the start/stop and reset (zero)
functions of a Modulo 4 event counter via a mono-shot type of action that can be triggered
by the stop-value comparator and re-armed via software control.
One shot mode:
Once armed, the eCAP module waits for 1 to 4 (defined by the stop-value) capture
events before freezing both the Modulo 4 event counter and the contents of registers
CAP1 to 4 (i.e. time-stamps). Re-arming prepares the eCAP module for another
capture sequence. Also re-arming clears the Modulo 4 counter to zero and permits
loading of CAP1-4 registers again, providing that the CAPLDEN bit is set.
Continuous Mode:
In continuous mode, the Modulo 4 event counter continues to run (0->1->2->3->0,
the one-shot action is ignored, and capture values continue to be written to capture
result registers CAP1 - x in a circular buffer sequence. The wrap around value will
limit number x to the pre-selected result register.

F2833x - PWM and Capture Units 7 - 77


Capture Units Registers

eCAP Interrupt Enable Register


Interrupts can be requested based on internal events of the capture or APWM module.
ECEINT [4-1] will enable an interrupt request with capture event 1 to 4.
ECEINT [5] can be used to request an ISR in case of an overflow of the 32-bit register
TBCTR. It is important to note such an overflow when results will be subtracted in a later
calculation.

eCAP Interrupt Enable Register


ECapxRegs.ECEINT
ECap Regs.ECEINT

CTR = CMP CTR = Overflow Capture Event 3 Capture Event 1


Interrupt Enable Interrupt Enable Interrupt Enable Interrupt Enable

15 - 8 7 6 5 4 3 2 1 0
reserved CTR=CMP CTR=PRD CTROVF CEVT4 CEVT3 CEVT2 CEVT1 reserved

CTR = PRD Capture Event 4 Capture Event 2


Interrupt Enable Interrupt Enable Interrupt Enable

0 = disable as interrupt source


1 = enable as interrupt source

7 - 65

ECEINT [7, 6] are interrupt enable bits used in APWM mode. If TBCTR matches either
register CMP or PRD, a corresponding interrupt service routine can be requested.

7 - 78 F2833x - PWM and Capture Units


Lab7_10: ePWM1A 1 kHz captured by eCAP1

Lab7_10: ePWM1A 1 kHz captured by eCAP1


Objective
The F28335ControlCARD is used in combination with the Peripheral Explorer Board to
output a 1 kHz square wave signal with a duty cycle of 50% at ePWM1A. We will use unit
eCAP1 to measure period and duty cycle of this signal.
Note: for this exercise you will have to connect header J6-1 (ePWM1A) to header J10-1
(eCAP1) on the Peripheral Explorer Board.

Procedure

Open Project File


1. In project "Lab7" open the file “Lab7_1.c” and save it as “Lab7_10.c”
2. Exclude the file “Lab7_9.c” from build.

Edit Source File


3. In the function "Gpio_select()", switch the eCAP1 to pin GPIO24. On the Peripheral
Explorer Board we can access eCAP1 via header J10-1, which is wired to pin
GPIO24. Adjust register GPAMUX2 accordingly.
4. At the beginning of "Lab7_10.c", add a function prototype for a new local function
"Setup_eCAP1()":
void Setup_eCAP1(void);
We will also need a new interrupt service routine for eCAP1. Add a new prototype:
interrupt void eCAP1_isr(void);
5. At the end of "Lab7_10.c" add the definition of the new function "Setup_eCAP1()".
The objective is to initialize eCAP1 to capture 3 edges of signal ePWM1A:
• 1st capture: rising edge
• 2nd capture: falling edge
• 3rd capture: rising edge
For register ECCTL2:
• use continuous mode
• set wrap counter to "wrap after 4 captures"
• do not re-arm
• enable counter
• disable the sync features
• select capture mode

For register ECCTL1:


• stop TSCTR immediately on Emulation Suspend

F2833x - PWM and Capture Units 7 - 79


Lab7_10: ePWM1A 1 kHz captured by eCAP1

• prescaler : divide by 1
• enable capture load results
• edge select: CAP1 - falling ; CAP2 - rising; CAP3 - falling; CAP4 - rising
• reset TSCTR on CAP4 - event

For register ECEINT:


• enable event CAP3 interrupt request
6. In the function "main()", add a line to call function "Setup_eCAP1". The best position
is directly after the function call to "Setup_ePWM1A()".
7. Next, in the function "main()", add a line to enable eCAP1 interrupt. Recall that
eCAP1 is connected to bit 0 in PIE group 4. Also, change the code line to enable core
interrupts in register IER. For the new exercise we have to enable INT1 (CPU Timer
0) and INT4 (eCAP1).
8. In the function "main()", search for the line in which we changed the PieVectTable
entry for the CPU Timer 0 interrupt service (TINT0) and add a new line to load a new
interrupt service routine address into PieVectTable for eCAP1:
PieVectTable.ECAP1_INT = & eCAP1_isr;
9. At the beginning of "Lab7_10.c", add two global variables:
Uint32 PWM_Period;
Uint32 PWM_Duty;
We will use the two variables to calculate the difference between CAP2 and CAP1
(duty) and CAP3 and CAP1 (period).
10. At the end of "Lab7_10.c", add the definition of the interrupt service function
"eCAP1_isr()". Add the following commands to this function:
• Clear flag "INT" in register ECCLR.
• Clear flag "CEVT3" in register ECCLR. This will re-enable the CAP3 interrupt.
• Calculate the differences:

PWM_Duty = (int32) ECap1Regs.CAP2 - (int32) ECap1Regs.CAP1;


PWM_Period = (int32) ECap1Regs.CAP3 - (int32) ECap1Regs.CAP1;

• Acknowledge the PIE - group interrupt 4:

PieCtrlRegs.PIEACK.all = 8;

Build, Load and Test


11. Build the modified project.
Project  Rebuild Active Project
12. Use a wire and connect header J6-1 (ePWM1A) to header J10-1 (eCAP1).
13. Load the modified code:
Target  Debug Active Project

7 - 80 F2833x - PWM and Capture Units


Lab7_10: ePWM1A 1 kHz captured by eCAP1

14. Test the code:


Scripts  Realtime Emulation Control  Run_Realtime_with_Restart
15. Open the Watch Window and add the variables "PWM_Duty", "PWM_Period" and
"ECap1Regs.TSCTR" to it. Also click right mouse in the Watch Window and enable
"Continuous Refresh".

What do the values in "PWM_Duty" and "PWM_Period" mean? Remember that


ePWM1A is a signal of 1 kHz with a period of 1 millisecond and a pulse width of 0.5
milliseconds. Our measurement unit has a resolution of 1/150MHz = 6.667 ns.
Therefore the value of 150,000 for "PWM_Period" translates into 150,000 * 6.667 ns
= 1 millisecond.
16. Finally halt the DSC:
Scripts  Realtime Emulation Control  Full_Halt_with_Reset

END of LAB 7_10

F2833x - PWM and Capture Units 7 - 81


Enhanced QEP module

Enhanced QEP module


The F28335 device contains to two enhanced Quadrature Encoder Positioning (eQEP)
modules. These modules are usually used as hardware support units for incremental encoder
devices.

What is an Incremental Quadrature


Encoder?
A digital (angular) position sensor

photo sensors spaced θ/4 deg. apart


slots spaced θ deg. apart θ/4
light source (LED)
θ

Ch. A

Ch. B
shaft rotation

Incremental Optical Encoder Quadrature Output from Photo Sensors

7 - 66

How is Position Determined from


Quadrature Signals?
Position resolution is θ/4 degrees

(00) (11)
increment decrement
(A,B) = counter 10 counter
(10) (01)

Illegal
Ch. A 00 Transitions;
generate 11
phase error
interrupt

Ch. B

01

Quadrature Decoder
State Machine
7 - 67

7 - 82 F2833x - PWM and Capture Units


Enhanced QEP module

eQEP Block Diagram


Measure the elapsed time
between the unit position events;
used for low speed measurement
Quadrature
Generate periodic
Capture
interrupts for velocity Quadrature - Direction -
calculations clock mode count mode
Monitors the quadrature
clock to indicate proper
operation of the motion EQEPxA/XCLK
EQEPxA/XCLK
control system
32-
32-Bit Unit EQEPxB/XDIR
EQEPxB/XDIR
Time-
Time-Base Quadrature
QEP Decoder EQEPxI
Watchdog
EQEPxS
SYSCLKOUT
Position/Counter
Compare
Generate the direction and
clock for the position counter
Generate a sync output in quadrature count mode
and/or interrupt on a
position compare match

7 - 68

The QEP is used (a) to estimate the speed and direction of a rotation or (b) to perform a
positioning movement.

eQEP Connections

Ch. A

Quadrature Ch. B
Capture

EQEPxA/XCLK
32-Bit Unit EQEPxB/XDIR
Time-Base
Quadrature
QEP Decoder EQEPxI Index
Watchdog
EQEPxS Strobe
from homing sensor
SYSCLKOUT
Position/Counter
Compare

7 - 69

F2833x - PWM and Capture Units 7 - 83


Infrared Remote Control

Infrared Remote Control


An interesting example for the capture unit is an infrared (IR) remote receiver. IR-signals are
widely used for all kinds of handheld remote control devices, such as TV, radio tuners and
amplifiers, DVD players, satellite receivers and many others. On the Peripheral Explorer
Board an IR - sensor (TSOP32238 - http://www.vishay.com) is connected to capture unit
ECAP4 (GPIO27). This unit will be used to measure the pulse widths of each pulse in a
series sent to the IR-receiver.

IR - Protocols
Although IR-remote is widely used in consumer electronics, there are different and
incompatible protocols. In a typical living room, you will usually find a collection of
different remote control units:
Typical IR protocols are:
• RC5 code:
• designed by Philips and also used by Loewe, Bang & Olufsen, Bose,
Grundig, Marantz, Hauppauge, in model making and other areas
• 14 - Bit code to address up to 32 devices with 64 instructions each
• SIRCS/ CNTRL - S Code:
• designed by Sony
• up to 21 data bits
• DENON code:
• 16 bit transmission
• MOTOROLA - Code:
• Similar to RC5
• 11 bit transmission

For our exercise we will focus on RC5 code.

RC5 protocol
A RC5 protocol consists of 14 bits per transmission:
• 2 Start Bits (always '1'). Used to synchronize the transmission and to adjust the
amplification of the receiver.
• 1 Toggle Bit (alternate '1' or '0'). Level is changed each time a button is pressed. Used to
distinguish between a long duration (permanent pressing of a button) and a repetitive use
of a button.
• 5 address bits. Allow the control of up to 32 devices by the same control unit.
00 01 02 03
TV1 TV2 Videotext Video VD
04 05 06 07
Video LV1 VCR1 VCR2 experimental
08 09 10
11
Sat-Receiver Camera Sat-Receiver 2

7 - 84 F2833x - PWM and Capture Units


Infrared Remote Control

12 13
14 15
Video-CD Camcorder
16 17 18 19
Audio- Receiver / Audio Tape Audio-Amplifier 2 /
Amplifier 1 Tuner Recorder experimental
23
20 21
22 DAT-Tape, MD-
CD-Player record player
Recorder
26
24 25 27
CDR
29 30 31
28
lighting lighting 2 Telephone
00 01 02 03
"0" "1" "2" "3"
04 05 06 07
"4" "5" "6" "7"
08 09
10 11
"8" "9"
12 13 14
15
Standby Mute Default Setup
16 17 18 19
Volume + Volume - Brightness + Brightness -
20 21 22 23
Color + Color - Bass + Bass -
24 25 26 27
Highs + Highs - Balance right Balance left
28 29 30 31
32 33 34 35
36 37 38 39
40 41 42 43
44 45 46 47
48 50
49 51
Pause <<
52 53 54 55
>> Play Stop Record
56 57 58 59
63
60 61 62
System select

F2833x - PWM and Capture Units 7 - 85


Infrared Remote Control

The figure above shows the pattern for the "POWER" - Button of the PHILIPS universal
remote control, as supplied with the Peripheral Explorer Board. RC5 is a bi-phase code with
duration of 1778µs for a single bit. The following figure will explains the details:

1 1 0 0 0 0 0 0 0 0 1 1 0 0
Start -C6 T A4 A3 A2 A1 A0 C5 C4 C3 C2 C1 C0
The diagram above translates into address = 0 (TV) and command = 12
(ON/OFF/STANDBY). We will use this command in Lab7_11 to toggle LED LD2 of the
Peripheral Explorer Board each time the POWER button of the remote control is pushed.
The space between the signal edges is either 889µs or 1778µs.
The RC5 idle separator between transmissions sequences is defined as 113ms.
We will use eCAP4 unit to capture four consecutive edges, in the sequence "falling - rising-
falling - rising" and repeat this four edges capture until the end of the pulse series. After the
capture of a full command, Lab7_11 must then decode the code and in case of address = 0
and code = 12 toggle led LD2.

7 - 86 F2833x - PWM and Capture Units


Lab7_11: eCAP4 to receive a RC5 IR-signal

Lab7_11: eCAP4 to receive a RC5 IR-signal


Objective
The F28335ControlCARD is used in combination with the Peripheral Explorer Board to
receive a RC5 sequence (Phillips-Specification) from an IR remote control unit.

Procedure

Open Project File


1. In the project "Lab7", open the file “Lab7_1.c” and save it as “Lab7_11.c”
2. Exclude the file “Lab7_10.c” from build.
3. Add the provided source code file "Lab7_11_IR.c" to your project. This file is located
in directory \Labs\Lab7.

Edit Source File


4. In file “Lab7_11.c” search the for function "Gpio_select()" and select eCAP4 function
for pin GPIO27, which is connected to the IR-receiver TSOP32238.
5. At the beginning of "Lab7_11.c", add two new function prototypes for external
functions:
extern void Calculate_IR_code(void);
extern interrupt void eCAP4_isr(void);
6. Also add a new function prototype for local function:
void Setup_eCAP4(void);
7. Add the following global variables:
Uint16 result[100]; // distances between edges
Uint16 signal_IR_ready=0; // decode switch
Uint16 IR_address; // IR device address
Uint16 IR_command; // IR command
Uint16 IR_Toggle; // status of IR - Toggle bit
8. In “main()”, after the basic initialization of the PIE vector table, add a line to load the
address of our local interrupt function "eCAP4_isr" into the PIE vector table:
PieVectTable.ECAP4_INT = &eCAP4_isr;
Remember that this memory location is EALLOW protected!
9. In “main()”, after the initialization of CPU Timer 0, add a for-loop to clear all
elements of array "result[100]".
10. Next, add a line to enable the PIE - interrupt line for eCAP4:
PieCtrlRegs.PIEIER4.bit.INTx4 = 1;

F2833x - PWM and Capture Units 7 - 87


Lab7_11: eCAP4 to receive a RC5 IR-signal

11. Modify the line to initialize register IER accordingly! Recall that eCAP4 is controlled
by line INT4!
12. In the endless while(1) loop of “main()”, after the wait construction to wait for 100
milliseconds, add the following code:
if (signal_IR_ready == 1)
{
Calculate_IR_code();
if(IR_command == 12) GpioDataRegs.GPATOGGLE.bit.GPIO11 = 1;
for (i=0;i<100;i++) result[i] = 0;
signal_IR_ready = 0;
}
13. At the beginning of “main()”, add a local integer variable "i".
14. In “main()”, after the function call to "Gpio_select()", add a function call to a new
function "Setup_eCAP4(). We will define this function shortly.
15. At the end of "Lab7_11.c", add the definition of function "Setup_eCAP4()". Take into
account:
• In register ECCTL1:
• Set Polarity for CAP1 to 4 to: falling - rising - falling - rising
• Select difference mode or "delta" mode for all 4 capture events
• Enable loading of CAP registers
• Do not use the prescale feature
• For register ECCTL2 initialize:
• Enable Capture mode
• Disable all synchronization signals
• For TSCTRSTOP select free running mode
• Select continuous mode
• Set Stop_Wrap to wrap after capture event 4
• For register ECEINT:
• Enable Interrupt after the 4th event.

Build, Load and Test


16. Build and Load the modified project.
• Project  Rebuild Active Project
• Target  Debug Active Project
17. In the “Debug” perspective, test the code:
• Scripts  Realtime Emulation Control  Run_Realtime_with_Restart
Now Use an IR-Remote control Unit with RC5 - code (Philips, Loewe) and press the
"ON/OFF" - key in front of the IR-Receiver at the Peripheral Explorer Board.
Each time you press the "POWER" - button of the remote control, LED LD2
(GPIO11) at the Peripheral Explorer Board should toggle.

7 - 88 F2833x - PWM and Capture Units


F2833x Analogue Digital Converter

Introduction
One of the most important peripheral units of an embedded controller is the Analogue to
Digital Converter (ADC). This unit provides an interface between the controller and the real
world. Most physical signals such as temperature, humidity, pressure, current, speed and
acceleration are analogue signals. With the aid of the appropriate transducer, almost all of
these can be represented as an electrical voltage between Vmin and Vmax, e.g. 0...3V, which is
proportional to the original signal. The purpose of the ADC is to convert this analogue
voltage to a digital number. The relationship between the analogue input -voltage (Vin), the
number of binary digits to represent the digital number (n) and the digital number (D) is
given by:

D ∗ (VREF + − VREF − )
Vin = + VREF −
2n − 1
VREF+ and VREF- are reference voltages and are used to limit the analogue voltage range. Any
input voltage beyond these reference voltages will produce a saturated digital number.
NOTE: Of course, all voltages must remain within the limits of their maximum ratings, as
specified in the data sheet.
In the case of the F2833x, the voltage VREF- is fixed at 0V and VREF+ is connected to +3.0V.
The F2833x internal ADC has a 12-bit resolution (n =12) for the digital number D. This
gives a simplified equation:

D ∗ 3.0V
Vin =
4095
Most applications require not only one analogue input signal to be converted into a digital
value, but their control loop usually needs several different sensor input signals. Therefore,
the F2833x is equipped with 16 dedicated input pins to measure analogue voltages. These 16
signals are multiplexed internally, which means they are processed sequentially. To perform
a conversion, the ADC has to ensure that during the conversion procedure there is no change
of the analogue input voltage Vin, otherwise the digital number would be erroneous. An
internal “sample and hold unit (s&h)” takes care of this. The F2833x is equipped with two
s&h-units, which can be used in parallel. This allows us to convert two input signals (e.g.
two currents of a 3-phase system) at the same time.
In addition, the F2833x ADC has an “auto-sequencer” capability of 16 stages. This means
that the ADC can automatically continue with the conversion of the next input channels after
the previous channels are completed. Thanks to this enhancement, we do not have to fetch
the digital results in the middle of a measurement sequence, the task being carried out by a
single interrupt service routine at the end of the sequence.

F2833x - Analogue Digital Converter 8-1


Module Topics

Module Topics

F2833x Analogue Digital Converter ......................................................................................................... 8-1


Introduction ............................................................................................................................................. 8-1
Module Topics ......................................................................................................................................... 8-2
ADC Module Overview ........................................................................................................................... 8-3
ADC operating modes ............................................................................................................................. 8-4
ADC in Cascaded Mode .......................................................................................................................... 8-5
ADC in Dual Sequencer Mode ................................................................................................................ 8-6
ADC Conversion Time ............................................................................................................................ 8-7
ADC Register Block ................................................................................................................................ 8-8
ADC Control Register 1...................................................................................................................... 8-9
ADC Control Register 2.................................................................................................................... 8-10
ADC Control Register 3.................................................................................................................... 8-12
ADC MAXCONV Register .............................................................................................................. 8-13
ADC Input Channel Select Registers ................................................................................................ 8-14
Example: 3 phase control system & measurement........................................................................... 8-15
ADC Result Register Set .................................................................................................................. 8-16
ADCREFSEL Register ..................................................................................................................... 8-17
Lab 8_1: Two Potentiometer Voltages .................................................................................................. 8-18
Objective ........................................................................................................................................... 8-19
Procedure .......................................................................................................................................... 8-19
Open Files, Create Project File ......................................................................................................... 8-19
Project Build Options ........................................................................................................................ 8-20
Modify Source Code ......................................................................................................................... 8-20
Build, Load and Test ......................................................................................................................... 8-21
Add ADC Initialization ..................................................................................................................... 8-22
Add ePWM2 Initialization ................................................................................................................ 8-23
Add ADC-Interrupt system ............................................................................................................... 8-23
Build, Load and Test ......................................................................................................................... 8-24
Run.................................................................................................................................................... 8-24
Lab 8_2: Analogue Speed Control of “LED- counter” ......................................................................... 8-25
Objective ........................................................................................................................................... 8-25
Procedure .......................................................................................................................................... 8-25
Open Project ..................................................................................................................................... 8-25
Modify Source Code ......................................................................................................................... 8-26
Build, Load and Test ......................................................................................................................... 8-26
Modify the main loop........................................................................................................................ 8-26
Rebuild, Load and Test ..................................................................................................................... 8-27

8-2 F2833x - Analogue Digital Converter


ADC Module Overview

ADC Module Overview


Before we go into the details of how to program the internals of the ADC, let us first
summarize some of the features of the ADC Module. It was stated earlier that the digital
resolution of the converted number is 12 bits. Assuming an input voltage range from 0...+3V,
we obtain a voltage resolution of 3.0V/4095 = 0.732mV per bit.
We have two Sample-and-Hold units, which can be used in parallel; the corresponding
operating mode is called “simultaneous sampling”. Each sample and hold unit is connected
to 8 multiplexed input lines. There is also an auto sequencer, which is a programmable state
machine that is capable of automatically converting up to 16 input signals. Each state of the
auto sequencer stores a measurement in its own dedicated result register.
The fastest conversion time is 80ns per sample in a sequence and 160ns for the very first
sample. Of course we will have to adapt this conversion rate to the signal system that is
actually used.

ADC Module
 12-bit resolution Analogue to Digital Converter
 Sixteen analog input channels, voltage range 0…3V
 Equation:
D ∗ (VREF + − VREF − )
Vin = + VREF −
2n − 1
 Vin = Analogue input voltage, range 0…3V
 Vref+ = 3.0V Vref- = 0V n = 12
 D = digital result, 12 Bit resolution
 Maximum Conversion Rate: 12.5 MSPS (80 ns)
 Two analog input multiplexers / two sample/hold units
 Sequential and simultaneous sampling modes
 Auto sequencing capability - up to 16 auto conversions
 Sixteen individually addressable result registers
 Trigger sources for start-of-conversion
 External trigger, S/W or ePWM - Modules
8-2

A start of a conversion sequence can be initiated from three sources:


• By software - just set a start bit to 1
• By an external signal on pin “GPIO/XINT2_ADCSOC”
• By an event (period, compare or underflow) of one of the PWM-units ePWM1 to
ePWM6

F2833x - Analogue Digital Converter 8-3


ADC operating modes

ADC operating modes


The ADC module can operate in different setups. An operating mode is always a
combination of the three different basic selections:

• Sequencer Mode

• Sampling Mode

• Start Mode
Not all of the 8 possible combinations do actually make sense, so be careful what you select.
The Sequencer Mode selects whether we use state machine of the Auto sequencer as a single
16 stage state machine (“Cascaded Mode”) or as a pair of two independent 8-stage
measurement units (“Dual Sequencer Mode”). By selecting “Simultaneous Sampling” for
the sampling mode we convert 2 analogue input signals at one time. If we choose
“Sequential Sampling” only one multiplexed input channel is converted at one time. Finally
by selecting “Single Sequence Mode” (or “Start/Halt - Mode”) the Auto sequencer starts at
the first input trigger signal, performs the predefined number of conversions and stops at the
end of this conversion sequence - then to wait for a second trigger. In continuous mode the
Auto sequencer starts all over again at the end of the first conversion sequence without
waiting for another trigger input signal.

ADC Operating Modes

 Sequencer Mode:
 Cascaded Sequencer Mode (16 states)
 Dual Sequencer Mode (2 x 8 states)
 Sampling Mode:
 Sequential Sampling (1 channel at a time)
 Simultaneous Sampling (2 channels at a time)
 Start Mode:
 Single Sequence Mode (stop at end of sequence)
 Continuous Mode (wrap sequencer at end of
sequence)

8-3

8-4 F2833x - Analogue Digital Converter


ADC in Cascaded Mode

ADC in Cascaded Mode


ADC Sequencer in Cascaded Mode
ADCINA0
ADCINA1 MUX S/H
A RESULT0
A
RESULT1
ADCINA7 12-bit A/D Result

MUX
RESULT2
Converter MUX
ADCINB0
ADCINB1 MUX S/H
B SOC EOC RESULT15
B
ADCINB7 SEQ1
ADC full-scale Autosequencer
input range is 0 MAX_CONV1
to 3V
Ch Sel (CONV00)
Ch Sel (CONV01)
Ch Sel (CONV02)
Software
Ch Sel (CONV03)
ePWM_SOC_A
ePWM_SOC_B
External Pin Ch Sel (CONV15)
(GPIO/XINT2_ADCSOC) Start Sequence
Trigger

8-4

The slide above (Slide 8-4) shows the block diagram for the ADC operating in “cascaded
mode”. One Auto-Sequencer controls the flow of the conversion. Before we can start a
conversion, we have to setup the number of conversions (“MAX_CONV1”) and which input
line should be converted in which stage (“CHSELxx”). The results are buffered in individual
result registers (“RESULT0” to “RESULT15”) for each stage.
We can choose between two more options: “Simultaneous” and “Sequential” sampling. In
the case of simultaneous sampling, both sample and hold units are used in parallel. Two
input lines with the same input code (for example ADCINA3 and ADCINB3) are converted
at the same time by stage CONV00. In “Sequential mode”, the input lines can be connected
to any of the states of the auto sequencer.
To trigger a conversion sequence, we can use a software start by setting a particular bit. We
also have three more start options using hardware events. Especially useful is the hard-wired
output of an ePWM event, which leads to very precise sample periods. This is a necessity for
correct operation of digital signal processing algorithms. There is no need to trigger an
interrupt service (with its possible jitter due to interrupt response delays) to switch the input
channel between subsequent conversions because the auto-sequencer will do that.
We can use the ADC interrupt after the end of a sequence (or for some applications at the
end of every other sequence) to read out the result register block.

F2833x - Analogue Digital Converter 8-5


ADC in Dual Sequencer Mode

ADC in Dual Sequencer Mode


ADC Sequencer in Dual - Sequencer Mode
ADCINA0
RESULT0
ADCINA1 MUX S/H
A RESULT1
A
Result
ADCINA7
12-bit A/D MUX

MUX
MUX
ADCINB0 Converter
ADCINB1 MUX S/H RESULT7
B
B Sequencer
Arbiter RESULT8
ADCINB7
SOC1/ SOC2/ RESULT9
EOC1 EOC2 Result
SEQ1 SEQ2 MUX
MUX
Autosequencer Autosequencer
MAX_CONV1 MAX_CONV2 RESULT15

Ch Sel (CONV00) Ch Sel (CONV08)


Ch Sel (CONV01) Ch Sel (CONV09)

Ch Sel (CONV07) Ch Sel (CONV15)


Software
Start Sequence Start Sequence Software
ePWM_SOC_A Trigger Trigger ePWM_SOC_B
External Pin
(GPIO/XINT2_ADCSOC) 8-5

The second operating mode of the ADC is called “Dual Sequencer Mode”, which splits the
Auto-Sequencer into two independent state machines (“SEQ1” and “SEQ2”). This mode
uses the signal ePWM_SOC_A (“Start Of Conversion A”) as the hardware trigger for SEQ1
and ePWM_SOC_B for SEQ2. To code the input channels for the individual states of the
two sequencers, we are free to select any of the 16 inputs for any of the 2x8 states. The
registers RESULT0 to RESULT7 contain the values from SEQ1 and registers RESULT8 to
RESULT15 for SEQ2.
The reason for this split mode is to have two independent ADCs, triggered by their own
control time base for SEQ1 and SEQ2. In the ePWM chapter you will learn that we can
generate ePWM_SOC_A and ePWM_SOC_B by various time events in any of the ePWM
units. As an example you can use ePWM1-3 as the control system for a first 3-phase motor
control unit and ePWM4-6 for a second one. In such a scenario SEQ1 will be the
measurement unit for motor 1 and SEQ for motor 2.
In case of a simultaneous start of SEQ1 and SEQ2 the Sequencer Arbiter takes care of this
situation. In this event SEQ1 has higher priority; the start of SEQ2 will be delayed until the
end of the SEQ1 conversion sequence.

8-6 F2833x - Analogue Digital Converter


ADC Conversion Time

ADC Conversion Time


F2833x ADC Clock Diagram
CLKIN PLLCR PLLSTS HISPCP
SYSCLKOUT HSPCLK
(30 MHz) DIV DIVSEL (150 MHz) HSPCLK (150 MHz)
bits bits bits
To CPU
1010b (x10) 10b (/2) 000b (/1)
PCLKCR0.ADCENCLK = 1

ADCTRL3 FCLK ADCTRL1 ADCCLK


(12.5 MHz) (12.5 MHz)
ADCCLKPS To ADC
bits CPS bit pipeline

0110b ADCTRL1
0b sampling
FCLK = HSPCLK/(2*ADCCLKPS) ACQ_PS window
ADCCLK =
FCLK/(CPS+1) bits

0111b
sampling window = (ACQ_PS + 1)*(1/ADCCLK)
Note: Maximum F2833x ADCCLK is 25 MHz, but INL (integral nonlinearity error) is greater
above 12.5 MHz. See the device datasheet (SPRU812A) for more information. 8-6

There are some limitations when setting up the ADC conversion time. First, the basic clock
source for the ADC is the internal clock HSPCLK - we cannot use any clock speed we like.
This clock is derived from the external oscillator, multiplied by PLLCR and divided by
HISPCP. We discussed these bit fields in earlier modules; so just in case you do not recall
their operation, please refer to the earlier chapters.
The second limitation is the maximum frequency for “FCLK” as the internal input signal for
the ADC unit. At the moment this signal is limited to 25MHz. However, when we use this
maximum frequency we get a rising nonlinearity error for the results. In cases where we do
not need that high conversion rate, it is better to limit FCLK to 12.5 MHz. To setup FCLK
we have to initialise the bit field “ADCCLKPS” accordingly. Bit “CPS” gives the option of
another divide by 2. The “ADCCLK” clock provides the time-base for the internal
processing pipeline of the ADC.
A third limitation is the sampling window controlled by the field “ACQ_PS”. This group of
bits defines the length of the window that is used between the multiplexer switch and the
time when we sample (or “freeze”) the input voltage. This time depends on the line
impedance of the input signal. So it is hardware dependent - we cannot specify an optimal
period for all applications. For our lab exercises in this chapter, it is a ‘don’t care’ because
we sample DC-voltages taken from two variable resistors of the Peripheral Explorer Board.

F2833x - Analogue Digital Converter 8-7


ADC Register Block

ADC Register Block


Three control registers “ADCTRL1 to ADCTRL3” are used to set up one of the various
operating conditions of the ADC unit. Register “ADCST” covers the current status of the
ADC.

Analog-to-Digital Converter Registers


Register Description
ADCTRL1 ADC Control Register 1
ADCTRL2 ADC Control Register 2
ADCTRL3 ADC Control Register 3
ADCMAXCONV ADC Maximum Conversion Channels Register
ADCCHSELSEQ1 ADC Channel Select Sequencing Control Register 1
ADCCHSELSEQ2 ADC Channel Select Sequencing Control Register 2
ADCCHSELSEQ3 ADC Channel Select Sequencing Control Register 3
ADCCHSELSEQ4 ADC Channel Select Sequencing Control Register 4
ADCASEQSR ADC Autosequence Status Register
ADCRESULT0 ADC Conversion Result Buffer Register 0
ADCRESULT1 ADC Conversion Result Buffer Register 1
ADCRESULT2 ADC Conversion Result Buffer Register 2

ADCRESULT14 ADC Conversion Result Buffer Register 14


ADCRESULT15 ADC Conversion Result Buffer Register 15
ADCREFSEL ADC Reference Select Register
ADCOFFTRIM ADC Offset Trim Register
ADCST ADC Status and Flag Register
8-7

ADC Control Register 1


Upper Register:
ADC Module Reset
0 = no effect Acquisition Time Prescale (S/H)
1 = reset (set back to 0 ACQ Window = (ACQ_PS + 1)*(1/ADCCLK)
by ADC logic)

15 14 13 - 12 11 - 8 7
reserved RESET SUSMOD ACQ_PS CPS

Emulation Suspend Mode Conversion Prescale


00 = free run (do not stop) 0: ADCCLK = FCLK / 1
01 = stop after current sequence 1: ADCCLK = FCLK / 2
10 = stop after current conversion
11 = stop immediately

Structure Variable in C: AdcRegs.ADCTRL1


8-8

8-8 F2833x - Analogue Digital Converter


ADC Register Block

ADC Control Register 1


Bit 14 (“RESET”) can be used to reset the whole ADC unit into its initial state. It is always
good practice to apply a RESET command before you initialise the ADC. Please note that
you cannot initialize the rest of this register in the same instruction, where you reset the ADC
- so use a follow-up instruction to initialize ADCTRL1.
Bits 13 and 12 (“SUSMOD”) define the interaction between the ADC and an emulator
command, similar to the behaviour that we already discussed in chapter 7 (ePWM-module).
Bits 11 to 8 (“ACQ_PS”) define the length of the sample window.
Bit 7 (“CPS”) is used to divide the input frequency by 1 or 2.

ADC Control Register 1


Lower Register:
Continuous Run Sequencer Mode
0 = stops after reaching 0 = dual mode
end of sequence 1 = cascaded mode
1 = continuous (starts all over
again from “initial state”)

6 5 4 3-0
CONT_RUN SEQ_OVRD SEQ_CASC reserved

Sequencer Override
(functions only if CONT_RUN = 1)
0 = sequencer pointer resets to “initial state” at end of MAX_CONVn
1 = sequencer pointer resets to “initial state” after “end state”

Structure Variable in C: AdcRegs.ADCTRL1


8-9

Bit 6 (“CONT_RUN”) defines whether the auto sequencer starts at the end of a sequence
(=0) and waits for another trigger or if the sequence should start all over again immediately
(= 1).
Bit 5(“SEQ_OVRD”) defines two different options for continuous mode. We will not use
this mode during our labs, so it is a ‘don’t care’.
Finally, Bit 4 (“SEQ_CASC”) is the sequence/cascade bit. It defines the Sequencer Mode to
be a state machine with 16 states (SEQCASC = 1), or to operate as two independent state
machines, each having 8 states (SEQ_CASC = 0).

F2833x - Analogue Digital Converter 8-9


ADC Register Block

ADC Control Register 2

ADC Control Register 2


Upper Register:
ePWM SOC A
ePWM SOC B SEQ1 Mask Bit
Start Conversion (SEQ1) 0 = cannot be started
(cascaded mode only) 0 = clear pending SOC trigger
0 = no action by ePWM trigger
1 = software trigger-start SEQ1 1 = can be started
1 = start by ePWM
signal by ePWM trigger

15 14 13 12 11 10 9 8
ePWM_SOCB INT_ENA INT_MOD ePWM_SOCA
_SEQ RST_SEQ1 SOC_SEQ1 reserved _SEQ1 _SEQ1 reserved _SEQ1

Reset SEQ1 Interrupt Enable (SEQ1) Interrupt Mode (SEQ1)


0 = no action 0 = interrupt disable 0 = interrupt every EOS
1 = immediate reset 1 = interrupt enable 1 = interrupt every other EOS
SEQ1 to “initial state”

Structure Variable in C: AdcRegs.ADCTRL2


8 - 10

The upper half of the ADCTRL2 register is responsible for controlling the operating mode of
sequencer SEQ1.
Setting Bit 15 (“ePWM_SOCB_SEQ”) allows the cascaded sequencer to be started by an
ePWM SOCB signal. The bit is not working in “Dual Sequencer Mode” (see bit 0).
Using Bit 14 (“RST_SEQ1”), we can reset the state machine of SEQ1 to its initial state. This
means that the next trigger will start a new conversion of the channel defined in CONV00.
When we set Bit 13 (“SOC_SEQ1”) to 1, we perform an immediate start of the conversion
under software control.
Bits 11 (“INT_ENA_SEQ1”) and 10 (“INT_MOD_SEQ1”) define the interrupt mode of
SEQ1. We can specify whether we have an interrupt request every “End of Sequence” (EOS)
or every other (EOS).
Bit 8 (“ePWM_SOCA_SEQ1”) is the mask bit to allow the ePWM-signal “SOCA” to be
used as the trigger for a conversion. In Lab8_1 we will use of this start feature, so please
remember to set this bit in the initialization part for Lab8_1!

8 - 10 F2833x - Analogue Digital Converter


ADC Register Block

ADC Control Register 2


Lower Register:
ePWM SOC B
SEQ2 Mask Bit
Start Conversion (SEQ2) 0 = cannot be started
External SOC (SEQ1) (dual-sequencer mode only)
0 = no action by ePWM trigger
0 = clear pending SOC trigger
1 = start by signal from 1 = can be started
1 = software trigger-start SEQ2
ADCSOC pin by ePWM trigger

7 6 5 4 3 2 1 0
EXT_SOC INT_ENA INT_MOD ePWM_SOCB
_SEQ1 RST_SEQ2 SOC_SEQ2 reserved _SEQ2 _SEQ2 reserved _SEQ2

Reset SEQ2 Interrupt Enable (SEQ2) Interrupt Mode (SEQ2)


0 = no action 0 = interrupt disable 0 = interrupt every EOS
1 = immediate reset 1 = interrupt enable 1 = interrupt every other EOS
SEQ2 to “initial state”

Structure Variable in C: AdcRegs.ADCTRL2


8 - 11

The lower byte of ADCTRL2 is similar to its upper half: it controls sequencer SEQ2.

Setting Bit 7 enables an ADC auto conversion sequence to be started by a signal from a
GPIO Port A pin (GPIO31-0) configured as XINT2 in the GPIOXINT2SEL register.

Bit 6 to Bit 0: The remaining part of ADCTRL2 is similar to Bits 14…8 in the upper half of
the register. However they are used to initialize the operating mode of SEQ2. If we do not
use sequencer 2 because we are in “Cascaded Mode”, these bits are “don’t care’s.

F2833x - Analogue Digital Converter 8 - 11


ADC Register Block

ADC Control Register 3

ADC Control Register 3

ADC Bandgap and ADC Power Down


Reference Power Down (except Bandgap & Ref.)
00 = powered down 0 = powered down
11 = powered up 1 = powered up

15 - 8 7-6 5 4-1 0
reserved ADCBGRFDN ADCPWDN ADCCLKPS SMODE_SEL

ADC Clock Prescale Sampling Mode Select


0 : FCLK = HSPCLK 0 = sequential sampling mode
1 to F : FCLK = HSPCLK / (2*ADCCLKPS) 1 = simultaneous sampling mode

Structure Variable in C: AdcRegs.ADCTRL3


8 - 12

Bit 0 selects the sampling mode to be sequential or simultaneous. Recall that in simultaneous
mode two analogue input signals are converted in parallel.

• Example: Let us assume that you would like to convert signals ADCINA4 and
ADCINB4 in parallel. All you have to do is to initialize:
o SMODE_SEL = 1 // simultaneous sampling
o MAXCONV = 0 // 1 conversion; actually 2, because of
SMODE_SEL = 1
o CONV00 = 4 // channel number for ADCINA4
After the conversion is complete, register RESULT0 will contain the value for
ADCINA4 and register RESULT1 the value for ADCINB4
Bits 4-1 will initialize the FCLK as basic clock of the ADC module (see also Slide 8-6).
Bit 5 is the main power switch for the analog circuitry inside the device. By setting this bit
we power up the ADC except the band gap and reference circuitry.

Bits 7-6 control the ADC band gap and reference voltage power down sequence of the inter-
nal reference voltage system.
• Bits 7-6 = 00: The band gap and reference circuitry is powered down.
• Bits 7-6 = 11: The band gap and reference circuitry is powered up.
Note: If we use the internal reference circuitry, we first have to set bits 7-6 to 11 followed by
the set of bit 5.

8 - 12 F2833x - Analogue Digital Converter


ADC Register Block

ADC MAXCONV Register


”MAXCONV” defines the number of conversion stages of the Auto sequencer. After a valid
trigger signal, the Auto sequencer will convert the predefined number of channels
automatically.
Please note that the number in the register bit fields corresponds to the number of
conversions minus 1.

• MAXCONV = 4 // means 5 conversions, with input channel numbers coded


// in bit fields CONV00 to CONV04 of register
// ADCCHSELSEQ1 and ADCCHSELSEQ2

Maximum Conversion Channels Register


♦ Bit fields define the number of conversions per trigger (binary+1)
Cascaded Mode

15-7 6 5 4 3 2 1 0
MAX_ MAX_ MAX_ MAX_ MAX_ MAX_ MAX_
reserved
CONV 2_2 CONV 2_1 CONV 2_0 CONV 1_3 CONV 1_2 CONV 1_1 CONV 1_0

SEQ2 SEQ1
Dual Mode

♦ Each sequencer starts at the “initial state” and advances sequentially


♦ Each will wrap at the “end state” unless software resets it sooner

SEQ1 SEQ2 Cascaded


Initial state CONV00 CONV08 CONV00
End state CONV07 CONV15 CONV15

8 - 13
Structure Variable in C: AdcRegs.ADCMAXCONV

If we would use “Dual Sequencer Mode” the interpretation of register MAXCONV changes
slightly. In this mode bits 0 to 2 are used to specify the number of conversions in sequencer
SEQ1 and bits 4 to 6 are used for SEQ2. Recall that in this mode each sequencer has a
maximum number of 8 conversions, hence the limitation to 3 bits in MAXCONV.
The Auto sequencer operates as a state machine that starts with an initial state and progresses
after each conversion to the next one. This principle continues until the end state or until we
reset the state machine pointer back to init state (Bit 14 and Bit 6 of ADCTRL2). If we do
not reset and the state machine has reached the end state, it will wrap back to state zero
automatically.

F2833x - Analogue Digital Converter 8 - 13


ADC Register Block

ADC Input Channel Select Registers


ADC Input Channel Select Sequencing Control Register

15 - 12 11 - 8 7-4 3-0
ADCCHSELSEQ1 CONV03 CONV02 CONV01 CONV00

ADCCHSELSEQ2 CONV07 CONV06 CONV05 CONV04

ADCCHSELSEQ3 CONV11 CONV10 CONV09 CONV08

ADCCHSELSEQ4 CONV15 CONV14 CONV13 CONV12

ADC input channels are binary counted:


ADCINA0 = 0000 ADCINB0 = 1000
ADCINA1 = 0001 ….
… ADCINB7 = 1111
Structure Variable in C: AdcRegs.ADCCHSELSEQ1 … AdcRegs.ADCCHSELSEQ4 8 - 14

The group of four registers ADCCHSELSEQ1…4 is used to specify the binary number of
the input channel ADCINA0…ADCINB7 by means of sixteen 4-bit -groups
CONV00…CONV15.
Recall that we can use up to 16 stages in the Auto sequencer. These stages correspond to
CONV00 to CONV15. All we have to do is to fill in the correct numbers for the analogue
input channels (see Slide 8-14).
Example:

• Conversion of 5 channels in a sequence:

• ADCINA6, ADCINB1, ADCINA2, ADCINA0 and ADCINB6


o CONV00 = 6
o CONV01 = 9
o CONV02 = 2
o CONV03 = 0
o CONV04 = 14

8 - 14 F2833x - Analogue Digital Converter


ADC Register Block

Example: 3 phase control system & measurement

Example - Sequencer “Start/Stop” Operation

ePWM
Time Base
Counter

ePWM
Output

V1, V2, V3 I1 , I 2 , I3 V1, V2, V3 I1 , I 2 , I3

Configuration Requirements:
 ePWM triggers the ADC
 Three auto conversions (V1, V2, V3) off trigger 1 (CTR = 0)
 Three auto conversions (I1, I2, I3) off trigger 2 (CTR = PRD)
 ADC in cascaded sequencer and sequential sampling modes

8 - 15

The two slides give a typical example of a 3-phase control system for digital motor control.

Example - Sequencer “Start/Stop” Operation


 MAX_CONV1 is set to 2 and Channel Select Sequencing Control Registers are set to:
Bits → 15-12 11-8 7-4 3-0
I1 V3 V2 V1 ADCCHSELSEQ1
x x I3 I2 ADCCHSELSEQ2

 Once reset and initialized, SEQ1 waits for a trigger


 First trigger, three conversions performed: CONV00 (V1), CONV01 (V2), CONV02 (V3)
 SEQ1 waits for second trigger
 Second trigger, three conversions performed: CONV03 (I1), CONV04 (I2), CONV05 (I3)
 End of second sequence, ADC Results registers have the following values:

RESULT0 V1
RESULT1 V2
RESULT2 V3
RESULT3 I1
RESULT4 I2
RESULT5 I3

 SEQ1 waits at current state for another trigger


 ISR to read results and reset SEQ1
8 - 16

F2833x - Analogue Digital Converter 8 - 15


ADC Register Block

ADC Result Register Set

ADC Conversion Result Registers


AdcRegs.ADCRESULTx, x = 0 - 15 (2 wait-state read)
MSB LSB
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

AdcMirror.ADCRESULTx, x = 0 - 15 (0 wait-state read)


MSB LSB
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

Input Digital AdcRegs. ADCRESULTx AdcMirror. ADCRESULTx


Voltage Result
3.0 0xFFF 1111|1111|1111|0000 0000|1111|1111|1111
1.5 0x7FF 0111|1111|1111|0000 0000|0111|1111|1111
0.00073 1 0000|0000|0001|0000 0000|0000|0000|0001
0 0 0000|0000|0000|0000 0000|0000|0000|0000
8 - 17

The 12-bit digital results are available in two different memory sections.

The ADCRESULTn registers are left justified when read from Peripheral Frame 2 (0x7108-
0x7117; global C- variable “AdcRegs”) with two wait states and right justified when read
from Peripheral Frame 0 (0x0B00-0x0B0F; global C-variable “AdcMirror”) with zero wait
states.
Left justified results are advantageous when a control system operates on “fractional”
numbers. We will see how this makes scaling easier in a later chapter of this course.

8 - 16 F2833x - Analogue Digital Converter


ADC Register Block

How Can We Handle Signed Input Voltages?


Example: -1.5 V ≤ Vin ≤ +1.5 V
R
R
Vin R C28x
1) Add 1.5 volts to the - R
-
1.5V + ADCINx
analog input R
+

ADCLO

GND
2) Subtract “1.5” from the digital result

#include “DSP2833x_Device.h”
#define offset 0x07FF
void main(void)
{
int16 value; // signed

value = AdcMirror.ADCRESULT0 – offset;


}
8 - 18

ADCREFSEL Register
To switch between internal or external ADC reference voltages, we could use register
ADCREFSEL. For our next lab experiments using the Peripheral Explorer Board we will
stay with the internal voltage source, which is selected by default.

ADC Reference Selection


 The F28335 ADC has an internal reference with
temperature stability of ~50 PPM/°C *
 As an option one can use an external reference device
 External reference choices: 2.048 V, 1.5 V, 1.024 V
 The reference value DOES NOT change the 0 - 3 V full-scale
range of the ADC
 The ADCREFSEL register controls the reference choice

15 - 14 13 - 0
REF_SEL reserved

ADC Reference Selection


00 = internal (default)
01 = external 2.048 V
10 = external 1.5 V
11 = external 1.024 V

8 - 19
Structure Variable in C: AdcRegs.ADCREFSEL

F2833x - Analogue Digital Converter 8 - 17


Lab 8_1: Two Potentiometer Voltages

Lab 8_1: Two Potentiometer Voltages

Lab 8_1: Dual AD - Conversion


Objective:
 AD-Conversion of ADCIN_A0 and ADCIN_A1
 Sampling frequency generated by ePWM2: 50kHz
 ADCIN_A0 and ADCIN_A1 are connected to two
variable resistors VR1, VR2 at Peripheral Explorer
Board.
 VR1 and VR2 voltage range: 0 Volt to 3.3 Volt
 Automatic start of ADC by ePWM2 period event
 ADC-Interrupt Service Routine to read out the ADC
results
 main loop to alternately show the results of ADCINA0
or ADCINA1 at 4 LEDs (LD1, LD2, LD3 and LD4) of the
Peripheral Explorer Board as a “light-beam”.

8 - 20

Additional Registers used in Lab8_1:


ePWM2 Time Base Control : TBCTL
ePWM2 Time Base Period : TBPRD
ePWM2 Time Base Counter : TBCNT
ePWM2 Event Trigger Prescale : ETPS
ePWM2 Event Trigger Select : ETSEL
ADC – Control 1 : ADCTRL1
ADC – Control 2 : ADCTRL2
ADC – Control 3 : ADCTRL3
Channel Select Sequencer 1 : ADCCHSELSEQ1
Max. number of conversions : ADCMAXCONV
ADC - Result 0 : ADCRESULT0
ADC - Result 1 : ADCRESULT1

8 - 21

8 - 18 F2833x - Analogue Digital Converter


Lab 8_1: Two Potentiometer Voltages

Objective
The objective of this lab is to practice using the integrated Analogue-Digital
Converter of the F2833x. The Peripheral Explorer Board is equipped with 2 variable
resistors VR1 and VR2, which are connected to the analogue input lines ADCIN_A0
and ADCIN_A1. The two input voltages can be adjusted between 0 and 3.0 volts. In
this lab we will read the current status of the potentiometers and display the
converted voltages on LEDs (LD1 to LD4) of the Peripheral Explorer Board
(GPIO9, GPIO11, GPIO34 and GPIO49) in form of a “light-beam”.
The ePWM2 unit will generate the sampling frequency of 50 kHz (or sampling
period of 20µs). The conversion is triggered automatically by signal “SOCA” at the
period event of ePWM2. The ADC interrupt service routine will be used to copy the
12-bit results into two global variables “Voltage_VR1” and “Voltage_VR2”.
CPU Timer 0 will be used to generate a time base for the monitoring part of this lab
exercise. It will be initialized to run at a period of 100 milliseconds. The interrupt
service routine will increment a global variable “CpuTimer0.InterruptCount”. Based
on the value in this variable we can establish an alternation in the display between
VR1 and VR2 every 0.5 seconds.

Procedure

Open Files, Create Project File


1. Create a new project, called Lab8.pjt in C:\DSP2833x_V4\Labs.

2. Open file Lab6.c from C:\DSP2833x_V4\Labs\Lab6 and save it as Lab8_1.c in


C:\DSP2833x_V4\Labs \Lab8.

3. Define the size of the C system stack. In the project window, right click at project
“Lab8” and select “Properties”. In category “C/C++ Build”, “C2000 Linker”, “Basic
Options” set the C stack size to 0x400.

Link some of the source code files, provided by Texas Instruments, to the project:
4. In the C/C++ perspective, right click at project “Lab8” and select “Link Files to
Project”. Go to folder “C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\source” and
link:

• DSP2833x_GlobalVariableDefs.c
5. Repeat the “Link Files to Project” step. From C:\tidcs\c28\dsp2833x\v131\
DSP2833x_common\source add:
• DSP2833x_CodeStartBranch.asm
• DSP2833x_SysCtrl.c
• DSP2833x_ADC_cal.asm
• DSP2833x_Adc.c
• DSP2833x_usDelay.asm

F2833x - Analogue Digital Converter 8 - 19


Lab 8_1: Two Potentiometer Voltages

• DSP2833x_CpuTimers.c
• DSP2833x_PieCtrl.c
• DSP2833x_PieVect.c
• DSP2833x_DefaultIsr.c
6. From C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\cmd link to project “Lab8”:

• DSP2833x_Headers_nonBIOS.cmd
7. Copy the provided source code file

• “Display_ADC.c”
into your project folder “C:\DSP2833x_V4\Labs\Lab8”. This file, enclosed in the file
“labs_08.zip”, defines a function “display_ADC()”, which converts a 12 bit unsigned
integer number into a “light-beam” at the four LEDs. The term “light-beam” means
that the bigger the input value is the more LEDs are switched on.

Project Build Options


8. Again we have to extent the search path of the C-Compiler for include files. Right
click at project “Lab8” and select “Properties”. Select “C/C++ Build”, “C2000
Compiler”, “Include Options”. In the box: “Add dir to #include search path”, add the
following lines:

C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include

Note: Use the “Add” Icon to add the new paths:

Close the Property Window by Clicking <OK>.

Modify Source Code


9. Open Lab8_1.c to edit: double click on “Lab8_1.c” inside the project window. First
delete the local variable “counter” from function “main()”, including the definition at
the beginning of “main()” and the access to “counter” in the endless-loop at the end of
“main()”.
10. Add two new global unsigned integer variables “Voltage_VR1” and “Voltage_VR2”.
11. In the endless loop of “main()”, change the wait construction based on the variable
“CpuTimer0.InterruptCount” to wait until it is equal to value 5. Recall that this

8 - 20 F2833x - Analogue Digital Converter


Lab 8_1: Two Potentiometer Voltages

variable is incremented every 100 milliseconds by CPU Timer 0 ISR. This way we can
include a time delay of 500 milliseconds. Also recall, that the maximum overflow
period for the watchdog unit is less than 500 milliseconds. While the second clear
instruction for the watchdog unit is part of CPU Timer 0 ISR, we have to embed the
0x55 - instruction into our while-wait loop.
12. After this wait-loop, add a call or function “display_ADC()”:

display_ADC(Voltage_VR1);
13. Next, add a similar wait-loop like in procedure step 11 and wait until variable
“CpuTimer0.InterruptCount” has a value of 10. This will give us another interval of
500 milliseconds.
14. Now call function “display_ADC()” for variable “Voltage_VR2”.
15. Right after step 14 clear variable “CpuTimer0.InterruptCount” back to zero.
16. The provided function “display_ADC()” has been defined in an external file. To be
able to use this function, we have to add an external prototype at the beginning of the
file “Lab8_1.c”:

extern void display_ADC(unsigned int);

Build, Load and Test


17. Although we haven’t initialized the ADC so far, it might make sense to perform a
preliminary test. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

and watch the tools run in the build window. If you get errors or warnings debug as
necessary.

18. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

19. Verify that in the debug perspective the window of the source code “Lab8_1.c” is
high-lighted and that the blue arrow for the current Program Counter position is placed
under the line “void main(void)”.

20. Perform a real time run.

Target  Run

Result: All 4 LEDs should blink at a rate of 0.5 seconds on and off period.

F2833x - Analogue Digital Converter 8 - 21


Lab 8_1: Two Potentiometer Voltages

Add ADC Initialization


21. Change back to the “C/C++” perspective. Inside “main()”, after the function call
“InitPieVectTable();” add the following line to call the basic ADC calibration and
internal reference enabling function:
InitAdc();
Also add an external function prototype at the beginning of “Lab8_1.c”:
extern void InitAdc(void);
22. In “main()”, straight after the function call of “InitAdc()”, add code to initialize the
ADC register. Refer to the reference section or to the slides shown earlier with this
presentation to complete the following register settings:
For register ADCTRL1:

• AdcRegs.ADCTRL1.bit.SEQ_CASC = ?; // Dual Sequencer Mode


• AdcRegs.ADCTRL1.bit.CONT_RUN = ?; // Single Run Mode
• AdcRegs.ADCTRL1.bit.ACQ_PS = ?; // 8 x ADC-Clock
• AdcRegs.ADCTRL1.bit.CPS = ?; // divide by 1
For register ADCTRL2:

• AdcRegs.ADCTRL2.bit.EPWM_SOCA_SEQ1 = ?; // ePWM_SOCA
trigger
• AdcRegs.ADCTRL2.bit.INT_ENA_SEQ1 = ?; // enable ADC int for seq1
• AdcRegs.ADCTRL2.bit.INT_ENA_SEQ1 = ?; // interrupt after every EOS
For register ADCTRL3:

• AdcRegs.ADCTRL3.bit.ADCCLKPS = ?; // set FCLK to 12.5 MHz


Note: do NOT modify other bit fields of ADCTRL3 than “ADCCLKPS”. All other
bits have been initialized by the function call “InitAdc()”. Use slide 8-6 to calculate
the value for ADCCLKPS. If your F28335ControlCard is equipped with a 30MHz
external clock, it runs at a SYSCLKOUT-Frequency of 150 MHz.
For register MAXCONV:

• AdcRegs.ADCMAXCONV.all = ?; // 2 conversions
For register ADCCHSELSEQ1:

• AdcRegs.ADCCHSELSEQ1.bit.CONV00 = ?; // 1st channel ADCINA0

• AdcRegs.ADCCHSELSEQ1.bit.CONV01 = ?; // 2nd channel ADCINA1

8 - 22 F2833x - Analogue Digital Converter


Lab 8_1: Two Potentiometer Voltages

Add ePWM2 Initialization


23. Unit ePWM2 will be the internal clock base for the sampling frequency. We will setup
this unit to run at 50 kHz and trigger a SOCA start of the ADC automatically at the
end of a period. Right after the ADC-register initialization add code:
For register EPwm2Regs.TBCTL, add code to:
• Ignore emulation suspend
• CLKDIV = HSPCLK/1
• HSPCLK = SYSCLKOUT/1
• no SWFSYNC
• SYNC-Out disabled
• no PHSEN
• Reload TBPRD on TBCTR = 0
• CTRMODE = count up mode

For register TBPRD:


• TPPRD +1 = TPWM / (HSPCLKDIV * CLKDIV * TSYSCLK)
= 20 µs / 6.667 ns

For register ETPS:


• SOCAPRD : generate SOCA-signal on first event
• Clear all remaining bits of ETPS

For register ETSEL:


• SOCAEN: enable SOCA-signal
• SOCASEL: generate SOCA-signal on PRD event

Add ADC-Interrupt system


24. In “main()”, search for the re-map instruction of the PIE-table entry for
“PieVectTable.TINT0 = &cpu_timer0_isr;”, which is embedded between “EALLOW”
and “EDIS”. Also between these two instructions add:
PieVectTable.ADCINT = &adc_isr;
25. Also add a line to enable the PIE-Interrupt for the ADC:
PieCtrlRegs.PIEIER1.bit.INTx6 = 1;
26. At the end of “Lab8_1.c” add a new interrupt service routine “adc_isr()” to your code.
Inside this function, add the following:

• Read the two ADC result register and load the value into variables
“Voltage_A0” and “Voltage_B0”:
Voltage_A0 = AdcMirror.ADCRESULT0;
Voltage_B0 = AdcMirror.ADCRESULT1;

• Reset ADC Sequencer1 (Register ADCCTRL2):

F2833x - Analogue Digital Converter 8 - 23


Lab 8_1: Two Potentiometer Voltages

AdcRegs.ADCTRL2.bit.RST_SEQ1 = 1;

• Clear Interrupt Flag ADC Sequencer 1 (Register ADCST)


AdcRegs.ADCST.bit.INT_SEQ1_CLR = 1;

• Acknowledge PIE Interrupt:


PieCtrlRegs.PIEACK.all = PIEACK_GROUP1;
27. At the beginning of “Lab8_1” add a function prototype for the ADC interrupt service
routine:
interrupt void adc_isr(void);

Build, Load and Test


28. Now rebuild, and load the new project to the target. Switch into “Debugger”
perspective.
29. Set a breakpoint in the interrupt service routine “adc_isr()” at the last line of code.

Run
30. When you have modified your code correctly and you execute running in real-time,
this breakpoint should be hit periodically. If not, you missed one or more steps in your
procedure for this lab exercise. In this case try to review your modifications. If you do
not spot a mistake immediately try to test systematically:

• A good start is to temporarily disable the watchdog timer

• Verify that ePWM2 is counting (TBCTR)

• Verify that the clock system is enabled (PCLKCR) for EPWM2 and ADC

• Inspect the Interrupt Registers (IER, PIEIER, INTM)

• Inspect the ADC Register Set (ADCTRL1-3)


If nothing helps, ask your instructor for advice. Please do not ask questions like
“It is not working” or “I do not know what’s wrong...” Instead, summarize your
test strategy and show intermediate results for inspection.
31. After you have verified that the interrupt service routine “adc_isr()” is called
periodically, check the ADC results. Inspect the variables “Voltage_VR1” and
“Voltage_VR2” in your watch window. With the breakpoint still set, modify the
analogue input voltages with the two potentiometers “VR1” and “VR2” of the
Peripheral Explorer Board. You should obtain values between 0 and 4095 for the
leftmost and rightmost positions of VR1 and VR2 respectively.
32. Now remove all breakpoints and run the code. LEDs LD1 to LD4 should display the
values for “Voltage_VR1” and “Voltage_VR2” every 0.5 seconds.

End of Lab 8_1

8 - 24 F2833x - Analogue Digital Converter


Lab 8_2: Analogue Speed Control of “LED- counter”

Lab 8_2: Analogue Speed Control of “LED- counter”


Objective
Now that we have performed an exercise both with the ADC (Lab 8_1) and the CPU
Timer 0 based binary counter in Lab6, we can combine the two exercises. The
objective is to control the speed step of the binary LED-counter from Lab6 by a
voltage taken from ADC-Input ADCIN_A0. The control law should be: The higher
the voltage ADCIN_A0, the higher the speed of the LED-counter.
Use your code from Lab8_1 and Lab6 as the starting point.

Optional Lab8_2
Modify Lab 6 (“4-bit Counter”):

• use the Analogue Input ADCIN0 to change


the counter speed
• use a LED-frequency range between 50Hz
and 1 Hz
• use (1) a linear or (2) a logarithm scale
between Fmin and Fmax.

8 - 22

Procedure

Open Project
1. If not still open from Lab8_1, re-open project Lab8.pjt in the “C/C++” –
perspective.
2. Open the file “Lab8_1.c” and save it as “Lab8_2.c”
3. Exclude file “Lab8_1.c” from build. Use a right mouse click at file “Lab8_1.c”, and
enable “Exclude File(s) from Build”.

F2833x - Analogue Digital Converter 8 - 25


Lab 8_2: Analogue Speed Control of “LED- counter”

Modify Source Code


4. Edit “Lab8_2.c”. In function “main()”, remove the whole contents of the endless
while(1) -loop and replace it with the contents of the while(1)-loop of file “Lab6.c”
5. At the beginning of “Lab8_2.c”, remove the global variable “Voltage_VR2” and add
an integer variable “counter”; initialize this counter to zero.
6. Change the ADC initialization to convert channel ADCINA0 only. Since we do not
need VR2 in this exercise, also remove the read instruction for ADCRESULT1 from
function “adc_isr()”.

Build, Load and Test


7. Time for a preliminary test. Rebuild the project (Project  Rebuild All), debug the
project (Target  Debug Active Project) and switch to the “Debug” – perspective.
Run the code. The LEDs should show the binary counter on LEDs LD1 to LD4. The
counter period is still fixed to 100 milliseconds.
In the watch window, the variable “Voltage_VR1” should have a value between 0 and
4095. Modify the position of potentiometer VR1, then right click into Watch Window,
select “Refresh” and verify that the value of “Voltage_VR1” changes accordingly.
So far we have reached the same result as in Lab6, a 100 millisecond period between
the steps of the counter. However, now we have additionally an active ADC running
in the background!

Modify the main loop


8. All we have to do now is to use variable “Voltage_VR1” to control the period of CPU-
Timer 0. Since we can exceed the Watchdog overflow period by the CPU Timer 0
period, it makes sense to include both watchdog clear instructions into the wait loop:
while(CpuTimer0.InterruptCount == 0)
{
EALLOW;
SysCtrlRegs.WDKEY = 0x55;
SysCtrlRegs.WDKEY = 0xAA;
EDIS;
}
Now we have to modify the period of CPU Timer0. Recall that the task is to generate
a period between 20,000µs (50Hz) and 1,000,000µs (1Hz). And that CPU Timer 0 can
be initialized by a function call as follows:
ConfigCpuTimer(&CpuTimer0,100,x);
Add such a function call directly after the wait-loop! Also, after this function call, re-
enable CPU-Timer 0:
ConfigCpuTimer(&CpuTimer0,100,x); // calculate x before calling
CpuTimer0Regs.TCR.bit.TSS = 0; // restart timer0

8 - 26 F2833x - Analogue Digital Converter


Lab 8_2: Analogue Speed Control of “LED- counter”

Parameter x in this function call is a floating-point variable and gives the period in
microseconds. What you have to do is to call this function with a value for x, which is
calculated based on “Voltage_VR1” (0…4095). Recall that x should be in the limits of
20,000 µs (50Hz) and 1,000,000 µs (1Hz).

Rebuild, Load and Test


9. Rebuild the project (Project  Rebuild All), debug the project (Target  Debug
Active Project) and switch to the “Debug” – perspective.
Run the code. The LEDs should show the binary counter at LEDs LD1 to LD4. If you
turn the potentiometer VR1 the speed of the binary counter at the four LEDs should
change.

End of Lab 8_2

F2833x - Analogue Digital Converter 8 - 27


Lab 8_2: Analogue Speed Control of “LED- counter”

This page has been left blank.

8 - 28 F2833x - Analogue Digital Converter


F2833x Serial Communication Interface

Introduction
The Serial Communication Interface (SCI) module is a serial I/O port that permits
asynchronous communication between the F2833x and other peripheral devices. It is usually
known as a UART (Universal Asynchronous Receiver Transmitter) and is often used
according to the RS232 standard.
The SCI receiver and transmitter each have a 16-deep FIFO for reducing servicing overhead,
each with its own separate enable and interrupt bits. Both can be operated independently for
half-duplex communication, or simultaneously for full-duplex communication. To maintain
data integrity, the SCI checks received data for break detection, parity, overrun, and framing
errors. The bit rate is programmable for different communication speeds through a 16-bit
baud-select register.

Parity checking and data formatting can also be done by the SCI port hardware, further re-
ducing the software overhead.

SCI Pin Connections


(Full Duplex Shown)
TX FIFO_0 TX FIFO_0

TX FIFO_15 TX FIFO_15
Transmitter-data Transmitter-data
buffer register buffer register
8 8

Transmitter SCITXD SCITXD Transmitter


shift register shift register

Receiver SCIRXD SCIRXD Receiver


shift register shift register
8 8

Receiver-data Receiver-data
buffer register buffer register
RX FIFO_0 RX FIFO_0

RX FIFO_15 RX FIFO_15

SCI Device #1 SCI Device #2 9-2

F2833x - Serial Communication Interface 9-1


Module Topics

Module Topics
F2833x Serial Communication Interface ......................................................................................... 9-1
Introduction ..................................................................................................................................... 9-1
Module Topics ................................................................................................................................. 9-2
SCI Data Format ............................................................................................................................. 9-3
SCI Data Timing ............................................................................................................................. 9-4
SCI Multi Processor Wake Up Modes ............................................................................................. 9-5
SCI Register Set............................................................................................................................... 9-7
SCI Communications Control Register (SCICCR) ..................................................................... 9-8
SCI Control Register 1(SCICTL1) ............................................................................................. 9-8
SCI Baud Rate Register .............................................................................................................. 9-9
SCI Control Register 2 – SCICTL2 .......................................................................................... 9-10
SCI Receiver Status Register – SCIRXST ................................................................................ 9-11
SCI FIFO Mode Register .......................................................................................................... 9-12
Lab 9_1: Basic SCI – Transmission .............................................................................................. 9-14
Objective ................................................................................................................................... 9-14
Procedure .................................................................................................................................. 9-15
Open Project “Lab9.pjt”............................................................................................................ 9-15
Modify Source Code ................................................................................................................. 9-15
Finish the main loop ................................................................................................................. 9-15
Build, Load and Run ................................................................................................................. 9-16
Lab 9_2: Interrupt SCI – Transmission......................................................................................... 9-17
Procedure .................................................................................................................................. 9-17
Open Files, Modify Project ....................................................................................................... 9-17
Modify Source Code ................................................................................................................. 9-17
Build, Load and Run ................................................................................................................. 9-18
Optional Exercise ...................................................................................................................... 9-19
Lab 9_3: SCI – FIFO Transmission .............................................................................................. 9-20
Procedure .................................................................................................................................. 9-20
Open Files, Modify Project File ................................................................................................ 9-20
Modify Source Code ................................................................................................................. 9-20
Build, Load and Test ................................................................................................................. 9-21
Lab 9_4: SCI – Receive & Transmit ............................................................................................. 9-22
Procedure .................................................................................................................................. 9-22
Open Files, Modify Project File ................................................................................................ 9-22
Modify Source Code ................................................................................................................. 9-22
Build, Load and Test ................................................................................................................. 9-24
Optional Exercise 9_5 ................................................................................................................... 9-25

9-2 F2833x - Serial Communication Interface


SCI Data Format

SCI Data Format


The basic unit of data is called a character and is 1 bit to 8 bits in length. Each character of
data is formatted with a start bit, 1 or 2 stop bits, an optional parity bit, and an optional
address/data bit. A character of data along with its formatting bits is called a frame. Frames
are organized into groups called blocks. If more than two serial ports exist on the SCI bus, a
block of data will usually begin with an address frame, which specifies the destination port
of the data as determined by the user’s protocol.
The start bit is a low bit at the beginning of each frame, which marks the start of a frame.
The SCI uses a NRZ (Non-Return-to-Zero) format, which means that in an inactive state the
SCIRX and SCITX lines will be held high. Peripherals are expected to pull the SCIRX and
SCITX lines to a high level when they are not receiving or transmitting on their respective
lines.

SCI Data Format

NRZ (non-return to zero) format

Addr/
Start LSB 2 3 4 5 6 7 MSB Parity Stop 1 Stop 2
Data

This bit present only in Address-bit mode

Communications Control Register (ScixRegs.SCICCR)


7 6 5 4 3 2 1 0
Stop Even/Odd Parity Loopback Addr/Idle SCI SCI SCI
Bits Parity Enable Enable Mode Char2 Char1 Char0

0 = 1 Stop bit 0 = Disabled 0 = Idle-line mode # of data bits = (binary + 1)


1 = 2 Stop bits 1 = Enabled 1 = Addr-bit mode e.g. 110b gives 7 data bits

0 = Odd 0 = Disabled
1 = Even 1 = Enabled

9-3

Note: If you are working on a RS232 – Interface, then all voltage-levels at the serial lines are
driven by external interface circuits, such as Texas Instruments MAX3221. A logical ‘0’ is
transmitted as a voltage between +5 and +15V, a logical ‘1’ as a negative Voltage between -
5 and -15V. On the receiver side, a voltage above +3V will be recognized as a valid ‘0’, a
voltage below -3V as a logical ‘1’.

F2833x - Serial Communication Interface 9-3


SCI Data Timing

SCI Data Timing


The SCI asynchronous communication format uses either single line (one way) or two line
(two ways) communications. In this mode, the frame consists of a start bit, one to eight data
bits, an optional even/odd parity bit, and one or two stop bits (shown in Slide 9-3). There are
eight SCICLK periods per data bit.

SCI Data Timing

• Start bit valid if 4 consecutive SCICLK periods of zero bits after falling edge
• Majority vote taken on 4th, 5th, and 6th SCICLK cycles

Majority
Vote

SCICLK
(Internal)
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2

SCIRXD

Start Bit LSB of Data

Falling Edge Detected

Note: 8 SCICLK periods per data bit


9-4

The receiver begins operation on receipt of a valid start bit. A valid start bit is identified by
four consecutive internal SCICLK periods of zero bits as shown in Slide 9-4. If any bit is not
zero, then the processor starts over and begins looking for another start bit.

For the bits following the start bit, the processor determines the bit value by making three
samples in the middle of the bits. These samples occur on the fourth, fifth, and sixth
SCICLK periods, and bit-value determination is on a majority (two out of three) basis. Slide
9-4 illustrates the asynchronous communication format for this with a start bit showing
where a majority vote is taken. Since the receiver synchronizes itself to frames, the external
transmitting and receiving devices do not have to use a synchronized serial clock. The clock
can be generated locally.

9-4 F2833x - Serial Communication Interface


SCI Multi Processor Wake Up Modes

SCI Multi Processor Wake Up Modes


Multiprocessor Wake-Up Modes
 Allows numerous processors to be hooked
up to the bus, but transmission occurs
between only two of them
 Idle-line or Address-bit modes
 Sequence of Operation
1. Potential receivers set SLEEP = 1, which disables RXINT
except when an address frame is received
2. All transmissions begin with an address frame
3. Incoming address frame temporarily wakes up all SCIs on bus
4. CPUs compare incoming SCI address to their SCI address
5. Process following data frames only if address matches

9-5

Although a SCI data transfer is usually a point-to-point communication, the F2833x SCI
interface allows two operation modes to communicate between a master and more than one
slave.

Idle-Line Wake-Up Mode


 Idle time separates blocks of frames
 Receiver wakes up with falling edge after SCIRXD
was high for 10 or more bit periods
 Two transmit address methods
 deliberate software delay of 10 or more bits
 set TXWAKE bit to automatically leave exactly
11 idle bits
Idle periods
of less than Block of Frames
10 bits

SCIRXD/ Last Data SP ST Addr SP ST Data SP ST Last Data SP ST Addr SP


SCITXD

Idle Address frame 1st data frame Idle


Period follows 10 bit Period
10 bits 10 bits
or greater or greater idle or greater

9-6

F2833x - Serial Communication Interface 9-5


SCI Multi Processor Wake Up Modes

Address-Bit Wake-Up Mode

 All frames contain an extra address bit


 Receiver wakes up when address bit detected
 Automatic setting of Addr/Data bit in frame by setting
TXWAKE = 1 prior to writing address to SCITXBUF

Block of Frames

SCIRXD/ Last Data 0 SP ST Addr 1 SP ST Data 0 SP ST Last Data 0 SP ST Addr 1 SP


SCITXD

First frame within 1st data frame


no additional
Idle Period block is Address. idle bits needed
length of no ADDR/DATA beyond stop bits
significance bit set to 1

9-7

SCI Summary
 Asynchronous communications format
 65,000+ different programmable baud rates
 Two wake-up multiprocessor modes
 Idle-line wake-up & Address-bit wake-up
 Programmable data word format
 1 to 8 bit data word length
 1 or 2 stop bits
 even/odd/no parity
 Error Detection Flags
 Parity error; Framing error; Overrun error; Break detection
 FIFO-buffered transmit and receive
 Individual interrupts for transmit and receive
 28335 include channel SCI-A and SCI-B
9-8

9-6 F2833x - Serial Communication Interface


SCI Register Set

SCI Register Set


The next slide summarizes all SCI control registers for SCI channel A. Note that there is a
second SCI channel B available in the F2833x.

SCI – A Register Set


Address Register Name
0x007050 SCICCR SCI-A communication control register
0x007051 SCICTL1 SCI-A control register 1
0x007052 SCIHBAUD SCI-A baud register, high byte
0x007053 SCILBAUD SCI-A baud register, low byte
0x007054 SCICTL2 SCI-A control register 2 register
0x007055 SCIRXST SCI-A receive status register
0x007056 SCIRXEMU SCI-A receive emulation data buffer
0x007057 SCIRXBUF SCI-A receive data buffer register
0x007059 SCITXBUF SCI-A transmit data buffer register
0x00705A SCIFFTX SCI-A FIFO transmit register
0x00705B SCIFFRX SCI-A FIFO receive register
0x00705C SCIFFCT SCI-A FIFO control register
0x00705F SCIPRI SCI-A priority control register
Note: Interface SCI – B Register Address space is 0x007750…0x00775F 9-9

SCI-A Communication Control Register


Communications Control Register (SCICCR) – 0x007050

7 6 5 4 3 2 1 0
STOP EVEN/ODD PARITY LOOP BACK ADDR/IDLE SCI SCI SCI
BITS PARITY ENABLE ENABLE MODE CHAR2 CHAR1 CHAR0

0 = 1 Stop bit 0 = Disabled 0 = Idle-line mode # of data bits = (binary + 1)


1 = 2 Stop bits 1 = Enabled 1 = Addr-bit mode e.g. 110b gives 7 data bits
0 = Odd 0 = Disabled
1 = Even 1 = Enabled

9 - 10

F2833x - Serial Communication Interface 9-7


SCI Register Set

SCI Communications Control Register (SCICCR)


The previous slide explains the setup for the SCI data frame structure. If Multi Processor
Wakeup Mode is not used, bit 3 should be cleared. This avoids the generation of an
additional address/data selection bit at the end of the data frame (see Slide 9-3). Some hosts
or other devices are not able to handle this additional bit.
The other bit fields of SCICCR can be initialized, as you like. For our lab exercises in this
chapter we will use:
• 8 data bit per character
• odd parity
• 1 Stop bit
• loop back disabled

SCI Control Register 1(SCICTL1)

SCI-A Control Register 1


Control Register 1 (SCICTL1) – 0x007051
7 6 5 4 3 2 1 0

reserved RX ERR SW reserved TXWAKE SLEEP TXENA RXENA


INT ENA RESET

0 = receiver disabled
1 = receiver enabled
0 = transmitter disabled
1 = transmitter enabled

0 = sleep mode disabled


1 = sleep mode enabled
Transmitter wakeup method select
1 = wakeup mode depends on SCICCR.3
0 = no wakeup mode
Write 0 = Reset SCI
Write 1 = release from Reset
0 = Receive Error Interrupt disabled
1 = Receive Error Interrupt enabled

9 - 11

When configuring the SCICCR register, the SCI port should first be held in an inactive
state. This is done using the SW RESET bit of the SCI Control Register 1 (SCICTL1.5).
Writing a 0 to this bit initializes and holds the SCI state machines and operating flags at their
reset condition. The SCICCR can then be configured. Afterwards, re-enable the SCI port by
writing a 1 to the SW RESET bit. At system reset, the SW RESET bit equals 0.
For our Lab exercises we will not use wakeup or sleep features (SCICTL1.3 = 0 and
SCICTL1.2 = 0).

9-8 F2833x - Serial Communication Interface


SCI Register Set

Depending on the direction of the communication we will have to enable the transmitter
(SCICTL1.1 = 1) or the receiver (SCICTL1.0 = 1) or both.
For a real project, we would need to take precautions to handle possible communication
errors. The receiver error could then be allowed to generate a receiver error interrupt request
(SCICTL1.6 = 1). To simplify our first labs, we will not use this feature. However, for a real-
world project, do NOT skip this part!

SCI Baud Rate Register

SCI-A Baud Rate


LSPCLK
, BRR = 1 to 65535
(BRR + 1) x 8
SCI baud rate =
LSPCLK
, BRR = 0
16

Baud-Select MSbyte Register (SCIHBAUD) – 0x007052


7 6 5 4 3 2 1 0
BAUD15 BAUD14 BAUD13 BAUD12 BAUD11 BAUD10 BAUD9 BAUD8
(MSB)

Baud-Select LSbyte Register (SCILBAUD) – 0x007053


7 6 5 4 3 2 1 0

BAUD7 BAUD6 BAUD5 BAUD4 BAUD3 BAUD2 BAUD1 BAUD0


(LSB)

9 - 12

The baud rate for the SCI is derived from the low speed pre-scaler (LSPCLK).
Assuming a SYSCLK frequency of 150MHz and a low speed pre-scaler initialized to “divide
by 4”, we can calculate the value for the BRR, let us say for a data rate of 9600 baud:

37.5MHz
9.600 Hz =
( BRR + 1) ∗ 8

37.5MHz
BRR = − 1 = 487.28
9.600 Hz ∗ 8
BRR must be an integer, so we have to round the result to 487. The reverse calculation with
BRR = 487 leads to the real data rate of 9605 bits/second (error = 0.05 %).

F2833x - Serial Communication Interface 9-9


SCI Register Set

SCI Control Register 2 – SCICTL2

SCI-A Control Register 2


SCICTL2 @ 0x007054

15 - 8 7 6 5-2 1 0
reserved TX reserved RX/BK TX
TXRDY
EMPTY INT ENA INT ENA

SCI RX/BK INT ENA


0 = Disable RXRDY/BRKDT interrupt
1 = Enable RXRDY/BRKDT interrupt
SCI TX EMPTY
0 = TXBUF or shift register are loaded with data
1 = Transmit buffer and shift register both empty
SCI TX READY SCI TX INT ENA
0 = SCITXBUF is full 0 = Disable TXRDY interrupt
1 = SCITXBUF is empty 1 = Enable TXRDY interrupt

9 - 13

Bit 1 and bit 0 enable or disable the SCI- transmit and receive interrupts. If interrupts are not
used, this feature can be disabled by clearing bit 1 and bit 0. In this case, we need to apply a
polling method to the transmitter status flags (SCICTL2.7 and SCICTL2.6). The flag
SCITXEMPTY waits until the whole data frame has left the SCI output, whereas flag
SCITXREADY indicates the situation that we can reload the next character into SCITXBUF,
before the previous character was physically sent.
The status flags for the receiver part can be found in the SCI receiver status register (see next
slide).
For the first basic lab exercise we will not use SCI interrupts. This means we have to rely on
the polling method described above. Later of course, we will include SCI interrupts in our
experiments.

9 - 10 F2833x - Serial Communication Interface


SCI Register Set

SCI Receiver Status Register – SCIRXST

SCI-A Receiver Status Register


SCIRXST @ 0x007055
7 6 5 4 3 2 1 0
RX RXRDY BRKDT FE OE PE RXWAKE reserved
ERROR

1 = Receiver wakeup
condition detected

1 = Parity Error detected

1 = Overrun Error detected

1 = Framing Error detected

1 = Break condition occurred


0 = no break condition
0 = no new character in SCIRXBUF
1 = new character in SCIRXBUF
0 = No error flags set
1 = Error flag(s) set

9 - 14

The SCI interrupt logic generates interrupt flags when it receives or transmits a complete
character, as determined by the SCI character length. This provides a convenient and
efficient way of timing and controlling the operation of the SCI transmitter and receiver. The
interrupt flag for the transmitter is TXRDY (SCICTL2.7), and for the receiver RXRDY
(SCIRXST.6). TXRDY is set when a character is transferred to TXSHF and SCITXBUF is
ready to receive the next character. In addition, when both the SCIBUF and TXSHF registers
are empty, the TX EMPTY flag (SCICTL2.6) is set.
When a new character has been received and shifted into SCIRXBUF, the RXRDY flag is
set. In addition, the BRKDT flag is set if a break condition occurs. A break condition is
where the SCIRXD line remains continuously low for at least ten bits after a stop bit has
been missed. The CPU to control SCI operations can poll each of the above flags, or
interrupts associated with the flags can be enabled by setting the RX/BK INT ENA
(SCICTL2.1) and/or the TX INT ENA (SCICTL2.0) bits active high.
Additional flag and interrupt capability exists for other receiver errors. The RX ERROR flag
is the logical OR of the break detect (BRKDT), framing error (FE), receiver overrun (OE),
and parity error (PE) bits. RX ERROR high indicates that at least one of these four errors has
occurred during transmission. This will also send an interrupt request to the CPU if the RX
ERR INT ENA (SCICTL1.6) bit is set.

F2833x - Serial Communication Interface 9 - 11


SCI Register Set

SCI FIFO Mode Register


SCI-A FIFO Transmit Register
SCIFFTX @ 0x00705A

SCI FIFO TX FIFO Status (read-only)


Enhancements 00000 TX FIFO empty
0 = disable TX FIFO Reset 00001 TX FIFO has 1 word
1 = enable 0 = reset (pointer to 0) 00010 TX FIFO has 2 words
SCI Reset 1 = enable operation 00011 ... TX FIFO has 3 words
... ...
0 = reset 10000 TX FIFO has 16 words
1 = enable operation
15 14 13 12 11 10 9 8
TXFIFO
SCIRST SCIFFENA TXFFST4 TXFFST3 TXFFST2 TXFFST1 TXFFST0
RESET

7 6 5 4 3 2 1 0
TXFFINT
TXFFINT TXFFIENA TXFFIL4 TXFFIL3 TXFFIL2 TXFFIL1 TXFFIL0
CLR

TX FIFO TX FIFO TX FIFO TX FIFO Interrupt Level


Interrupt Interrupt Interrupt
Flag (read-only) Flag Clear (on match) Interrupt when TXFFST4-0
0 = not occurred 0 = no effect Enable and TXFFIL4-0 match
1 = occurred 1 = clear 0 = disable
1 = enable 9 - 15

The F2833x SCI is equipped with an enhanced buffer mode with 16 levels of FIFO for the
transmitter and receiver. We will use this enhanced mode at the end of the lab exercise series
of this chapter.

SCI-A FIFO Receive Register


SCIFFRX @ 0x00705B

RX FIFO Status (read-only)


RX FIFO RX FIFO 00000 RX FIFO empty
Overflow Overflow RX FIFO Reset 00001 RX FIFO has 1 word
Flag (read-only) Flag Clear 0 = reset (pointer to 0) 00010 RX FIFO has 2 words
0 = no overflow 0 = no effect 1 = enable operation 00011 RX FIFO has 3 words
1 = overflow 1 = clear ... ... ...
10000 RX FIFO has 16 words

15 14 13 12 11 10 9 8
RXFF- RXFF- RXFIFO
RXFFST4 RXFFST3 RXFFST2 RXFFST1 RXFFST0
OVF OVF CLR RESET

7 6 5 4 3 2 1 0
RXFFINT
RXFFINT RXFFIEN RXFFIL4 RXFFIL3 RXFFIL2 RXFFIL1 RXFFIL0
CLR

RX FIFO RX FIFO RX FIFO RX FIFO Interrupt Level


Interrupt Interrupt Interrupt
Flag (read-only) Flag Clear (on match) Interrupt when RXFFST4-0
0 = not occurred 0 = no effect Enable and RXFFIL4-0 match
1 = occurred 1 = clear 0 = disable
1 = enable 9 - 16

9 - 12 F2833x - Serial Communication Interface


SCI Register Set

SCI-A FIFO Control Register


SCIFFCT @ 0x00705C

Auto Baud Auto Baud


detection detection CDC calibrate ‘A’
Flag (read-only) Flag Clear 0 = disabled auto-baud alignment
0 = not complete 0 = no effect 1 = enables auto-baud alignment
1 = complete 1 = clear

15 14 13 12 11 10 9 8
ABD
ABD CDC reserved
CLR

7 6 5 4 3 2 1 0

FFTXDLY
Time delay between every transfer from FIFO
to transmit shift register
in number of SCI baud clock cycles
( 0 to 255 )
9 - 17

In the enhanced feature set, the SCI module supports auto baud-detect logic in hardware. The
following section explains the enabling sequence for auto baud-detect feature. Auto Baud is
a feature, which can be used to adjust the data rate of the F2833x to the transmission speed
of a host device. If the host sends character ‘A’ or ‘a’ the auto baud unit will lock this cha-
racter and set the internal baud rate registers accordingly.

To use this feature, the following sequence needs to be followed:

1. Enable auto baud-detect mode for the SCI by setting the CDC bit (bit 13) in
SCIFFCT and clearing the ABD bit (Bit 15) by writing a 1 to ABDCLR bit (bit 14).
2. Initialize the baud register to be 1 or less than a baud rate limit of 500 Kbps.
3. Allow SCI to receive either character ‘A’ or ‘a’ from a host at the desired baud rate.
If the first character is either 'A' or 'a', the auto baud- detect hardware will detect the
incoming baud rate and set the ABD bit.
4. The auto-detect hardware will update the baud rate register with the equivalent baud
value in hex. The logic will also generate an interrupt to the CPU.
5. Respond to the interrupt clear ADB bit by writing a 1 to ABD CLR (bit 14) of
SCIFFCT register and disable further auto baud locking by clearing CDC bit by
writing a 0.
6. Read the receive buffer for character ‘A’ or ‘a’ to empty the buffer and buffer status.
7. If ABD is set while CDC is 1, which indicates auto baud alignment, the SCI transmit
FIFO interrupt will occur (TXINT). After the interrupt service CDC bit must be
cleared by software.

In the first lab exercises we will not use the auto baud feature. However, if you laboratory
time permits, you can add the auto baud unit into your experiments.

F2833x - Serial Communication Interface 9 - 13


Lab 9_1: Basic SCI – Transmission

Lab 9_1: Basic SCI – Transmission


SCI Example 9_1: transmit a text - message

 Lab 9_1: Basic SCI Communication

 Send a single line text message from F28335 to a PC’s COM-port.


 Connect the RS232 - Connector (J12) of the Peripheral Explorer
Board with a standard DB9 - cable (1:1) to a serial COM –port of
the PC.
 Periodic transmission of the message every 2 seconds.
 No SCI interrupt services in this lab.
 After transmission of the first character we just poll the
transmission ready flag (TXEMPTY) before loading the next
character into the transmit buffer - and wait again.
 A Windows Terminal program is used as the counterpart from the
PC’s-side and must be initialized properly for correct
function(9,600 bit/s, odd Parity, no protocol).

9 - 18

Objective
The objective of this lab is to establish an SCI transmission between the F28338x and a serial
port of a PC.
The SCI-A communication channel is used to send data from F28335 to a host, using RS232
voltage levels. The F28335 controlCARD has an onboard RS232-transceiver and the signals
Tx and Rx are available at header J12 of the Peripheral Explorer Board. Plug in the serial
cable provided to header J12 making sure the red wire aligns with the Rx pin on the
Peripheral Explorer Board.
A standard DB9 cable (1:1) with male and female connectors can be used to connect to the
host, for example to a COMx – interface of a PC. On the host side you need a terminal
program (e.g. Windows XP Hyper Terminal Program or a freeware tool for XP and Vista,
such as “Hercules” (www.HW-group.com). The setup for the communication is as follows:

• 9600 bit/second
• 8 characters
• odd parity
• 1 stop bit
• no protocol
The task for the F2833x is to transmit a text message, e.g. “The F28335 – UART is fine!\n\r”
periodically. No interrupt services are used for this first and basic test.

9 - 14 F2833x - Serial Communication Interface


Lab 9_1: Basic SCI – Transmission

Procedure

Open Project “Lab9.pjt”


1. Unzip the provided file “labs_09.zip” and expand the files in
C:\DSP2833x_V4\Labs\Lab9. Next, open the project “Lab9_1.pjt”

Modify Source Code


2. Open the file “Lab9_1.c” to edit: double click on “Lab9_1.c” inside the project
window.
3. Inside function “Gpio_select()”modify multiplex register GPAMUX2 to use the two
SCI-signals “SCIRXDA” and “SCITXDA” for GPIO28 and GPIO29:
GpioCtrlRegs.GPAMUX2.bit.GPIO28 = ?; // SCIRXDA
GpioCtrlRegs.GPAMUX2.bit.GPIO29 = ?; // SCITXDA
4. At the beginning of “main()”, define a string variable with the following message:
char message[] = {"The F28335 - UART is fine !\n\r"};
5. Also at the beginning of “main()”, add an integer variable “index”. We will use this
variable to address the next character of the text message:
unsigned int index = 0;
6. In “main()”, right after the function call of “Gpio_select()”, add a function call of
“SCIA_Init()”. Also add a function prototype at the beginning of your code file
“Lab9_1.c”.
7. At the end of your code, add the definition of function “SCIA_Init()”.
Inside this function, initialize the following registers:

• SCICCR:
o 1 stop bit, no loop back, odd parity, 8 bits per character

• SCICTL1:
o Enable TX- and RX - output
o Disable RXERR INT, SLEEP and TXWAKE

• SCIHBAUD / SCILBAUD:
o BRR = (LSPCLK/(SCI_Baudrate *8)) – 1
o Example: assuming LSPCLK = 37.5MHz and SCI_Baudrate =
9600 the SCIBRR must be set to 487. Split this number into a lower
8-bit part and a higher 8-bit part and load the registers.

Finish the main loop


8. Now we can finalize the while(1)-loop of “main()”. Recall, we have to add the
following actions:

F2833x - Serial Communication Interface 9 - 15


Lab 9_1: Basic SCI – Transmission

• Load the next character out of the string variable “message[]” into
SciaRegs.SCITXBUF.
• Wait (poll) bit “TXEMPTY” of register SCICTL2. It will be set to 1 when the
character has been sent. The bit will be cleared automatically when the next
character is written into SCITXBUF.
• Increment variable “index” to address the next character of the string.
• Add a test if the whole text message has been sent (Hint: Recall that the end of
a string variable is always the hidden end of string character ‘\0’). In case your
program has reached the end of the message:
o Reset variable “index” to 0 in preparation of the next transmission
sequence.
o Use CPU Timer 0 and install a wait – loop of 2 seconds (Hint: CPU
Timer 0 has been initialized to 50 milliseconds. Each Interrupt Service
Routine increments variable “CpuTimer0.InterruptCount”; therefore you
can wait until this variable equals 40. While you wait, service the
watchdog with 0xAA).
o At the end of your wait – code, reset variable
“CpuTimer0.InterruptCount” to zero in preparation of the next 2
seconds waiting loop.

Build, Load and Run


9. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

and watch the tools run in the build window. If you get errors or warnings debug as
necessary.

10. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.


11. The PC terminal program should display an incoming text message every 2 seconds.
If not  Debug!

End of Lab 9_1

9 - 16 F2833x - Serial Communication Interface


Lab 9_2: Interrupt SCI – Transmission

Lab 9_2: Interrupt SCI – Transmission


More SCI Examples

 Lab 9_2: SCI Transmit


 SCI – TX interrupt service
 CPU Timer 0 interrupt service

 Lab 9_3: SCI FIFO Transmit Interrupt


 TX FIFO Interrupt Service to send 16 characters

 Lab 9_4: SCI Transmit and Receive


 TX and RX FIFO Interrupt services
 F28335 to wait for “Texas” and answer with
“Instruments”
9 - 19

The objective of the next lab exercise is to improve Lab 9_1 by including both the
SCI – Transmit interrupt to service an empty transmit buffer. Use your code from
Lab9_1 as a starting point.

Procedure

Open Files, Modify Project


1. In project “Lab9” open file “Lab9_1.c” and save it as “Lab9_2.c”
2. Exclude file “Lab9_1.c” from build. Use a right mouse click at file “Lab9_1.c”, and
enable “Exclude File(s) from Build”.

Modify Source Code


3. We have to modify the SCI initialization function “SCIA_Init()”. It is not a big
change, the only modification is that for this test we have to enable the SCI-Transmit
Interrupt:

SciaRegs.SCICTL2.bit.TXINTENA = 1;
4. The SCI Transmit Interrupt must be also enabled inside the PIE unit and the address of
the interrupt service routine must be written into the PIE vector table. We already have
some code lines to change such entries for CpuTimer0 (TINT0). Please add the two
following lines into your code:

F2833x - Serial Communication Interface 9 - 17


Lab 9_2: Interrupt SCI – Transmission

PieVectTable.SCITXINTA = &SCIA_TX_isr;
PieCtrlRegs.PIEIER9.bit.INTx2 = 1;
5. Also change the setup for register “IER”. For this exercise we have to enable lines 1
and 9!
6. If the SCI-TX interrupt is enabled we have to provide an interrupt service routine
“SCIA_TX_isr()”. At the top of your code add a function prototype and at the very
end of the code add the definition of this function. What should be done inside this
function? Answer:
• Load the next character of the message into SCITXBUF, if index has not already
reached the last character of the text message; increment variable “index”.
• If variable “index” points beyond the last character of the message, do NOT load
anything into SCITXBUF. Transmission of the message is finished.
• In every single call of this function acknowledge it’s call by resetting the
PIEACK-register:

PieCtrlRegs.PIEACK.all = 0x0100;
7. Because the string variable and the variable “index” are now used both in main and
“SCIA_TX_isr” they must be defined as global variables. To make the two variables
global, move the definition of the variables from main to the beginning of your code:

char message[ ]= {" The F28335 - UART ISR is fine !\n\r"};


int index =0;
8. Now it is time change the while(1) – loop of “main()”. We do not need the while –
wait line to wait for TXEMPTY == 1 from lab 9_1 – because we now will use
interrupt services to reload TXBUF as soon as the previous character has been
transmitted.
We can also remove the test code, which we used in lab 9_1 to test for the end of
message character (‘\0\’) – because this will be also done by the interrupt service
routine.
We have to keep the wait construction for a time interval of 2 seconds in the while(1)-
loop of “main()”.
After the wait – loop reset variables “CpuTimer0.InterruptCount” and “index” both to
0.
Now the code is prepared for the next repetition of the while(1)-loop.

Build, Load and Run


9. Rebuild the project (Project  Rebuild All), debug the project (Target  Debug
Active Project) and switch to the “Debug” – perspective.

9 - 18 F2833x - Serial Communication Interface


Lab 9_2: Interrupt SCI – Transmission

10. As we have done in Lab9_1, open a Terminal Program. Use 9600 bit/s, odd parity, 1
stop bit and no protocol (or no handshake) as parameters. Every 2 seconds you should
receive the text message from the DSP.

If your code does not work try to debug systematically.


• Does the CPU core timer work?
• Is the CPU core timer interrupt service called periodically?
• Is the SCITX interrupt service called?

Try to watch important variables and set breakpoints as needed.

Optional Exercise
11. Instead of transmitting the text message to the PC your task is now to transmit the
current status of the Hexadecimal Encoder input (GPIO12- GPIO15), which is an
integer value, to the PC. Recall, to use a PC-Terminal program to display data, you
must transmit ASCII-code characters. To convert a long integer into an ASCII-string
we can use function a standard C-function “ltoa” (see help menu of CCS).

End of Lab 9_2

F2833x - Serial Communication Interface 9 - 19


Lab 9_3: SCI – FIFO Transmission

Lab 9_3: SCI – FIFO Transmission


The objective of this lab is to improve Lab 9_2 by using the transmit FIFO capabilities of the
F2833x. Instead of generating a lot of SCI – transmit interrupts to send the whole text
message we now will use a type of ‘burst transmit’ technique to fill up to 16 characters into
the SCI transmit FIFO. This will reduce the number of SCI-interrupt services from 16 to 1
per message!
Use your code from file “Lab9_2.c” as the starting point.

Procedure

Open Files, Modify Project File


1. In project “Lab9” open file “Lab9_2.c” and save it as “Lab9_3.c”
2. Exclude file “Lab9_2.c” from build. Use a right mouse click at file “Lab9_2.c”, and
enable “Exclude File(s) from Build”.

Modify Source Code


3. Open Lab9_3.c to edit: double click on “Lab9_3.c” inside the project window.
Modify the SCI Initialization in function “SCIA_Init()”. Add the Initialization for
register “SCIFFTX”. Include the following:
• Relinquish FIFO unit from reset
• Enable FIFO- Enhancements
• Enable TX FIFO Operation
• Clear TXFFINT-Flag
• Enable TX FIFO match
• Set FIFO interrupt level to interrupt, if FIFO is empty (0)
4. Change the contents of the variable “message[]” from “The F28335 - UART ISR is
fine !\n\r” to “BURST-Transmit\n\r”. The length of the string is now limited to 16
characters and using the TX-FIFO, we can transmit the whole string in one single SCI
interrupt service routine.
5. Search for function “SCIA_TX_isr()” and modify it. Recall that this service will be
called when the FIFO interrupt level was hit. Because we have set this level to 0 we
can load 16 characters into the TX-FIFO:

for(i=0;i<16;i++) SciaRegs.SCITXBUF = message[i];


Note: Variable i should be a local variable inside “SCIA_TX_isr()”. Also, do NOT
remove the PIEACK- reset instruction at the end of this function!
6. Modify the while(1)-loop of “main()”. We still will use the CPU Core Timer 0 as our
time base. It is still initialized to increment the variable “CpuTimer0.InterruptCount”
once every 50ms. There is no need to change our wait construction to wait for 40
increments (equals to 2 seconds).

9 - 20 F2833x - Serial Communication Interface


Lab 9_3: SCI – FIFO Transmission

Delete the next two lines of the old code:


index = 0;
SciaRegs.SCITXBUF = message[index++];
The difference between Lab9_2.c and Lab9_3.c is the initialization of the SCI-unit. In
this lab, we have enabled the TX-FIFO interrupt to request a service when the FIFO-
level is zero. This will be true immediately after the initialization of the SCI-unit and
will cause the first TX-interrupt! The next TX-interrupt will be called only after
setting the TX FIFO INT CLR – bit to 1, clears the TX FIFO INT FLAG. If we
execute this clear instruction every 2 seconds we will allow the next TX FIFO
transmission to take place immediately. To do so, add the following instruction:

SciaRegs.SCIFFTX.bit.TXINTCLR = 1;
That’s it.

Build, Load and Test


7. Apply all the commands needed to translate and debug your project. Meanwhile you
should be familiar with the individual steps to do so; therefore we skip a detailed
procedure. If you are successful, you should receive the string every 2 seconds at the
hyper terminal window. If not – debug!

8. Summary: The big improvement of this Lab9_3 is that we reduced the number of
interrupt services to transmit a 16-character string from 16 services to 1 service. This
adds up to a considerable amount of time that can be saved! The exercise has shown
the advantage of the F2833x SCI-transmit FIFO enhancement compared to a standard
UART interface.

END of LAB 9_3

F2833x - Serial Communication Interface 9 - 21


Lab 9_4: SCI – Receive & Transmit

Lab 9_4: SCI – Receive & Transmit


The objective of this final exercise is to add the SCI receiver. Lab9_4 should
wait until the message “Texas” has been received and answer transmitting
“Instruments” back to the PC.
Use your code from Lab9_3 as a starting point.

Procedure

Open Files, Modify Project File


1. In project “Lab9” open file “Lab9_3.c” and save it as “Lab9_4.c”
2. Exclude file “Lab9_3.c” from build. Use a right mouse click at file “Lab9_3.c”, and
enable “Exclude File(s) from Build”.

Modify Source Code


3. Open file “Lab9_4.c” to edit.
First we have to remove everything that deals with CPU Core Timer0 – we do not
need a timer for this exercise.

• Remove prototype and definition of function “cpu_timer0_isr”.

• In main, remove the interrupt vector table load instruction:


EALLOW;
PieVectTable.TINT0 = &cpu_timer0_isr;
EDIS;
• Remove the function calls:
InitCpuTimers();
ConfigCpuTimer(&CpuTimer0, 150, 50000);
and the interrupt enable lines:

PieCtrlRegs.PIEIER1.bit.INTx7 = 1;
• Remove the start instruction for CpuTimer0:

CpuTimer0Regs.TCR.bit.TSS = 0;
• Change the interrupt enable register to:

IER = 0x100;
• In the while(1)-loop of “main()” remove everything. Replace it by new code:
while(1)
{

9 - 22 F2833x - Serial Communication Interface


Lab 9_4: SCI – Receive & Transmit

EALLOW;
SysCtrlRegs.WDKEY = 0x55; // service watchdog #1
SysCtrlRegs.WDKEY = 0xAA; // service watchdog #2
EDIS;
}
All activities will be done by interrupt service routines, nothing to do in the main loop
but to service the watchdog!
4. Change the contents of the variable “message[ ]” to “ Instruments! \n\r”. Note: Make
sure to have 16 characters in this text message; ‘\n’ and ‘\r’ count as single characters!
5. Now we have to introduce a new interrupt service routine for the SCI receiver, called
“SCIA_RX_isr()”. Declare its prototype at the beginning of your code:

interrupt void SCIA_RX_isr(void);


6. Replace the entry for this function inside the PIE vector table. Add this line directly
after the entry-instruction for TXAINT:

PieVectTable.RXAINT = &SCIA_RX_isr;
7. Enable the PIE interrupt for RXAINT:

PieCtrlRegs.PIEIER9.bit.INTx1 = 1;
8. Modify the initialization function for the SCI: “SCIA_Init()”.

• Inside register “SCICTL2” set bit “RXBKINTENA” to 1 to enable the receiver


interrupt.

• For register “SCIFFTX”, do NOT enable the TX FIFO operation (bit 13) yet. It
will be enabled later, when we have something to transmit.

• Add the initialization for register “SCIFFRX”. Recall, we wait for 5 characters
“Texas”, so why not initialize the FIFO receive interrupt level to 5? This setup
will cause the RX interrupt when at least 5 characters have been received.
9. At the end of your source code add interrupt function “SCIA_RX_isr()”.

• What should be done inside? Well, this interrupt service will be requested if 5
characters have been received. First we need to verify that the 5 characters
match the string “Texas”.

• With five consecutive read instructions of register


“SciaRegs.SCIRXBUF.bit.RXDT” you can empty the FIFO into a local variable
“buffer[16]”.

• The C standard string compare function “strncmp()” can be used to compare


two strings of a fixed length. The lines:
if( strncmp(buffer, “Texas” , 5) == 0)
{
SciaRegs.SCIFFTX.bit.TXFIFORESET = 1;
SciaRegs.SCIFFTX.bit.TXINTCLR = 1;

F2833x - Serial Communication Interface 9 - 23


Lab 9_4: SCI – Receive & Transmit

}
will compare the first 5 characters of “buffer” with “Texas”. If they match the
two next instructions will start the SCI Transmission of “ Instruments\n\r” with
the help of the TX-interrupt service.

• At the end of interrupt service routine we need to reset the RX FIFO, clear the
RX FIFO Interrupt flag and acknowledge the PIE interrupt:

SciaRegs.SCIFFRX.bit.RXFIFORESET = 0; // reset pointer


SciaRegs.SCIFFRX.bit.RXFIFORESET = 1; // enable op.
SciaRegs.SCIFFRX.bit.RXFFINTCLR = 1; // reset RX int
PieCtrlRegs.PIEACK.all = 0x0100; // acknowledge PIE
10. Delete global variable “index”.
11. At the beginning of “Lab9_4.c”, add an include instruction for header file “string.h”:

#include <string.h>
That’s it.

Build, Load and Test


12. Apply all the commands needed to translate and debug your project.
13. Start your Terminal program and type in the text “Texas”. The F2833x will respond
with the string “ Instruments\n\r”. If not  debug!

9 - 24 F2833x - Serial Communication Interface


Optional Exercise 9_5

Optional Exercise 9_5


DSC – Junkies only!  Remote Control of the F2833x by a PC!
Try to combine the “binary counter” exercise “Lab6.c” with the SCI-lab “Lab9_4.c”. Let the
PC send a string with a numerical value and use this value to control the speed of the “binary
counter”!
If a new value was received by the DSP it should answer back to the PC with a text like
“control value xxx received”.
Note: The C standard function “atoi” can be used to convert an ASCII-string into a
numerical value (see Code Composer Studio Help for details).

F2833x - Serial Communication Interface 9 - 25


Optional Exercise 9_5

This page has been left blank intentionally.

9 - 26 F2833x - Serial Communication Interface


F2833x Serial Peripheral Interface

Introduction
The TMS320F2833x contains built-in features that allow several methods of communication
and data exchange between the F2833x and other devices. In the previous chapter we
discussed the asynchronous UART interface SCI. Chapter 10 introduces a first synchronous
interface, the Serial Peripheral Interface (SPI). More synchronous interface techniques, such
as McBSP and CAN, will be discussed in later chapters.
The SPI module is a synchronous serial I/O port that shifts a serial bit stream of variable
length and data rate between the ‘F2833x’ and other peripheral devices. Here “synchronous”
means that the data transmission is synchronized to a clock signal.
During data transfers, one SPI device must be configured as the transfer MASTER, and all
other devices configured as SLAVES. The master drives the transfer clock signal for all
SLAVES on the bus. SPI communication can be implemented in any of three different
modes:
• MASTER sends data, SLAVES send dummy data
• MASTER sends data, one SLAVE sends data
• MASTER sends dummy data, one SLAVE sends data

SPI Data Flow

 Simultaneous transmits and receive


 SPI Master provides the clock signal

SPI Device #1 - Master SPI Device #2 - Slave


shift shift
SPI Shift Register SPI Shift Register

clock

10 - 2

F2833x - Serial Peripheral Interface 10 - 1


Module Topics

Module Topics
F2833x Serial Peripheral Interface ........................................................................................................ 10-1
Introduction ........................................................................................................................................... 10-1
Module Topics ....................................................................................................................................... 10-2
Serial Peripheral Interface (SPI) - Overview ........................................................................................ 10-3
SPI Data Transfer ................................................................................................................................. 10-4
SPI Register Set ..................................................................................................................................... 10-5
SPI Confguration Control Register - SPICCR .................................................................................. 10-6
SPI Operation Control Register - SPICTL ........................................................................................ 10-6
SPI Receive Emulation Buffer Register - SPIRXEMU .................................................................... 10-6
SPI Baud Rate Register - SPIBRR .................................................................................................... 10-7
SPI Status Register - SPISTS ............................................................................................................ 10-7
SPI FIFO Transmit Register ............................................................................................................. 10-8
SPI Summary ......................................................................................................................................... 10-9
SPI Lab Exercises ................................................................................................................................. 10-9

10 - 2 F2833x - Serial Peripheral Interface


Serial Peripheral Interface (SPI) - Overview

Serial Peripheral Interface (SPI) - Overview


In its simplest form, the SPI can be thought of as a programmable shift register. Data bits are
shifted in and out of the SPI through the SPIDAT register. Two more registers configure the
programming interface. To transmit a data frame, we have to write the 16-bit message into
the SPITXBUF buffer. A received frame will be read by the SPI directly into the SPIRXBUF
buffer. For our lab exercises, this means we write directly to SPITXBUF and we read from
SPIRXBUF.
There are two operating modes for the SPI: “basic mode” and “enhanced FIFO-buffered
mode”. In “basic mode”, a receive operation is double-buffered, that is the CPU need not
read the current received data from SPIRXBUF before a new receive operation can be
started. However, the CPU must read SPIRXBUF before the new operation is complete or a
receiver-overrun error will occur. Double-buffered transmit is not supported in this mode;
the current transmission must be complete before the next data character is written to
SPITXDAT or the current transmission will be corrupted. The Master can initiate a data
transfer at any time because it controls the SPICLK signal.

SPI Block Diagram


C28x - SPI Master Mode Shown
SPISIMO
RX FIFO_0

RX FIFO_15
SPIRXBUF.15-0

MSB LSB
SPIDAT.15-0 SPISOMI

SPITXBUF.15-0
TX FIFO_0

TX FIFO_15

LSPCLK baud clock clock


rate polarity phase SPICLK
10 - 3

In “enhanced FIFO - buffered mode” we can build up to 16 levels of transmit and receive
FIFO memory. Again, our program interfaces to the SPI unit are the registers SPITXBUF
and SPIRXBUF. This expands the SPI’s buffer capacity for receive and transmit by up to 16
times. In this mode we are also able to specify an interrupt level that depends on the filled
state of the two FIFOs.

F2833x - Serial Peripheral Interface 10 - 3


SPI Data Transfer

SPI Data Transfer


As you can see from the previous slide, the SPI master is responsible for generating the data
rate of the communication. Beeing derived from the internal low speed clock prescaler
(LSPCLK), we can specify an individual baud rate for the SPI. Because not all SPI devices
are interfaced in the same way, we can adjust the shape of the clock signal by two more bits,
“clock polarity” and “clock phase”. Strictly speaking, the SPI is not a standard; slave
devices such as EEPROMs, DACs, ADCs, Real-time clocks and temperature sensors do
have different requirements for the interface timing. For this reason, TI includes options to
adjust the SPI timing.
Data transmission always starts with the MSB (most significant bit) out of SPIDAT first and
received data will be shifted into the device, also with MSB first. Both transmitter and
receiver perform a left shift with every SPI clock period. For frames of less than 16 bits, data
to be transmitted must be left justified before transmission starts. Received frames of less
than 16 bits must be masked by user software to suppress unused bits.

SPI Data Character Justification

 Programmable data
length of 1 to 16 bits
 Transmitted data of less SPIDAT – Device #1
than 16 bits must be left 11001001XXXXXXXX
justified
 MSB transmitted first

 Received data of less


than 16 bits are right
justified SPIDAT - Device #2
XXXXXXXX11001001
 User software must
mask-off unused MSB’s

10 - 4

10 - 4 F2833x - Serial Peripheral Interface


SPI Register Set

SPI Register Set


The next slide summarizes all SPI control registers. Some of the devices in the C2000 family
feature more than one SPI channel, numbered A, B, C and so on. Therefore the register
names of the first SPI are expanded with an ‘A’.

SPI-A Registers
Address Register Name
0x007040 SPICCR SPI-A configuration control register
0x007041 SPICTL SPI-A operation control register
0x007042 SPISTS SPI-A status register
0x007044 SPIBRR SPI-A baud rate register
0x007046 SPIRXEMU SPI-A receive emulation buffer register
0x007047 SPIRXBUF SPI-A serial receive buffer register
0x007048 SPITXBUF SPI-A serial transmit buffer register
0x007049 SPIDAT SPI-A serial data register
0x00704A SPIFFTX SPI-A FIFO transmit register
0x00704B SPIFFRX SPI-A FIFO receive register
0x00704C SPIFFCT SPI-A FIFO control register
0x00704F SPIPRI SPI-A priority control register

10 - 5

SPI-A Configuration Control Register


SPICCR @ 0x007040

15-8 7 6 5-4 3 2 1 0
reserved reserved

SPI CHAR.3-0
character length = number + 1
e.g. 0000b ⇒ length = 1
1111b ⇒ length = 16
CLOCK POLARITY
0 = rising edge data transfer
1 = falling edge data transfer

SPI SW RESET
0 = SPI flags reset
1 = normal operation
10 - 6

F2833x - Serial Peripheral Interface 10 - 5


SPI Register Set

SPI Confguration Control Register - SPICCR


It is good practice to RESET the SPI unit at the beginning of the initialization procedure.
This is done by clearing bit 7 (SPI SW RESET) to 0 using a first instruction, followed by
setting it back to 1 using a second instruction. Bit 6 selects the active clock edge to declare
the data as valid. This setup depends on the particular SPI - device. Bits 3...0 define the
character length of the SPI-frame.

SPI Operation Control Register - SPICTL


SPI-A Operation Control Register
SPICTL @ 0x007041

OVERRUN INT ENABLE MASTER/SLAVE


0 = disabled 0 = slave SPI INT ENABLE
1 = enabled 1 = master 0 = disabled
1 = enabled

15-5 4 3 2 1 0
reserved

CLOCK PHASE TALK


0 = no CLK delay 0 = transmission disabled,
1 = CLK delayed 1/2 cycle SPISIMO at high impedance
1 = transmission enabled

10 - 7

Bit 4 and bit 0 enable or disable the SPI- interrupts; Bit 4 enables the receiver’s overflow
interrupt. Bit 2 defines the operating mode for the F2833x to be master or slave of the SPI-
chain. With the help of bit 3 we can implement another half clock cycle delay between the
active clock edge and the point of time, when data are valid. Again, this bit depends on the
particular SPI-device. Bit 1 controls whether the F2833x listens only (bit 1 = 0) or if it is
initialized as receiver and transmitter (bit 1 = 1).

SPI Receive Emulation Buffer Register - SPIRXEMU


By reading register SPIRXBUF the corresponding interrupt flag SPI INT FLAG (SPISTS.6)
is cleared automatically to allow a next character to be received. However, when we read
SPIRXBUF just for test purposes, e.g. in a watch window, we would not want to have this
bit cleared automatically. Therefore SPIRXEMU contains the same received data as
SPIRXBUF, but reading SPIRXEMU does not clear the SPI INT FLAG bit. So every emula-
tor access to SPIRXBUF actually reads data from SPIRXEMU without clearing the SPI INT
FLAG.

10 - 6 F2833x - Serial Peripheral Interface


SPI Register Set

SPI Baud Rate Register - SPIBRR


SPI-A Baud Rate Register
SPIBRR @ 0x007044

Need to set this only when in master mode!


15-7 6-0
reserved SPI BIT RATE

LSPCLK
, SPIBRR = 3 to 127
(SPIBRR + 1)
SPICLK signal =
LSPCLK
, SPIBRR = 0, 1, or 2
4

10 - 8

Clock base for the SPI baud rate selection is the Low speed Clock Prescaler (LSPCLK).

SPI Status Register - SPISTS


SPI-A Status Register
SPISTS @ 0x007042

15-8 7 6 5 4-0
reserved reserved

TX BUF FULL (read only)


• Set to 1 when char written
to SPITXBUF
• Cleared when char in SPIDAT
SPI INT FLAG (read only)
• Set to 1 when transfer completed
• Interrupt requested if SPI INT ENA
bit set (SPICTL.0)
• Cleared by reading SPIBRXUF
RECEIVER OVERRUN (read/clear only)
• Set to 1 if next reception completes before SPIRXBUF read
• Interrupt requested if OVERRUN INT ENA bit set (SPICTL.4)
• Cleared by writing a 1

10 - 9

F2833x - Serial Peripheral Interface 10 - 7


SPI Register Set

SPI FIFO Transmit Register


SPI-A FIFO Transmit Register
SPIFFTX @ 0x00704A

TX FIFO Status (read-only)


SPI FIFO 00000 TX FIFO empty
TX FIFO Reset 00001 TX FIFO has 1 word
Enhancements 0 = reset (pointer to 0)
0 = disable 00010 TX FIFO has 2 words
1 = enable operation 00011 TX FIFO has 3 words
... ...
1 = enable ...
10000 TX FIFO has 16 words

15 14 13 12 11 10 9 8
TXFIFO
reserved SPIFFEN TXFFST4 TXFFST3 TXFFST2 TXFFST1 TXFFST0
RESET

7 6 5 4 3 2 1 0
TXFFINT
TXFFINT TXFFIEN TXFFIL4 TXFFIL3 TXFFIL2 TXFFIL1 TXFFIL0
CLR

TX FIFO TX FIFO TX FIFO TX FIFO Interrupt Level


Interrupt Interrupt Interrupt
Flag (read-only) Flag Clear (on match) Interrupt when TXFFST4-0
0 = not occurred 0 = no effect Enable and TXFFIL4-0 match
1 = occurred 1 = clear 0 = disable
1 = enable 10 - 10

SPI-A FIFO Receive Register


SPIFFRX @ 0x00704B

RX FIFO Status (read-only)


RX FIFO RX FIFO 00000 RX FIFO empty
Overflow Overflow RX FIFO Reset 00001 RX FIFO has 1 word
Flag (read-only) Flag Clear 0 = reset (pointer to 0) 00010 RX FIFO has 2 words
0 = no overflow 0 = no effect 1 = enable operation 00011 RX FIFO has 3 words
1 = overflow 1 = clear ... ... ...
10000 RX FIFO has 16 words

15 14 13 12 11 10 9 8
RXFF- RXFF- RXFIFO
RXFFST4 RXFFST3 RXFFST2 RXFFST1 RXFFST0
OVF OVF CLR RESET

7 6 5 4 3 2 1 0
RXFFINT
RXFFINT RXFFIEN RXFFIL4 RXFFIL3 RXFFIL2 RXFFIL1 RXFFIL0
CLR

RX FIFO RX FIFO RX FIFO RX FIFO Interrupt Level


Interrupt Interrupt Interrupt
Flag (read-only) Flag Clear (on match) Interrupt when RXFFST4-0
0 = not occurred 0 = no effect Enable and RXFFIL4-0 match
1 = occurred 1 = clear 0 = disable
1 = enable 10 - 11

The FIFO operation of the SPI is controlled by bit 14 as master switch. The SPI-Transmit
FIFO interrupt service call depends on the match between TX FIFO Status and TX FIFO
Interrupt Level. The TX FIFO Reset can be used to reset the FIFO state machine (bit13= 0)
and to re-enable it (bit 13=1).

10 - 8 F2833x - Serial Peripheral Interface


SPI Summary

SPI Summary
SPI Summary
 Provides synchronous serial
communications
 Two wire transmit or receive (half duplex)
 Three wire transmit and receive (full duplex)
 Software configurable as master or slave
 C28x provides clock signal in master mode
 Data length programmable from 1-16 bits
 125 different programmable baud rates

10 - 12

SPI Lab Exercises


At the Peripheral Explorer board the SPI-A channel is hard wired to the control lines of an
audio codec device TLV320AIC23 (U7), which will be discussed at the end of the McBSP-
chapter. In this context we will also discuss the setup of channel SPI-A.
Because of the hard wired SPI-A lines it is not possible to connect other SPI devices, such as
EEPROMs, FRAMs, DACs or real-time clocks to the Peripheral Explorer Board.
Unfortunately, we cannot perform an exercise with SPI-EEPROMs or DACs. However, if
you use the previous Version 2.0 of this teaching CD-ROM based on the F2812, you will be
able to perform an exercise with a SPI-EEPROM and a SPI-DAC.
Note: The Peripheral Explorer Board has an onboard SPI-EEPROM AT25256 (U6).
However, this device has been wired to McBSP channel B. The Interface McBSP is able to
operate in a “SPI-Emulation” operating mode, which will be also used at the end of the
McBSP chapter to access the SPI-EEPROM.

F2833x - Serial Peripheral Interface 10 - 9


SPI Lab Exercises

This page is blank.

10 - 10 F2833x - Serial Peripheral Interface


F2833x Controller Area Network

Introduction
One of the most successful stories of the developments in automotive electronics in the last
decade of the 20th century has been the introduction of distributed electronic control units in
passenger cars. Customer demands, the dramatic decline in costs of electronic devices and
the amazing increase in the computing power of microcontrollers has led to more and more
electronic applications in a car. Consequently, there is a strong need for all those devices to
communicate with each other, to share information or to co-ordinate their interactions.
The “Controller Area Network” was introduced and patented by Robert Bosch GmbH,
Germany. After short and heavy competition, CAN was accepted by almost all
manufacturers. Nowadays, it is the basic network system in nearly all automotive
manufacturers’ shiny new cars. Latest products use CAN accompanied by other network
systems such as LIN (a low-cost serial net for body electronics), MOST (used for in-car
entertainment) or Flexray (used for safety critical communication) to tailor the different
needs for communication with dedicated net structures.
Because CAN has high and reliable data rates, built-in failure detection and cost-effective
prices for controllers, nowadays it is also widely used outside automotive electronics. It is a
standard for industrial applications such as a “Field Bus” used in process control. A large
number of distributed control systems for mechanical devices use CAN as their “backbone”.

CAN Physical Layers


CAN - High - Speed (ISO 11898):

node 1 node 30

CAN_H

120 120
Ohm
Ohm
CAN_L

11 - 19

F2833x - Controller Area Network 11 - 1


Module Topics

Module Topics
F2833x Controller Area Network................................................................................................... 11-1
Introduction ................................................................................................................................... 11-1
Module Topics ............................................................................................................................... 11-2
Basic CAN Features ...................................................................................................................... 11-4
Automotive Network Systems......................................................................................................... 11-5
CAN Implementation / Data Format ............................................................................................. 11-7
CAN Data Frame .......................................................................................................................... 11-8
Standardization ISO and SAE ..................................................................................................... 11-10
CAN Application Layer ............................................................................................................... 11-11
CAN Bus Arbitration - CSMA/CA ............................................................................................... 11-12
High Speed CAN ......................................................................................................................... 11-14
CAN Error Frames ...................................................................................................................... 11-15
Active Error Frame ................................................................................................................. 11-16
Passive Error Frame ................................................................................................................ 11-17
CAN Error Types .................................................................................................................... 11-19
CAN Error Status .................................................................................................................... 11-19
CAN - Error Counter .............................................................................................................. 11-20
F2833x CAN Module................................................................................................................... 11-21
F2833x Programming Interface .................................................................................................. 11-22
CAN Register Map ................................................................................................................. 11-23
Mailbox Enable – CANME Mailbox Direction - CANMD .................................................... 11-23
Transmit Request Set & Reset - CANTRS / CANTRR .......................................................... 11-24
Transmit Acknowledge - CANTA .......................................................................................... 11-24
Receive Message Pending - CANRMP................................................................................... 11-25
Remote Frame Pending - CANRFP ........................................................................................ 11-25
Global Acceptance Mask - CANGAM ................................................................................... 11-26
Master Control Register - CANMC ........................................................................................ 11-27
CAN Bit - Timing ......................................................................................................................... 11-28
Bit-Timing Configuration - CANBTC .................................................................................... 11-29
CAN Error Register ..................................................................................................................... 11-31
Error and Status - CANES ...................................................................................................... 11-31
CAN Error Counter – CANTEC / CANREC .......................................................................... 11-32
CAN Interrupt Register ............................................................................................................... 11-32
Global Interrupt Mask - CANGIM ......................................................................................... 11-32
Global Interrupt 0 Flag - CANGIF0 ....................................................................................... 11-33
Global Interrupt 1 Flag - CANGIF1 ....................................................................................... 11-33
Mailbox Interrupt Mask - CANMIM ...................................................................................... 11-34
Overwrite Protection Control - CANOPC .............................................................................. 11-34
Transmit I/O Control - CANTIOC.......................................................................................... 11-35
Receive I/O Control - CANRIOC ........................................................................................... 11-35
Alarm / Time Out Register .......................................................................................................... 11-36
Local Network Time - CANLNT............................................................................................ 11-36
Time Out Control - CANTIOC ............................................................................................... 11-36
Local Acceptance Mask - LAMn ............................................................................................ 11-37

11 - 2 F2833x - Controller Area Network


Module Topics

Message Object Time Stamp - MOTSn ................................................................................. 11-37


Message Object Time Out - MOTOn ..................................................................................... 11-38
Mailbox Memory ......................................................................................................................... 11-39
Message Identifier - CANMID ............................................................................................... 11-39
Message Control Field - CANMCF........................................................................................ 11-39
Message Data Field Low - CANMDL ................................................................................... 11-40
Message Data Field High - CANMDH .................................................................................. 11-40
Lab Exercise 11_1 ...................................................................................................................... 11-41
Preface .................................................................................................................................... 11-41
Objective ................................................................................................................................ 11-42
Procedure ................................................................................................................................ 11-43
Open Files, Create Project File ............................................................................................... 11-43
Project Build Options ............................................................................................................. 11-44
Preliminary Test ..................................................................................................................... 11-44
Add CAN Initialization Code ................................................................................................. 11-45
Initialize CAN Mailbox .......................................................................................................... 11-46
Add the Data Byte and Transmit ............................................................................................ 11-47
Build, Load and Run .............................................................................................................. 11-48
Lab Exercise 11_2 ...................................................................................................................... 11-49
Preface .................................................................................................................................... 11-49
Objective ................................................................................................................................ 11-50
Procedure ................................................................................................................................ 11-50
Open Files, Create Project File ............................................................................................... 11-50
Project Build Options ............................................................................................................. 11-51
Preliminary Test ..................................................................................................................... 11-51
Add CAN Initialization Code ................................................................................................. 11-52
Modify Source Code .............................................................................................................. 11-53
Prepare Receiver Mailbox #1 ................................................................................................. 11-53
Wait for a message in mailbox 1 ............................................................................................ 11-54
Build, Load and Run .............................................................................................................. 11-54
What’s next? ............................................................................................................................... 11-55

F2833x - Controller Area Network 11 - 3


Basic CAN Features

Basic CAN Features


CAN is a serial communication network, the information is transmitted over 1 (“fault
tolerant low speed”) or 2 (“high speed” differential) physical signal lines. Although there is
no explicit clock information in form of an additional clock line, the receivers are able to re-
synchronize themselves based on a “non return to zero” (NRZ) modulation technique and an
additional “stuff” bit rule, which forces the transmitter to include a stuff bit after 5
consecutive bits of ‘0’ or ‘1’.
CAN does not use physical addresses to address stations. Each message is sent with an
identifier that is recognized by the different nodes. The identifier has two functions - it is
used for message filtering and for message priority. The identifier determines if a transmitted
message will be received by CAN modules and determines the priority of the message when
two or more nodes want to transmit at the same time.

Controller Area Network (CAN)


• developed by Robert Bosch GmbH, Germany in 1987
• Products available from all microcontroller manufacturers
• International Standards: ISO11898 (Europe), SAE J2284 (US) for
“high – speed” CAN; ISO 11519-2 for “fault-tolerant low speed”
CAN
• backbone serial bus system for automotive applications, but also
used in industrial automation & control
• Event triggered Serial Bus System; Self-Synchronisation

More Features :
• multi master bus access
• random access with collision avoidance (CSMA / CA )
• short message length , at max. 8 Bytes per message
• data rates 100KBPS to 1MBPS
• short bus length, physical length depends on data rate
• self-synchronised bit coding technology
• Robust EMC - behaviour
• build in fault tolerance

11 - 2

The bus access procedure is a multi-master principle, all nodes are allowed to use CAN as a
master node. One of the basic differences to Ethernet is the adoption of non-destructive bus
arbitration in case of collisions, called “Carrier Sense Multiple Access with Collision
Avoidance“(CSMA/CA). This procedure ensures that in case of an access conflict, the
message with higher priority will not be delayed by this collision.
The physical length of the CAN is limited, depending on the baud rate. The data frame
consists of a few bytes only (maximum 8), which increases the ability of the net to respond
to new transmit requests. On the other hand, this feature makes CAN unsuitable for very
high data throughputs, for example, for real time video processing.
There are several physical implementations of CAN, such as differential twisted pair
(automotive class: CAN high speed), single line (automotive class: CAN low speed) or fibre
optic CAN, for use in harsh environments.

11 - 4 F2833x - Controller Area Network


Automotive Network Systems

Automotive Network Systems


Electronic Control Units
Examples for Microcontrollers used in car:
Antilock Break System - ABS ( 1 + 4)
Keyless Entry System(1)
Active Wheel Drive Control (4)
Engine Control (2)
Airbag Sensor Systems (6+) Seat occupation sensors(4)
Automatic Gearbox(1) Electronic Park Brake(1)
diagnostic computer(1)
driver display unit(1)
air conditioning system(1)
adaptive cruise control(1)
radio / CD-player(2)
collision warning radar(2)
rain/ice/snow sensor systems (1)
each)
dynamic drive control(4)
active damping system (4)
driver information system(1)
GPS navigation system(3)
11 - 3

Today a car is packed with electronic devices, sensors, actuators and control units. To name
a few, Slide 11-3 shows some of the functional blocks and the number of microcontrollers in
brackets. There is a lot of information to be shared by such electronic control units: a
network is required.

Why a car network like CAN?


 Requirements of an in car network:
• low cost solution
• good and high performance with few overhead transmission
• high volume production
• high reliability and electromagnetic compatibility (EMC)
• data security due to a fail-safe data transmission protocol
• short message length, only a few bytes per message

Where in a car is CAN used?


• communication between electronic control units
• separated CAN – sections at different speed for:
• “Auto - Body” electronic control units
(chassis, light, central locking)
• Engine control units and Power train modules
• Comfort modules

11 - 4

F2833x - Controller Area Network 11 - 5


Automotive Network Systems

As you can guess, there are some options to implement a communication network into a car.
Depending on the application field, the bandwidth for data throughput, the safety level and
the budget limitation, we can find different communication standards:

• Controller Area Network (CAN)


o High - speed CAN (1 Mbit/s, 500 kbit/s)
o Low - Speed CAN (100 kbit/s, 83.3 kbit/s)

• Local Interconnect Network (LIN)


o 20 kbit/s

• Media Oriented Systems Transport (MOST)


o 25Mbit/s, 50 Mbit/s, 150 Mbit/s

• FlexRay®
o 10 Mbit/s

Automotive network systems


 Other automotive networks than CAN:
• LIN – “Local Interconnect Network”
• Body Electronic; Door, Mirror, Seat, Dashboard, Roof
• 20 Kbit/s
• Master / Slave time triggered protocol
• Single wire system; 12 V signal level
• www.lin-subbus.org

• MOST – “Media Oriented Systems Transport”


• Optical System for Multi – Media and infotainment
• Audio, Video, Mobile Phone, GPS
• Fibre optical circular system at 25 Mbit/s or 150 Mbit/s or
• Electrical layer at 50 Mbit/s.
• www.mostcooperation.com

• FlexRay
• Time Triggered Protocol for fail safe applications;
• 10 Mbit/s; dual channel redundancy
• www.flexray.com
11 - 5

11 - 6 F2833x - Controller Area Network


CAN Implementation / Data Format

CAN Implementation / Data Format


Implementation / Classification of CAN
Implementation: amount of functionality in CAN- Silicon

Don’t get confused !

Communication is standardized and identical for all


implementations of CAN. However, there are two types
of hardware implementation and two versions of data
format:

Implementation Data Format

Full - CAN Basic CAN Standard Extended


11 - 6

There are two versions of how the CAN-module is implemented in silicon, called “Basic”
and “Full” - CAN. Almost all new processors with a built-in CAN module offer both modes
of operation. Basic-CAN as the only mode is normally used in cost sensitive applications.

Basic- and Full-CAN communication


• Close coupled MCU-core and CAN
• only one transmit buffer
Basic CAN • only two receive buffer
• only one filter for incoming messages
• Software routines are needed to select
between incoming messages

• provide a message server


• extensive acceptance filtering on incoming
messages
Full - CAN • user configurable mailboxes
• mailbox memory area , size of mailbox
areas depends on manufacturer
• advanced error recognition

11 - 7

F2833x - Controller Area Network 11 - 7


CAN Data Frame

CAN Data Frame


The Data Format of CAN

• CAN-Version 2.0A
Standard • messages with 11-bit -
identifiers

• CAN-Version 2.0B
Extended • messages with 29-bit-
identifiers

==> Suitably configured, each implementation ( BASIC or FULL)


can handle both standard and extended data formats.
11 - 8

The two versions of the data frame format allow the reception and transmission of standard
frames and extended frames in a mixed physical set up; provided the silicon is able to handle
both types simultaneously (CAN version 2.0A and 2.0B respectively).

The CAN Data Frame

DATA-Frame CAN 2.0A (11-bit-identifier)

start data
1 bit RTR r0 0...8 byte CRC
SRR 1bit 1 bit 15 bits EOF + IFS
1bit r1 10 bits
IDE 1bit
1bit DLC ACK
Identifier 4 bits 2 bits
11 bits Identifier
18bit

DATA-Frame CAN 2.0B (29-bit-identifier)


11 - 9

11 - 8 F2833x - Controller Area Network


CAN Data Frame

The CAN Data Frame


each data frame consists of four segments :
(1) arbitration-field :
• denote the priority of the message
• logical address of the message (identifier)
• Standard frame, CAN 2.0A: 11 bit-identifier
• Extended frame, CAN 2.0B: 29 bit-identifier
(2) data field :
• up to 8 bytes per message ,
• a 0 byte message is also permitted
(3) CRC field:
• cyclic redundancy check ; contains a checksum
generated by a CRC-polynomial
(4) end of frame field:
• contains acknowledgement, error-messages, end
of message

11 - 10

The arbitration field is used to denote both the priority and the type of the message. CAN
uses a broadcast type of transmission, there are no node addresses. Instead of node addresses,
CAN implements logical groups of message identifiers. The next slide explains all bit fields
of a CAN data frame in detail.

The CAN Data Frame


start bit (1 bit - dominant): beginning of a message; after idle-time falling-edge to
synchronize all transmitters
identifier (11 bit): mark the name of the message and its priority ;the lower the value
the higher the priority
RTR (1 bit): remote transmission request; if RTR=1 (recessive) no valid data inside
the frame - it is a request for receivers to send their messages
IDE (1 bit): Identifier Extension; if IDE=1 then extended CAN-frame
r0 (1 bit): reserved
CDL (4 bit): data length code in byte (0...8)
data (0...8 byte): the data of the message
CRC (15 bit): cyclic redundancy code for error detection, no correction; hamming-
distance 6 (up to 6 single bit errors can be detected)
ACK (2 bit): acknowledge; if a receiving node has received a valid message, it
must transmit an dominant acknowledge – bit
EOF (7 bit = 1, recessive): end of frame; intentional violation of the bit-stuff-rule ;
normally after five recessive bits one stuff-bit follows automatically
IFS (3 bit = 1, recessive): inter frame space; time space to copy a received
message from bus-handler into buffer
Extended Frame only :
SRR (1 bit = recessive): substitute remote request ; substitution of the RTR-bit in
standard frames
r1 (1 bit ): reserved

11 - 11

F2833x - Controller Area Network 11 - 9


Standardization ISO and SAE

Standardization ISO and SAE


The Standardisation of CAN
• CAN is an open system and has been standardized by
ISO
• CAN follows the ISO - OSI seven layer model for open
system interconnections
• CAN implements layer 1, 2 and 7 only
• However, Layer 7 is not standardised

Physical Layer Type Europe North America


www.iso.org www.sae.org
Single – Wire CAN n/a SAE J2411
Single Wire CAN for Vehicle
Applications
Low-Speed Fault Tolerant ISO 11519 - 2 n/a.
CAN ISO 11898 - 3
High-Speed CAN ISO 11898 SAEJ2284

11 - 12

As an open system, CAN today is standardized both by the European Standardization


Organization (ISO) and the Society of Automotive Engineers (SAE). All CAN standards
define layer 1 and 2 of the OSI - layer model only. For layer 7 some higher layer solutions
exist.

ISO Reference Model


Open Systems Interconnection (OSI):

Layer 1: transmission line(s)


• differential two-wire-line, twisted
pair with/without shield
• Transceiver Integrated Circuit
• Optional: fibre optical lines (passive
coupled star, carbon )
• Optional: Coding as PWM, NRZ,
Manchester Code
• ISO 11898

Layer 2: Data Link Layer


• message format and transmission
protocol
• ISO 11898
• CSMA/CA access protocol

Layer 7: Application Layer


• different standards in industry, not
standardized in automotive

11 - 13

11 - 10 F2833x - Controller Area Network


CAN Application Layer

CAN Application Layer


CAN Layer 7
1. CAN Application Layer (CAL):
• European CAN user group ”CAN in Automation (CiA)”
• originated by Philips Medical Systems 1993
• CiA DS-201 to DS-207
• standardised communication objects, -services and -protocols (CAN-
based Message Specification)
• Services and protocols for dynamic attachment of identifiers (DBT)
• Services and protocols for initialise, configure and obtain the net (NMT)
• Services and protocols for parametric set-up of layer 2 &1 (LMT)
• Automation, medicine, traffic-industry

2. OSEK/VDX
• “Offene Systeme für Elektronik im Kraftfahrzeug”
• Standard of European automotive electronics industry
• include services of a standardised real-time-operating system
• Network Management Services
• Communication Services

11 - 14

For OSI - layer 7, some user groups have defined specific layers, such as CAL, CANOpen or
DeviceNet, which are tailored to certain application areas. These layers are not compatible
with each other. In automotive applications, layer 7 is usually a proprietary (and
confidential) in - house solution.

CAN Layer 7
3. CANopen
• European Community funded project “ESPRIT”
• 1995 : CANopen profile :CiA DS-301
• 1996 : CANopen device profile for I/O : CiA DS-401
• 1997 : CANopen drive profile
• industrial control , numeric control in Europe

4. DeviceNet
• Allen-Bradley, now ODVA-group (www. odva.org)
• device profiles for drives, sensors and actuators
• master-slave communication as well as peer to peer
• industrial control , mostly USA

5. Smart Distributed Systems (SDS)


• Honeywell , device profiles
• only 4 communication functions , less hardware resources
• industrial control and PC-based control

11 - 15

F2833x - Controller Area Network 11 - 11


CAN Bus Arbitration - CSMA/CA

CAN Bus Arbitration - CSMA/CA


Bus Access Procedure
The “Ethernet”: CSMA / CD
Send Message

time delay
CSMA /CD:
listen to bus
Carrier
Sense
bus no Multiple
empty ?

yes
Access with
Collision
transmit &
receive
Detection

yes
Collision
abort transmit

no

Note: This flowchart does NOT apply to


End CAN! See following page
11 - 16

CAN feature a modified CSMA/CD access control principle, where a message with the
highest priority will continue its transmission regardless of the collision with other messages.
Therefore the modification is called “collision avoidance” (/CA), sometimes “collision
resolution” (/CR).

CAN Access Procedure: CSMA/CA


CSMA/ CA: “Carrier Sense Multiple Access with Collision
Avoidance”

• access-control with non


start id10 id8 id7 destructive bit-wide
id6
id9
Tx arbitration
node A
Rx • if there is a collision , the
“winner” continues
Tx
node B • the message with higher
Rx priority is not delayed!
• real-time capability for high
bus line prioritised messages
• the lower the identifier, the
higher the priority

11 - 17

11 - 12 F2833x - Controller Area Network


CAN Bus Arbitration - CSMA/CA

CSMA/CA (cont.)
CSMA / CA =
"bit - wide arbitration during transmission with simultaneous
receiving and comparing of the transmitted message"
means :
• if there is a collision within the arbitration-field, only the
nodes with lower priorities cancel transmission.
• The node with the highest priority continues with the
transmission of the message.

Vcc

node 1 node 2 node 3

high : reccessive node 1 node 2 node 3 bus


high high high high
low : dominant high low high low
low low high low

11 - 18

As you can see from the previous slide the arbitration procedure at a physical level is quite
simple: it is a “wired-AND” principle. Only if all 3 node voltages (node 1, node2 or node3)
are equal to 1 (recessive), the bus voltage stays at Vcc (recessive). If only one node voltage is
switched to 0 (dominant), the bus voltage is forced to the dominant state (0).

The beauty of CAN is that the message with highest priority is not delayed at all in case of a
collision. For the message with highest priority, we can determine the worst-case response
time for a data transmission. For messages with lower priorities, to calculate the worst-case
response time is a little bit more complex task. It could be done by applying a so-called “time
dilatation formula for non-interruptible systems”:

 Rin − C i 
Rin +1 = C i + Bm axi + ∑  T  ∗Cj
j∈hp( i )  j 

HARTER, P.K: “Response Times in level structured systems” Techn.


Report, Univ. of Colorado, 1991

In detail, the hardware structure of a CAN-transceiver is more complex. Due to the principle
of CAN-transmissions as a “broadcast” type of data communication, all CAN-modules are
forced to “listen” to the bus all the time. This also includes the arbitration phase of a data
frame. It is very likely that a CAN-module might lose the arbitration procedure. In this case,
it is necessary for this particular module to switch into receive mode immediately. This re-
quires every transceiver to provide the current bus voltage status permanently to the CAN-
module.

F2833x - Controller Area Network 11 - 13


High Speed CAN

High Speed CAN


CAN Physical Layers
CAN - High - Speed (ISO 11898):

node 1 node 30

CAN_H

120 120
Ohm
Ohm
CAN_L

11 - 19

To generate the voltage levels for the differential voltage transmission according to CAN
High Speed, we need an additional transceiver device, e.g. the SN65HVD23x.

CAN High speed Node

F2833x with on-chip


CAN module

Rxd Txd

CAN Transceiver
SN65HVD23X

CAN_H

CAN_L

CAN - bus

11 - 20

11 - 14 F2833x - Controller Area Network


CAN Error Frames

CAN Error Frames


Layer 2 of CAN also includes an enhanced strategy to detect transmission errors, which is
based on error -levels and the exchange of error messages. Please note that the exchange of
error messages is managed by the CAN communication controller in OSI layer 2; it is
therefore totally independent of application layer 7.

CAN Error – Frame


• any node that detects a bus error generates an error - frame
• an error frame is transmitted as soon as an error has been
detected, e.g. inside a data frame
• consists of two fields: Error Flag Field; Error Delimiter Field

• Error Delimiter Field:


• 8 recessive bits
• allow bus nodes to restart bus communication after an error
• Error Flag Field:
Type depends on the error-state of the node:
• error active: 6 consecutive dominant error bits; all other
nodes will respond to this violation with their own error
frames  Error Flag Field = 6…12 dominant bits
• error passive: 6 consecutive recessive bits plus 8 error
delimiter bits = 14 recessive bits
• receiver: does not corrupt the message
• transmitter: other nodes may respond with active
error frames

11 - 21

The error management of a node is based on one of 3 states, in which a node operates:

• Error Active State

• Error Passive State

• Bus OFF state


Depending on the state a node is able to transmit “Active Error” - frames, “Passive Error” -
frames or no error frames at all.
The objective behind these 3 levels is to have the ability to identify a potential fault node, to
isolate this node and to keep the remaining part of the bus running. This principle will be
explained shortly. For now, let us concentrate on the characteristics of the different error
frames.

F2833x - Controller Area Network 11 - 15


CAN Error Frames

Active Error Frame

CAN Error – Frame


Example1: Active error frame

data error frame Inter frame space

6 bit error flag


6..12 bit error overlay 8 bit error delimiter

Active error frame

11 - 22

The first example in Slide 11-22 shows the timing diagram of an active error frame. As soon
as a node detects faulty data, it will send such a frame to the bus. Since the error flag field
contains 6 zero bits, which is (an intended) violation of the stuff bit rule, other nodes will
respond with their own active error frames. Depending on how many bits of the last data
group have been 0, the other nodes will start sooner or later with the transmission of their
follow-up active error frames, leading to a 6...12 bit error overlay as shown in Slide 11-22.
If a receiving node receives an active error frame, it will mark the data contents of this
message as faulty and cancel it. The message will not be forwarded to the mailbox server and
to the application. Instead, the receiver mailbox will be cleared to be able to await a re-
transmission of the message.
If a transmitting node receives an active error frame, it will immediately stop the current
transmission. As soon as the bus is empty, it will try to re-transmit the message. As long as
no successful transmission has happened, the application will not get the “Transmission
Acknowledged” (TA) status flag.

11 - 16 F2833x - Controller Area Network


CAN Error Frames

Passive Error Frame


If a node has reached “error passive” level, is no longer able to generate active error frames.
Instead, it will issue passive error frames in case of a detected data corruption.

CAN Error – Frame


data error frame Inter frame space

6 bit error flag 8 bit error delimiter

passive error frame from a receiver


data error frame Inter frame space

6 bit passive error flag


8 bit error delimiter
6 bit active error overlay
from another active node
passive error frame from a transmitter
11 - 23

Slide 11-23 shows what happen, if a node is in error passive mode.


If a receiver spots faulty data, it will issue a passive error frame. The 6 recessive error bits
can now be overwritten by dominant bits of the original transmitter data, which is still in
active mode.
If a transmitter is in passive error mode and generates a passive error frame, this (intended)
violation will be answered by receivers in error active mode with a 6 bit active error overlay,
shown in the bottom half of Slide 11-23. Since the original transmitting node is the only
transmitter at that time, the active error overlay ensures that all nodes will cancel the
corrupted message, which has already been detected by the transmitter.
Using these two principles, it ensures that nodes in error active mode will always be able to
overrule nodes in error passive state. Only if all nodes of a CAN subnet are in error passive
mode, the recessive level of error passive frames from receivers will be treated as error
messages.
The next slides will illustrate what happens in case of an error in a more realistic scenario.

F2833x - Controller Area Network 11 - 17


CAN Error Frames

CAN Error – Frame


data

Transmitter X 2 6
CAN - Tx

Receiver Y 4
CAN - Tx

Receiver Z 4
CAN - Tx

1 5
CAN
Bus - level 3

6 6 8 3

Example: active error frame


11 - 24

The bullets 1 to 6 indicate events on the time line. At position 5, node X tries to generate 6
recessive bits for the error delimiter but the actual bus level is dominated by node Y and Z
and their delayed active error frames. The time delay between bus and the Tx - line of node
X is used to define the node, which has first spotted the error.

CAN Error – Frame


1 Node X detects a bit error
2 Node X generates an active error flag field
3 Nodes Y, Z realize a stuff bit error after bit 6 of the active error flag field
(note: if the corrupted data frame had dominant bits, the stuff bit error is
detected earlier)
4 Nodes Y,Z transmit their own active error flag field of 6 dominant bits

5 All nodes transmit the recessive error delimiter field. Node Y and Z see
no difference @ bus level, but node X detects a delay of 6 bits
between bus level and its own output  First node to message error

6 After the last 8 recessive error delimiter bits @ CAN-bus and 3 bit of
inter frame space a new arbitration is entered by node X, e.g. it has to
compete again with other nodes

11 - 25

11 - 18 F2833x - Controller Area Network


CAN Error Frames

CAN Error Types

CAN Error Recognition


1. Bit-Error
the transmitted bit doesn’t read back with the same digital
level (except arbitration and acknowledge- slot )
2. Bit-Stuff-Error
more than 5 continuous bits read back with the same digital
level (except ‘end of frame’-part of the message )
3. CRC-Error
the received CRC-sum doesn’t match with the calculated sum
4. Format-Error
Violation of the data-format of the message , e.g.: CRC-
delimiter is not recessive or violation of the ‘end -of-frame’-
field
5. Acknowledgement-Error
transmitter receives no dominant bit during the
acknowledgement slot, i.e. the message was not received by
another node.
11 - 26

CAN Error Status


Here is a summary for the node’s error states:

CAN Error Status


Purpose: avoid persistent
error
handling
disturbances of the CAN by switching
off defective nodes

error error error three Error States :


detection managing limitation

error error bus


active passive off

Error Active: normal mode, messages will be received and


transmitted. In case of error an active error frame will be transmitted.

Error Passive: after detection of a certain number of errors, the node


reaches this state. Messages will be received and transmitted but in
case of an error the node sends a passive error frame.

Bus Off: the node is separated from CAN, neither transmission nor
receive of messages is allowed and the node is no longer able to
transmit error frames.
11 - 27

F2833x - Controller Area Network 11 - 19


CAN Error Frames

CAN - Error Counter


The transitions between error states of a node is based on the current value in two error
counters, called Receive Error Counter (REC) and Transmit Error Counter (TEC).

CAN Error Counter

State - Diagram: • transitions will be carried out automatically by


the CAN-chip
• states are managed by 2 Error Counters :
Receive Error Counter (REC)
REC <127 Transmit Error Counter (TEC)
and
TEC <=127
error active • Possible situations :
'reset' or 'init a) a transmitter recognises an error:
node'
REC >127 or TEC:=TEC + 8
127<TEC<255
b) a receiver sees an error : REC:=REC + 1
c) a receiver sees an error, after transmitting an
error frame: REC:=REC + 8
error passive
bus off d) if an ‘error active’-node find’s a bit-stuff-error
during transmission of an error frame:
TEC > 255 TEC:=TEC+ 1
e) successful transmission:
TEC:=TEC - 1
f) successful receive:
REC:=REC - 1

11 - 28

The current values both of REC and TEC are permanently available in two registers of the
F2833x CAN Controller. For maintenance purposes it is a good idea to read the values from
time to time to monitor the quality of the data transmission. Rising numbers in TEC and/or
REC give an indication that something is going wrong with the communication and that this
may be an appropriate time to take preventative action, e.g. switch into a local operating
mode of the device.
The state diagram above shows the transitions between error active, error passive and bus off
states. Successful communication is always represented by the number -1. Depending on the
seriousness of a failure, the penalty is either +8 or +1 of the corresponding error counter.
After a RESET, the node is in error active mode. If REC or TEC is increased beyond 127,
the node goes into error passive state. From this state the node can (a) go back to error active,
if both REC and TEC are decreased below 127; or (b) will be forced into bus OFF state, if
TEC is greater than 255.
The original CAN specification did not allow a recovery from bus OFF. The only option was
to reset and re-initialize the device. This was really bad news as it meant that your car would
lose full CAN communication and could grind to a halt.
However, newer microcontrollers, such as the F2833x, allow an automatic recovery, if a
certain amount of idle time was applied to the bus. This additional feature can be enabled or
disabled during the initialization of the CAN communication controller.

11 - 20 F2833x - Controller Area Network


F2833x CAN Module

F2833x CAN Module


F2833x CAN Features
 Fully CAN protocol compliant, version 2.0B
 Supports data rates up to 1 Mbps
 Thirty-two mailboxes
 Configurable as receive or transmit
 Configurable with standard or extended identifier
 Programmable receive mask
 Supports data and remote frame
 Composed of 0 to 8 bytes of data
 Uses 32-bit time stamp on messages
 Programmable interrupt scheme (two levels)
 Programmable alarm time-out
 Programmable wake-up on bus activity
 Self-test mode 11 - 29

The F2833x CAN unit is a full CAN Controller. It contains a message handler for transmis-
sion, reception management and frame storage. The specification is CAN 2.0B Active - that
is, the module can send and accept standard (11-bit identifier) and extended frames (29-bit
identifier).

F2833x CAN Block Diagram


Address Data
eCAN0INT eCAN1INT
32

Mailbox RAM Memory Management


(512 Bytes) Unit eCAN Memory
(512 Bytes)
32-Message Mailbox CPU Interface, Register and Message
of 4 x 32-Bit Words 32 Receive Control Unit 32 Object Control
Timer Management Unit

32

Receive Buffer
Transmit Buffer
Control Buffer
Status Buffer

SN65HVD23x
3.3-V CAN Transceiver

.
. CAN Bus
11 - 30

F2833x - Controller Area Network 11 - 21


F2833x Programming Interface

F2833x Programming Interface


F2833x CAN Memory

Data Space
0x00 0000
Control and
Status Register
6040 Local
Acceptance
Masks
6080 Message
0x00 6000 Object
Time Stamps
CAN 60C0 Message
0x00 61FF
Object
Time Out
6100 Mailbox 0
6108 Mailbox 1

Mailbox 31
0x 3F FFFF 61FF

11 - 31

The CAN controller module contains 32 mailboxes for objects of 0- to 8-byte data lengths:
• configurable transmit/receive mailboxes
• configurable with standard or extended identifier

The CAN module mailboxes comprise of the following components:


• MID - contains the identifier of the mailbox
• MCF (Message Control Field) - contains the length of the message (to
transmit or receive) and the RTR bit (Remote Transmission Request - used
to send remote frames)
• MDL and MDH - contain the data

The CAN module contains registers, which are divided into five groups. These registers are
located in data memory from 0x006000 to 0x0061FF. The five register groups are:
• Control and Status Registers
• Local Acceptance Masks
• Message Object Time Stamps
• Message Object Timeout
• Mailboxes

It is the responsibility of the programmer to go through all those registers and set every sin-
gle bit according to the designated operating mode of the CAN module. It is also a challenge
for the student to exercise the skills required to debug. So let us start!

First, we will discuss the different CAN registers. If this chapter becomes too tedious, ask
your teacher for some practical examples how to use the various options. Be patient!

11 - 22 F2833x - Controller Area Network


F2833x Programming Interface

CAN Register Map

CAN Control & Status Register


31 0 31 0
6000 CANME 6020 CANGIM
6002 CANMD 6022 CANGIF1
6004 CANTRS 6024 CANMIM
6006 CANTRR 6026 CANMIL
6008 CANTA 6028 CANOPC
600A CANAA 602A CANTIOC
600C CANRMP 602C CANRIOC
600E CANRML 602E CANLNT
6010 CANRFP 6030 CANTOC
6012 CANGAM 6032 CANTOS
6014 CANMC 6034 reserved
6016 CANBTC 6036 reserved
6018 CANES 6038 reserved
601A CANTEC 603A reserved
601C CANREC 603C reserved
601E CANGIF0 603E reserved

11 - 32

Mailbox Enable – CANME Mailbox Direction - CANMD


CAN Mailbox Enable Register (CANME) – 0x006000
31 16

CANME[31:16]

15 0

CANME[15:0]

Mailbox Enable Bits


0 = corresponding mailbox is disabled
1 = The corresponding mailbox is enabled. A mailbox must be disabled before
writing to the contents of any mailbox identifier field.

CAN Mailbox Direction Register (CANMD) – 0x006002


31 16

CANMD[31:16]

15 0

CANMD[15:0]

Mailbox Direction Bits


0 = corresponding mailbox is defined as a transmit mailbox.
1 = corresponding mailbox is defined as a receive mailbox.

11 - 33

F2833x - Controller Area Network 11 - 23


F2833x Programming Interface

Transmit Request Set & Reset - CANTRS / CANTRR


CAN Transmission Request Set Register (CANTRS) – 0x006004
31 16

CANTRS[31:16]

15 0

CANTRS[15:0]

Mailbox Transmission Request Set Bits (TRS)


0 = no operation. NOTE: Bit will be cleared by CAN-Module logic after successful transmission.
1 = Start of transmission of corresponding mailbox. Set to 1 by user software;
OR by CAN –logic in case of a Remote Transmit Request.

CAN Transmission Request Reset Register (CANTRR) – 0x006006


31 16

CANTRR[31:16]

15 0

CANTRR[15:0]

Mailbox Transmission Reset Request Bits (TRR)


0 = no operation.
1 = setting TRRn cancels a transmission request, if not already in progress.

11 - 34

Transmit Acknowledge - CANTA

CAN Transmission Acknowledge Register (CANTA) – 0x006008


31 16

CANTA[31:16]

15 0

CANTA[15:0]

Mailbox Transmission Acknowledge Bits (TA)


0 = the message is not sent.
1 = if the message of mailbox n is sent successfully, the bit n of this register is set.
Note: To reset a TA bit by software: write a ‘1’ into it.

CAN Abort Acknowledge Request Register (CANAA) – 0x00600A


31 16

CANAA[31:16]

15 0

CANAA[15:0]

Mailbox Abort Acknowledge Bits (AA)


0 = The transmission is not aborted.
1 = The transmission of mailbox n is aborted.
Note: To reset a AA bit by software: write a ‘1’ into it.
11 - 35

11 - 24 F2833x - Controller Area Network


F2833x Programming Interface

Receive Message Pending - CANRMP

CAN Receive Message Pending Register (CANRMP) – 0x00600C


31 16

CANRMP[31:16]

15 0

CANRMP[15:0]

Mailbox Receive Message Pending Bits (RMP)


0 = the mailbox does not contain a message.
1 = the mailbox contains a valid message.
Note: To reset a RMP bit by software: write a ‘1’ into it.

CAN Receive Message Lost Register (CANRML) – 0x00600E


31 16

CANRML[31:16]

15 0

CANRML[15:0]

Mailbox Receive Message Lost Bits (RML)


0 = no message was lost.
1 = an old unread message has been overwritten by a new one in that mailbox.
Note: To reset a RML bit by software: write a ‘1’ into it.
11 - 36

Remote Frame Pending - CANRFP

CAN Remote Frame Pending Register (CANRFP) – 0x006010


31 16

CANRFP[31:16]

15 0

CANRFP[15:0]

Mailbox Remote Frame Pending Bits (RFP)


0 = no remote frame request was received.
1 = a remote frame request was received by the CAN module.
Note: To reset a RFP bit by software: write a ‘1’ into the corresponding TRR bit.

11 - 37

F2833x - Controller Area Network 11 - 25


F2833x Programming Interface

Global Acceptance Mask - CANGAM

CAN Global Acceptance Mask Register (CANGAM) – 0x006012


31 30-29 28 16
AMI reserved CANGAM[28:16]

15 0

CANGAM[15:0]

Note : This Register is used in Standard Can Controller (SCC) mode only. It is hers a single
input filter for mailboxes 6…15, if the AME bit (MID.30) of the corresponding mailbox is set.
CANGAM is not used in extended eCAN – Mode!

Acceptance Mask Identifier Bit (AMI)


0 = the identifier extension bit in the mailbox determines which messages shall be received.
Filtering is not applicable.
1 = standard and extended frames can be received. In case of an extended frame all 29 bits of the identifier
and all 29 bits of the GAM are used for the filter. In case of a standard frame only bits 28-18 of the identifier
and the GAM are used for the filter.

Global Acceptance Mask (GAM)


0 = bit position must match the corresponding bit in register CANMIDn.
1 = bit position of the incoming identifier is a “don’t’ care”.

11 - 38

The F2833x CAN module is able to operate in one of two operating modes:

• Standard CAN Controller Mode (SCC)

• Extended CAN Controller Mode, or “High End CAN Controller Mode (HECC)”.
The SCC is a legacy mode to keep the CAN communication controller software compatible
to the 16-bit family TMS320F240x. In this mode there are 16 mailboxes only and the
receiver system can use 3 common filters for incoming messages, LAM0, LAM1 and
CANGAM. Register LAM0 is the mask register for mailboxes 0, 1 and 2; LAM1 for
mailboxes 3, 4 and 5 and CANGAM for mailboxes 6...15. If you start a new design there is
no advantage in using SCC mode.
In HECC mode, each of the 32 mailboxes can be programmed to use an individual
acceptance filter. Filter here means that we declare certain bits of the identifier combination
of the incoming message to be “don’t cares”. This is done by setting the corresponding bits
in register LAMx to ‘1’.
For example, if we operate in HECC mode and set LAM0 = 0x0000 0007, mailbox 0 will
ignore bits 0, 1 and 2 of the incoming identifier and will store the message, if the rest of the
identifier bits match the combination in register MSGID of mailbox 0.
SCC or HECC - mode is selected by bit “SCB” in register CANMC - see following slide.
Note that after reset SCC is the default mode!

11 - 26 F2833x - Controller Area Network


F2833x Programming Interface

Master Control Register - CANMC


CAN Master Control Register (CANMC) – 0x006014
31 16

reserved

15 14 13 12 11 10 9 8 7 6 5 4 0

MBCC TCC SCB CCR PDR DBO WUBA CDR ABO STM SRES MBNR

Change Configuration Request (CCR)


0 = software requests normal operation
1 = software requests write access to CANBTC, CANGAM, LAM[0] and LAM[3].
A request is granted by the CAN module with flag CCE ( CANES) = 1.

High end CAN Mode HECC:


SCC Compatibility bit (SCB)
Full functionality;
0 = standard CAN mode (SCC)
Mailboxes 0...31
1 = high end CAN (HECC) mode
32 acceptance masks
Standard CAN Mode SCC:
Timestamp counter MSB clear (TCC)
Reduced functionality;
0 = no operation
Mailboxes 0...15 only
1 = timestamp counter MSB is reset to 0
3 acceptance masks only
No timestamp features

Mailbox Timestamp counter clear (MBCC)


0 = no operation
1 = timestamp counter is reset to 0 after a successful transmission or reception of mailbox 16.
11 - 39

CAN Master Control Register (CANMC) – 0x006014


Power Down Mode Request (PDR) Auto bus on (ABO)
0 = normal operation 0 = “bus off’ state is permanent.
1 = power down mode is requested. 1 = “bus off” state is left into “bus on”
NOTE: bit is automatically cleared after 128*11 recessive bits have been received.
upon wakeup from power down!

Wake up on bus activity (WUBA)


0 = Module leaves power down only
Software Reset(SRES)
after writing a 0 to PDR
0 = no effect
1 = Module leaves power down on
1 = CAN Module reset
any bus activity

15 14 13 12 11 10 9 8 7 6 5 4 0

MBCC TCC SCB CCR PDR DBO WUBA CDR ABO STM SRES MBNR

Data Byte Order (DBO) in Mailbox Registers


MDH[31:0] and MDL[31:0]
0 = MDH[31:0] : Byte 4,5,6,7 ; MDL[31:0] : Byte 0,1,2,3 Mailbox Number(MBNR)
1 = MDH[31:0] : Byte 7,6,5,4 ; MDL[31:0] : Byte 3,2,1,0 Number , used for CDR

Change data field request (CDR) Self Test Mode (STM)


0 = normal operation 0 = normal mode
1 = software requests access to the data field in 2MBNR”. 1 = Module generates its own ACK
NOTE: software must clear this bit after access is done.
11 - 40

F2833x - Controller Area Network 11 - 27


CAN Bit - Timing

CAN Bit - Timing

CAN Bit-Timing Configuration


 CAN protocol specification splits the nominal
bit time into four different time segments:
 SYNC_SEG
 Used to synchronize nodes
 Length : always 1 Time Quantum (TQ)
 PROP_SEG
 Compensation time for the physical delay times within the net
 Twice the sum of the signal’s propagation time on the bus line, the
input comparator delay and the output driver delay.
 Programmable from 1 to 8 TQ
 PHASE_SEG1
 Compensation for positive edge phase shift
 Programmable from 1 to 8 TQ
 PHASE_SEG2
 Compensation time for negative edge phase shift
 Programmable from 2 to 8 TQ 11 - 41

CAN Bit-Timing Configuration


CAN Nominal Bit Time
SYNCSEG
sjw
sjw
tseg1 tseg2

TQ

Transmit Point Sample Point


 tseg1: PROP_SEG + PHASE_SEG1
 tseg2: PHASE_SEG2
 TQ: SYNCSEG

TCAN = TQ + tseg1 + tseg2


11 - 42

11 - 28 F2833x - Controller Area Network


CAN Bit - Timing

CAN Bit-Timing Configuration

 According to the CAN – Standard the following bit


timing rules apply:
 tseg1 ≥ tseg2
 3/BRP ≤ tseg1 ≤ 16 TQ
 3/BRP ≤ tseg2 ≤ 8 TQ
 1 TQ ≤ sjw ≤ MIN[ 4*TQ , tseg2]
 BRP ≥ 5, if three sample mode is used

11 - 43

Bit-Timing Configuration - CANBTC

CAN Bit-Timing Configuration Register (CANBTC) – 0x006016


31 24 23 16

reserved BRP.7 BRP.6 BRP.5 BRP.4 BRP.3 BRP.2 BRP.1 BRP.0

Baud Rate Prescaler (BRP):


defines the Time Quantum (TQ):

TQ = BRP +1
BaseCLK

Note:
BaseCLK = SYSCLK / 2 for 283xx, 2803x devices
BaseCLK = SYSCLK for 281x, 280x and 2801x devices
11 - 44

F2833x - Controller Area Network 11 - 29


CAN Bit - Timing

CAN Bit-Timing Configuration Register (CANBTC) – 0x006016


15 11 10 9 8 7 6 3 2 0

reserved SBG SJW SAM TSEG1 TSEG2

Time Segment 1( tseg1)


Synchronisation Jump Width (SJW)

sjw = TQ ∗  SJW + 1) tseg1 = TQ ∗  TSEG1 + 1)

Time Segment 2( tseg2)


Synchronisation Edge Select (SBG)

tseg2 = TQ ∗  TSEG2 + 1)


0 = re synchronisation with falling edge only
1 = re-sync. with rising & falling edge

Sample Points (SAM)


0 = one sample at sample point
1 = 3 samples at sample point – majority vote

11 - 45

CAN Bit-Timing Examples


 Bit Configuration for BaseCLK = 75 MHz
 Sample Point at 80% of Bit Time :

CAN - BRP TSEG1 TSEG2


data rate

1 Mbit/s 4 10 2

500 kbit/s 9 10 2

250 kbit/s 19 10 2

125 kbit/s 39 10 2

100 kbit/s 49 10 2

50 kbit/s 99 10 2

 Example 100 kbit/s


TQ = (49+1)/ 75 MHz = 0.667 µs
tseg1 = 0.667 µs (10 + 1) = 7.337 µs  tCAN = 10 µs;
tseg2 = 0.667 µs (2 + 1) = 2 µs
11 - 46

11 - 30 F2833x - Controller Area Network


CAN Error Register

CAN Error Register


Error and Status - CANES

CAN Error and Status Register (CANES) – 0x006018


31 24 23 22 21 20 19 18 17 16

reserved FE BE SA1 CRCE SE ACKE BO EP EW

Form Error (FE)


0 = normal operation
1 = one of the fixed form bit fields of a message was wrong.

Bit Error (BE) Acknowledgement Error (ACKE)


0 = no bit error detected 0 = normal operation
1 = a received bit does not match a transmitted bit 1 = CAN module has not received an ACK.
(outside of the arbitration field).
Bus Off State (BO)
Stuck at dominant Error (SA1) 0 = normal operation
0 = The CAN module detected a recessive bit 1 = CANTEC has reached the limit of 256. Module
1 = The CAN module never detected a recessive bit. has been switched of the bus.

Cyclic Redundancy Check Error (CRCE) Error Passive State (EP)


0 = normal operation 0 = CAN is in Error Active Mode
1 = a wrong CRC was received. 1 = CAN is in Error Passive Mode

Stuff Bit Error (SE) Warning Status (EW)


0 = normal operation 0 = values of both error counters are less than 96
1 = a stuff bit error has occurred. 1 = one error counter has reached 96

11 - 47

CAN Error and Status Register (CANES) – 0x006018

15 6 5 4 3 2 1 0

reserved SMA CCE PDA Res. RM TM

Suspend Mode Acknowledge (SMA) Power Down Mode Acknowledge (PDA)


0 = normal operation 0 = normal operation
1 = CAN module has entered suspend mode. 1 = CAN module has entered power down mode.
Note: Suspend mode is activated by the debugger
when the DSP is not in run mode.

Receive Mode (RM)


Change Configuration Enable (CCE) 0 = CAN controller is not receiving a message.
0 = CPU cannot write into 1 = CAN controller is receiving a message.
configuration registers.
1 = CPU has write access into
configuration registers. Transmit Mode (TM)
0 = CAN controller is not transmitting a message.
1 = CAN controller is transmitting a message.

11 - 48

F2833x - Controller Area Network 11 - 31


CAN Interrupt Register

CAN Error Counter – CANTEC / CANREC


CAN Transmit Error Counter Register (CANTEC) – 0x00601A
31 16

reserved

15 0
reserved TEC

Transmit Error Counter (TEC)


Value TEC is incremented or decremented according to the CAN protocol specification

CAN Receive Error Counter Register (CANREC) – 0x00601C


31 16

reserved

15 0
reserved REC

Receive Error Counter (REC)


Value REC is incremented or decremented according to the CAN protocol specification

11 - 49

CAN Interrupt Register


Global Interrupt Mask - CANGIM
CAN Global Interrupt Mask Register (CANGIM) – 0x006020
31 18 17 16

reserved MTOM TCOM

15 14 13 12 11 10 9 8 7 3 2 1 0

Res. AAM WDIM WUIM RMLIM BOIM EPIM WLIM reserved GIL I1EN I0EN

Interrupt Mask Bits: Global Interrupt Level (GIL)


For Interrupts TCOF,WDIF,WUIF,BOIF and WLIF
MTOM = Mailbox Timeout Mask 0 = mapped into HECC_INT_REQ[0] line – GIF0
TCOM = Timestamp Counter Overflow Mask 1 = mapped into HECC_INT_REQ[1] line – GIF1
AAM = Abort Acknowledge Interrupt Mask
WDIM = Write Denied Interrupt Mask
WUIM = Wake-up Interrupt Mask Interrupt 1 Enable (I1EN)
RMLIM = Receive message lost Interrupt Mask 0 = HECC_INT_REQ[1] line is disabled
BOIM = Bus Off Interrupt Mask 1 = HECC_INT_REQ[1] line is enabled
EPIM = Error Passive Interrupt Mask
WLIM = Warning level Interrupt Mask Interrupt 0 Enable (I0EN)
0 = HECC_INT_REQ[0] line is disabled
Interrupt Mask Bits 1 = HECC_INT_REQ[0] line is enabled
0 = Interrupt disabled
1 = Interrupt enabled

11 - 50

11 - 32 F2833x - Controller Area Network


CAN Interrupt Register

Global Interrupt 0 Flag - CANGIF0

CAN Global Interrupt Flag 0 Register (CANGIF0) – 0x00601E


31 18 17 16

reserved MTOF0 TCOF0

15 14 13 12 11 10 9 8 7-5 4 3 2 1 0

GMIF0 AAIF0 WDIF0 WUIF0 RMLIF0 BOIF0 EPIF0 WLIF0 Res. MIV0.4 MIV0.3 MIV0.2 MIV0.1 MIV0.0

Interrupt Flag Bits:

MTOF0 = Mailbox Timeout Flag


TCOF0 = Timestamp Counter Overflow Flag
GMIF0 = Global Mailbox Interrupt Flag
AAIF0 = Abort Acknowledge Interrupt Flag
WDIF0 = Write Denied Interrupt Flag Mailbox Interrupt Vector (MIV0)
WUIF0 = Wake-up Interrupt Flag Indicates the number of the message object that set the
RMLIF0 = Receive message lost Interrupt Flag global mailbox interrupt flag (GMIF0)
BOIF0 = Bus Off Interrupt Flag
EPIF0 = Error Passive Interrupt Flag
WLIF0 = Warning level Interrupt Flag

Interrupt Flag Bits


0 = Interrupt has not occurred
1 = Interrupt has occurred

11 - 51

Global Interrupt 1 Flag - CANGIF1


CAN Global Interrupt Flag 1 Register (CANGIF1) – 0x006022
31 18 17 16

reserved MTOF1 TCOF1

15 14 13 12 11 10 9 8 7-5 4 3 2 1 0

GMIF1 AAIF1 WDIF1 WUIF1 RMLIF1 BOIF1 EPIF1 WLIF1 Res. MIV1.4 MIV1.3 MIV1.2 MIV1.1 MIV1.0

Interrupt Flag Bits:

MTOF1 = Mailbox Timeout Flag


TCOF1 = Timestamp Counter Overflow Flag
GMIF1 = Global Mailbox Interrupt Flag
AAIF1 = Abort Acknowledge Interrupt Flag
WDIF1 = Write Denied Interrupt Flag Mailbox Interrupt Vector (MIV1)
WUIF1 = Wake-up Interrupt Flag Indicates the number of the message object that set the
RMLIF1 = Receive message lost Interrupt Flag global mailbox interrupt flag (GMIF1)
BOIF1 = Bus Off Interrupt Flag
EPIF1 = Error Passive Interrupt Flag
WLIF1 = Warning level Interrupt Flag

Interrupt Flag Bits


0 = Interrupt has not occurred
1 = Interrupt has occurred

11 - 52

F2833x - Controller Area Network 11 - 33


CAN Interrupt Register

Mailbox Interrupt Mask - CANMIM


CAN Mailbox Interrupt Mask Register (CANMIM) – 0x006024
31 16

CANMIM[31:16]

15 0

CANMIM[15:0]

Mailbox Interrupt Mask Bits (MIM)


0 = mailbox interrupt is disabled.
1 = mailbox interrupt is enabled. An Interrupt is generated if a
message has been transmitted successfully or if a message has
been received without an error.

CAN Mailbox Interrupt Level Register (CANMIL) – 0x006026


31 16

CANMIL[31:16]

15 0

CANMIL[15:0]

Mailbox Interrupt Level Bits (MIL)


0 = mailbox interrupt is generated on HECC_INT_REQ[0] line.
1 = mailbox interrupt is generated on HECC_INT_REQ[1] line.

11 - 53

Overwrite Protection Control - CANOPC

CAN Overwrite Protection Control Register (CANOPC) – 0x006028


31 16

CANOPC[31:16]

15 0

CANOPC[15:0]

Overwrite Protection Control Bits (OPC)


0 = the old message in mailbox N may be overwritten by a new one.
This will be notified by the receive message lost bit RML[n].
1 = an old message in mailbox N is protected against being overwritten
by a new one.
Thus, the next mailboxes are checked for a matching ID.
If no other mailbox is found, the new message is lost.

11 - 54

11 - 34 F2833x - Controller Area Network


CAN Interrupt Register

Transmit I/O Control - CANTIOC


CAN I/O Control Register (CANTIOC) – 0x00602A
31 16

reserved

15 3 2 1 0

reserved TXFUNC TXDIR TXOUT TXIN

TXFUNC
0 = CANTX pin is a normal I/O pin.
1 = CANTX is used for CAN transmit functions.

TXDIR
0 = CANTX pin is an input pin if configured as a normal I/O pin.
1 = CANTX pin is an output pin if configured as a normal I/O pin.

TXOUT
Output value for CANTX pin, if configured as normal output pin

TXIN
0 = Logic 0 present on pin CANTX.
1 = Logic 1 present on pin CANTX.

11 - 55

Receive I/O Control - CANRIOC


CAN I/O Control Register (CANRIOC) – 0x00602C
31 16

reserved

15 3 2 1 0

reserved RXFUNC RXDIR RXOUT RXIN

RXFUNC
0 = CANRX pin is a normal I/O pin.
1 = CANRX is used for CAN receive functions.

RXDIR
0 = CANRX pin is an input pin if configured as a normal I/O pin.
1 = CANRX pin is an output pin if configured as a normal I/O pin.

RXOUT
Output value for CANRX pin, if configured as normal output pin

RXIN
0 = Logic 0 present on pin CANRX.
1 = Logic 1 present on pin CANRX.

11 - 56

F2833x - Controller Area Network 11 - 35


Alarm / Time Out Register

Alarm / Time Out Register


Local Network Time - CANLNT
CAN Local Network Time Register (CANLNT) – 0x00602E
31 16

LNT[31:16]

15 0

LNT[15:0]

 LNT is a Free Running Counter, Clocked from the bit


clock of the CAN module.
 LNT is written into the time stamp register (MOTS ) of
the corresponding mailbox when a received message
has been stored or a message has been transmitted.
 LNT is cleared when mailbox #16 is transmitted or
received. Thus mailbox #16 can be used for a global
network time synchronization.

11 - 57

Time Out Control - CANTIOC


CAN Time Out Control Register (CANTOC) – 0x006030
31 0

TOC[31:0]

Time Out Control Bits (TOC)


0 = Time Out function is disabled for mailbox n.
1 = Time Out function is enabled for mailbox n.
If LNT is greater than the corresponding MOTO register, a time out event will be generated

CAN Time Out Status Register (CANTOS) – 0x006032


31 0
TOS[31:0]

Time Out Status Flags (TOS)


0 = No Time Out occurred for mailbox n.
1 = The value in LNT is greater or equal to the value in the corresponding MOTO register

11 - 58

11 - 36 F2833x - Controller Area Network


Alarm / Time Out Register

Local Acceptance Mask - LAMn


CAN Local Acceptance Mask Register
0x00 6040 - 0x00 607F
0 = IDE bit of mailbox determines which message shall be received
1 = extended or standard frames can be received.
extended: all 29 bit of LAM are used for filter against all 29 bit of mailbox .
standard: only first eleven bits of mailbox and LAM [28-18] are used.

31 30-29 28 16

LAMI reserved LAMn[28:16]

15 0
LAMn[15:0]

LAMn[28-0]: Masking of identifier bits of incoming messages


1 = don’t care ( accept 1 or 0 for this bit position ) of incoming identifier.
0 = received identifier bit must match the corresponding message identifier bit (MID).

Note: There are two operating modes of the CAN module : “HECC” and “SCC”.
In “SCC” (default after reset ) LAM0 is used for mailboxes 0 to 2, LAM3 is used for mailboxes 3 to 5
and the global acceptance mask (CANGAM) is used for mailboxes 6 to 15.

In “HECC” ( CANMC:13 = 1) each mailbox has its own mask register LAM0 to LAM31.

11 - 59

Message Object Time Stamp - MOTSn


CAN Message Object Time Stamp
0x00 6080 - 0x00 60BF

31 16

MOTSn[31:16]

15 0

MOTSn[15:0]

A free running counter (register CANLNT) is used to get a stamp


of the time of reception or transmission of a message.

CANLNT is a 32 bit timer that is clocked by the CAN – bit – time unit.

The current content of CANLNT is written into MOTSn when a


received message has been stored or a message has been
transmitted successfully.

11 - 60

F2833x - Controller Area Network 11 - 37


Alarm / Time Out Register

Message Object Time Out - MOTOn


CAN Message Object Time-Out
0x00 60C0 - 0x00 60FF

31 16

MOTOn[31:16]

15 0

MOTOn[15:0]

If the value in CANLNT is equal or greater than the value in


MOTOn, the appropriate bit in register CANTOS will be set ,
assuming this feature was allowed in CANTOC.

Also, an Interrupt Service can be triggered from such an event.

11 - 61

11 - 38 F2833x - Controller Area Network


Mailbox Memory

Mailbox Memory
Message Identifier - CANMID
CAN Mailbox Memory
0x00 6100 - 0x00 61FF
Message Identifier Register (MID) Mailbox n
31 30 29 28 16 15 0

IDE AME AAM IDn[28:16] IDn[15:0]

Message Identifier
Standard Frames : IDn[28:18] are used
Extended Frames : IDn[28:0] are used

Auto Answer Mode Bit ( transmitter only)


0 = mailbox does not reply to remote requests.
1 = if a matching Remote Request is received, the contents of this mailbox will be sent.
Acceptance Mask Enable Bit ( receiver only)
0 = no Acceptance Mask used. All identifier bits must match to receive the message
1 = the corresponding Mailbox Acceptance Mask is used
Address Content
Identifier Extension Bit
0 = Standard Identifier (11 Bits) 0x6100 MSGID Mailbox 0
1 = Extended Identifier (29 Bits)
0x6102 MSGCTRL Mailbox 0
0x6104 CANMDL Mailbox 0; 4 lower data bytes
0x6106 CANMDH Mailbox 0; 4 upper data bytes11 - 62

Message Control Field - CANMCF


CAN Mailbox Memory
0x00 6100 - 0x00 61FF
Message Control Field Register (MCF) Mailbox n
31 16 15 13 12 8 7 5 4 3 0

reserved reserved TPL reserved RTR DLC

Transmit Priority Level


Priority compared to the other 31 mailboxes. Data Length Code
Highest number has highest priority. Valid numbers are 0 to 8.

Remote Transmission Request


0 = no RTR requested.
1 = for receiver mailboxes:
if TRS bit is set, a remote frame is transmitted and the corresponding
data frame will be received in the same mailbox.
1 = for transmit mailboxes:
if TRS bit is set, a remote frame is transmitted but the corresponding
data frame has to be received in another mailbox.

11 - 63

F2833x - Controller Area Network 11 - 39


Mailbox Memory

Message Data Field Low - CANMDL


CAN Mailbox Memory
0x00 6100 - 0x00 61FF

Message Data Low (MDL) Register with DBO = 0 Mailbox n


31 24 23 16 15 8 7 0

Data Byte 0 Data Byte 1 Data Byte 2 Data Byte 3

Message Data Low (MDL) Register with DBO = 1 Mailbox n


31 24 23 16 15 8 7 0

Data Byte 3 Data Byte 2 Data Byte 1 Data Byte 0

11 - 64

Message Data Field High - CANMDH

CAN Mailbox Memory


0x00 6100 - 0x00 61FF

Message Data High (MDH) Register with DBO = 0 Mailbox n


31 24 23 16 15 8 7 0

Data Byte 4 Data Byte 5 Data Byte 6 Data Byte 7

Message Data High (MDH) Register with DBO = 1 Mailbox n


31 24 23 16 15 8 7 0

Data Byte 7 Data Byte 6 Data Byte 5 Data Byte 4

11 - 65

11 - 40 F2833x - Controller Area Network


Lab Exercise 11_1

Lab Exercise 11_1


CAN Example: transmit a frame
 Lab 11_1: Transmit a CAN message
 CAN baud rate: 100 kBit/s
 Transmit a one byte message every second
 Message Identifier 0x 1000 0000 (extended frame)
 Use Mailbox #5 as transmit mailbox
 Message content: current value of a binary
counter
 Transceiver SN65HVD230 in use
 Connect CAN at header J4 of Peripheral Explorer
 J4-1: CAN_H
 J4-2: CAN_L

11 - 66

Preface
After this lengthy (and boring) discussion of all CAN registers in an F2833x, it is time for an
exercise. Again, it is a good idea to start with some simple experiments to get our hardware
to work. Later, we can try to refine the projects by setting up enhanced operation modes such
as “Remote Transmission Request”, “Auto Answer Mode”, “Pipelined Mailboxes” or
“Wakeup Mode”. We will also refrain from using the powerful error recognition and error
management, which of course would be an essential part of a real - world project. To keep it
simple, we will first use a polling method instead of an interrupt driven communication be-
tween the core of the DSP and the CAN mailbox server. Once you have a working example,
it is much simpler to improve the code in this project by adding more enhanced operating
modes to it.

The CAN physical layer requires a transceiver circuit between the digital signals of the
F2833x and the bus lines to adjust the physical voltages. The Peripheral Explorer Board is
equipped with a Texas Instruments SN65HVD230 for high speed ISO 11898 applications.
This transceiver is connected to GPIO30 (CAN - RX) and GPIO31 (CAN - TX).

The physical CAN lines for ISO 11898 require a correct line termination at the ends of the
transmission lines by 120 Ohm terminator resistors. The Peripheral Explorer Board has a
terminator of 120 Ohm (R8) connected between CANH and CANL. This resistor can be ac-
tivated by closing header J24 of the Peripheral Explorer Board. However, if your laboratory
layout consists of a group of devices, only the two outmost devices should be equipped with
that terminator resistor. In such circumstances all inner boards should keep jumper J24 open.

F2833x - Controller Area Network 11 - 41


Lab Exercise 11_1

Recall that the overall line resistance should match 60 Ohms. If you are in doubt, ask your
teacher which set up is the correct one.

To test your code, you will need a partner team with a second F2833x doing Lab 11_2. This
lab is an experiment to receive a CAN message and display its data at GPIO9, GPIO11,
GPIO34 and GPIO49 (LEDs LD1 to LD4) on the Peripheral Explorer Board.
The lines CANH and CANL are available at header J4 of the Peripheral Explorer Board. A
common technique according to CiA DS 102 (www.can-cia.org) for physical CAN cables is
based on DB9 connectors:

Pin Nr. Signal Description


1 - Reserved
2 CAN_L CAN Bus Signal (dominant low)
3 CAN_GND CAN ground
4 - Reserved
5 CAN_SHLD Optional shield
6 GND Optional CAN ground
7 CAN_H CAN Bus Signal (dominant high)
8 - Reserved
9 CAN_V+ Optional external voltage supply Vcc

At minimum we need CANL (pin 2), CANH (pin 7) and preferably CAN_GND (pin3).

Before you start the hard wiring, ask your teacher or a laboratory
technician what exactly you are supposed to do to connect the
boards!

Objective
• The objective of Lab 11_1 is to transmit a one byte data frame every second via
CAN.

• The transmitted data byte is the current value of a binary counter, which is in-
cremented after each transmission.

• The baud rate for this CAN exercise should be set to 100 kbit/s.

• The exercise will use extended identifier 0x1000 0000 for the transmit message.
You can also use any other number as identifier, but please make sure that your
partner team (Lab 11_2) knows about your intentions. If several Peripheral Ex-
plorer Boards in your classroom are in use simultaneously, there is the option to
set-up pairs of teams sharing the CAN by using different identifiers. It is also

11 - 42 F2833x - Controller Area Network


Lab Exercise 11_1

possible that due to the structure of the laboratory set-up at your university, not
all identifier combinations might be available to you. You surely don’t want in-
advertently to start the ignition of a combustion engine control unit that is also
connected to the CAN for some other experiments. Before you select other iden-
tifiers, ask your teacher!

• Use Mailbox #5 as your transmit mailbox.

• Once you have started a CAN transmission, wait for completion by polling the
status bit. Doing so we can avoid using CAN interrupts for this first CAN exer-
cise.

• Use CPU core timer 0 to generate the one second interval.

Procedure

Open Files, Create Project File


1. Using Code Composer Studio, create a new project, called Lab11.pjt in
C:\DSP2833x_V4\Labs (or in another path that is accessible by you; ask your teacher
or a technician for an appropriate location!).
2. A good point to start with is the source code of Lab6.c, which produces a hardware
based time period using CPU core timer 0. Open the file Lab6.c from
C:\DSP2833x_V4\Labs\Lab6 and save it as Lab11_1.c in folder
C:\DSP2833x_V4\Labs\Lab11.
3. Define the size of the C system stack. In the project window, right click at project
“Lab11” and select “Properties”. In category “C/C++ Build”, “C2000 Linker”, “Basic
Options” set the C stack size to 0x400.

Link some of the source code files, provided by Texas Instruments, to the project:
4. In the C/C++ perspective, right click at project “Lab8” and select “Link Files to
Project”. Go to folder “C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\source” and
link:

• DSP2833x_GlobalVariableDefs.c
From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\source link:
• DSP2833x_PieCtrl.c
• DSP2833x_PieVect.c
• DSP2833x_DefaultIsr.c
• DSP2833x_CpuTimers.c
• DSP2833x_SysCtrl.c
• DSP2833x_CodeStartBranch.asm
• DSP2833x_ADC_cal.asm
• DSP2833x_usDelay.asm
From C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\cmd link:

F2833x - Controller Area Network 11 - 43


Lab Exercise 11_1

• DSP2833x_Headers_nonBIOS.cmd

Project Build Options


5. We have to extent the search path of the C-Compiler for include files. Right click at
project “Lab11” and select “Properties”. Select “C/C++ Build”, “C2000 Compiler”,
“Include Options”. In the box: “Add dir to #include search path”, add the following
lines:

C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include

Note: Use the “Add” Icon to add the new paths:

Close the Property Window by Clicking <OK>.

Preliminary Test
6. So far we have just created a new project “Lab11.pjt” with the same functionality as in
Lab6. A good step would be to rebuild Lab11, load the code into the controller and
verify the binary counter at LEDs LD1 to LD4 of the Peripheral Explorer Board. The
LEDs should display the counter at 100 milliseconds time steps.
7. Now change time step size in “Lab11_1.c” from 100 ms to 1 second. All you need to
do is to change the initialization call for CPU Timer 0:

ConfigCpuTimer(&CpuTimer0,150,1000000);
8. Rebuild the code and test again; the counter frequency should be 1 second.
Is your result as expected? NO, the LEDs are not blinking anymore!
Do you have the answer?
Well, we forgot to take care of the watchdog unit! When you inspect the while(1)-loop
in main, you see that we wait until variable “CpuTimer0.InterruptCount” gets set to 1.
Because of our change in the Timer 0 setup we now wait exactly 1000 milliseconds,
which is too long for the watchdog unit.
What can be done? We have to include the watchdog service instructions (0x55 and
0xAA) into the wait - construction.
Change the code accordingly, rebuild and test again.
The LEDs should now change once every second.

11 - 44 F2833x - Controller Area Network


Lab Exercise 11_1

Note: To place both watchdog service instructions into the same place in the program
is not the best solution. A better initialization would be to keep the first service
instruction inside the CPU Timer 0 Interrupt service function and to add the second
service instruction only into the wait - construction. However, we have to reduce the
period of CPU - Timer 0 back to 100 milliseconds to keep it inside the watchdog
range. In this case we have to wait until variable “CpuTimer0.InterruptCount” gets set
to 10 to get the 1 second interval. If your laboratory time permits, you should try to
improve your code in such a way.

Add CAN Initialization Code


9. From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\source link to your project:

• DSP2833x_ECan.c
Before we can start editing our own code we have to inspect two files, which have
been provided by Texas Instruments.
10. From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\include open
“DSP2833x_Examples.h”.
Verify that the following macros are defined as below:
#define DSP28_DIVSEL 2 // Enable /2 for SYSCLKOUT
#define DSP28_PLLCR 10 // multiply by 10/2
#define CPU_RATE 6.667L // for 150MHz (SYSCLKOUT)
#define CPU_FRQ_150MHZ 1 // 150 MHz CPU Freq (30 MHz Osc.)
The source code in “DSP2833x_ECan.c” uses the macro “CPU_FRQ_150MHZ” to
initialize the CAN data rate; therefore we have to make sure that this macro is set to 1.
11. Open and edit file “DSP2833x_ECan.c”.
We have to set the CAN data rate to 100 kbit/s. If the F2833x runs at SYSCLKOUT =
150MHz, the CAN input clock is 75 MHz. According to the numbers given in Slide 11
- 46, we have to initialize register CANBTC with:

• BRP = 49
• TSEG1 = 10
• TSEG2 = 2

F2833x - Controller Area Network 11 - 45


Lab Exercise 11_1

CAN Bit-Timing Examples


 Bit Configuration for BaseCLK = 75 MHz
 Sample Point at 80% of Bit Time :

CAN - BRP TSEG1 TSEG2


data rate

1 Mbit/s 4 10 2

500 kbit/s 9 10 2

250 kbit/s 19 10 2

125 kbit/s 39 10 2

100 kbit/s 49 10 2

50 kbit/s 99 10 2

 Example 100 kbit/s


TQ = (49+1)/ 75 MHz = 0.667 µs
tseg1 = 0.667 µs (10 + 1) = 7.337 µs  tCAN = 10 µs;
tseg2 = 0.667 µs (2 + 1) = 2 µs
11 - 46

In function “InitECana(void)” search for the line

#if (CPU_FRQ_150MHZ)

and change the initialization values for BRPREG, TSEG1REG and TSEG2REG.

Initialize CAN Mailbox


12. Now open Lab11_1.c to edit.
First, add a new structure “ECanaShadow” as a local variable in main:

struct ECAN_REGS ECanaShadow;


This structure will be used as a local copy of the original CAN registers. A
manipulation of individual bits is done inside the copy. At the end of the access, the
whole copy is reloaded into the original CAN structures. This operation is necessary
because of the inner structure of the CAN unit; some registers are only accessible by
32 - bit accesses and by copying the whole structure, we make sure to generate 32 - bit
accesses only.
13. In “main()”, after the function call “Gpio_select()”, add a function call of
“InitECan()”. Also, add an external prototype for that function at the beginning of
“main()”.
14. Next, inside function “Gpio_select()”, enable the peripheral function of CANA_TX
and CANA_RX connected to lines GPIO30 and GPIO31.

11 - 46 F2833x - Controller Area Network


Lab Exercise 11_1

15. In “main()”, after the function call to “InitECan()”, add code to prepare the transmit
mailbox. In this exercise, we will use mailbox #5, an extended identifier of
0x10000000 and a data length code of 1. Add the following steps:
• Write the identifier 0x10000000 into register “EcanaMboxes.MBOX5.MSGID”.
• To transmit with extended identifiers set bit “IDE” of register
“EcanaMboxes.MBOX5.MSGID” to 1.
• Configure Mailbox #5 as a transmit mailbox. This is done by setting bit MD5 of
register “ECanaRegs.CANMD” to 0. Caution! Due to the internal structure of the
CAN-unit, we cannot execute single bit accesses to the original CAN registers. A
good practice is to copy the whole register into a shadow register, manipulate the
shadow register and copy the modified 32 - bit shadow value back into the original
register :
ECanaShadow.CANMD.all = ECanaRegs.CANMD.all;
ECanaShadow.CANMD.bit.MD5 = 0;
ECanaRegs.CANMD.all = ECanaShadow.CANMD.all;
• Enable Mailbox #5:
ECanaShadow.CANME.all = ECanaRegs.CANME.all;
ECanaShadow.CANME.bit.ME5 = 1;
ECanaRegs.CANME.all = ECanaShadow.CANME.all;
• Set up the Data Length Code Field (DLC) in Message Control Register
“ECanaMboxes.MBOX5.MSGCTRL” to 1 and clear all remaining bits of this
register.

Add the Data Byte and Transmit


16. Now we are almost done. The last part of code modification is the periodical loading
of the data byte into the mailbox and the transmit request command. This must be
done inside the while(1)-loop of “main()”. Locate the code where we waited for the
next period of 1 second. Here add:
• Load the current value of variable counter into register
“ECanaMboxes.MBOX5.MDL.byte.BYTE0”. Recall that we would like to send a
one - byte message; therefore we have to load only the lower 8 bits of “counter”!
• Request a transmission of mailbox #5. Init register “ECanaShadow.CANTRS”.
Set bit TRS5=1 and all other 31 bits to 0. Next, load the whole register into
“ECanaRegs.CANTRS”
• Wait until the CAN unit has acknowledged the transmit request. The flag
“ECanaRegs.CANTA.bit.TA5” will be set to 1 if your request has been
acknowledged.
• Clear bit “ECanaRegs.CANTA.bit.TA5”. Again the access must be made as a 32
- bit access:
ECanaShadow.CANTA.all = 0;
ECanaShadow.CANTA.bit.TA5 = 1;

F2833x - Controller Area Network 11 - 47


Lab Exercise 11_1

ECanaRegs.CANTA.all = ECanaShadow.CANTA.all;
17. Remove the old code that was used to display the binary counter at LEDs LD1 to LD4.
Just keep the increment instruction for “counter”.

Build, Load and Run


18. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)


and watch the tools run in the build window. If you get errors or warnings debug as
necessary.

19. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

20. Verify that in the debug perspective the window of the source code “Lab11_1.c” is
high-lighted and that the blue arrow for the current Program Counter position is placed
under the line “void main(void)”.

21. Perform a real time run.

Target  Run

Providing you have found a partner team with another F2833x connected to your
laboratory CAN system that has prepared the receiver task (Lab11_2) you can do a
real network test. The current value from variable “counter” should be transmitted
every second via CAN.
If your teacher can provide a CAN analyser you should be able to trace your data
frames at CAN.
If you end up in a fight between the two teams about whose code might be wrong, ask
your teacher to provide a working receiver node. Recommendation for teachers: Store
a working receiver code version in the internal Flash of one node and start this node
out of flash memory.

End of Lab 11_1

11 - 48 F2833x - Controller Area Network


Lab Exercise 11_2

Lab Exercise 11_2


CAN Example : receive a frame
 Lab 11_2: Receive a CAN message
 CAN baud rate : 100 kBit/s
 Message Identifier 0x 1000 0000 (extended frame)
 Use Mailbox #1 as receive mailbox
 Display the binary counter at LEDs LD1 to LD4
(GPIO9, GPIO11, GPIO34 and GPIO49)

Pin Nr. Signal Description


1 - Reserved
2 CAN_L CAN Bus Signal (dominant low)
3 CAN_GND CAN ground
4 - Reserved
5 CAN_SHLD Optional shield
6 GND Optional CAN ground
7 CAN_H CAN Bus Signal (dominant high)
8 - Reserved
9 CAN_V+ Optional external voltage supply Vcc
11 - 67

Preface
This laboratory experiment is the second part of a CAN-Lab. Again we have to set up
the physical CAN-layer according to the layout of your laboratory.

The CAN physical layer requires a transceiver circuit between the digital CAN signal
levels of the F2833x and the bus lines to adjust the physical voltages. The Peripheral
Explorer Board is equipped with a Texas Instruments SN65HVD230 for high speed
ISO 11898 applications. This transceiver is connected to GPIO30 (CAN - RX) and
GPIO31 (CAN - TX).

The physical CAN lines for ISO 11898 require a correct line termination at the ends
of the transmission lines by 120 Ohm terminator resistors. The Peripheral Explorer
Board has a terminator of 120 Ohm (R8) connected between CANH and CANL. This
resistor can be enabled by closing header J24 of the Peripheral Explorer Board.
However, if your laboratory layout consists of a group of devices, only the two out-
most devices should be equipped with that terminator resistor. In such circumstances
all inner boards should keep jumper J24 open. Recall that the overall line resistance
should match 60 Ohms. If you are in doubt, ask your teacher which set up is the cor-
rect one.

To test your code you will need a partner team with a second F2833x doing Lab
11_1, e.g. sending a one byte message with identifier 0x10 000 000 every second.
Before you start the hard wiring, ask your teacher or a laboratory techni-
cian what exactly you are supposed to do to connect the boards!

F2833x - Controller Area Network 11 - 49


Lab Exercise 11_2

Objective
• The objective of Lab 11_2 is to receive a one byte data message from CAN and
display the four least significant bits of that byte at LEDs LD1 to LD4 (GPIO9,
GPIO11, GPIO34 and GPIO49) of the Peripheral Explorer Board.

• The CAN data rate must be set to 100 kbit/s to match with Lab11_1.

• Also, to be compatible with Lab11_1, this exercise should use extended identi-
fier 0x1000 0000 for the receive filter of mailbox 1. You can also use any other
number as identifier, but please make sure that your partner team (Lab 11_1)
knows about your change. If several Peripheral Explorer Boards in your class-
room are in use simultaneously, it could be an option to set up pairs of teams
sharing the CAN by using different identifiers.

• Use Mailbox #1 as your receiver mailbox

• Once you have initialized the CAN module, wait for a reception of mailbox #1
by polling the status bit. Again, we do not need to use CAN interrupts for this
CAN exercise.

Procedure

Open Files, Create Project File


1. If you have already completed Lab11_1, you can use project Lab11.pjt as a starting
point. In this case, open project Lab11 and continue with procedure step #13.
If this Lab is your first CAN exercise, you will have to setup a new project. Using
Code Composer Studio, create a new project, called Lab11.pjt in
C:\DSP2833x_V4\Labs (or in another path that is accessible by you; ask your teacher
or a technician for an appropriate location!).
2. A good point to start with is the source code of Lab6.c, which produces a hardware
based time period using CPU core timer 0. Open the file Lab6.c from
C:\DSP2833x_V4\Labs\Lab6 and save it as Lab11_2.c in
C:\DSP2833x_V4\Labs\Lab11.
3. Define the size of the C system stack. In the project window, right click at project
“Lab11” and select “Properties”. In category “C/C++ Build”, “C2000 Linker”, “Basic
Options” set the C stack size to 0x400.

Link some of the source code files, provided by Texas Instruments, to the project:
4. In the C/C++ perspective, right click at project “Lab11” and select “Link Files to
Project”. Go to folder “C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\source” and
link:

• DSP2833x_GlobalVariableDefs.c

11 - 50 F2833x - Controller Area Network


Lab Exercise 11_2

From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\source link:


• DSP2833x_PieCtrl.c
• DSP2833x_PieVect.c
• DSP2833x_DefaultIsr.c
• DSP2833x_CpuTimers.c
• DSP2833x_SysCtrl.c
• DSP2833x_CodeStartBranch.asm
• DSP2833x_ADC_cal.asm
• DSP2833x_usDelay.asm
From C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\cmd link:

• DSP2833x_Headers_nonBIOS.cmd

Project Build Options


5. We have to extent the search path of the C-Compiler for include files. Right click at
project “Lab11” and select “Properties”. Select “C/C++ Build”, “C2000 Compiler”,
“Include Options”. In the box: “Add dir to #include search path”, add the following
lines:

C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include

Note: Use the “Add” Icon to add the new paths:

Close the Property Window by Clicking <OK>.

Preliminary Test
6. So far we have just created a new project “Lab11.pjt” with the same functionality as in
Lab6. A good step would be to rebuild Lab11, load the code into the controller and
verify the binary counter at LEDs LD1 to LD4 of the Peripheral Explorer Board. The
LEDs should display the counter at 100 milliseconds time steps.

F2833x - Controller Area Network 11 - 51


Lab Exercise 11_2

Add CAN Initialization Code


7. From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\source link:

• DSP2833x_ECan.c
Before we can start editing our own code, we have to modify two files, which have
been provided by Texas Instruments:
8. From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\include open
“DSP2833x_Examples.h”.
Verify that the following macros are defined as:
#define DSP28_DIVSEL 2 // Enable /2 for SYSCLKOUT
#define DSP28_PLLCR 10 // multiply by 10/2
#define CPU_RATE 6.667L // for 150MHz CPU SYSCLKOUT
#define CPU_FRQ_150MHZ 1 // 150 MHz CPU Freq (30 MHz Osc.)
The source code in “DSP2833x_ECan.c” uses the macro “CPU_FRQ_150MHZ” to
initialize the CAN data rate; therefore we have to make sure that this macro is set to 1.
9. Open and edit file “DSP2833x_ECan.c”.
We have to set the CAN data rate to 100 Kbit/s. If the F2833x runs at SYSCLKOUT
= 150MHz, the CAN input clock is 75 MHz. According to the numbers given in Slide
11 - 46, we have to initialize register CANBTC with:
• BRP = 49
• TSEG1 = 10
• TSEG2 = 2

CAN Bit-Timing Examples


 Bit Configuration for BaseCLK = 75 MHz
 Sample Point at 80% of Bit Time :

CAN - BRP TSEG1 TSEG2


data rate

1 Mbit/s 4 10 2

500 kbit/s 9 10 2

250 kbit/s 19 10 2

125 kbit/s 39 10 2

100 kbit/s 49 10 2

50 kbit/s 99 10 2

 Example 100 kbit/s


TQ = (49+1)/ 75 MHz = 0.667 µs
tseg1 = 0.667 µs (10 + 1) = 7.337 µs  tCAN = 10 µs;
tseg2 = 0.667 µs (2 + 1) = 2 µs
11 - 46

11 - 52 F2833x - Controller Area Network


Lab Exercise 11_2

In function “InitECana(void)” search for the line

#if (CPU_FRQ_150MHZ)

and change the initialization values for BRPREG, TSEG1REG and TSEG2REG.
Save and close file “DSP2833x_ECAN.c”.

Modify Source Code


10. Open Lab11_2.c to edit.
In “main()”, remove local variable “counter” and all instructions that use “counter” to
display bits 0, 1, 2 and 3 of “counter” at GPIO9, GPIO11, GPIO34 and GPIO49.
Add a new structure “ECanaShadow” as a local variable in main:

struct ECAN_REGS ECanaShadow;


This structure will be used as a local copy of the original CAN registers. A
manipulation of individual bits is done inside the copy. At the end of the access the
whole copy is reloaded into the original CAN structures. This principle of operation is
necessary because of the inner structure of the CAN unit; some registers are only
accessible by 32-bit accesses and by copying the whole structure, we make sure to
generate 32-bit accesses only.
11. In “main()”, after the function call “Gpio_select()”, add a function call to
“InitECan()”. Also, add an external prototype for this function at the beginning of
“main()”.
12. In function “Gpio_select()”, enable the peripheral function of CANA_TX and
CANA_RX connected to lines GPIO30 and GPIO31.
Continue with procedure step #16!
13. If you have already completed Lab11_1, open the file Lab11_1.c from
C:\DSP2833x_V4\Labs\Lab11 and save it as Lab11_2.c in
C:\DSP2833x_V4\Labs\Lab11.
14. Exclude file “Lab11_1.c” from build. Use a right mouse click at file “Lab11_1.c”, and
enable “Exclude File(s) from Build”.
15. In function “main()” of the file “lab11_2”, remove all the code, which we used to
initialize the transmit mailbox #5 and the code to transmit messages with mailbox #5.

Prepare Receiver Mailbox #1


16. In “main()”, after the function call of “InitECan()”, add code to prepare the receiver
mailbox. In this exercise, we will use mailbox #1, an extended identifier of
0x10000000 and a data length code of 1. Add the following steps:
• Write the identifier into register “EcanaMboxes.MBOX1.MSGID”.

F2833x - Controller Area Network 11 - 53


Lab Exercise 11_2

• To transmit with extended identifiers set bit “IDE” of register


“EcanaMboxes.MBOX1.MSGID” to 1.
• Configure Mailbox #1 as a receive mailbox. This is done by setting bit MD1
of register “ECanaRegs.CANMD” to 1. Caution! Due to the internal
structure of the CAN-unit, we cannot execute single bit accesses to the
original CAN registers. A good practice is to copy the whole register into a
shadow register, manipulate the shadow register and copy the modified 32 -
bit shadow value back into the original register :
ECanaShadow.CANMD.all = ECanaRegs.CANMD.all;
ECanaShadow.CANMD.bit.MD1 = 1;
ECanaRegs.CANMD.all = ECanaShadow.CANMD.all;
• Enable Mailbox #1:
ECanaShadow.CANME.all = ECanaRegs.CANME.all;
ECanaShadow.CANME.bit.ME1 = 1;
ECanaRegs.CANME.all = ECanaShadow.CANME.all;

Wait for a message in mailbox 1


17. Now we are almost done. The last missing piece is a poll a status flag “RMP1” to see,
if we have received data in mailbox 1. The best position to do this is after the 100
millisecond “while(…)” - wait construct in “main()”. Register
“ECanaRegs.CANRMP” - bit field “RMP1” will be set to 1 if a valid message has
been received. If this bit has been set, we can proceed and process the new message.
18. If bit “RMP1” was set to 1 by the CAN - Mailbox logic we can read the data byte 0
from the mailbox and load it into a local Uint16 variable “temp”:
temp = ECanaMboxes.MBOX1.MDL.byte.BYTE0;
Of course, we have to define “temp” at the beginning of “main()”.
Next, we have to reset bit RMP1. This is done by writing a ‘1’ to it:
ECanaRegs.CANRMP.bit.RMP1 = 1;
19. Finally we need some code to decode bits 0, 1, 2 and 3 of “temp” and update the LEDs
at GPIO9, GPIO11, GPIO34 and GPIO49.

Build, Load and Run


20. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

and watch the tools run in the build window. If you get errors or warnings debug as
necessary.

21. Load the output file in the debugger session:

11 - 54 F2833x - Controller Area Network


Target  Debug Active Project

and switch into the “Debug” perspective.

22. Verify that in the debug perspective the window of the source code “Lab11_2.c” is
high-lighted and that the blue arrow for the current Program Counter position is placed
under the line “void main(void)”.

23. Perform a real time run.

Target  Run
24. Assuming you have paired with another team which transmits a one-byte data frame
with identifier 0x10000000 you can do a real network test. Ask your partner team to
start their board and transmit a binary counter every second.
If your teacher can provide a CAN analyzer you can also generate a transmit message
from this CAN analyzer.
If you end up in a fight between the two teams about whose code might be wrong, ask
your teacher to provide a working transmitter node.
Recommendation for teachers: Store a working transmitter code version in the internal
Flash of one node and start this node out of flash memory.

End of Lab 11_2

What’s next?
Congratulations! You’ve successfully finished your first two lab exercises using Controller
Area Network. As mentioned earlier in this chapter these two labs were chosen as a sort of
“getting started” with CAN. To learn more about CAN it is necessary to book additional
classes at your university.

To experiment a little bit more with CAN, choose one or more of the following optional
exercises:

Lab 11_3:
Combine Lab11_1 (CAN - Transmit) and Lab11_2 (CAN-Receive) into a bi-directional
solution. The task for your node is to transmit the status of the 4-bit hex encoder
(GPIO12...15) every second (or optional: every time the status has changed) with a one-byte
frame and identifier 0x10 000 000. Simultaneously, your node must also be able to receive
CAN messages with identifier 0x11 000 000 and display bits 0 to 3 of that message’s byte 0
at the LEDs (GPIO9 , GPIO11, GPIO34 and GPIO49) of the Peripheral Explorer Board.

F2833x - Controller Area Network 11 - 55


What’s next?

Lab 11_4:
Try to improve Lab11_2 and Lab11_3 by using the F2833x Interrupt System for the receiver
part of the exercises. Instead of polling the “CANRMP-bit field” to wait for an incoming
message your task is to use a mailbox interrupt request to read out the mailbox when
necessary.

Lab 11_5:
We did not consider any possible error situations on the CAN side so far. That is not a good
solution for a real - world project. Try to improve your previous CAN experiments by
including the servicing of potential CAN errors. Review the CAN error status register flags
and all possible errors. A good solution would be to allow CAN error interrupts to request
their individual service routines in case of a CAN failure. What should be done in the case of
an error request? Answer: Well, our Peripheral Explorer Board does not feature a lot of
additional hardware that we could use to indicate such an error situation. So let us just switch
LED LD1 to ON in case of a failure.
Another option could be to monitor the status of the two CAN - error counters. If one of the
two counters goes above 50, switch on LED LD2.
If your laboratory is equipped with a CAN failure generator like “CANstress” (Vector
Informatik GmbH, Germany) you can generate reproducible disturbance of the physical
layer, you can destroy certain messages and manipulate certain bit fields with bit resolution.
Ask your laboratory technician whether you have access to this type of equipment to invoke
CAN errors.

Lab 11_6:
An enhanced experiment is to request a remote transmission from another CAN-node. An
operating mode, that is quite often used is the so-called “automatic answer mode”. A
transmit mailbox, that receives a remote transmission request (“RTR”) answers
automatically by transmitting a predefined frame. Try to establish this operating mode for the
transmitter node (Lab11_1 or Lab11_3). Wait for a RTR and send the current status of the 4-
bit hex encoder (GPIO12...15) back to the requesting node. The node that has requested the
remote transmission should be initialized to wait for the requested answer and display the
four LSBs of byte 1 from the received data frame at LEDs LD1 to LD4(GPIO9, GPIO11,
GPIO34 and GPIO49).
There are a lot more options for RTR operations available. Again, look out for additional
CAN classes at your university!

11 - 56 F2833x - Controller Area Network


F2833x Inter Integrated Circuit

Introduction
This module discusses the features and operation of the inter-integrated circuit (I2C) module
that is available on the F2833x digital signal controller (DSC). The I2C module provides an
interface between DSCs and devices compliant with Philips Semiconductors Inter-IC bus
(I2C-bus) specification version 2.1 and connected by way of an I2C-bus. External compo-
nents attached to this 2-wire serial bus can transmit and/or receive data between 1-bit and 8-
bits to/from the F2833x through the I2C module. This student guide assumes the reader is
somewhat familiar with the I2C-bus specification.

Each device connected to an I2C-bus is identified by a unique address. It can operate as ei-
ther a transmitter or a receiver, depending on the function of the device. A device connected
to the I2C - bus can also be considered as the master or the slave when performing data
transfers. A master device is the device that initiates a data transfer on the bus and generates
the clock signals to permit that transfer. During this transfer, any device addressed by this
master is considered to be a slave.

The I2C module supports the multi-master mode, in which one or more devices are capable
of controlling an I2C-bus and can be connected to the same I2C-bus.

For data communication, the I2C module has a serial data pin (SDA) and a serial clock pin
(SCL). The SDA and SCL pins both are bidirectional. They must each be connected to a
positive 3.3 V supply voltage using pull-up resistors. When the bus is free, both pins are
high. The driver of these two pins has an open-drain configuration to perform the required
wired-AND function. The F2833x includes internal pull-up resistors for SDA and SCL,
which can be enabled during the setup of the GPIO - pins.

F2833x - Inter Integrated Circuit 12 - 1


Module Topics

Module Topics
F2833x Inter Integrated Circuit ..................................................................................................... 12-1
Introduction ................................................................................................................................... 12-1
Module Topics ............................................................................................................................... 12-2
Basic I2C Features ........................................................................................................................ 12-4
F2833x I2C Block Diagram .......................................................................................................... 12-5
I2C Clock Generation ................................................................................................................... 12-6
I2C Operating Modes .................................................................................................................... 12-8
Master / Slave modes ................................................................................................................ 12-8
Input and Output Voltage Levels .............................................................................................. 12-8
Data Validity ............................................................................................................................. 12-9
Serial Data Formats ................................................................................................................ 12-10
Arbitration ................................................................................................................................... 12-11
I2C Interrupts .............................................................................................................................. 12-12
I2C Module Registers .................................................................................................................. 12-13
I2C Mode Register .................................................................................................................. 12-13
I2C Interrupt Enable Register ................................................................................................. 12-17
I2C Status Register ................................................................................................................. 12-17
I2C Interrupt Source Register ................................................................................................. 12-18
I2C Clock Register.................................................................................................................. 12-18
I2C Slave Address Register .................................................................................................... 12-19
I2C Own Address Register ..................................................................................................... 12-20
I2C Data Count Register ......................................................................................................... 12-20
I2C Data Registers .................................................................................................................. 12-21
I2C FIFO Buffers ........................................................................................................................ 12-21
I2C TX-FIFO Register ............................................................................................................ 12-22
I2C RX-FIFO Register ............................................................................................................ 12-22
Temperature Sensor TMP100 ..................................................................................................... 12-23
TMP100 Register Structure .................................................................................................... 12-25
Temperature Register .............................................................................................................. 12-26
Configuration Register ............................................................................................................ 12-26
TMP100 Timing Diagrams ..................................................................................................... 12-27
Lab Exercise 12_1 ....................................................................................................................... 12-30
Preface .................................................................................................................................... 12-30
Objective ................................................................................................................................. 12-30
Procedure ................................................................................................................................ 12-30
Open Files, Create Project File ............................................................................................... 12-30
Project Build Options .............................................................................................................. 12-31
Preliminary Test ...................................................................................................................... 12-32
Add TMP100 and I2C Initialization Code .............................................................................. 12-32
Build, Load and Run ............................................................................................................... 12-34
Lab Exercise 12_2 ....................................................................................................................... 12-35
Objective ................................................................................................................................. 12-35
Procedure ................................................................................................................................ 12-35
Open Project, Modify Source File .......................................................................................... 12-35
Build, Load and Run ............................................................................................................... 12-36
Troubleshooting ...................................................................................................................... 12-38

12 - 2 F2833x - Inter Integrated Circuit


Module Topics

Lab Exercise 12_3 ...................................................................................................................... 12-40


Objective ................................................................................................................................ 12-40
Procedure ................................................................................................................................ 12-40
Open Project, Modify Source File .......................................................................................... 12-40
Build, Load and Run .............................................................................................................. 12-41
Lab Exercise 12_4 ...................................................................................................................... 12-42
Objective ................................................................................................................................ 12-42
Procedure ................................................................................................................................ 12-42
Open Project, Modify Source File .......................................................................................... 12-42
Build, Load and Run .............................................................................................................. 12-44

F2833x - Inter Integrated Circuit 12 - 3


Basic I2C Features

Basic I2C Features


The I2C module supports any slave or master I2C-compatible device.

Inter Integrated Circuit(I2C, IIC)


• Philips I2C-bus specification compliant, version 2.1
• Data transfer rate from 10 kbps up to 400 kbps
• Each device can be considered as a Master or Slave
• Master initiates data transfer and generates clock signal
• Device addressed by Master is considered a Slave
• Multi-Master mode supported
• Standard Mode – send exactly n data values (specified in register)
• Repeat Mode – keep sending data values (use software to initiate
a stop or new start condition)
VDD

Pull-up 2833x 2nd - I2C


Resisters I2C Controller

Serial Data (SDA)


Serial Clock (SCL)

I2C TMP101
EPROM I2C
12 - 2

The I2C module has the following features:

• Compliance with the Philips Semiconductors I2C-bus specification (version 2.1):


o Support for 8-bit format transfers
o 7-bit and 10-bit addressing modes
o General call
o START byte mode
o Support for multiple master-transmitters and slave-receivers
o Support for multiple slave-transmitters and master-receivers
o Combined master transmit/receive and receive/transmit mode
o Data transfer rate of from 10 kbps up to 400 kbps (Philips Fast-mode rate)
• One 16-byte deep receive FIFO and one 16-byte deep transmit FIFO
• An interrupt can be generated as a result of one of the following conditions:
o transmit-data ready,
o receive-data ready,
o register-access ready,
o no-acknowledgment received,
o arbitration lost,
o stop condition detected,
o addressed as slave.
• Free data format mode

12 - 4 F2833x - Inter Integrated Circuit


F2833x I2C Block Diagram

F2833x I2C Block Diagram


I2C Block Diagram

I2CXSR I2CDXR

TX FIFO
SDA
RX FIFO

I2CRSR I2CDRR

Clock
SCL
Circuits

12 - 3

The I2C module consists of the following primary blocks:


• A serial interface: one data pin (SDA) and one clock pin (SCL)
• Data registers and FIFOs to temporarily hold receive data and transmit data travel-
ling between the SDA pin and the CPU
• Control and status registers
• A peripheral bus interface to enable the CPU to access the I2C module registers and
FIFOs.
• A clock synchronizer to synchronize the I2C input clock (from the DSP clock gen-
erator) and the clock on the SCL pin, and to synchronize data transfers with masters
of different clock speeds required.
• A pre-scaler to divide down the input clock that is driven to the I2C module
• A noise filter on each of the two pins, SDA and SCL
• An arbitrator to handle arbitration between the I2C module (when it is a master) and
another master
• Interrupt generation logic, so that an interrupt can be sent to the CPU.

Slide 12-3 shows the four registers used for transmission and reception in non-FIFO mode.
The CPU writes data for transmission to I2CDXR and reads received data from I2CDRR.
When the I2C module is configured as a transmitter, data written to I2CDXR is copied to
I2CXSR and shifted out on the SDA pin one bit a time. When the I2C module is configured
as a receiver, received data is shifted into I2CRSR and then copied to I2CDRR.

F2833x - Inter Integrated Circuit 12 - 5


I2C Clock Generation

I2C Clock Generation


As shown in Slide 12-4, the I2C input clock is equivalent to the CPU clock (SYSCLKOUT)
and is then divided twice more inside the I2C module to produce the module clock and the
master SCL clock.

I2C Clock Generation

I2C – Clock Module

IPSC ICCL, ICCH

SYSCLKOUT SCL (*)


÷ ÷

I2C Module Clock

(*) SCL is output in master – mode only


12 - 4

The I2C module clock determines the frequency at which the I2C module operates. A pro-
grammable pre-scaler in the I2C module divides down the I2C input clock to produce the
module clock. To specify the divide-down value, initialize the IPSC field of the pre-scaler
register, I2CPSC. The resulting frequency should be in the range of 7 - 12 MHz and is given
by:

SYSCLKOUT
I 2C _ Module _ Clock =
( IPSC + 1)

IPSC must be initialized only while the I2C module is in the reset state (IRS = 0 in
I2CMDR). The pre-scaled frequency takes effect only when IRS is changed to 1. Changing
the IPSC value while IRS = 1 has no effect.

The master clock appears on the SCL pin when the I2C module is configured to be a master
on the I2C-bus. This clock controls the timing of communication between the I2C module
and a slave. As shown in slide 12-4, a second clock divider in the I2C module divides down
the module clock to produce the master clock. The clock divider uses the ICCL value of
I2CCLKL to divide down the low portion of the module clock signal and uses the ICCH
value of I2CCLKH to divide down the high portion of the module clock signal.

12 - 6 F2833x - Inter Integrated Circuit


I2C Clock Generation

Example for I2C-clock calculation:

The period of the master clock (TMASTER) is a multiple of the period of the I2C module clock:

( IPSC + 1)[( ICCL + d ) + ( ICCH + d )]


TMASTER =
SYSCLKOUT

Parameter d is a systematic offset, which depends on the device type.

Example: Set I2C-Master clock to 50 kHz for a 150 MHz device

(1) Set I2C module clock to 10MHz:

100 MHz
10 MHz = ; IPSC = 14
( IPSC + 1)

(2) Set I2C Master clock to 20µs; use d = 5

(14 + 1)[( ICCL + 5) + ( ICCH + 5)]


20 µs =
150 MHz

ICCL + ICCH = 190;

To produce an I2C master clock with a duty cycle of 50% set:

• IPSC = 14
• ICCL = 95
• ICCH = 95

The following table give some more options for the I2C clock unit:

SYSCLKOUT 100 MHz 100MHz 150MHz 150MHz

I2C-clock IPSC ICCL / ICCH IPSC ICCL / ICCH

50 kHz 9 95 / 95 14 95 /95

100 kHz 9 45 / 45 14 45 /45

400 kHz 9 10 / 5 14 10 / 5

F2833x - Inter Integrated Circuit 12 - 7


I2C Operating Modes

I2C Operating Modes


Master / Slave modes
The I2C module has four basic operating modes to support data transfers as a master and as a
slave.

If the I2C module is a master, it begins as a master-transmitter and typically transmits an ad-
dress for a particular slave. When giving data to the slave, the I2C module must remain a
master-transmitter. To receive data from a slave, the I2C module must be changed to the
master-receiver mode.

When the I2C module is a slave, it begins as a slave-receiver and typically sends acknowl-
edgment when it recognizes its slave address from a master. If the master is sending data to
the I2C module, the module must remain a slave-receiver. If the master has requested data
from the I2C module, the module must be changed to the slave-transmitter mode.

I2C Operating Modes

Operating Mode Description

Slave-receiver mode Module is a slave and receives data from a master


(all slaves begin in this mode)

Slave-transmitter mode Module is a slave and transmits data to a master


(can only be entered from slave-receiver mode)

Master-receiver mode Module is a master and receives data from a slave


(can only be entered from master-transmit mode)

Master-transmitter mode Module is a master and transmits to a slave


(all masters begin in this mode)

12 - 5

Input and Output Voltage Levels


One clock pulse is generated by the master device for each data bit transferred. Due to a va-
riety of different technology devices that can be connected to the I2C-bus, the levels of logic
0 (low) and logic 1 (high) are not fixed and depend on the associated level of VDD. For de-
tails, see the data manual for your particular F2833x.

12 - 8 F2833x - Inter Integrated Circuit


I2C Operating Modes

Data Validity
The data on SDA must be stable during the high period of the clock (see Slide 12-6). The
high or low state of the data line, SDA, should change only when the clock signal on SCL is
low.

I2C Data Validity

12 - 6

START and STOP conditions can be generated by the I2C module when the module is con-
figured to be a master on the I2C-bus.
• The START condition is defined as a high-to-low transition on the SDA line while
SCL is high. A master drives this condition to indicate the start of a data transfer.
• The STOP condition is defined as a low-to-high transition on the SDA line while
SCL is high. A master drives this condition to indicate the end of a data transfer

After a START condition and before a subsequent STOP condition, the I2C-bus is consid-
ered busy, and the bus busy (BB) bit of I2CSTR is 1. Between a STOP condition and the
next START condition, the bus is considered free, and BB is 0.

For the I2C module to start a data transfer with a START condition, the master mode bit
(MST) and the START condition bit (STT) in I2CMDR must both be 1. For the I2C module
to end a data transfer with a STOP condition, the STOP condition bit (STP) must be set to 1.

F2833x - Inter Integrated Circuit 12 - 9


I2C Operating Modes

Serial Data Formats


I2C is programmable to operate in different addressing formats, selected by bits “FDF” and
“XA” in register I2CMDR.

I2C Serial Data Formats

7-Bit Addressing Format


1 7 1 1 n 1 n 1 1
S Slave Address R/W ACK Data ACK Data ACK P

10-Bit Addressing Format


1 7 1 1 8 1 n 1 1
S 11110AA R/W ACK AAAAAAAA ACK Data ACK P

Free Data Format


1 n 1 n 1 n 1 1
S Data ACK Data ACK Data ACK P

R/W = 0 – master writes data to addressed slave


R/W = 1 – master reads data from the slave
n = 1 to 8 bits
S = Start (high-to-low transition on SDA while SCL is high)
P = Stop (low-to-high transition on SDA while SCL is high)
12 - 7

FDF XA Format

1 X Free Data Format

0 0 7-Bit Addressing Format

0 1 10-Bit Addressing Format

In the 7-bit addressing format, which is often used, the first byte after a START condition (S)
consists of a 7-bit slave address followed by an R/W bit. R/W determines the direction of the
data:
• R/W = 0: The master writes (transmits) data to the addressed slave.
• R/W = 1: The master reads (receives) data from the slave.

An extra clock cycle dedicated to acknowledgment (ACK) is inserted after each byte. If the
ACK bit is inserted by the slave after the first byte from the master, it is followed by n bits of
data from the transmitter (master or slave, depending on the R/W bit). N is a number from 1
to 8 determined by the bit count (BC) field of I2CMDR. After the data bits have been trans-
ferred, the receiver inserts an ACK bit.

12 - 10 F2833x - Inter Integrated Circuit


Arbitration

Arbitration
If two or more master-transmitters attempt to start a transmission on the same bus at ap-
proximately the same time, an arbitration procedure is invoked. The arbitration procedure
uses the data presented on the serial data bus (SDA) by the competing transmitters. Slide 12-
8 illustrates the arbitration procedure between two devices. The first master-transmitter,
which releases the SDA line high, is overruled by another master-transmitter that drives SDA
low. The arbitration procedure gives priority to the device that transmits the serial data
stream with the lowest binary value. Should two or more devices send identical first bytes,
arbitration continues on the subsequent bytes.

I2C Arbitration
 Arbitration procedure invoked if two or more master-
transmitters simultaneously start transmission
 Procedure uses data presented on serial data bus (SDA) by
competing transmitters
 First master-transmitter which drives SDA high is overruled by
another master-transmitter that drives SDA low
 Procedure gives priority to the data stream with the lowest binary
value

SCL
Device #1 lost arbitration
and switches to slave-
Data from 1 0 receiver mode
device #1
Data from Device #2
1 0 0 1 0 1 drives SDA
device #2
SDA 1 0 0 1 0 1

12 - 8

If the I2C module is the losing master, it switches to the slave-receiver mode, sets the arbitra-
tion lost (AL) flag, and generates the arbitration-lost interrupt request.

If during a serial transfer the arbitration procedure is still in progress when a repeated
START condition or a STOP condition is transmitted to SDA, the master-transmitters in-
volved must send the repeated START condition or the STOP condition at the same position
in the format frame. Arbitration is not allowed between:

• A repeated START condition and a data bit


• A STOP condition and a data bit
• A repeated START condition and a STOP condition

F2833x - Inter Integrated Circuit 12 - 11


I2C Interrupts

I2C Interrupts
The I2C module generates the interrupt requests described in Slide 12-9. All interrupt
sources are multiplexed through an arbiter to a single I2C interrupt request to the CPU. Each
interrupt request has a flag bit in the status register (I2CSTR) and an enable bit in the inter-
rupt enable register (I2CIER). When one of the specified events occurs, its flag bit is set. If
the corresponding enable bit is 0, the interrupt request is blocked. If the enable bit is 1, the
request is forwarded to the CPU as an I2C interrupt.

I2C Interrupts
Interrupt Source Description
XRDYINT Transmit ready condition: The data transmit register (I2CDXR) is ready
to accept new data because the previous data has been copied from
I2CDXR to the transmit shift register (I2CXSR).
RRDYINT Receive ready condition: The data receive register (I2CDRR) is ready to
be red because data has been copied from the receive shift register
(I2CRSR) to I2CDRR.
ARDYINT Register-access ready condition: The I2C module registers are ready to
be accessed because the previously programmed address, data, and
command values have been used.
NACKINT No-acknowledgment condition: The I2C module is configured as a
master-transmitter and did not received acknowledgment from the
slave-receiver.
ALINT Arbitration-lost condition: The I2C module has lost an arbitration contest
with another master-transmitter.
SCDINT Stop condition detected: A STOP condition was detected on the I2C
bus.

AASINT Addressed as slave condition: The I2C has been addressed as a slave
device by another master on the I2C bus.

I2CFIFO see FIFO - Registers

12 - 9

The I2C interrupt is one of the maskable interrupts of the CPU. Like any other maskable in-
terrupt request, if it is properly enabled, the CPU executes the corresponding interrupt ser-
vice routine (I2CINT1A_ISR). The I2CINT1A_ISR for the I2C interrupt can determine the
interrupt source by reading the interrupt source register, I2CISRC. Then the I2CINT1A_ISR
can branch to the appropriate subroutine.
After the CPU reads I2CISRC, the following events occur:
(1) The flag for the source interrupt is cleared in I2CSTR. Exception: The ARDY,
RRDY, and XRDY bits in I2CSTR are not cleared when I2CISRC is read. To clear
one of these bits, write a 1 to it.
(2) The arbiter determines which of the remaining interrupt requests has the highest pri-
ority, writes the code for that interrupt to I2CISRC, and forwards the interrupt re-
quest to the CPU.
In addition to the seven basic I2C interrupts, the transmit and receive FIFOs each have the
ability to generate an additional interrupt (I2CINT2A). The FIFOs can be configured to gen-
erate an interrupt after transmitting/receiving a defined number of bytes, up to 16. These two
interrupt sources are ORed together into a single maskable CPU interrupt. The interrupt ser-
vice routine can then read the FIFO interrupt status flags to determine from which source the
interrupt came. See the I2C transmit FIFO register (I2CFFTX) and the I2C receive FIFO reg-
ister (I2CFFRX) descriptions.

12 - 12 F2833x - Inter Integrated Circuit


I2C Module Registers

I2C Module Registers


I2C Registers
Register Name Description
I2COAR I2C own address register

I2CIER I2C interrupt enable register

I2CSTR I2C status register

I2CCLKL I2C clock low-time divide register

I2CCLKH I2C clock high-time divide register

I2CCNT I2C data count register

I2CDRR I2C data receive register

I2CSAR I2C slave address register

I2CDXR I2C data transmit register

I2CMDR I2C mode register

I2CISRC I2C interrupt source register

I2CEMDR I2C extended mode register

I2CPSC I2C prescaler register

I2CFFTX I2C FIFO transmit register

I2CFFRX I2C FIFO receive register


12 - 10

I2C Mode Register


I2C Mode Register (I2CMDR)
I2caRegs.I2CMDR

NACKMOD FREE STT


(receiver mode only) 0 = I2C stop on EMULCK 0 = no START
0 = I2C sends ACK 1 = no I2C stop on EMUL 1 = generate a START
1 = I2C sends NACK

15 14 13 12 11 10 9 8
NACKMOD FREE STT reserved STP MST TRX XA

STP
0 = no STOP TRX
1 = generate a STOP 0 = Receiver Mode
1 = Transmitter Mode
MST
0 = Slave Mode
1 = Master Mode XA
0 = 7 Bit Address
1 = 10 Bit Address

12 - 11

The I2C mode register (I2CMDR) is a 16-bit register that contains the control bits of the I2C
module. The bit fields of I2CMDR are shown in slides 12-11 and 12-12.

F2833x - Inter Integrated Circuit 12 - 13


I2C Module Registers

NACKMOD
This bit is only applicable when the I2C module is acting as a receiver.
0 In the slave-receiver mode: The I2C module sends an acknowledge (ACK) bit to the
transmitter during each acknowledge cycle on the bus. The I2C module only sends a
no-acknowledge (NACK) bit if you set the NACKMOD bit.
In the master-receiver mode: The I2C module sends an ACK bit during each ac-
knowledge cycle until the internal data counter counts down to 0. At that point, the
I2C module sends a NACK bit to the transmitter. To have a NACK bit sent earlier,
you must set the NACKMOD bit.
1 In either slave-receiver or master-receiver mode: The I2C module sends a NACK bit
to the transmitter during the next acknowledge cycle on the bus. Once the NACK bit
has been sent, NACKMOD is cleared. Note: To send a NACK bit in the next ac-
knowledge cycle, NACKMOD must be set before the rising edge of the last data bit.

FREE
This bit controls the action taken by the I2C module when a debugger breakpoint is encoun-
tered.
0 When the I2C module is a master:
If SCL is low when the breakpoint occurs, the I2C module stops immediately and
keeps driving SCL low, whether the I2C module is the transmitter or the receiver. If
SCL is high, the I2C module waits until SCL becomes low and then stops.
When I2C module is slave:
A breakpoint forces the I2C module to stop when the current transmission/reception
is complete.
1 The I2C module runs free; that is, it continues to operate when a breakpoint occurs.

STT
START condition bit (only applicable when the I2C module is a master). The RM, STT, and
STP bits determine when the I2C module starts and stops data transmissions (see Table 6).
Note that the STT and STP bits can be used to terminate the repeat mode, and that this bit is
not writable when IRS = 0.
0 In the master mode, STT is automatically cleared after the START condition has
been generated.
1 In the master mode, setting STT to 1 causes the I2C module to generate a START
condition on the I2C-bus.

STP
STOP condition bit (only applicable when the I2C module is a master). In the master mode,
the RM, STT, and STP bits determine when the I2C module starts and stops data transmis-
sions. Note that the STT and STP bits can be used to terminate the repeat mode, and that this
bit is not writable when IRS=0.
0 STP is automatically cleared after the STOP condition has been generated.
1 STP has been set to generate a STOP condition when the internal data counter of the
I2C module counts down to 0.

12 - 14 F2833x - Inter Integrated Circuit


I2C Module Registers

MST
Master mode bit. MST determines whether the I2C module is in the slave mode or the master
mode. MST is automatically changed from 1 to 0 when the I2C master generates a STOP
condition.
0 Slave mode. The I2C module is a slave and receives the serial clock from the master.
1 Master mode. The I2C module is a master and generates the serial clock on the SCL
pin.

TRX
Transmitter mode bit. When relevant, TRX selects whether the I2C module is in the trans-
mitter mode or the receiver mode.
0 Receiver mode. The I2C module is a receiver and receives data on the SDA pin.
1 Transmitter mode. The I2C module is a transmitter and transmits data on the SDA
pin.

XA
Expanded address enable bit.
0 7-bit addressing mode (normal address mode). The I2C module transmits 7-bit slave
addresses (from bits 6-0 of I2CSAR).
1 10-bit addressing mode (expanded address mode). The I2C module transmits 10-bit
slave addresses (from bits 9-0 of I2CSAR).

I2C Mode Register (I2CMDR)


I2caRegs.I2CMDR

RM DLB IRS
0 = no repeat mode 0 = no loopback 0 = I2C in RESET
1 = repeat mode 1 = loopback mode 1 = I2C enabled

7 6 5 4 3 2-0
RM DLB IRS STB FDF BC

STB
0 = no START byte mode
1 = START byte mode BC
0 = 8 bit per data
FDF 1 = 1 bit per data
2 = 2 bit per data
0 = no free data format …
1 = free data format 7 = 7 bit per data
12 - 12

RM
Repeat mode bit (only applicable when the I2C module is a master-transmitter). The RM,
STT, and STP bits determine when the I2C module starts and stops data transmissions.
0 Non-repeat mode. The value in the data count register (I2CCNT) determines how
many bytes are received / transmitted by the I2C module.

F2833x - Inter Integrated Circuit 12 - 15


I2C Module Registers

1 Repeat mode. A data byte is transmitted each time the I2CDXR register is written to
(or until the transmit FIFO is empty when in FIFO mode) until the STP bit is manu-
ally set. The value of I2CCNT is ignored. The ARDY bit/interrupt can be used to de-
termine when the I2CDXR (or FIFO) is ready for more data, or when the data has all
been sent and the CPU is allowed to write to the STP bit.

DLB
Digital loopback mode bit.
0 Digital loopback mode is disabled.
1 Digital loopback mode is enabled. For proper operation in this mode, the MST bit
must be 1.
IRS
I2C module reset bit.
0 The I2C module is in reset/disabled. When this bit is cleared to 0, all status bits (in
I2CSTR) are set to their default values.
1 The I2C module is enabled. This has the effect of releasing the I2C bus if the I2C
peripheral is holding it.

STB
START byte mode bit. This bit is only applicable when the I2C module is a master. As de-
scribed in version 2.1 of the Philips Semiconductors I2C-bus specification, the START byte
can be used to help a slave that needs extra time to detect a START condition. When the I2C
module is a slave, it ignores a START byte from a master, regardless of the value of the STB
bit.
0 The I2C module is not in the START byte mode.
1 The I2C module is in the START byte mode.

FDF
Free data format mode bit.
0 Free data format mode is disabled. Transfers use the 7-/10-bit addressing format se-
lected by the XA bit.
1 Free data format mode is enabled.

BC
Bit count bits. BC defines the number of bits (1 to 8) in the next data byte that is to be re-
ceived or transmitted by the I2C module. The number of bits selected with BC must match
the data size of the other device. Notice that when BC = 000b, a data byte has 8 bits. BC
does not affect address bytes, which always have 8 bits.

000 8 bits per data byte


001 1 bit per data byte
010 2 bits per data byte
011 3 bits per data byte
100 4 bits per data byte
101 5 bits per data byte
110 6 bits per data byte
111 7 bits per data byte

12 - 16 F2833x - Inter Integrated Circuit


I2C Module Registers

I2C Interrupt Enable Register


I2C Interrupt Enable Register
I2caRegs.I2CIER
15 14 13 12 11 10 9 8
reserved reserved reserved reserved reserved reserved reserved reserved

7 6 5 4 3 2 1 0
reserved AAS SCD XRDY RRDY ARDY NACK AL

1 = enable interrupt source 0 = disable

AAS: an I2C - master has addressed the DSC as slave


SCD: Stop condition detected
XRDY: Transmit data ready for new data
RRDY: Receive data available
ARDY: I2C register access ready
NACK: No – Acknowledge received
AL: Arbitration lost during competition

12 - 13

I2C Status Register


I2C Status Register
I2caRegs.I2CSTR
15 14 13 12 11 10 9 8
reserved SDIR NACKSNT BB RSFULL XSMT AAS AD0

7 6 5 4 3 2 1 0
reserved reserved SCD XRDY RRDY ARDY NACK AL

SDIR: 1 = I2C is addressed as a slave transmitter; 0 = as receiver


NACKSNT: 1 = a NACK was sent as receiver from I2C
BB: 1 = Bus is busy, a START has been sent
RSFULL: 1 = Overrun of the receiver detected
XSMT: 0 = underflow of transmit shift register detected
AAS: 1 = I2C was addressed a s slave
AD0: 1 = a general call (address 0) has been detected
SCD: 1 = a STOP condition has been detected
XRDY: 1 = Transmit register I2CDXR ready for new data
RRDY: 1 = Receive data available in I2CDRR
ARDY: 1 = a previous cycle has completed
NACK: 0 = ACK received; 1 = NACK received
AL: 1 = Arbitration lost during competition by 2 masters
12 - 14

F2833x - Inter Integrated Circuit 12 - 17


I2C Module Registers

I2C Interrupt Source Register


I2C Interrupt Source Register
I2caRegs.I2CISRC
15 - 3 2-0
reserved INTCODE

INTCODE Event
000 None
001 Arbitration lost
010 No-acknowledgment
011 Registers ready to be accessed
100 Receive data ready
101 Transmit data ready
110 Stop condition detected
111 Addressed as slave

Note: A CPU read of INTCODE will clear this field. If another lower priority
interrupt is pending and enabled, the value corresponding to that interrupt will
then be loaded. Otherwise, the value will stay cleared.

12 - 15

I2C Clock Register

I2C Clock Register


I2caRegs.I2CPSC
15 - 8 7-0
reserved IPSC

I2C module clock frequency = SYSCLKOUT / (IPSC + 1)


Note: should be 7…12 MHz

I2caRegs.I2CCLKL
15 0
ICCL

I2caRegs.I2CCLKH
15 0
ICCH

TI2C_MASTER_CLOCK = TI2C_MODULE_CLOCK * [ (ICCL +d ) + (ICCH + d ) ]


12 - 16

12 - 18 F2833x - Inter Integrated Circuit


I2C Module Registers

I2C Master Clock

(A): IPSC Value for d


0 7
1 6
greater than 1 5

12 - 17

I2C Slave Address Register

I2C Slave Address Register


I2caRegs.I2CSAR

15 - 10 9-0
reserved SAR

SAR: next slave address that will be transmitted


Bits 6…0 in 7 Bit - Address - Mode (XA = 0 in I2CMDR)
Bits 9…0 in 10 Bit - Address _ Mode (XA = 1)

12 - 19

F2833x - Inter Integrated Circuit 12 - 19


I2C Module Registers

I2C Own Address Register

I2C Own Address Register


I2caRegs.I2COAR

15 - 10 9-0
reserved OAR

OAR: F2833x address in case of slave mode


Bits 6…0 in 7 Bit - Address - Mode (XA = 0 in I2CMDR)
Bits 9…0 in 10 Bit - Address _ Mode (XA = 1)

12 - 20

I2C Data Count Register

I2C Data Count Register


I2caRegs.I2CCNT

15 0
ICDC

ICDC: Data Count Value

ICDC indicates the number of data bytes to transfer or receive.

0x0000: The start value loaded to the internal data counter is 65536.

00001-0xFFFF: The start value loaded to internal data counter is 1-65535.

12 - 20

12 - 20 F2833x - Inter Integrated Circuit


I2C Data Registers
To read or write data from / to I2C, we use the lower 8 bits of two data registers:

I2C Data Receive Register


I2caRegs.I2CDRR

15 - 8 7-0
reserved DATA

I2C Data Transmit Register


I2caRegs.I2CDXR
15 - 8 7-0
reserved DATA

12 - 21

I2C FIFO Buffers


The I2C module of the F2833x is enhanced by a set of FIFO-buffers for register I2CDRR
and I2CDXR. The FIFO-buffers, each of them 16 levels deep, can be used to buffer up to 16
characters, before they are transmitted into I2C (TXFIFO) or after they have been received
(RXFIFO). This greatly reduces the workload for the CPU to service the I2C.
Note that the FIFO-units have no individual register names or address spaces; once the
FIFOs are enabled, a repeated write into register I2CDXR will indirectly use this background
transmit buffer to store the data. Values from this background FIFO are loaded into the
foreground automatically as soon as register I2CDXR is ready for new data.
The same principle applies to the I2CDRR register for data, received by the I2C input
channel. By defining a threshold for an interrupt request, when a certain number of FIFO
entries are consumed, the number of interrupts for I2C can be reduced.
The FIFO-option is disabled by default. Since we will use the FIFO in lab exercise 12_3, we
will have to discuss the two control registers in the following two slides:

F2833x - Inter Integrated Circuit 12 - 21


I2C FIFO Buffers

I2C TX-FIFO Register


I2C Transmit FIFO Register
I2caRegs.FFTX
15 14 13 12 – 8
reserved I2CFFEN TXFFRST TXFFST

7 6 5 4-0
TXFFINT TXFFINTCLR TXFFIENA TXFFIL

I2CFFEN: 1 = enable TXFIFO - mode


TXFFRST: 0 = reset TXFIFO; 1 = enable TX - operation
TXFFST: Filling level of TXFIFO (0 – 16 )
TXFFINT: TXFIFO Interrupt flag
1 = TX FIFO interrupt condition has occurred.
0 = TX FIFO interrupt condition has not occurred.
cleared by writing a 1 into bit TXFFINTCLR
TXFFINTCLR: 1 = clear flag TXFFINT
TXFFIENA: 1 = enabled. TXFFINT generates an interrupt when set.
TXFFIL: TX FIFO Interrupt level. If TXFFST is equal or less than
TXFFIL, the flag TXFFINT is set.
12 - 22

I2C RX-FIFO Register


I2C Receive FIFO Register
I2caRegs.I2CFFRX
15 14 13 12 – 8
reserved reserved RXFFRST RXFFST

7 6 5 4-0
RXFFINT RXFFINTCLR RXFFIENA RXFFIL

RXFFRST: 0 = reset RXFIFO; 1 = enable RX – FIFO - operation


RXFFST: Filling level of RXFIFO (0 – 16 )
RXFFINT: RXFIFO Interrupt flag
1 = RX FIFO interrupt condition has occurred.
0 = RX FIFO interrupt condition has not occurred.
cleared by writing a 1 into bit RXFFINTCLR
RXFFINTCLR: 1 = clear flag RXFFINT
RXFFIENA: 1 = enabled. RXFFINT generates an interrupt when set.
RXFFIL: RX FIFO Interrupt level. If RTXFFST is equal or greater
than RXFFIL, the flag RXFFINT is set.

12 - 23

12 - 22 F2833x - Inter Integrated Circuit


Temperature Sensor TMP100

Temperature Sensor TMP100


To exercise the I2C module of the F2833x we need to connect external I2C-device(s). The
Peripheral Explorer Board is equipped with a Texas Instruments temperature sensor TMP100
(or TMP 100) - see datasheet literature number “SBOS231G”.

Temperature Sensor TMP101

• Digital Interface: I2C Serial 2-Wire


• Resolution: 9- to 12-Bits, User-Selectable
• 9 – Bit: 0.5 °C; 12 – Bit:0.0625 °C
• Accuracy:
• ±2.0°C from −25°C to +85°C (max)
• ±3.0°C from −55°C to +125°C (max)
• Low quiescent current of 45μA, 0.1μA Standby
• Power supply range: 2.7V to 5.5V
• Tiny SOT23-6 package

12 - 25

The TMP100 and TMP101 are two-wire, serial output temperature sensors available in
SOT23-6 packages. Requiring no external components, the TMP100 and TMP101 are capa-
ble of reading temperatures with a resolution of 0.0625°C. The TMP100 and TMP101 fea-
ture I2C interface compatibility, with the TMP100 allowing up to eight devices on one bus.

The TMP101 offers SMBus alert function with up to three devices per bus. The TMP100 and
TMP101 are ideal for extended temperature measurement in a variety of communication,
computer, consumer, environmental, industrial, and instrumentation applications.

The TMP100 and TMP101 are specified for operation over a temperature range of −55°C to
+125°C.

F2833x - Inter Integrated Circuit 12 - 23


Temperature Sensor TMP100

The following Slide 12-26 shows the physical pin out of the device. Signals SCL and SDA
are the I2C clock and data lines discussed above. Signal V+ is connected to +3.3V. Pins
“ADD0” and “ADD1” are code pins to define the device slave address:

ADD1 ADD0 Slave address


0 0 0x48
0 Float 0x49
0 1 0x4A
1 0 0x4C
1 Float 0x4D
1 1 0x4E
Float 0 0x4B
Float 1 0x4F

At the Peripheral Explorer Board pins ADD0 and ADD1 are fixed to 0.

Temperature Sensor TMP100

12 - 26

12 - 24 F2833x - Inter Integrated Circuit


Temperature Sensor TMP100

TMP100 Register Structure


The TMP100 must be initialized by a set of 5 internal registers:

Temperature Sensor TMP100

Pointer:

00

01

10

11

12 - 27

The 8-bit Pointer Register of the TMP100 and TMP101 is used to address a given data
register. The Pointer Register uses the two LSBs to identify which of the data registers
should respond to a read or write command.
The Pointer Register has the following layout:

P7 P6 P5 P4 P3 P2 P1 P0

0 0 0 0 0 0 Register - Bits

Using the “Register-Bits”, one of the registers available in the TMP100 and TMP101 can be
pre-selected. The Power-up Reset value of P1/P0 is 00.

P1 P0 Register

0 0 Temperature Register

0 1 Configuration Register

1 0 Low Temperature Threshold Register

1 1 High Temperature Threshold Register

F2833x - Inter Integrated Circuit 12 - 25


Temperature Sensor TMP100

Temperature Register

The Temperature Register of the TMP100 or TMP101 is a 12-bit read-only register that
stores the output of the most recent conversion. Two bytes must be read to obtain the data:

Temperature Sensor TMP100

12 - 28

Configuration Register

The Configuration Register is an 8-bit read/write register used to store bits that control the
operational modes of the temperature sensor. Read/write operations are performed MSB
first. The format of the Configuration Register for the TMP100 and TMP101 is shown in
Slide 12-29.

12 - 26 F2833x - Inter Integrated Circuit


Temperature Sensor TMP100

TMP100 Configuration Register


7 6 5 4 3 2 1 0
OS/ALERT R1 R0 F1 F0 POL TM SD

OS/ALERT: write 1: single temperature conversion


write 0: continuous temperature conversion
read 1: temperature above THIGH
read 0: temperature below TLOW
R1, R0: Resolution 9 bit (0,0) … 12 bit (1,1)
F1,F0: activate ALERT after number of consecutive faults (1,2,4,6)
POL: Polarity of ALERT (0 or 1)
TM: write 0: Comparator Mode
(ALERT stays active as long as condition is true)
write 1: Interrupt Mode
( ALERT is cleared by a read instruction of any reg)
SD: write 1: shutdown
write 0: active mode

12 - 29

The power-up/reset value of the Configuration Register is with all bits equal to 0.

TMP100 Timing Diagrams


The I2C Bus Timing is based on different bus conditions:

Bus Idle:
Both SDA and SCL lines remain HIGH.

Start Data Transfer:


A change in the state of the SDA line, from HIGH to LOW, while the SCL line is HIGH,
defines a START condition. Each data transfer is initiated with a START condition.

Stop Data Transfer:


A change in the state of the SDA line from LOW to HIGH while the SCL line is HIGH de-
fines a
STOP condition. Each data transfer is terminated with a repeated START or STOP condi-
tion.

Data Transfer:
The number of data bytes transferred between a START and a STOP condition is not limited
and is determined by the master device. The receiver acknowledges the transfer of data.

Acknowledge and Not-Acknowledge:

F2833x - Inter Integrated Circuit 12 - 27


Temperature Sensor TMP100

Each receiving device, when addressed, is obliged to generate an Acknowledge bit. A device
that acknowledges must pull down the SDA line during the Acknowledge clock pulse in such
a way that the SDA line is stable LOW during the HIGH period of the Acknowledge clock
pulse. Setup and hold times must be taken into account. On a master receive, the termination
of the data transfer can be signalled by the master generating a Not-Acknowledge (NACK)
on the last byte that has been transmitted by the slave.

Note: Data books on I2C sometimes state that “the master does NOT acknowledge”. This
means that “the master performs Not-Acknowledge (NACK)”, rather than skipping the ac-
knowledge part of the cycle.

TMP100 / TMP101 Write Timing

TMP101 Write Timing

12 - 30

12 - 28 F2833x - Inter Integrated Circuit


Temperature Sensor TMP100

TMP100 / TMP101 Write Timing

TMP101 Read Timing

12 - 31

F2833x - Inter Integrated Circuit 12 - 29


Lab Exercise 12_1

Lab Exercise 12_1


Preface
The Peripheral Explorer Board is equipped with an external temperature sensor TMP100
(device U9). During the early stages of this textbook the first version of the Peripheral Ex-
plorer Board was not equipped with such an I2C- device.

Here is the description what to do, in case if your Peripheral Explorer Board does not include
a TMP101 or TMP100. Connect the following four pins of the TMP101 with wires to the
headers of the Peripheral Explorer Board:

Pin TMP101 Header of Peripheral Explorer


1: SCL J15:1 (I2C - SCL)
2: GND J12:3 (RS232 - GND)
4: V+ J12:2 (RS232 - V33)
6: SDA J15:2(I2C - SDA)

The two I2C-signals are multiplexed at GPIO32 (SDA) and GPIO33 (SCL). To guarantee the
voltage levels for the two signals we need external pull-up - resistors of 4.7 kOhm between
the signal line SCL and 3.3V and between SDA and 3.3V. Note: The F2833x is equipped
with internal pull-up- resistors. However, their resistance is not low enough to guarantee the
timing of an I2C-bit period.

Objective
The objective of Lab 12_1 is to initialize the I2C interface and to read the current tempera-
ture from the external device TMP100. For simplification we will use a watch window to
monitor the current value of integer variable “temperature”. Note that the result 16-bit regis-
ter of the TMP100 has 8 integer bits and 8 binary fraction bits; so if we display this value as
I8Q8-number (type: int, Radix: Q8) we can immediately verify the temperature value.

Procedure

Open Files, Create Project File


1. Using Code Composer Studio, create a new project, called Lab12.pjt in
C:\DSP2833x_V4\Labs (or in another path that is accessible by you; ask your teacher
or a technician for an appropriate location!).
2. A good point to start with is the source code of Lab6.c, which produces a hardware
based time period using CPU core timer 0. Open file Lab6.c from
C:\DSP2833x_V4\Labs\Lab6 and save it as Lab12_1.c in
C:\DSP2833x_V4\Labs\Lab12.

12 - 30 F2833x - Inter Integrated Circuit


Lab Exercise 12_1

3. Define the size of the C system stack. In the project window, right click at project
“Lab12” and select “Properties”. In category “C/C++ Build”, “C2000 Linker”, “Basic
Options” set the C stack size to 0x400.

Link some of the source code files, provided by Texas Instruments, to the project:
4. In the C/C++ perspective, right click at project “Lab12” and select “Link Files to
Project”. Go to folder “C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\source” and
link:

• DSP2833x_GlobalVariableDefs.c
From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\source link:
• DSP2833x_PieCtrl.c
• DSP2833x_PieVect.c
• DSP2833x_DefaultIsr.c
• DSP2833x_CpuTimers.c
• DSP2833x_SysCtrl.c
• DSP2833x_CodeStartBranch.asm
• DSP2833x_ADC_cal.asm
• DSP2833x_usDelay.asm
From C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\cmd link:

• DSP2833x_Headers_nonBIOS.cmd

Project Build Options


5. We have to extent the search path of the C-Compiler for include files. Right click at
project “Lab12” and select “Properties”. Select “C/C++ Build”, “C2000 Compiler”,
“Include Options”. In the box: “Add dir to #include search path”, add the following
lines:

C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include

Note: Use the “Add” Icon to add the new paths:

Close the Property Window by Clicking <OK>.

F2833x - Inter Integrated Circuit 12 - 31


Lab Exercise 12_1

Preliminary Test
6. So far, we have just created a new project “Lab12.pjt” with the same functionality as
in Lab6. A good step would be to rebuild Lab12, load the code into the controller and
verify the binary counter at LED’s LD1 to LD4 of the Peripheral Explorer Board.
The LEDs should be updated by the counter in 100 milliseconds time steps.
If not: Debug!

Add TMP100 and I2C Initialization Code


7. Now let us add code to initialize the I2C and the TMP100.
The TMP100 is addressed as I2C-Slave. If pin ADDR0 is floating, its address is
hexadecimal 0x49. The initialization is based on TMP100 internal registers with the
following addresses:
• Temperature Register: 0
• Configuration Register: 1
• Temperature Low Register: 2
• Temperature High Register: 3
To allow a simple addressing of these registers, add the following macros at the
beginning of Lab12_1.c:
#define TMP100_SLAVE 0x48
#define POINTER_TEMPERATURE 0
#define POINTER_CONFIGURATION 1
#define POINTER_T_LOW 2
#define POINTER_T_HIGH 3
8. At the beginning of “main()”, remove variable “counter”. Define a global integer
variable “temperature”. Note: it is good software practice to write out the word
“temperature” in full, rather than using the abbreviation “temp”. This is because the
abbreviation could mean either “temporary” or “temperature”.
9. In local function “Gpio_select()” change register GPBMUX1 to enable lines GPIO32
and GPIO33 for I2C operation. In register GPBPUD enable the internal pull-up -
resistors for lines GPIO32 and GPIO33. In register GPBQSEL1 set lines GPIO32 and
GPIO33 to asynchronous input.
10. In main, after the function call of “Gpio_select()”, add a function call of a new
function “I2CA_Init()”.
11. At the end of “main()”, add the definition of the new function “I2CA_Init()” with void
both as input and return parameter type. In “I2CA_Init()” perform the following:

• Reset the I2C-module (Register I2CMDR, bit IRS)

• Set the slave address register to 0x49 (Register I2CSAR)

• Initialize the I2C module clock to 10MHz. If SYSCLKOUT is 150 MHz, set
Register I2CPSC to 14:

12 - 32 F2833x - Inter Integrated Circuit


Lab Exercise 12_1

SYSCLKOUT
10 MHz = ;
( PSC + 1)

• Set low and high phase of the I2C-clock signal to 50% each. As an example, we will
use an I2C-clock frequency of 50 kHz (clock period = 20µs).

(14 + 1)[( ICCL + 5) + ( ICCH + 5)]


20 µs =
150 MHz
The equation above results in ICCL = ICCH = 95. Initialize registers I2CCLKL and
I2CCLKH accordingly.

• Finally take the I2C module out of reset (Register I2CMDR bit IRS).

• At the beginning of “Lab12_1.c” add a prototype for the new local function
“I2CA_Init()”.
12. In the endless while(1)-loop of function "main()", remove all lines which are related to
variable “counter” and to the monitoring with LEDs LD1 to LD4.
13. After the watchdog service code lines in the while(1)-loop of “main()”, add code to
read the current temperature from TMP100:

• Set register “I2CCNT” to 2 to read a 2 byte temperature information from TMP100

• Initialize register “I2CMDR”:


• Bit15 = 0; no NACK in receiver mode
• Bit14 = 1; FREE on emulation halt
• Bit13 = 1; STT generate START
• Bit12 = 0; reserved
• Bit11 = 1; STP generate STOP
• Bit10 = 1; MST master mode
• Bit9 = 0; TRX master-receiver mode
• Bit8 = 0; XA 7-bit address mode
• Bit7 = 0; RM non-repeat mode, I2CCNT determines # of bytes
• Bit6 = 0; DLB no loopback mode
• Bit5 = 1; IRS I2C module enabled
• Bit4 = 0; STB no start byte mode
• Bit3 = 0; FDF no free data format
• Bit2…0 = 0; BC 8 bit per data byte

14. Install a wait loop until the 1st byte has been received from TMP100:
while(I2caRegs.I2CSTR.bit.RRDY == 0);

15. Read the upper 8 bits of temperature:


temperature = I2caRegs.I2CDRR << 8;

16. Wait for the 2nd byte and add it as the 8 lower bits to temperature:
while(I2caRegs.I2CSTR.bit.RRDY == 0);
temperature += I2caRegs.I2CDRR;

F2833x - Inter Integrated Circuit 12 - 33


Lab Exercise 12_1

Build, Load and Run


17. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

and watch the tools run in the build output window. If you get errors or warnings de-
bug as necessary.

18. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

19. Verify that in the debug perspective the window of the source code “Lab12_1.c” is
high-lighted and that the blue arrow for the current Program Counter position is placed
under the line “void main(void)”.

20. Open a watch window and enter variable “temperature”. With a left mouse click into
column “Format”, select “Q-Value(8). Activate “Continuous Refresh” button in the
Watch Window.

Now start a “Real Time Run”:

 Scripts  Realtime Emulation Control  Run_Realtime_with_Restart

The Variable “temperature” should display the current ambient temperature with a
resolution of 0.5 °C (the example above shows 29.0 °C).

21. Stop the code- execution:

 Scripts  Realtime Emulation Control  Full Halt

12 - 34 F2833x - Inter Integrated Circuit


Lab Exercise 12_2

Lab Exercise 12_2


Objective
In Lab12_1 we used the TMP100 in a basic scenario with a resolution of 9 bits (or 0.5 °C)
only. However, the TMP100 is able to operate with a resolution of 12 bits (or 1/16 °C). This
high resolution must be initialized in the configuration register of the TMP100. This is the
task for Lab12_2.

Procedure

Open Project, Modify Source File


1. If not still open from Lab12_1, re-open project Lab12.pjt in C:\DSP2833x_V4\Labs.
2. Open file “Lab12_1.c” and save it as “Lab12_2.c”
3. Exclude file “Lab12_1.c” from build. Use a right mouse click at file “Lab12_1.c”, and
enable “Exclude File(s) from Build”.
4. In function main, after the function call of “I2CA_Init()”, add I2C-code to address the
configuration register of the TMP100:
• Set register “I2CCNT” to 2 to send a 2-byte command (configuration
register address, followed by configuration data) to TMP100.
• Load register “I2CDXR” with the configuration register address:
I2caRegs.I2CDXR = POINTER_CONFIGURATION;
• Initialize register “I2CMDR”:
• Bit15 = 0; no NACK in receiver mode
• Bit14 = 1; FREE on emulation halt
• Bit13 = 1; STT generate START
• Bit12 = 0; reserved
• Bit11 = 1; STP generate STOP
• Bit10 = 1; MST master mode
• Bit9 = 1; TRX master-transmitter mode
• Bit8 = 0; XA 7-bit address mode
• Bit7 = 0; RM non-repeat mode, I2CCNT defines # of bytes
• Bit6 = 0; DLB no loopback mode
• Bit5 = 1; IRS I2C module enabled
• Bit4 = 0; STB no start byte mode
• Bit3 = 0; FDF no free data format
• Bit2…0 = 0; BC 8 bit per data byte
• Install a wait loop until the 1st byte has been transmitted to TMP100:
while(I2caRegs.I2CSTR.bit.XRDY == 0);

F2833x - Inter Integrated Circuit 12 - 35


Lab Exercise 12_2

• Load register “I2CDXR” with the configuration data (0x60, see Slide 12-
29) to initialize the temperature measurement with 12-bit resolution.
• Wait for the successful generation of the stop-condition:
while(I2caRegs.I2CSTR.bit.SCD == 0);
• Clear the stop condition flag:
I2caRegs.I2CSTR.bit.SCD = 1;
5. In the endless while(1)- loop of “main()” we have to change the code to read the TMP
100 temperature register. According to the “read temperature” time diagram (Slide 12-
31) we have to generate a 5-byte I2C frame (slave address, temperature register
address, slave address, read temperature high, read temperature low). Note that there
are two “Start By Master” conditions in this sequence. Also, we have to transmit the
first two bytes as Master-Transmitter and then to switch into Master-Receiver-Mode.

TMP101 Read Timing

12 - 31

Whilst the second half of the required code is identical to the code from Lab12_1, we
have to add the code to generate byte 1 and 2 of diagram 12-31. In the while(1)-loop
before the line “I2caRegs.I2CCNT = 2”, add:
I2caRegs.I2CCNT = 1; // 1 byte message
I2caRegs.I2CDXR = POINTER_TEMPERATURE;
I2caRegs.I2CMDR.all = 0x6620; // master-receiver, START, STOP
while(I2caRegs.I2CSTR.bit.ARDY == 0); // wait for STOP condition

Build, Load and Run


6. Click the “Rebuild Active Project ” button or perform:

12 - 36 F2833x - Inter Integrated Circuit


Lab Exercise 12_2

Project  Rebuild All (Alt +B)

and watch the tools run in the build output window. If you get errors or warnings de-
bug as necessary.

7. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

8. Verify that in the debug perspective the window of the source code “Lab12_2.c” is
high-lighted and that the blue arrow for the current Program Counter position is placed
under the line “void main(void)”.

9. Perform a real time run.

Target  Run

10. Open a watch window and enter variable “temperature”. With a left mouse click into
column “Format”, select “Q-Value(8). Activate “Continuous Refresh” button in the
Watch Window.

Now start a “Real Time Run”:

 Scripts  Realtime Emulation Control  Run_Realtime_with_Restart

Variable “temperature” should display the current ambient temperature with a resolu-
tion of 1/16 °C (the example above shows 29.0625 °C).

11. Stop the code - execution:

 Scripts  Realtime Emulation Control  Full Halt

F2833x - Inter Integrated Circuit 12 - 37


Lab Exercise 12_2

Troubleshooting
If your variable “temperature” does not show correct numbers but the code is run-
ning as expected, then it might be useful to measure the signals SCL and SDA with
an oscilloscope or logic analyzer.

The following image is a screenshot of a logic analyzer measurement of bytes 1 and


2 of an I2C-frame “Read -Timing” according to Slide 12-31 (see above) after the 1st
START-Condition.

What follows is a description of the screenshot above from left to right:


• M1 (green marker): START Condition
• M2 (pink marker): 100100100
| | | | | | | | |___ ACK by TMP101
| | | | | | | |____ Write
| | | | | | |_____ device address 0x49

• M3 (yellow marker): 000000000


| | | | | | | | |___ ACK by TMP101
| | | | | | | |_____ pointer to temperature register: 0x00


nd
M4 (green marker): 2 START Condition

12 - 38 F2833x - Inter Integrated Circuit


Lab Exercise 12_2

The next image is a screenshot of a logic analyzer measurement of bytes 3, 4 and 5


of an I2C-frame “Read -Timing” according to Slide 12-31 (see above) after the 2nd
START-Condition.

What follows is a description of the screenshot from left to right:



nd
M4 (green marker): 2 START Condition
• M5 (blue marker): 100100110
| | | | | | | | |___ ACK by TMP101
| | | | | | | |____ Read
| | | | | | |_____ device address 0x49

• M6 (cyan marker): 000101110


| | | | | | | | |___ ACK by F2833x
| | | | | | | |_____ temperature high (16+4+2+1 = 23 °C)

• M8 (red marker): 110100001


| | | | | | | | |___ NACK by F2833x
| | | | | | | |_____ temperature low ( ½ + ¼ + 1/16 = 0.8125 °C)

• M9 (gray marker):STOP condition

F2833x - Inter Integrated Circuit 12 - 39


Lab Exercise 12_3

Lab Exercise 12_3


Objective
In Lab12_1 and Lab12_2 we used the TMP100 with a temperature resolution of 9 bits (or 0.5
°C) or 12 bits (1/16 °C). For the I2C-communication we installed a non FIFO data transmis-
sion, which leads to an increasing CPU load, especially when one would use a more demand-
ing slave device, such as an EEPROM, ADC or DAC. To reduce the CPU load we should try
to setup the FIFO-buffered operating mode of the I2C-interface. This is the objective of
Lab12_3.

Procedure

Open Project, Modify Source File

1. If not still open from Lab12_2, re-open project Lab12.pjt in C:\DSP2833x_V4\Labs.


2. Open file “Lab12_2.c” and save it as “Lab12_3.c”
3. Exclude file “Lab12_2.c” from build. Use a right mouse click at file “Lab12_2.c”, and
enable “Exclude File(s) from Build”.
4. First we have to change function “I2CA_Init()”. Add new code to initialize registers
I2CFFTX and I2CFFRX at the end of this function directly in front of the last code
line to take the I2C out of reset:
• For register I2CFFTX:
• First reset the whole register to zero.
• Next, set the transmit interrupt level (bit field TXFFIL) to zero.
• Enable the FIFOs (bit I2CFFEN).
• Enable the FIFO-transmit support (bit TXFFRST)
• For register I2CFFRX:
• First reset the whole register to zero.
• Next, set the receive interrupt level (bit field RXFFIL) to 2, because
we will receive a 2 byte temperature message from the TMP100.
• Enable the FIFO-receiver support (bit RXFFRST)
5. Change the code in function “main()”. Before we enter the endless while(1)-loop, we
already have some lines to address the TMP100 configuration register. This command
consists of a 2-byte message from the F2833x to the TMP100. In Lab12_2 we first
wrote byte “POINTER_CONFIGURATION” into register I2CDXR, then we waited
until the first byte had been transmitted, before we wrote the next byte “0x60” (12-bit
resolution mode) into register I2CDXR. For now, since we have enabled the transmit
FIFO, there is no need to wait. We can write the two bytes directly one after another:

I2caRegs.I2CCNT = 2;

12 - 40 F2833x - Inter Integrated Circuit


Lab Exercise 12_3

I2caRegs.I2CDXR = POINTER_CONFIGURATION;
I2caRegs.I2CDXR = 0x60;
I2caRegs.I2CMDR.all = 0x6E20;

6. In Lab12_2 we read the temperature value from TMP100 in a 2-byte sequence at the
end of the while(1)-loop. First we waited until the first byte was received (register
I2CSTR bit RRDY), then we copied the information into variable “temperature” and
finally we waited for another RRDY flag before we read the remaining byte and added
it to “temperature”. For the new lab 12_3 we initialized the receive FIFO to set the
interrupt flag “RXFFINT” after 2 bytes have been received. Using this new flag we
can simplify the wait construction to a single line and read the two temperature bytes
directly one after another:

while(I2caRegs.I2CFFRX.bit.RXFFINT == 0);
I2caRegs.I2CFFRX.bit.RXFFINTCLR = 1;
temperature = I2caRegs.I2CDRR << 8; //read upper 8 Bit (integers)
temperature += I2caRegs.I2CDRR; //add lower 8 Bit (fractions)

Build, Load and Run


7. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

8. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective. Verify that in the debug perspective the win-
dow of the source code “Lab12_3.c” is high-lighted and that the blue arrow for the
current Program Counter position is placed under the line “void main(void)”.

9. Perform a real time run.

 Scripts  RealTime Emulation Control  Run_Realtime_with_Restart

10. Open a watch window and enter variable “temperature”. With a left mouse click into
column “Format”, select “Q-Value(8). Activate “Continuous Refresh” button in the
Watch Window.

Variable “temperature” should display the current ambient temperature with a resolu-
tion of 1/16 °C (the example above shows 27.625 °C).

11. Stop the code - execution:


 Scripts  Realtime Emulation Control  Full Halt

F2833x - Inter Integrated Circuit 12 - 41


Lab Exercise 12_4

Lab Exercise 12_4


Objective
As final laboratory exercise we will use the I2C-interrupt system to start “follow-up” - activi-
ties. You might have noticed that in “Lab12_1.c” to “Lab12_3.c” we used while-loops to
wait until the I2C-interface had finished previous parts of a data frame. This was simple and
easy; but we wasted CPU performance with this technique. Now we will activate interrupt
services to replace such while-loops.

The I2C interface has two groups of interrupts, (1) basic interrupts, described in Slide 12-13
and (2) FIFO-interrupts. Basic Interrupts are wired to Peripheral Interrupt Expansion (PIE)
8.1; FIFO - Interrupts are wired to PIE 8.2

Procedure

Open Project, Modify Source File

1. If not still open from Lab12_3, re-open project Lab12.pjt in C:\DSP2833x_V4\Labs.


2. Open file “Lab12_3.c” and save it as “Lab12_4.c”
3. Exclude file “Lab12_3.c” from build. Use a right mouse click at file “Lab12_3.c”, and
enable “Exclude File(s) from Build”.
4. Edit file “Lab12_4.c”. First we have to change function “I2CA_Init()”. Since we will
use the RXFIFO - interrupt after receiving two temperature bytes from the TMP100,
we have to enable this interrupt source. Add the following line:
I2caRegs.I2CFFRX.bit.RXFFIENA = 1;
As a basic I2C-interrupt we will use the “Access Ready” - signal (ARDY), which is
generated, when the first two bytes of the “TMP100 Read Timing” I2C - data frame
(see Slide 12-31) are transmitted. Add the following line:
I2caRegs.I2CIER.bit.ARDY = 1;
5. In function “main()”, before we enter the endless while(1)-loop we have to enable two
more PIE - interrupt lines for I2C-basic (8.1) and I2C-receiver-FIFO (8.2):
PieCtrlRegs.PIEIER8.bit.INTx1 = 1; // i2c - basic
PieCtrlRegs.PIEIER8.bit.INTx2 = 1; // i2c - FIFO
Also, the register IER must now allow lines INT1 and INT8:
IER |=0x81;
In Lab12_3.c we used only one interrupt source, CPU-Timer 0. Now we have three,
which requires that we load two more addresses of interrupt service routines into the
PieVectTable. At the appropriate spot in your code, add:

12 - 42 F2833x - Inter Integrated Circuit


Lab Exercise 12_4

PieVectTable.I2CINT2A = &i2c_fifo_isr;
PieVectTable.I2CINT1A = &i2c_basic_isr;
6. Change the type of variable “temperature” from a local variable in “main()” to a
global variable.
7. At the beginning of “Lab12_4.c”, add two prototypes for new interrupt service
routines:
interrupt void i2c_fifo_isr(void);
interrupt void i2c_basic_isr(void);
8. At the end of “Lab12_4.c” add a new interrupt function “i2c_fifo_isr()”. There are two
possible interrupt sources, a receiver FIFO-level and a transmitter FIFO-level
interrupt. We will use the receiver FIFO only. However, it is good practice to verify
which one of the two sources is active. In case the receiver interrupt is active, we will
find bit “RXFFINT” is set. We will use this bit in an if-condition to perform the
following activities:
• Read two times the I2CDRR - register to get the temperature values
• Clear the RXFFINT - flag by setting bit RXFFINTCLR
• Acknowledge the PIE - Interrupt of PIE - group 8.
The code in this interrupt service should look like:
unsigned int i;
if (I2caRegs.I2CFFRX.bit.RXFFINT == 1) // RX-FIFO - interrupt
{
i = I2caRegs.I2CDRR << 8; // read upper 8 bit (integers)
i += I2caRegs.I2CDRR; // add lower 8 bit (fractions)
temperature = i; // update temperature
I2caRegs.I2CFFRX.bit.RXFFINTCLR = 1; // clear ISR
}
PieCtrlRegs.PIEACK.all = PIEACK_GROUP8;

9. At the end of “Lab12_4.c” add a new interrupt function “i2c_basic_isr()”. This


function is shared between all basic I2C - interrupt sources. Register “I2CISRC” (see
Slide 12-15) contains a code number for the current source of the interrupt. Although
we have enabled only 1 of these basic interrupts (ARDY), it is good practice and will
be very important later, when you enable more than one basic source, to make a local
copy of this register. The reason is that the first read of this register will clear it
automatically.
In Lab12_4 we wait for ARDY (code number 3, see Slide 12-15), which is set after
the first two bytes of the “TMP100 Read Timing” (Slide 12-31) are transmitted. At
this moment we have to switch I2C from Master-Transmitter into Master-Receiver via
register I2CMDR. Since the TMP100 will send two temperature bytes, we also set
register I2CCNT = 2.
The whole body of function “i2c_basic_isr()” should look like:
unsigned int IntSource;
IntSource = I2caRegs.I2CISRC.all;
if (IntSource == 3) // ARDY was source of int

F2833x - Inter Integrated Circuit 12 - 43


Lab Exercise 12_4

{
I2caRegs.I2CCNT = 2; // read 2 byte temperature
I2caRegs.I2CMDR.all = 0x6C20; // Master-Receiver-Mode
}
PieCtrlRegs.PIEACK.all = PIEACK_GROUP8;

10. In the endless while(1) - loop of “main()”, remove the wait construction, which waits
until bit “ARDY” is set.
After that line, remove also the code to initialize registers I2CCNT and I2CMDR. We
moved this code in procedure step 9 into interrupt service routine “i2c_basic_isr()”,
which is now called automatically by ARDY.
Remove also the following lines, where we waited until bit “RXFFINT” was set and
the lines to read the temperature values. We moved this code in procedure step 8 into
interrupt service routine “i2c_fifo_isr()”. This function is now called automatically
after two bytes have been received (RXFFINT).

Build, Load and Run


11. Click the “Rebuild Active Project ” button or perform:

 Project  Rebuild All (Alt +B)

12. Load the output file in the debugger session:

 Target  Debug Active Project

and switch into the “Debug” perspective. Verify that in the debug perspective the win-
dow of the source code “Lab12_3.c” is high-lighted and that the blue arrow for the
current Program Counter position is placed under the line “void main(void)”.

13. Perform a real time run.

 Scripts  RealTime Emulation Control  Run_Realtime_with_Restart

14. Open a watch window and enter variable “temperature”. With a left mouse click into
column “Format”, select “Q-Value(8). Activate “Continuous Refresh” button in the
Watch Window.

Variable “temperature” should display the current ambient temperature with a reso-
lution of 1/16 °C (the example above shows 27.6875 °C).

15. Stop the code - execution:


 Scripts  Realtime Emulation Control  Full Halt

12 - 44 F2833x - Inter Integrated Circuit


F2833x Multichannel Buffered Serial Port

Introduction
The Multi Channel Buffered Serial Port (McBSP) is a synchronous serial data communi-
cation channel for high-speed data transfer between the F2833x and external serial devices. It
is quite often used to directly connect Audio - or Video - Codec's to an F2833x system. The
2833x device provides up to two high-speed multichannel buffered serial ports (McBSPs).

An independent clock signal (CLK(R/X) for receiver and transmitter can be generated by the
F2833x (master - mode) or by the external device (slave - mode).

A frame sync signal (FS(R/X) indicates the beginning of a new data sequence (frame).

A frame contains between 1 and 128 words (or channels); a word is a number of bits (8, 12,
16, 20, 24 or 32).

The serial data streams are available on the “Data Transmit” (DX) and “Data Receive” (DR)
pins.

A hardware compression and expanding technique by coding standards “A - law” (US and
Japan) or “µ - law” (Europe) can be included into the transmission path. The specifications
for µ-law and A-law log PCM are part of the CCITT G.711 recommendation.

One of the ranges of operating modes of McBSP is a hardware emulation of an additional


Serial Peripheral Interface (SPI).

The Peripheral Explorer Board provides interfaces to two McBSP related devices:
• A stereo audio codec TLV320AIC23B, connected to interface McBSP - A for the
stereo in/out audio data stream and to interface SPI-A for the AIC23B control data
stream.
• A serial EEPROM AT25C256K connected to interface McBSP - B.

F2833x - Multichannel Buffered Serial Port 13 - 1


Module Topics

Module Topics
F2833x Multichannel Buffered Serial Port.................................................................................... 13-1
Introduction ................................................................................................................................... 13-1
Module Topics ............................................................................................................................... 13-2
F2833x McBSP Block diagram ..................................................................................................... 13-4
Basic F2833x McBSP Features ..................................................................................................... 13-6
McBSP Data Frame Diagram ....................................................................................................... 13-7
Companding (Compressing and Expanding) ................................................................................ 13-9
McBSP - clocking ........................................................................................................................ 13-10
McBSP Frame Phases ................................................................................................................. 13-11
McBSP Receive ........................................................................................................................... 13-12
McBSP Transmission .................................................................................................................. 13-13
McBSP - Interrupts and DMA ..................................................................................................... 13-14
McBSP Module Registers ............................................................................................................ 13-15
Data Receive and Transmit Register ....................................................................................... 13-16
Serial Port Control Register 1 (SPCR1) .................................................................................. 13-17
Serial Port Control Register 2 (SPCR2) .................................................................................. 13-17
Receive Control Register 1 (RCR1)........................................................................................ 13-18
Receive Control Register 2 (RCR2)........................................................................................ 13-18
Transmit Control Register 1 (XCR1) ...................................................................................... 13-19
Transmit Control Register 2 (XCR2) ...................................................................................... 13-19
Sample Rate Generator Register 1 (SRGR1) .......................................................................... 13-20
Sample Rate Generator Register 2 (SRGR2) .......................................................................... 13-20
Pin Control Register (PCR) .................................................................................................... 13-21
Interrupt Enable Register (MFFINT) ...................................................................................... 13-21
Multichannel Mode Enable Registers (RCERx, XCERx)....................................................... 13-22
Stereo Audio Codec TLV320AIC23B .......................................................................................... 13-23
Functional Block Diagram ...................................................................................................... 13-24
Initialization of SPI - channel A ............................................................................................. 13-26
Initialization of the AIC23 ...................................................................................................... 13-26
Lab Exercise 13_1: single audio tone ......................................................................................... 13-33
Objective ................................................................................................................................. 13-33
Preface .................................................................................................................................... 13-34
Procedure ................................................................................................................................ 13-38
Open Files, Create Project File ............................................................................................... 13-38
Project Build Options .............................................................................................................. 13-38
Preliminary Test ...................................................................................................................... 13-39
Change the GPIO - Multiplex Registers ................................................................................. 13-39
Remove code from Lab6 ......................................................................................................... 13-39
Add SPI-A Initialzation Code ................................................................................................. 13-40
Add McBSP-A Initialzation Code .......................................................................................... 13-40
Initialize the codec AIC23B .................................................................................................... 13-40
Change the Interrupt Structure for Lab13_1 ........................................................................... 13-40
Add global variables and IQ-Math.......................................................................................... 13-41
Calculate new DAC - Value ................................................................................................... 13-42
Add McBSP - Transmit Interrupt Service ............................................................................... 13-43
Build, Load and Run ............................................................................................................... 13-43

13 - 2 F2833x - Multichannel Buffered Serial Port


Module Topics

Lab Exercise 13_2: Dual audio tone .......................................................................................... 13-45


Objective ................................................................................................................................ 13-45
Procedure ................................................................................................................................ 13-45
Open Project, Modify Source File .......................................................................................... 13-45
Build, Load and Run .............................................................................................................. 13-46
Lab 13_3: Dual audio tone and XRDY - Interrupt ..................................................................... 13-48
Objective ................................................................................................................................ 13-48
Procedure ................................................................................................................................ 13-48
Open Project, Modify Source File .......................................................................................... 13-48
Build, Load and Run .............................................................................................................. 13-49
Lab Exercise 13_4: EEPROM via McBSP ................................................................................. 13-51
Objective ................................................................................................................................ 13-51
Hardware Description:............................................................................................................ 13-52
Timing Diagram ..................................................................................................................... 13-53
AT25256 Status Register ........................................................................................................ 13-54
Instruction Register ................................................................................................................ 13-55
Procedure ................................................................................................................................ 13-58
Open Project, Modify Source File .......................................................................................... 13-58
Build, Load and Run .............................................................................................................. 13-62
Optional Exercise (EEPROM and SCI):..................................................................................... 13-64

F2833x - Multichannel Buffered Serial Port 13 - 3


F2833x McBSP Block diagram

F2833x McBSP Block diagram


Each McBSP - interface consists of six electrical signals:

Multichannel Buffered Serial Port (McBSP)


Introduction:
• Two High – Speed multichannel synchronous serial ports (McBSP-
A and McBSP-B)
• Maximum data rate: 20 MHz
• Each McBSP consists of a data - flow – path and a control - path

• Six Pins per channel


• MDX: data transmit
• MDR: data received
• MCLKX: transmit clock
• MCLKR: receive clock
• MFSX: frame sync transmit
• MFSR: frame sync receive

13 - 2

The following slide explains the data flow:

McBSP Block Diagram

Peripheral / DMA Bus MFSXx


16 16
MCLKXx
DXR2 TX Buffer DXR1 TX Buffer
16 16

XSR2 XSR1 MDXx

CPU
RSR2 RSR1 MDRx
16 16

RBR2 Register RBR1 Register


16 16

DRR2 RX Buffer DRR1 RX Buffer MCLKRx


16 16
MFSRx
Peripheral / DMA Bus

13 - 3

13 - 4 F2833x - Multichannel Buffered Serial Port


F2833x McBSP Block diagram

The electrical signals of a McBSP interface are listed in the following table. The direction of
the clock signals depends on the setup of the McBSP as a master device (output) or as a slave
device (input):

McBSP - A McBSP - B Signal Description


MCLKRA MCLKRB Receiver clock signal
MCLKXA MCLKXB Transmitter clock signal
MFSRA MFSRB Receiver Frame-Sync pulse signal
MFSXA MFSXB Transmitter Frame-Sync pulse signal
MDRA MDRB Data Input (Receiver)
MDXA MDXB Data Output (Transmitter)

The McBSP - interface is also connected to the CPU and to the DMA - unit of the F2833x
via four internal event signals:
• MRINT: McBSP - Receive Interrupt signal
• MXINT: McBSP - Transmit Interrupt signal
• REVT: Receive Synchronization event to DMA - unit
• XEVT: Transmit Synchronization event to DMA - unit

Data values are communicated to devices interfaced to the McBSP via the data transmit
(MDX) pin for transmission and via the data receive (MDR) pin for reception. Control in-
formation in the form of clocking and frame synchronization is communicated via the fol-
lowing pins: MCLKX (transmit clock), MCLKR (receive clock), MFSX (transmit frame
synchronization), and MFSR (receive frame synchronization).

The CPU and the DMA controller communicate with the McBSP through 16-bit-wide regis-
ters, accessible via the internal peripheral bus. The CPU or the DMA controller writes the
data to be transmitted to the data transmit registers (DXR1, DXR2). Data written to the
DXRs is shifted out to DX via the transmit shift registers (XSR1, XSR2). Similarly, receive
data on the DR pin is shifted into the receive shift registers (RSR1, RSR2) and copied into
the receive buffer registers (RBR1, RBR2). The contents of the RBRs are then copied to the
DRRs, which can be read by the CPU or the DMA controller. This allows simultaneous data
movement of internal and external data communications.

DRR2, RBR2, RSR2, DXR2, and XSR2 are not used (written, read, or shifted) if the serial
word length is 8 bits, 12 bits, or 16 bits. For larger word lengths, these registers are needed to
hold the most significant bits.

F2833x - Multichannel Buffered Serial Port 13 - 5


Basic F2833x McBSP Features

Basic F2833x McBSP Features


Features of McBSP
• Full - duplex communication
• Double-buffered transmission and triple-buffered reception,
allowing a continuous data stream
• Independent clocking and framing for reception and transmission
• send interrupts to the CPU and send DMA events to the DMA -
controller
• 128 channels for transmission and reception
• Multichannel selection modes that enable or disable block
transfers in each of the channels
• Direct interface to industry-standard CODECs, analogue interface
chips (AICs), and other serially connected A/D and D/A devices
• Support for external generation of clock signals and frame -
synchronization signals
• A programmable sample rate generator for internal generation and
control of clock signals and frame - synchronization signals
13 - 4

Features of McBSP
• Direct interface to:
• T1/E1 framers
• IOM-2 compliant devices
• AC97-compliant devices with multiphase
frame capability
• I2S compliant devices
• SPI devices
• Variable data sizes: 8, 12, 16, 20, 24, and 32 bits
• A-law (Europe) and µ-law (US & Japan)
hardware compression / expanding
13 - 5

13 - 6 F2833x - Multichannel Buffered Serial Port


McBSP Data Frame Diagram

McBSP Data Frame Diagram


Since McBSP is a synchronous serial data communication interface, all bits are time syn-
chronized by a clock signal (“CLK” in Slide 13-6). The receiver and transmitter part can use
different timings (clock signals “MCLKX” and “MCLKR”)

A McBSP data frame is started by a frame sync signal (“FS”) shown in Slide 13-6. Again the
transmitter and receiver can use independent frame sync signals (transmitter: “MFSX”, re-
ceiver: “MFSR”).

Definition: Word and Frame

FS

D w6 w7 w0 w1 w2 w3 w4 w5 w6 w7

Frame
Word

 “Frame” - contains one or multiple words


 Number of words per frame: 1-128

13 - 6

A frame consists of multiple “words”. The number of words is programmable between 1 and
128 words.

A “word” is a certain number of bits, which can be programmed as:


• 8
• 12
• 16
• 20
• 24 or
• 32 bits per word.

In addition, there is the option to initialize the McBSP to a “single” phase mode or in a
“dual” phase mode. In the latter we can use different setups for “words per frame” and “bits
per word” in phase 1 and in phase 2. In Lab exercise 13_3 we will use a dual phase setup to
send different stereo signals to right channel (phase 1) and left channel (phase 2) of the
AIC23B audio codec.

F2833x - Multichannel Buffered Serial Port 13 - 7


McBSP Data Frame Diagram

Definition: Bit and Word

CLK

FS

D a1 a0 b7 b6 b5 b4 b3 b2 b1 b0

Word
Bit

 “Bit” - one data bit per serial clock period


 “Word” or “channel” contains number of bits
(8, 12, 16, 20, 24, 32)

13 - 7

Another operating mode of the McBSP is called “multi-channel” - mode, in which we can
time slice a frame and process only preselected words of this frame. The following slide is an
example, in which a codec sends 32 words per frame, but the F2833x reads only words 0, 5
and 27 from each frame. Since we will not use this mode in our lab exercises, we will not go
deeper into details of this operating mode for now.

Multi-Channel Selection
Ch0-0
Multi-channel
Frame TDM Bit Stream Ch0-1
M Transmit
C 0 Ch31 ... Ch1 Ch0
c &
O Ch5-0
D ... B Receive
1 Ch31 Ch1 Ch0 Ch5-1
E S only selected
C P Channels Ch27-0
Ch27-1
 Allows multiple channels (words) to be independently selected for transmit
and receive (e.g. only enable Ch0, 5, 27 for receive, then process via CPU)

 The McBSP keeps time sync with all channels, but only “listens” or “talks”
if the specific channel is enabled (reduces processing/bus overhead)

 Multi-channel mode controlled primarily via two registers:


Multi-channel Control Reg Rec/Xmt Channel Enable Regs
MCR R/XCER (A-H)
(enables Mc-mode) (enable/disable channels)
 Up to 128 channels can be enabled/disabled
13 - 8

13 - 8 F2833x - Multichannel Buffered Serial Port


Companding (Compressing and Expanding)

Companding (Compressing and Expanding)


Companding (COMpressing and exPANDing) hardware allows compression and expansion
of data in either µ-law or A-law format. The companding standard employed in the United
States and Japan is µ-law. The European companding standard is referred to as A-law. The
specifications for µ-law and A-law log PCM are part of the CCITT G.711 recommendation.

The dynamic ranges of A-law and µ-law are 13 bits and 14 bits, respectively. Any values
outside this range are set to the most positive or most negative value. Thus, for companding
to work best, the data transferred to and from the McBSP via the CPU or DMA controller
must be at least 16 bits wide. The µ-law and A-law formats both encode data into 8-bit code
words. Companded data are always 8-bits wide; the appropriate word length bits
(RWDLEN1, RWDLEN2, XWDLEN1 and XWDLEN2) must therefore be set to 0, indicat-
ing an 8-bit wide serial data stream.

Compression & Expanding Data

13 - 9

When companding is chosen for the transmitter, compression occurs during the process of
copying data from DXR1 to XSR1. The transmit data is encoded according to the specified
companding law (A-law or µ-law). When companding is chosen for the receiver, expansion
occurs during the process of copying data from RBR1 to DRR1. The receive data values are
decoded into twos-complement format.

F2833x - Multichannel Buffered Serial Port 13 - 9


McBSP - clocking

McBSP - clocking

McBSP - Clocking

• Data is shifted one bit at a time


• from the DR pin to the RSR(s) or
• from the XSR(s) to the DX pin.

• The receive clock signal (CLKR) controls bit transfers


from the DR pin to the RSR(s).

• The transmit clock signal (CLKX) controls bit transfers


from the XSR(s) to the DX pin.

13 - 10

Data words are shifted one bit at a time from the DR pin to the RSR(s) or from the XSR(s) to
the DX pin. The time for each bit transfer is controlled by the rising or falling edge of the
receiver and transmitter clock signals.

The receive clock signal (CLKR) controls bit transfers from the DR pin to the RSR(s).

The transmit clock signal (CLKX) controls bit transfers from the XSR(s) to the DX pin.

CLKR or CLKX can be derived from a pin at the boundary of the McBSP (slave mode) or
derived from inside the McBSP (master mode).

The polarities of CLKR and CLKX are programmable.

Please note: The McBSP cannot operate at a frequency faster than ½ the LSPCLK fre-
quency. When driving CLKX or CLKR at the pin, choose an appropriate input clock fre-
quency. When using the internal sample rate generator for CLKX and/or CLKR, choose an
appropriate input clock frequency and divide down value (CLKDV) (i.e., be certain that
CLKX or CLK do not exceed LSPCLK/2).

13 - 10 F2833x - Multichannel Buffered Serial Port


McBSP Frame Phases

McBSP Frame Phases


The McBSP allows you to configure each frame to contain one or two phases. The number
of words and the number of bits per word can be specified differently for each of the two
phases of a frame, allowing greater flexibility in structuring data transfers. For example, you
might define a frame as consisting of one phase containing two words of 16 bits each, fol-
lowed by a second phase consisting of 10 words of 8 bits each. This configuration permits
you to compose frames for custom applications or, in general, to maximize the efficiency of
data transfers.

McBSP – Frame Phases


Single Phase Frame, 8 bits per word

Dual Phase Frame

Phase 1: 2 words of 12 bits each


Phase 2: 3 words of 8 bit each
13 - 11

One clock pulse is generated by the master device for each data bit transferred. Due to a va-
riety of different technology devices that can be connected to the I2C-bus, the levels of logic
0 (low) and logic 1 (high) are not fixed and depend on the associated level of VDD. For de-
tails, see the data manual for your particular F2833x.

F2833x - Multichannel Buffered Serial Port 13 - 11


McBSP Receive

McBSP Receive
The following process describes how data travels from the DR pin to the CPU or to the
DMA controller:

McBSP – Reception
Reception physical data path

Reception signal activity

DRR = Data Receive Register


RRDY = status bit “Receiver Ready”
13 - 12

1. The McBSP waits for a receive frame-synchronization pulse on the internal FSR.
2. When the pulse arrives, the McBSP inserts the appropriate data delay that is selected
with the RDATDLY bits of register RCR2 (with 1 data bit delay shown in Slide 13-12
above).
3. The McBSP accepts data bits on the DR pin and shifts them into the receive shift regis-
ter(s). If the word length is 16 bits or smaller, only RSR1 is used. If the word length is
larger than 16 bits, RSR2 and RSR1 are used; RSR2 contains the most significant bits.
4. When a full word is received, the McBSP copies the contents of the receive shift regis-
ter(s) to the receive buffer register(s), provided that RBR1 is not full with previous data.
If the word length is 16 bits or smaller, only RBR1 is used. If the word length is larger
than 16 bits, RBR2 and RBR1 are used and RBR2 contains the most significant bits.
5. The McBSP copies the contents of the receive buffer register(s) into the data receive
register(s), provided that DRR1 is not full with previous data. When DRR1 receives
new data, the receiver ready bit (RRDY) is set in SPCR1. This indicates that received
data is ready to be read by the CPU or the DMA controller. If the word length is 16 bits
or smaller, only DRR1 is used. If the word length is larger than 16 bits, DRR2 and
DRR1 are used and DRR2 contains the most significant bits. If companding is used dur-
ing the copy (RCOMPAND = 10b or 11b in RCR2), the 8-bit compressed data value in
RBR1 is expanded to a left-justified 16-bit value in DRR1. If companding is disabled,
the data value copied from RBR[1,2] to DRR[1,2] is justified and bit filled according to
the RJUST bits.
6. The CPU or the DMA controller reads the data from the data receive register(s). When
DRR1 is read, RRDY is cleared and the next RBR-to-DRR copy is initiated.

13 - 12 F2833x - Multichannel Buffered Serial Port


McBSP Transmission

McBSP Transmission
This section explains the fundamental process of transmission in the McBSP.

McBSP – Transmission
Transmission physical data path

Transmission signal activity

DXR = Data Transmit Register


XRDY = status bit “Transmitter Ready”
13 - 13

1. The CPU or the DMA controller writes data to the data transmit register(s). When
DXR1 is loaded, the transmitter ready bit (XRDY) is cleared in SPCR2 to indicate
that the transmitter is not ready for new data. If the word length is 16 bits or smaller,
only DXR1 is used. If the word length is larger than 16 bits, DXR2 and DXR1 are
used and DXR2 contains the most significant bits.
2. When new data arrives in DXR1, the McBSP copies the contents of the data transmit
register(s) to the transmit shift register(s). In addition, the transmit ready bit (XRDY)
is set. This indicates that the transmitter is ready to accept new data from the CPU or
the DMA controller. If the word length is 16 bits or smaller, only XSR1 is used. If
the word length is larger than 16 bits, XSR2 and XSR1 are used and XSR2 contains
the most significant bits. If companding is used during the transfer (XCOMPAND =
10b or 11b in XCR2), the McBSP compresses the 16-bit data in DXR1 to 8-bit data
in the µ-law or A-law format in XSR1. If companding is disabled, the McBSP passes
data from the DXR(s) to the XSR(s) without modification.
3. The McBSP waits for a transmit frame-synchronization pulse on the internal FSX.
4. When the pulse arrives, the McBSP inserts the appropriate data delay that is selected
with the XDATDLY bits of XCR2. In the preceding timing diagram, a 1-bit data de-
lay is selected.
5. The McBSP shifts data bits from the transmit shift register(s) to the DX pin.

F2833x - Multichannel Buffered Serial Port 13 - 13


McBSP - Interrupts and DMA

McBSP - Interrupts and DMA


The McBSP sends notification of important events to the CPU and DMA via the internal
signals shown in Slide 13-14:

McBSP – Interrupts and DMA


Internal Signals from McBSP to CPU or DMA:

Internal Signal Description


RINT Receiver Interrupt from McBSP to CPU; based
on a selected condition in the receiver
XINT Transmitter Interrupt from McBSP to CPU;
based on a selected condition in the transmitter
REVT Receive synchronization event from McBSP to
DMA; triggered when data has been received in
DRR.
XEVT Transmit synchronization event from McBSP to
DMA; triggered when DXR is ready to accept
new data.

13 - 14

13 - 14 F2833x - Multichannel Buffered Serial Port


McBSP Module Registers

McBSP Module Registers


A register summary of the set of McBSP - Registers is shown at the following two slides:

McBSP – Register Set


McBSP Control & Data Registers:
Register Description
DRR2 Data Receive Register 2 (high)
DRR1 Data Receive Register 1 (low)
DXR2 Data Transmit Register 2 (high)
DXR1 Data Receive Register 1 (low)
SPCR2 Serial Port Control Register 2
SPCR1 Serial Port Control Register 1
RCR2 Receive Control Register 2
RCR1 Receive Control Register 1
XCR2 Transmit Control Register 2
XCR1 Transmit Control Register 1
SRGR2 Sample Rate Generator Register 2
SRGR1 Sample Rate Generator Register 1

13 - 15

McBSP – Register Set


McBSP Multi Channel Control Registers:
Register Description
MCR2 Multichannel Control Register 2
MCR1 Multichannel Control Register 1
RCERx Receive Channel Enable Register Partition x
XCERx Transmit Channel Enable Register Partition x
PCR Pin Control Register
XCERB Transmit Channel Enable Register Partition B
PCR Pin Control Register Partition Channels
MFFINT Interrupt Enable Register A 0 -15
B 16 – 31
x = Partition A, B, C, D, E, F, G, H C 32 – 47
D 48 – 63
E 64 – 79
F 80 – 95
G 96 – 111
H 112 - 127
13 - 16

F2833x - Multichannel Buffered Serial Port 13 - 15


McBSP Module Registers

Data Receive and Transmit Register


The CPU or the DMA controller reads received data from one or both of the data receive
registers. If the serial word length is 16 bits or smaller, only DRR1 is used. If the serial
length is larger than 16 bits, both DRR1 and DRR2 are used and DRR2 holds the most sig-
nificant bits.

McBSP – Data Register


McBSP Data Receive Register (DRR2 and DRR1):

McBSP Data Transmit Register (DXR2 and DXR1):

13 - 17

If the serial word length is 16 bits or smaller, receive data on the MDRx pin is shifted into
receive shift register 1 (RSR1) and then copied into receive buffer register 1 (RBR1). The
content of RBR1 is then copied to DRR1, which can be read by the CPU or by the DMA
controller. The RSRs and RBRs are not accessible by the user.
If the serial word length is larger than 16 bits, receive data bits on the MDRx pin are shifted
into both of the receive shift registers (RSR2, RSR1) and then copied into both of the receive
buffer registers (RBR2, RBR1). The contents of the RBRs are then copied into both of the
DRRs, which can be read by the CPU or by the DMA controller.
If companding is used during the copy from RBR1 to DRR1 (RCOMPAND = 10b or 11b),
the 8-bit compressed data value in RBR1 is expanded to a left-justified 16-bit value in
DRR1. If companding is disabled, the data copied from RBR[1,2] to DRR[1,2] is justified
and bit filled according to the RJUST bits.

If the serial word length is 16 bits or fewer, data written to DXR1 is copied to transmit shift
register 1 (XSR1). From XSR1, the data is shifted onto the DX pin one bit at a time. If the
serial word length is more than 16 bits, data written to DXR1 and DXR2 is copied to both
transmit shift registers (XSR2, XSR1). From the XSRs, the data is shifted onto the DX pin
one bit at a time. If companding is used during the transfer from DXR1 to XSR1
(XCOMPAND = 10b or 11b), the McBSP compresses the 16-bit data in DXR1 to 8-bit data
in the µ-law or A-law format in XSR1. If companding is disabled, the McBSP passes data
from the DXR(s) to the XSR(s) without modification.

13 - 16 F2833x - Multichannel Buffered Serial Port


McBSP Module Registers

Serial Port Control Register 1 (SPCR1)


McBSP – Serial Port Control Register (SPCR1)

DLB: Digital Loopback Mode 0 = disabled; 1 = enabled


RJUST: Receive Justification Mode0 = Right justify data and zero fill MSBs
1 = Right justify data and sign – extend MSBs
2 = Left justify data and zero fill LSBs
CLKSTP: Clock Stop Mode 0 and 1 = disabled
2 = enabled, without clock delay (SPI – Mode)
3 = enabled, with half-cycle clock delay (SPI – Mode)
DXENA: DX Delay Enable 0 = OFF
1 = ON; extra delay for turn – ON - time
RINTM: Receiver Interrupt Mode 0 = INT when RRDY = 1
1 = INT after 16 channels (multichannel mode)
2 = INT of frame sync pulse
3 = INT on Receive Frame Sync Error
RSYNCERR: Receive Frame Sync Error 0 = no error; 1 = error
RFULL: Receiver Full Status bit 1 = Receiver Full condition (RSR, RBR and DRR full)
RRDY: Receiver Ready Status bit 1 = Receiver Ready; new data in DRR
RRST: Receiver Reset Control Bit 0 = Reset Receiver; 1 = release Receiver from Reset
13 - 18

Serial Port Control Register 2 (SPCR2)

McBSP – Serial Port Control Register (SPCR2)

FREE: Free Run JTAG Mode 0 = Stop at breakpoint; 1 = Free Run


Soft: Soft Stop JTAG Mode 0 = if FREE = 0, stop immediately in case of breakpoint
1 = if FREE = 0, stop at end of frame

FRST: Frame Sync Logic Reset 0 = Reset; 1 = release Frame Logic from Reset
GRST: Sample Rate Generator Reset 0 = Reset; 1 = release SRG from Reset
XINTM: Transmit Interrupt Mode 0 = INT when XRDY = 1
1 = INT after 16 channels (multichannel mode)
2 = INT of frame sync pulse
3 = INT on Transmit Frame Sync Error
XSYNCERR: Receive Frame Sync Error 0 = no error; 1 = error
XEMPTY: Transmitter Empty Status bit 0 = Transmitter empty (DXR1); 1 = not empty
XRDY: Transmitter Ready Status bit 1 = Transmitter ready (DXR1,2) to accept new data
XRST: Transmitter Reset Control Bit 0=Reset Transmitter; 1=release Transmitter from Reset

13 - 19

F2833x - Multichannel Buffered Serial Port 13 - 17


McBSP Module Registers

Receive Control Register 1 (RCR1)


McBSP – Receive Control Register 1 (RCR1)

RFRLEN1: Receive Frame Length1(0…0x7F)


Single Phase Frame: Number of Words in a frame (1…128)
Dual Phase Frame: Number of Words in frame – phase 1 (1...128)

RWDLEN1: Receive Word Length1 (0…7)


Single Phase Frame: Number of Bits in a Word
Dual Phase Frame: Number of Bits in a Word of frame - phase 1
0 = 8 Bit
1 = 12 Bit
2 = 16 Bit
3 = 20 Bit
4 = 24 Bit
5 = 32 Bit
6 and 7: reserved

13 - 20

Receive Control Register 2 (RCR2)


McBSP – Receive Control Register 2 (RCR2)

RPHASE: Receive Phase Number 0 = Single Phase Frame


1 = Dual Phase Frame

RFRLEN2: Receive Frame Length 2 (0…0x7F)


Single Phase Frame: don’t care
Dual Phase Frame: Number of Words in frame – phase 2 (1...128)

RWDLEN2: Receive Word Length 2 (0…7)


Single Phase Frame: don’t care
Dual Phase Frame: Number of Bits in a Word of frame - phase 2
0 = 8 Bit, 1 = 12 Bit, 2 = 16 Bit, 3 = 20 Bit, 4 = 24 Bit, 5 = 32 Bit
RCOMPAND: Receive Companding Mode 0 = no companding, MSB received first
1 = no companding, 8-bit-data, LSB first
2 = µ-law; 8-bit-data, MSB received first
3 = A-law; 8-bit-data, MSB received first
RFIG: Receive Frame Sync Ignore 1 = unexpected Frame Sync ignored
RDATDLY: Receive Data Delay 0 = 0 clock cycles delay after frame Sync
1 = 1 cycle; 2 = 2 cycles; 3 =reserved
13 - 21

13 - 18 F2833x - Multichannel Buffered Serial Port


McBSP Module Registers

Transmit Control Register 1 (XCR1)


McBSP – Transmit Control Register 1 (XCR1)

XFRLEN1: Transmit Frame Length1(0…0x7F)


Single Phase Frame: Number of Words in a frame (1…128)
Dual Phase Frame: Number of Words in frame – phase 1 (1...128)

XWDLEN1: Transmit Word Length1 (0…7)


Single Phase Frame: Number of Bits in a Word
Dual Phase Frame: Number of Bits in a Word of frame - phase 1
0 = 8 Bit
1 = 12 Bit
2 = 16 Bit
3 = 20 Bit
4 = 24 Bit
5 = 32 Bit
6 and 7: reserved

13 - 22

Transmit Control Register 2 (XCR2)


McBSP – Transmit Control Register 2 (XCR2)

XPHASE: Transmit Phase Number 0 = Single Phase Frame


1 = Dual Phase Frame

XFRLEN2: Transmit Frame Length 2 (0…0x7F)


Single Phase Frame: don’t care
Dual Phase Frame: Number of Words in frame – phase 2 (1...128)

XWDLEN2: Transmit Word Length 2 (0…7)


Single Phase Frame: don’t care
Dual Phase Frame: Number of Bits in a Word of frame - phase 2
0 = 8 Bit, 1 = 12 Bit, 2 = 16 Bit, 3 = 20 Bit, 4 = 24 Bit, 5 = 32 Bit
XCOMPAND: Transmit Companding Mode 0 = no companding, MSB transmitted first
1 = no companding, 8-bit-data, LSB first
2 = µ-law; 8-bit-data, MSB transmitted first
3 = A-law; 8-bit-data, MSB transmitted first
XFIG: Transmit Frame Sync Ignore 1 = unexpected Frame Sync ignored
XDATDLY: Transmit Data Delay 0 = 0 clock cycles delay after frame Sync
1 = 1 cycle; 2 = 2 cycles; 3 =reserved 13 - 23

F2833x - Multichannel Buffered Serial Port 13 - 19


McBSP Module Registers

Sample Rate Generator Register 1 (SRGR1)


McBSP – Sample Rate Generator (SRGR1)

FWID: Frame Sync Pulse Width 0…255


Pulse Width of Frame Sync Signal in McBSP
clock cycles

CLKGDV: Divide Down Value for Clock-Generator 0…255

CLKG frequency = (Input clock frequency)/ (CLKGDV + 1)


The input clock is selected by the SCLKME (Register PCR) and CLKSM
(Register SRGR) bits:

SCLKME CLKSM Input Clock Source


0 0 Reserved
0 1 LSPCLK
1 0 Signal on pin MCLKR
1 1 Signal on pin MCLKX
13 - 24

Sample Rate Generator Register 2 (SRGR2)


McBSP – Sample Rate Generator (SRGR2)

GSYNC: Clock Sync Mode only used, if clock source is external


1 = Clock Synchronization;
CLKG is adjusted to MCLKR / MCLKX
0 = no clock sync;
CLKG free running, FSG every FPER-cycles
CLKSM: Sample Clock Mode
SCLKME CLKSM Input Clock Source
0 0 Reserved
0 1 LSPCLK
1 0 Signal on pin MCLKR
1 1 Signal on pin MCLKX
FSGM: Frame Sync Mode; Frame Pulse from pin FSX (if FSXM = 0)
0: if FSXM = 1, generate frame pulse when DXR is copied into XSR
1: if FSXM = 1, generate frame pulse based on FPER and FWID
FPER: Frame Sync Period (1…4096); Number of CLKG cycles between frame
pulses 13 - 25

13 - 20 F2833x - Multichannel Buffered Serial Port


McBSP Module Registers

Pin Control Register (PCR)


McBSP – Pin Control Register (PCR)

FSXM: Transmit Frame Sync Mode 0 = Frame Pulse is supplied externally via pin FSX
1 = Frame Pulse generated internally by Sample Rate
Generator (bit FSGM of register SRGR2)
FSRM: Receive Frame Sync Mode 0 = Frame Pulse is supplied externally via pin FSR
1 = Frame Pulse generated internally by Sample Rate
Generator (bit FSGM of register SRGR2)
CLKXM: Transmit Clock Mode if CLKSTP = 0 or 1:
0 = external transmit clock from pin MCLKX
1 = internal transmit clock; MCLKX is output
if CLKSTP = 2 or 3:
0 = McBSP is slave in SPI – Protocol; MCLKX is input
1 = McBSP is master in SPI – Mode; MCLKX is output
SCLKME:Sample Rate Generator Input Mode (see CLKSM in Register SRGR2)
DXSTAT: DX pin Status Bit 1 = drive DX pin high; 0 = DX pin low (GPIO mode)
DRSTAT: DR pin Status Bit 1 = drive DR pin high; 0 = DR pin low (GPIO mode)
FSXP: Transmit Frame Sync Polarity 0 = active high; 1 = active low
FSRP: Receive Frame Sync Polarity 0 = active high; 1 = active low
CLKXP: Transmit Clock Polarity data valid on rising (0) or falling (1) edge of CLKX
CLKRP: Receive Clock Polarity data sampled on rising (1) or falling (0) edge 13 - 26

Interrupt Enable Register (MFFINT)


McBSP – Interrupt Enable Register (MFFINT)

RINT ENA: 0 = disable McBSP Receive Interrupts


1 = enable McBSP Receive Interrupts

XINT ENA: 0 = disable McBSP Transmit Interrupts


1 = enable McBSP Transmit Interrupts

13 - 27

F2833x - Multichannel Buffered Serial Port 13 - 21


McBSP Module Registers

Multichannel Mode Enable Registers (RCERx, XCERx)


We will not use the multichannel operation mode in our next lab exercises. Therefore we will
not discuss these registers here. For more information about these registers and the multi-
channel operation mode please refer to user manual “TMS320F2833x Multichannel Buffered
Serial Port (McBSP) Reference Guide”, literature number: SPRUFB7A at www.ti.com.

In the next pages we will discuss the first external device of the Peripheral Explorer Board,
which is connected via McBSP - A:

Stereo Audio Codec TLV320AIC23B

13 - 22 F2833x - Multichannel Buffered Serial Port


Stereo Audio Codec TLV320AIC23B

Stereo Audio Codec TLV320AIC23B


Here is what the data sheet says:

“The TLV320AIC23B is a high-performance stereo audio codec with highly integrated ana-
logue functionality. The analogue-to-digital converters (ADCs) and digital-to-analogue con-
verters (DACs) within the TLV320AIC23B use multi-bit sigma-delta technology with inte-
grated oversampling digital interpolation filters. Data-transfer word lengths of 16, 20, 24,
and 32 bits, with sample rates from 8 kHz to 96 kHz, are supported. The ADC sigma-delta
modulator features third-order multi-bit architecture with up to 90-dBA signal-to-noise ratio
(SNR) at audio sampling rates up to 96 kHz, enabling high-fidelity audio recording in a
compact, power-saving design. The DAC sigma-delta modulator features a second-order
multi-bit architecture with up to 100-dBA SNR at audio sampling rates up to 96 kHz, ena-
bling high-quality digital audio-playback capability, while consuming less than 23 milliwatts
during playback only. The TLV320AIC23B is the ideal analogue input/output (I/O) choice
for portable digital audio-player and recorder applications, such as MP3 digital audio play-
ers.”

Wow, sounds impressive, doesn’t it? But the question is: how can we get this device to
work? And, more importantly, if it is running, can we explain why? So let us try to use it in a
simple application first. At the end of this chapter we will use the internal DAC to “synthe-
size” an audio stereo output signal, based on the TMS320F2833x internal sine wave lookup
table. With a headphone plugged into J25 of the Peripheral Explorer Board we can make this
signal audible (or we use a scope to measure it).

To start with, let us start with a brief discussion of the functionality of this device. Here are
the main features:

Stereo Audio Codec TLV320AIC23B


Main Features:

• 90dB SNR Multibit Sigma-Delta ADC


• 100-dB SNR Multibit Sigma-Delta DAC
• 8 kHz …96 kHz Sampling-Frequency
• SPI- Interface for Control Channel Compatible Serial-
Port Protocols
• 2 - Phase Audio - Data Input/Output via McBSP
• Standard I2S, MSB, or LSB Justified-Data Transfers
• 16/20/24/32-Bit Audio Data Word Length
• Volume Control With Mute on Input and Output
• ADC Multiplexed Input for Stereo-Line Inputs and
Microphone
• Highly Efficient Linear Headphone Amplifier (30 mW into
32 Ohm from a 3.3-V Analogue Supply Voltage
13 - 28

F2833x - Multichannel Buffered Serial Port 13 - 23


Stereo Audio Codec TLV320AIC23B

Functional Block Diagram

Stereo Audio Codec TLV320AIC23B


Functional Block
Diagram:

Signals:
RHPOUT =
right headphone out
LHPOUT =
left headphone out

© Document Number : SLWS106H,


page 1-3 (www.ti.com)

13 - 29

The AIC23 is connected to the F2833x by the following signal lines:

GPIO -MUX F2833x - Function Description AIC23-signal

GPIO20 = 2 McBSPA - MDXA Audio data out DIN

GPIO21 = 2 McBSPA - MDRA Audio data in DOUT

GPIO22 = 2 McBSPA - MCLKXA Transmit clock BCLK

GPIO23 = 2 McBSPA - MFSXA Transmit frame sync LRCIN

GPIO58 = 1 McBSPA - MCLKRA Receive Clock BCLK

GPIO59 = 1 McBSPA - MFSRA Receive frame sync LRCOUT

GPIO16 = 1 SPIA - SPISIMO Control data out SDIN

GPIO18 = 1 SPIA - SPICLK Control data clock SCLK

GPIO19 = 1 SPIA - SPISTE Slave trans. enable /CS

13 - 24 F2833x - Multichannel Buffered Serial Port


Stereo Audio Codec TLV320AIC23B

Description:

• MXDA: serial audio data output stream from F2833x to AIC23

• MRDA: serial audio data input stream from AIC23 to F2833x

• MCLKXA: McBSPA Transmit Bit Clock.


Generated by AIC23 (signal: “BCLK”; 12 MHz).

• MCLKRA: McBSPA Receive Bit Clock.


Generated by AIC23 (signal: “BCLK”; 12 MHz).

• MFSXA: McBSPA Frame Sync Transmit.


Generated by AIC23 (signal: “LRCIN”; 44.1 kHz).

• MFSRX: McBSPA Frame Sync Transmit.


Generated by AIC23 (signal: “LRCIN”; 44.1 kHz).

• SPISIMO: SPIA “Slave In - Master Out” - signal.


Generated by F2833x

• SPICLK: SPIA - clock signal.


Generated by F2833x (1.0 MHz).

• SPISTE: SPIA - “Slave Transmit Enable”.


Generated by F2833x.
Signal “BCLK” is the data clock signal for the audio data transmission between the AIC23
and the F2833x. It defines the bit rate of the digital audio data stream. After a successful
initialization of the AIC23, this 12 MHz - signal should look like:

F2833x - Multichannel Buffered Serial Port 13 - 25


Stereo Audio Codec TLV320AIC23B

Signal “LRCIN” is a 44.1 kHz - signal that starts the transmission of a new McBSP - frame.
After a successful initialization it will look like this:

To generate the signal waveforms from above and to use the DAC of the codec to produce a
sinusoidal stereo audio signal, we have to initialize the codec. The control channel of the
AIC23 is connected to SPI-channel A of the F2833x (for SPI - details see also Chapter 10).

Initialization of SPI - channel A


The SPI communication between the F2833x and the AIC23 will be used to initialize the
operating mode of the AIC23. For the SPI-A setup, we only need to perform a simple
initialization:
• Register SPICCR:
o SPICHAR: 16 bit character transmission
o CLKPOLARITY: Clock polarity: Output on falling edge
o SPILBK: no loopback mode
o SPISWRESET: release from RESET
• Register SPIBRR:
o SPI-clock = LSPCLK / (BRR +1)
• Register SPICTL:
o MASTER_SLAVE: Master
o CLK_PHASE: no
o Disable interrupts
o Enable Talk

Initialization of the AIC23


To initialize the AIC23, we have to send a series of SPI - commands. Let us inspect the
command structure of the AIC23. A control word consists of 16 bits, starting with the MSB.
The control word is divided into two parts. The first part (bits 15 - 9) is the AIC23 register
address block; the second part (bits 8 - 0) is the data block.

13 - 26 F2833x - Multichannel Buffered Serial Port


Stereo Audio Codec TLV320AIC23B

The TLV320AIC23B has the following set of registers, which are used to program the
modes of operation:
ADDRESS REGISTER
0000000 Left line input channel volume control
0000001 Right line input channel volume control
0000010 Left channel headphone volume control
0000011 Right channel headphone volume control
0000100 Analog audio path control
0000101 Digital audio path control
0000110 Power down control
0000111 Digital audio interface format
0001000 Sample rate control
0001001 Digital interface activation
0001111 Reset register

When we initialize the AIC23 to accept a stereo audio data stream, we have to initialize this
list of registers. This requires the merging of the 7-bit register address (15-9) with the 8-bit
data (8-0), before it will be transmitted as a 16 - bit result via SPI. Please try to follow the
given sequence:

1. Reset Register
Clear all 8 data bits to zero.

Stereo Audio Codec TLV320AIC23B


Reset Register:

Power Down Control Register:

LINE = Line Input


MIC = Microphone Input
ADC = Internal ADC
DAC = Internal DAC
OUT = Output Signals
0 = ON; 1 = OFF
OSC = Oscillator
CLK = CLOCK
OFF = Device Power
13 - 31

2. Power Down Control Register

Switch OFF: LINE, MIC, ADC, DAC and OUT. Switch ON: OSC, CLK and OFF.

F2833x - Multichannel Buffered Serial Port 13 - 27


Stereo Audio Codec TLV320AIC23B

3. Left Headphone Volume Control Register

• Set Left Headphone Volume (LHV) to 0dB.


• Enable Left Zero Crossing (LZC) to update volume on zero crossing only.

Stereo Audio Codec TLV320AIC23B


Left Channel Headphone Volume Control Register:

LRS = Left / Right simultaneous update volume ( 0 = OFF, 1 = ON)


LZC = Left channel zero cross (0 = OFF, 1 = ON). If ON, volume updates
only at zero crossings
LHV = Left Headphone Volume (0x7F = +6dB; 0x79 = 0dB; 0x30 = -73dB (mute)

Right Channel Headphone Volume Control Register:

RLS = Right / Left simultaneous update volume ( 0 = OFF, 1 = ON)


RZC = Right channel zero cross (0 = OFF, 1 = ON). If ON, volume updates only
at zero crossings
RHV = Right Headphone Volume (0x7F = +6dB; 0x79 = 0dB; 0x30 = -73dB (mute)
13 - 32

4. Right Headphone Volume Control Register

• Set Right Headphone Volume (RHV to 0dB).


• Enable Right Zero Crossing (RZC) to update volume on zero crossing only.

5. Analogue Audio Path Control Register

• Switch ON the DAC.


• Mute the Microphone.
• Microphone boost = 0dB.
• Audio Input Select = Line.
• Disable ADC and DAC Bypass mode.
• Switch OFF the Microphone Side Tone

13 - 28 F2833x - Multichannel Buffered Serial Port


Stereo Audio Codec TLV320AIC23B

Stereo Audio Codec TLV320AIC23B


Analogue Audio Path Control Register:

MICB = Microphone boost (0 = 0dB; 1 = 20dB)


MICM = Microphone mute (0 = normal; 1 = muted)
INSEL = Input Select for Audio (0 = line; 1 = Microphone)
BYP = Bypass (0 = disabled; 1 = enabled (line in to line out))
DAC = DAC select ( 0 = DAC OFF; 1 = DAC ON)
STE = Added Side Tone ( 0 = OFF; 1 = ON)
STA = Side Tone Volume (If STE = ON, MIC is routed both to headphone & line out ).

13 - 33

6. Digital Audio Path Control Register

• Enable ADC High Pass Filter, Disable De - emphasis, disable DAC soft mute.

Stereo Audio Codec TLV320AIC23B


Digital Audio Path Control Register:

ADCHP = ADC High Pass Filter (0 = enabled; 1 = disabled)


DEEMP = De-emphasis control (0 = disabled, 1 = 32kHz, 2 = 44.1kHz, 3 = 48kHz)
DACM = DAC soft mute (0 = disabled; 1 = enabled)

13 - 34

F2833x - Multichannel Buffered Serial Port 13 - 29


Stereo Audio Codec TLV320AIC23B

7. Digital Audio Interface Format Register

Stereo Audio Codec TLV320AIC23B


Digital Audio Interface Format Register:

FOR = Data Format 0 = MSB first, right aligned


1 = MSB first, left aligned
2 = I2S – Format, MSB first, left -1 aligned
3 = DSP – Format; Frame sync followed by 2 words
IWL = Input word length 0 = 16 bit
1 = 20 bit
2 = 24 bit
3 = 32 bit
LRP = DAC left /right phase 0 = right channel on and LRCIN = high
1 = right channel on and LRCIN = low
LRSWAP = DAC left / right swap (0 = NO, 1 = YES)
MS = Master Mode ( 0 = Slave; 1 = Master)

13 - 35

• FOR: set to DSP-Mode


• IWL: set to 32 - bit mode
• LRP: Right Channel with LRCIN = low
• LRSWAP: no swap
• MS: set to Master

13 - 30 F2833x - Multichannel Buffered Serial Port


Stereo Audio Codec TLV320AIC23B

8. Sample Rate Control Register

• Set USB - Mode.


• Set BOSR to 272 fs.
• Set SR to 44.1 kHz for ADC and DAC

Stereo Audio Codec TLV320AIC23B


Sample Rate Control Register:

USB = Clock Mode Select (0 = Normal, 1 = USB)


BOSR = Base Oversampling Rate
USB – Mode: 0 = 250fs, 1 = 272fs;
Normal – Mode: 0 = 256fs; 1 = 384fs
SR = Sampling Rate

CLKIN = Clock Input Divider (0 = MCLK; 1 = MCLK/2)


CLKOUT = Clock Output Divider (0 = MCLK; 1 = MCLK/2) 13 - 36

F2833x - Multichannel Buffered Serial Port 13 - 31


Stereo Audio Codec TLV320AIC23B

9. Digital Interface Activation Register

• Activate Interface

Stereo Audio Codec TLV320AIC23B


Digital Interface Activation Register:

ACT = Activate Interface (0 = NO, 1 = YES)


RES = reserved

13 - 37

10. Power Down Control Register

• As a final step, activate everything except Microphone.

1= OFF, 0 = ON

13 - 32 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_1: single audio tone

Lab Exercise 13_1: single audio tone


Objective
After the previous extensive (and probably boring) description of control registers for
McBSP and the stereo audio codec AIC23B it is time for experiments. In Lab13_1 we will
use the DAC of the AIC23B to synthesize a signal of 200 Hz on both the left and right head-
phone channels. In Lab 13_2 we will improve the code to use interrupts. Finally, in Lab13_3
we will generate two independent signals on the left and right stereo channels. Since we will
generate audio signals, they do have to be sinusoidal - we have to update the DAC periodi-
cally - exactly at 44.1 kHz. To do so, we will initialize the codec to operate at this frequency
- a typical frequency for audio devices, such as CD - Players or MP3 - devices.

The question is: How do we generate a sinusoidal output value? One answer could be: “Use
the trigonometric function y = sin(x).” However, the call to a trigonometric function is a time
- consuming task and in time - critical applications we would need to make this function
faster. A better solution is to use a “look-up-table”. In such a table, we pre-calculate all the
values, we will need in the code. For example, for y = sin(x), we could calculate 360 sine -
values for a 360° unit circle, to obtain 360 points for interpolation.

Fortunately Texas Instruments already implemented a sine - wave look - up table in the
boot - ROM memory of the F2833x! It consists of 512 entries for a unit circle of 360°, which
will give us a next value at 360 degree / 512 = 0.7 degree. The values of this table are 32 bit
wide and stored in fractional I2Q30 - format (range -2.0 ... +1.9999). The table starts at ad-
dress 0x3FE000 with value y = sin (0), followed by value y = sin (0.7) and so on. We will
use this table for the labs in this chapter.

But let us first inspect this sine look-up table (note: Q30 is currently not working in CCS4.1):

• Open a memory window (View  Memory)


• In the top left corner of the memory window, enter address 0x3FE000
• In the bottom left corner, change the data type to: 32 Bit Signed Integer
• Open the properties of memory window (right mouse click) and change Q Value to
30:

F2833x - Multichannel Buffered Serial Port 13 - 33


Lab Exercise 13_1: single audio tone

Preface
Before we start the laboratory procedure, it would be helpful to summarize the necessary
steps to initialize the audio codec. The control channel of the AIC23B is connected to inter-
face SPI-A. Of the F2833x and the audio data stream is interfaced to McBSP. Here is what
we have to do:

SPI - A - Initialization
To initialize the control channel of the AIC23B, we have to set up the SPI - A unit of the
F2833x. Since we will not use SPI - interrupts or SPI - FIFO units for this first exercise, the
initialization sequence is quite simple:

For Register “SPICCR”:

• First hold SPI-A in Reset (Bit “SPIWRESET”)


• Select16 - bit Mode (Bit field “SPICHAR”)
• Select output data on falling edge of clock (Bit “CLKPOLARITY”)
• Disable loopback Mode (Bit “SPILBK”)
• Finally, release SPI - A from Reset (Bit “SPIWRESET”)

For Register “SPICTL”:

• Select Master Mode (Bit “MASTER_SLAVE”)


• Select no clock delay (Bit “CLK_PHASE”)
• Enable SPI - transmissions (Bit “TALK”)
• Disable Interrupts (Bits “SPIINTENA” and “OVERRUNINTENA”)

For Register “SPIBRR”:

• Although the data rate of this channel is not really critical, because SPI-A is used for
initialization purpose only, let us agree to initialize it to 1 MBit/s. Assuming that you
have not changed the provided function “InitSysCtrl()” from Texas Instruments
Header Files, your F2833xControlCard will run at 150 MHz (SYSCLKOUT) and
with a LSPCLK = 37.5 MHz The SPI - data rate is calculated as:

𝑆𝑆𝑆𝑆𝑆𝑆 − 𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑 − 𝑟𝑟𝑟𝑟𝑟𝑟𝑟𝑟


𝐿𝐿𝐿𝐿𝐿𝐿𝐿𝐿𝐿𝐿𝐿𝐿
=
𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆 + 1

• Load Register SPIBRR with the calculated value.

In preparation for Lab13_1, we can write a new function “SPIA_init()”, which covers the
initialization steps discussed above.

13 - 34 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_1: single audio tone

AIC23B Control Command Sequence


Next, we need to prepare the control sequence for the AIC23B. Please refer to pages 13-27
of this textbook module, where we discussed the AIC23B registers. Now we have to define
the initialization sequence:

1. Apply a Reset - command to the Reset Register.


Hint: The address of the Reset-Register is 0001111 (see Slide 13-31). A reset command
consists of 9 zero bits 0000 0000 0. The resulting 16 - bit value is 0x1E00. Send this
value as first command via SPI-A to the AIC23B.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0

2. Address the Power - Down - Control Register (Slide 13-31). For now switch OFF
“Line”, “Mic”, “ADC”, “DAC”, and “OUT”. Switch to ON bits for “OSC”, “CLK” and
“OFF”. Fill in the values for all 16 bits in the table below:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

3. Address the Left Headphone Control Register (Slide 13-32). Switch ON “LZC” and set
“LHV” to volume = 0 db. LZC is the left zero crossing. When ON, it changes volume
levels only at the zero crossing of the sinusoidal signal.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

4. Address the Right Headphone Control Register (Slide 13-32). Switch ON “RZC” and set
“RHV” to volume = 0 db. RZC is the right zero crossing. When ON, it changes volume
levels only at the zero crossing of the sinusoidal signal.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

5. Address the Analogue Audio Path Control Register (Slide 13-33). Enable the DAC and
mute the microphone. Disable bypass and side tone. Set Audio Input to “Line”.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

6. Address the Digital Audio Path Control Register (Slide 13-34). Set all 9 data bits to zero.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

7. Address the Digital Audio Interface Format Register (Slide 13-35). Set the AIC23B to
Master Mode (MS). Set the data format to DSP (FOR). Set the input word length to 32
bit (IWL). Set LRP to 1 (right channel when LRCIN = low). Do not swap the DAC -
channels (LRSWAP).
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

8. Address the Sample Rate Control Register (Slide 13-36). Select USB-Mode (USB). Se-
lect 44.1 kHz both for ADC and DAC (SR and BOSR). Set CLKIN and CLKOUT to
MCLK.

F2833x - Multichannel Buffered Serial Port 13 - 35


Lab Exercise 13_1: single audio tone

9. Address the Digital Interface Activation Register (Slide 13-37). Activate the interface
(ACT).
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

10. Address the Power - Down - Control Register (Slide 13-31). Turn on everything except
the microphone (MIC).
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

McBSP - A Initialization Sequence


To be able to send audio data to the AIC23B we also have to initialize McBSP-A.
1. Register Serial Port Control 1 (SPCR1) - see Slide 13-18:

• Reset Receiver. We don’t use the McBSP-Receiver for Lab13_1


15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

2. Serial Port Control 2 Register (SPCR2) - see Slide 13-19:


• Do not stop McBSP on JTAG - Breakpoints (Bit “FREE”)
• Request Transmit Interrupt Service on Frame Sync Pulse (Bit field “XINTM”)
• Release Frame Sync Logic from Reset (Bit “FRST”)
• Release Sample Rate Generator from Reset (Bit “GRST”)
• Set all remaining bits to zero.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

3. Interrupt Enable Register (MFFINT) - see Slide 13 - 27:


• Enable Transmit Interrupts (XINT)
• Disable Receive Interrupts (RINT)
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

4. Transmit Control Register 1 (XCR1) - see Slide 13 - 22:


• Select “32 - bit” data in phase 1 (XWDLEN1)
• Select 1 word in phase 1 (XFRLEN1)
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

5. Transmit Control Register 2 (XCR2) - see Slide 13 - 23:


• Select “Dual Phase” - Frame (XPHASE). We will use phase 1 for the left audio
signal and phase 2 for the right signal
• Select “32 - bit” data in phase 2 (XWDLEN2)
• Select 1 word in phase 2 (XFRLEN2)
• Set data delay to 1 clock cycle after frame sync (XDATDLY)
• Disable Compand, MSB first (XCOMPAND)
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

13 - 36 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_1: single audio tone

6. Sample Rate Generator Register 2 (SRGR2) - see Slide 13 - 25:

• Select pin MCLKX as source for sample clock (bit “CLKSM”).


• Set all remaining bits to zero.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

7. Pin Control Register (PCR) - see Slide 13 - 26:


• Select external pulses for Receive and Transmit Frame Sync (Bits “FSXM” and
“FSRM”).
• Select external clock from pin MCLKX (Bit “CLKXM”)
• Select external clock from pin MCLKR (Bit “CKLRM”)
• Set Bit “SCLKME” = 1 to select MCLKX as clock source for sample rate generator
• Select Frame Sync Polarity as “active low” (Bits “FSXP” and “FSRP”)
• Select Transmit Clock polarity to “rising edge” (Bit “CLKXP”)
• Select Receive Clock Polarity to “rising edge” (Bit “CLKRP”)
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

AIC23B Exercises:
Lab13_1:
• Initialize SPI-A as control channel for AIC23B
• Initialize McBSP-A as data channel for AIC23B
• AIC23B is master and sends the 12MHz base clock
• AIC23B sends a 44.1 kHz frame sync signal to McBSP
• Send a sinusoidal signal, based on the BOOT-ROM
look-up table to the DAC of the AIC23B; sample rate is
44.1 kHz

Lab13_2:
• Send two different signals to left and right audio channel
• Add volume control

Lab13_3:
• Improvement of Lab13_2; reduce Interrupt Service time
13 - 38

F2833x - Multichannel Buffered Serial Port 13 - 37


Lab Exercise 13_1: single audio tone

Procedure
Now we are ready to code a new project for Lab13_1:

Open Files, Create Project File


1. Using Code Composer Studio, create a new project called Lab13.pjt in
C:\DSP2833x_V4\Labs (or in another path that is accessible by you; ask your teacher
or a technician for an appropriate location!).
2. A good point to start with is the source code of Lab6.c, which produces a hardware
based time period using CPU core timer 0. Open file Lab6.c from
C:\DSP2833x_V4\Labs\Lab6 and save it as Lab13_1.c in
C:\DSP2833x_V4\Labs\Lab13.
3. Define the size of the C system stack. In the project window, right click at project
“Lab13” and select “Properties”. In category “C/C++ Build”, “C2000 Linker”, “Basic
Options” set the C stack size to 0x400.

Link some of the source code files, provided by Texas Instruments, to the project:
4. In the C/C++ perspective, right click at project “Lab13” and select “Link Files to
Project”. Go to folder “C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\source” and
link:

• DSP2833x_GlobalVariableDefs.c
From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\source link:
• DSP2833x_PieCtrl.c
• DSP2833x_PieVect.c
• DSP2833x_DefaultIsr.c
• DSP2833x_CpuTimers.c
• DSP2833x_SysCtrl.c
• DSP2833x_CodeStartBranch.asm
• DSP2833x_ADC_cal.asm
• DSP2833x_usDelay.asm
From C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\cmd link:

• DSP2833x_Headers_nonBIOS.cmd

Project Build Options


5. We have to extent the search path of the C-Compiler for include files. Right click at
project “Lab13” and select “Properties”. Select “C/C++ Build”, “C2000 Compiler”,
“Include Options”. In the box: “Add dir to #include search path”, add the following
lines:

C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include

13 - 38 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_1: single audio tone

C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include

Note: Use the “Add” Icon to add the new paths:

Close the Property Window by Clicking <OK>.

Preliminary Test
6. So far we only created a new project “Lab13.pjt”, with the same functionality as in
Lab6. A good step would be to rebuild Lab13, load the code into the controller and
verify the binary counter at LEDs LD1 to LD4 of the Peripheral Explorer Board.
The LEDs should display the counter at 100 milliseconds time steps.
If not: Debug!

Change the GPIO - Multiplex Registers


7. Open file “Lab13_1.c” and edit the function “Gpio_select()”:

• The control channel of the AIC23B is connected to the SPI-A interface. Change
the setup for multiplex register “GPAMUX2” to use SPI-A at pins GPIO16
(SPISIMO), 18(SPICLK) and 19(SPISTE).

• The digital audio data channel to and from the AIC23B uses the McBSP-A
interface. Change the setup for multiplex register “GPAMUX2” to use McBSP-
A functions on pins GPIO20 (MDXA), 21(MDRA), 22 (MCLKXA) and 23
(MFSXA). With the help of register “GPAQSEL2”, set all four lines to
“asynchronous”.

• For register “GPBMUX2”, select two more McBSP-A signals at pin 58


(MCLKRA) and pin 59 (MFSRA).

Remove code from Lab6


8. In the function “main()”, remove the local variable “counter” and the all the code
inside the while(1) -loop that is related to the variable “counter”.
Please note: although we do not need CPU Timer 0 and its interrupt service routine for
lab exercise 13_1, we keep this unit in our code, (a) as an exercise to have multiple
interrupt sources and (b) as a placeholder for further extensions to this lab exercise.

F2833x - Multichannel Buffered Serial Port 13 - 39


Lab Exercise 13_1: single audio tone

Add SPI-A Initialzation Code


9. At the end of “Lab13_1”, add a function “SPIA_Init()” to initialize the interface for
SPI-A. In the preface of this exercise (pages 13-34 to 13-37), we discussed all
necessary initialization steps.
10. At the beginning of “Lab13_1”, add a function prototype for “SPIA_Init()”.
11. In “main()”, after the function call to “Gpio_select()”, add a function - call to
“SPIA_Init()”.

Add McBSP-A Initialzation Code


12. At the end of “Lab13_1”, add the function “McBSPA_Init()” to initialize the interface
for McBSP-A. In the preface of this exercise (pages 13-36 to 13-37), we discussed all
the necessary initialization steps.
13. At the beginning of “Lab13_1”, add a function prototype for “McBSPA_Init()”.
14. In “main()”, after the function call to “SPIA_Init()”, add a function - call to
“McBSPA_Init()”.

Initialize the codec AIC23B


15. At the end of “Lab13_1” add the function “AIC23_Init()” to initialize the AIC23B
stereo audio codec. The initialization process is a sequence of SPI - A commands that
must be transmitted from the F2833x to the AIC23. In the Preface for this lab we
discussed the necessary commands (pages 13-35 and 13-36).
The code in function “AIC23_Init()” must consist of a series of write commands of
16-bit words into register “SPITXBUF”, followed by a wait construction for the end
of the transmission and a dummy read of SPIRXBUF to clear the interrupt flag:
SpiaRegs.SPITXBUF = command_1;
while (SpiaRegs.SPISTS.bit.INT_FLAG != 1);
i = SpiaRegs.SPIRXBUF;
SpiaRegs.SPITXBUF = command_2;
while (SpiaRegs.SPISTS.bit.INT_FLAG != 1);
i = SpiaRegs.SPIRXBUF;

16. At the beginning of “Lab13_1”, add a function prototype for “AIC23_Init()”.


17. In “main()”, after the function call to “McBSPA_Init()” add a function - call to
“AIC23_Init()”.

Change the Interrupt Structure for Lab13_1


18. We will use the McBSP - Transmit Frame - Sync signal, which is generated by the
AIC23B at a frequency of 44.1 kHz, to request an interrupt service. This interrupt
service routine will be used to send the next pair of stereo amplitude values for the
sinusoidal audio signal to the AIC23B. In main, search for the line, that we used to

13 - 40 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_1: single audio tone

overload the PieVectTable with the address of function “cpu_timer0_isr()”. After that
line add:

PieVectTable.MXINTA = &McBSP_A_TX_isr;
19. By adding a new code - line enable the PIE - interrupt - line McBSP-A (which is PIE
line 6, interrupt number 6):

PieCtrlRegs.PIEIER6.bit.INTx6 = 1;

20. Change the line to enable interrupt lines in Register IER. Now we have to enable line
INT1 (CPU - Timer 0) and line INT6 (McBSP-A).
21. At the beginning of “Lab13_1”, add a function prototype for the interrupt function
“McBSP_A_TX_isr()”.

Add global variables and IQ-Math


22. At the beginning of “Lab13_1.c”, add two global variables:
float volume = 0.2; // relative sound volume control (0...1)
unsigned int fsin= 220; // audio stereo sine frequency in Hertz

23. Also at the beginning of “Lab13_1.c” add a global array variable “sine_table[512]” to
obtain access to the ROM - sine - value lookup-table. This table consists of 512 values
for a unit circle (see page 13-33) in I2Q30 - format. A “pragma DATA_SECTION”
directive will connect this variable to a linker symbol “IQmathTables”, which is
defined in file “28335_RAM_lnk.cmd”:

#pragma DATA_SECTION(sine_table,"IQmathTables");
_iq30 sine_table[512]; // lookup-table 512 values in I2Q30 (+1...-1)

24. The new data type “_iq30” is defined in another header file, provided by Texas
Instruments and called “IQmathLib.h”. Include this file in your source code
“Lab13_1.c”:

#include "IQmathLib.h"
25. We have to extent the include search path. Right click at project “Lab13” and select
“Properties”. Select “C/C++ Build”, “C2000 Compiler”, “Include Options”. In the
box: “Add dir to #include search path”, add the following line:

C:\tidcs\c28\IQmath\v15a\include

Note: Depending on the installation on your PC, the IQ-Math library can be installed
at a different location. If the IQ-math - library is not installed at all, search for
“sprc087” on Texas Instruments website (www.ti.com) and download it from there.

26. Link the IQ-Math - Library to your project. From C:\tidcs\c28\IQmath\v15a\lib, link:

IQmath.lib

F2833x - Multichannel Buffered Serial Port 13 - 41


Lab Exercise 13_1: single audio tone

Calculate new DAC - Value


Before we go into the coding details, we should discuss how to calculate the next
amplitude based on the sine-lookup-table in boot-ROM.
The sine table consists of 512 entries for 360 degrees. If we would read the next value
each time we get a frame synch pulse (fframe = 44.1 kHz), we would generate a resulting
signal of
𝑓𝑓 𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓 44.1 𝑘𝑘𝑘𝑘𝑘𝑘
𝑓𝑓𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠 = 512
= = 86 𝐻𝐻𝐻𝐻 [1]
512
To produce a higher signal frequency fsignal, we have to reduce the number of sample
points taken from the table. For example, if we were to take every other sample point
(Step_Size = 2), we would obtain:

𝑓𝑓 𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓 44.1 𝑘𝑘𝑘𝑘𝑘𝑘 𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆 ∗ 44.1 𝑘𝑘𝑘𝑘𝑘𝑘 2∗ 44.1 𝑘𝑘𝑘𝑘𝑘𝑘


𝑓𝑓𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠 = = 512 = = = 172 𝐻𝐻𝐻𝐻 [2]
512 512 512
𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆 _𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆

Rearranging this formula to Step_Size gives:


𝑓𝑓 𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠 ∗512
𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆_𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆 = 𝑓𝑓 𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓
[3]

For example to produce a signal of fsignal = 100 Hz we would need a Step_Size of 1.16.

To calculate the next index into the look-up - table (lut_idx) we have to multiply the
linear index by Step_Size:

𝑙𝑙𝑙𝑙𝑙𝑙_𝑖𝑖𝑖𝑖𝑖𝑖 = 𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙_𝑖𝑖𝑖𝑖𝑖𝑖 ∗ 𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆_𝑆𝑆𝑆𝑆𝑆𝑆𝑆𝑆 [4]

The linear index “linear_idx” (0…511) is incremented with each 44.1 kHz - Interrupt.
The look-up - table index “lut_idx” is the resulting integer index into the sine - table. The
final equation to calculate the next index is:

𝑓𝑓 𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠 ∗512
𝑙𝑙𝑙𝑙𝑙𝑙_𝑖𝑖𝑖𝑖𝑖𝑖 = 𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙_𝑖𝑖𝑖𝑖𝑖𝑖 ∗ 𝑓𝑓 𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓
[5]

This formula will be used to read the next lookup table value, which is a value between
+1 and -1 in I2Q30 - Format. We will multiply this value with the relative value
“volume” (0…1) for volume control. A conversion function “_IQ30()” can be used to
convert a float type “volume” into an I2Q30 type. The multiply is done using function
“_IQ30mpy()”:

amplitude = _IQ30mpy(sine_table[lut_idx],_IQ30(volume)); [6]

The result of the multiply operation is an I2Q30 - number. The AIC23B expects it as a
‘per unit’ value or, in other words an I1Q31 - number. When we left shift the amplitude
by 1 bit, we have the final value for the AIC23B:

amplitude <<= 1; [7]

Now let us resume the lab procedure!

13 - 42 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_1: single audio tone

Add McBSP - Transmit Interrupt Service


27. At the beginning of “Lab13_1.c”, add a function prototype for a new interrupt service
function:
interrupt void McBSP_A_TX_isr(void);
28. At the end of “Lab13_1.c”, add a new interrupt service function
“McBSP_A_TX_isr()”. This function will be called by the frame sync signal
(MFSXA), which is produced by the AIC23B as signal “LCRIN” at a frequency of
44.1 kHz. With this pulse, the AIC23B requests a new pair of amplitude values for the
right and left stereo audio channel of its DAC. We have to include the following steps
in the function “McBSP_A_TX_isr()”:

• First, we need three local variables:


static unsigned int linear_idx=0;
unsigned int lut_idx;
long amplitude;

• Next, calculate “lut_idx” according Equation [5] from page 3-42.

• If the result of the calculation for “lut_idx” is greater than 511, reset both
“linear_idx” and “lut_idx” to zero.

• Calculate the new amplitude for the audio signal according equation [6] and [7].

• Load register McspaRegs.DXR2 with the upper 16 bits of “amplitude”.

• Load register McspaRegs.DXR1 with the lower 16 bits of “amplitude”.

• Increment variable “linear_idx”. If the value exceeds 511, reset it to zero.

• Finally, acknowledge PIE - Interrupt - Group 6:


PieCtrlRegs.PIEACK.bit.ACK6 = 1;

Build, Load and Run


29. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

30. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

31. Verify that in the debug perspective the window of the source code “Lab13_1.c” is
high-lighted and that the blue arrow for the current Program Counter position is placed
under the line “void main(void)”.

F2833x - Multichannel Buffered Serial Port 13 - 43


Lab Exercise 13_1: single audio tone

32. Perform a real time run.

Target  Run

33. Connect headphones to J25 (Headphone - Out) of the Peripheral Explorer Board. A
signal of 220 Hz should be audible on the right and left ear pieces. Or use an oscillos-
cope to measure the signal amplitudes on J25 left and right channels:

Right (yellow) and left (blue) stereo audio signal at headphone connector J25

34. Open a Watch Window and modify the values for variables “fsin” and “volume” to
change the signal on the headphones:

Note: If you use “real-time debug mode”, which we already used in previous chap-
ters, you can change the variables whilst the code is running!

13 - 44 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_2: Dual audio tone

Lab Exercise 13_2: Dual audio tone


Objective
In Lab13_1, we generated a single frequency on both audio channels. Now we will generate
two different frequencies for the left and right channels. Recall that we initialized the
AIC23B in dual phase operating mode. In this mode each frame sync signal (MFSXA) starts
the transmission of two 32 Bit words from McBSP to the AIC23B. The first 32-bit word
(phase 1) is the new data for the left channel and the 2nd 32-bit word (phase 2) is for the right
channel.

In Lab13_1 we loaded the 32 - bit register-pair DX2/DX1 only once. As a result, the McBSP
transmitted the same word twice, for the left and right channels. For the new lab, we have to
load a 2nd 32-bit number into DX2/DX1, after the first one has been transmitted to drive the
two channels with different signals.

Procedure

Open Project, Modify Source File


1. If not still open from Lab13_1, re-open project Lab13.pjt in C:\DSP2833x_V4\Labs.
2. Open the file “Lab13_1.c” and save it as “Lab13_2.c”
3. Exclude file “Lab13_1.c” from build. Use a right mouse click at file “Lab13_1.c”, and
enable “Exclude File(s) from Build”.
4. In “Lab13_2.c”, replace the variable “fsin” by two new global variables:
unsigned int fsine_left= 110; // left audio frequency in Hertz
unsigned int fsine_right = 220; //right audio frequency in Hertz
Next, we have to change the interrupt service routine “McBSP_A_TX_isr()”. The calculation
for the next amplitude must now be performed independently for the left and right signals.
5. In the function “McBSP_A_TX_isr()” double the local variables, one set for left and one
set for the right channel:
static unsigned int left_linear_idx=0, right_linear_idx;
unsigned int left_lut_idx,right_lut_idx;
long left_amplitude,right_amplitude;
6. Using the new set for the “left”- variables, change the code sequence to calculate
“amplitude” into a sequence to calculate “left_amplitude”.
7. Add a similar calculation for value “right_amplitude”.
8. Load registers DX2 and DX1 with the upper and lower halves of the variable
“left_amplitude”.
9. Add a waiting loop to wait until the first 32 - bit value has been copied into the McBSP -
shift Register XSR2/XSR1. The status flag “XRDY” is set in such a case:

F2833x - Multichannel Buffered Serial Port 13 - 45


Lab Exercise 13_2: Dual audio tone

while(McbspaRegs.SPCR2.bit.XRDY == 0);
Note: The line above is a wait construction, which should never be used in an interrupt
service routine of a real project. The two basic rules of coding ISRs are (1) keep ISRs
as short as possible and (2) never include wait loops, because they can stall the whole
project. However, since we are learning students, we are allowed to do everything
(unless your teacher intervenes…). In “Lab3_3” we will improve the code in a way
that we can avoid the wait - construction from above!
10. After the wait - construction, add two more load instructions for registers DX2 and DX1,
now for value “right_amplitude”.
11. Change the code to increment and limit variable “linear_idx” into “left_linear_idx”.
12. Add similar instructions as in step 11 for the variable “right_linear_idx”.

Build, Load and Run


13. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

14. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

15. Verify that in the debug perspective the window of the source code “Lab13_2.c” is
high-lighted and that the blue arrow for the current Program Counter position is placed
under the line “void main(void)”.

16. Perform a real time run.

Target  Run

17. Connect headphones to J25 (Headphone - Out) of the Peripheral Explorer Board. A
signal of 220 Hz should be audible on the right channel and a signal of 110 Hz on the
left channel. Or, use an oscilloscope to measure the signal amplitudes on J25 left and
right channels:

13 - 46 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_2: Dual audio tone

Right Channel (yellow) and Left Audio Channel (blue)

18. Using a Watch Window change the signals “fsine_left” and “fsine_right” of the head-
phone:

Note: If you use “real-time debug mode”, which we used in previous chapters, you
can change the variables whilst the code is running!

F2833x - Multichannel Buffered Serial Port 13 - 47


Lab 13_3: Dual audio tone and XRDY - Interrupt

Lab 13_3: Dual audio tone and XRDY - Interrupt


Objective
In Lab13_2 we used an interrupt service routine with a wait construction in it. For a real pro-
ject such a technique is unacceptable. Therefore we have to improve our AIC23B Lab now!

The solution is based on using a different interrupt source. Labs13_2 was based on frame
sync - interrupts, which were caused by the AIC23B at 44.1 kHz. In response, we had to load
two pairs of values into registers DX2/DX1. But before we could load the 2nd pair, we had to
wait, because there is only one register pair DX2/DX1. This was the reason for the unfortu-
nate wait-loop in Lab13_2.

For Lab13_3 we will use the XRDY - signal to request an interrupt service. This interrupt is
triggered each time a 32 - bit word is loaded from DX2/DX1 into the McBSP-internal shift
registers XSR2/XSR1. The idea for the new lab is this:

Left Right Left Right

In the middle of the left transmission we get the 1st XRDY - interrupt. We use this ISR to
load the right channel data into DX2/DX1. Similar, in the middle of the right transmission,
we get the 2nd XRDY - interrupt. We use this ISR to load the next left channel data into
DX2/DX1 - in preparation of the next transmission, which will be started by the next exter-
nal frame - sync - signal (MFSXA).

Summary: We will use an alternating technique in the interrupt service for XRDY. Every
odd interrupt will load the next left value, every odd interrupt the next right value.

Procedure

Open Project, Modify Source File

1. If not still open from Lab13_2, re-open project Lab13.pjt in C:\DSP2833x_V4\Labs.


2. Open the file “Lab13_2.c” and save it as “Lab13_3.c”
3. Exclude file “Lab13_2.c” from build. Use a right mouse click at file “Lab13_2.c”, and
enable “Exclude File(s) from Build”.
4. In the function “McBSPA_Init()”, change the initialization for the register “SPRC2”,
to now request a transmit interrupt service on event “XRDY” (hint: change bit
“XINTM”).

13 - 48 F2833x - Multichannel Buffered Serial Port


Lab 13_3: Dual audio tone and XRDY - Interrupt

5. Change interrupt service function “McBSP_A_TX_isr()”


• Add a new local variable “even”. We will use this variable as a switch to
alternately execute the reload code for phase 1 (left channel) or phase 2 (right
channel):

static unsigned int even = 0; //switch reload phase1 / phase2


• Next, add an if-statement and include all instructions that are related to the
“left”-variables into the “TRUE” - block and all “right”-variables into the
“FALSE” - block:
if (even == 0)
{
// Calculation for amplitude left channel
// load left_amplitude to DX2/DX1
// increment and limit left_linear_idx
// even = 1
}
else
{
// Calculation for amplitude right channel
// load right_amplitude to DX2/DX1
// increment and limit right_linear_idx
// even = 0
}

6. The McBSP - Transmit - Interrupt is now based on XRDY. This signal is generated
after a word has been loaded from DX2/DX1 into XSR2/XSR1. To get the first
interrupt, we have to force a load into DX2/DX1. In main, just before we enter the
endless while(1) loop, add the two following lines:

McbspaRegs.DXR2.all = 0;
McbspaRegs.DXR1.all = 0;
This code will force a first XRDY - interrupt.

Build, Load and Run


7. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

8. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

9. Verify that in the debug perspective the window of the source code “Lab13_3.c” is
high-lighted and that the blue arrow for the current Program Counter position is placed
under the line “void main(void)”.

F2833x - Multichannel Buffered Serial Port 13 - 49


Lab 13_3: Dual audio tone and XRDY - Interrupt

10. Perform a real time run.

Target  Run

11. Connect headphones to J25 (Headphone - Out) of the Peripheral Explorer Board. A
signal of 220 Hz should be audible on the right channel and a signal of 110 Hz on the
left channel. Or, use an oscilloscope to measure the signal amplitudes on J25 left and
right channel:

Right Channel (yellow) and Left Audio Channel (blue)

12. Using a Watch Window change the signals “fsine_left” and “fsine_right” of the head-
phones:

Note: If you use “real-time debug mode”, which we used in previous chapters, you
can change the variables whilst the code is running!

13 - 50 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_4: EEPROM via McBSP

Lab Exercise 13_4: EEPROM via McBSP


Objective
The Peripheral Explorer Board is equipped with a serial SPI - EEPROM (CSI25C256K or
AT25256). This lab exercise will write and read into this memory.

Write:
We will use the Peripheral Explores Boards push-button PB1 (GPIO17) to start a write to the
EEPROM. The data to be written into the EEPROM is the current position of the 4 - bit
hexadecimal digital input encoder (GPIO12...15). Only bits 3...0 of the EEPROM memory
address will be used.

Read:
We will use push-button PB2 (GPIO48) to read the EEPROM. From the 8 bit data only bits
2...0 will be displayed on LEDs LD4 (GPIO49), LD3 (GPIO34), and LD1 (GPIO9). Note:
LED LD2 (GPIO11) cannot be used for this exercise, because the Peripheral Explorer Board
uses this output line to control the “chip-select” signal (/CS) of the EEPROM.

EEPROM AT25256 Exercise:


Lab13_4:
• Initialize McBSP-B in SPI-Mode for AT25256
• Write data to EEPROM, if button PB1 (GPIO17) is
pushed. Read the current value from Hex-Encoder
(GPIO12…15) and store it into EEPROM-address
0x0040, bits 3…0.
• Read data from EEPROM-address 0x0040, when button
PB2 (GPIO48) is pushed and display bits 2…0 at LEDs
LD4 (GPOI49), LD3 (GPIO34) and LD1 (GPIO9).

13 - 39

F2833x - Multichannel Buffered Serial Port 13 - 51


Lab Exercise 13_4: EEPROM via McBSP

Hardware Description:
The SPI - Interface of this device is connected to the F28335 - McBSP - channel B. The fol-
lowing schematic gives the hardware - details:

Peripheral Explorer Board EEPROM Circuitry

• Input pin “/CS” connected to GPIO11, which could be initialized as Signal “SPI-Slave
Transmit Enable (SPISTE)”. However, since we will use McBSP-B in a SPI operating -
mode, we are not able to generate “SPISTE” from this interface. Therefore we will use
GPIO11 as digital output line controlled by software.

• Output pin “Slave Out (SO)” is connected to GPIO25, which can be initialized as
McBSP-signal “MDRB”. In SPI - mode, this pin will operate as “Slave Out Master In”
signal.

• Input pin “Slave Clock (SCLK)” is connected to GPIO26, which can be initialized as
McBSP-signal “MCLKB”. In SPI - mode this pin will operate as “SPI - clock” signal.

• Input pin “Slave In (SIN)” is connected to GPIO24, which will be initialized as McBSP-
signal “MDXB”. In SPI-mode, this pin will feature the “Master Out Slave In” data sig-
nal.

13 - 52 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_4: EEPROM via McBSP

Timing Diagram
The AT25256 has the following timing requirements:

EEPROM AT25256
Timing Diagram:

13 - 40

Source: http://www.atmel.com document “doc0872.pdf”

An access cycle is enclosed within an active /CS - signal. At the beginning, we will need to
set /CS low and when we have transmitted the frame, we need to de-activate /CS by making
it high again.

To write data into the EEPROM, the F2833x has to generate the data bit first; with a clock
delay of ½ cycles, the rising edge is the strobe pulse for the EEPROM to store the data.

When reading the EEPROM, the falling clock edge causes the EEPROM to send out data
and the rising clock edge the F2833x can read the valid data bit.

F2833x - Multichannel Buffered Serial Port 13 - 53


Lab Exercise 13_4: EEPROM via McBSP

AT25256 Status Register


The AT25256 internal Status Register controls write accesses to the internal memory.

EEPROM AT25256
Access Status Register:

7 6 5 4 3 2 1 0
WPEN 0 0 0 BP1 BP0 WEN /RDY

Block protect select Write in progress


00 = no protection
0 = no write cycle
01 = 0x6000 – 0x7FFF protected 1 = write in progress
10 = 0x4000 – 0x7FFF protected
11 = 0x0000 – 0x7FFF protected

Write Enable Latch


Write Protect Enable 0 = write disabled
1 = no write access 1 = write enabled
0 = normal operation
13 - 41

It also flags the current status of the EEPROM:


Bit 0 (“/RDY’) flags whether an internal write cycle is in progress or not. Internal write
cycles are started at the end of a command sequence and last quite long (maximum 10ms).
To avoid the interruption of a write cycle in progress any other write access should be
delayed as long as /RDY=1.
Bit 1(“Write Enable Latch”) is a control bit that must be set to 1 for every write access to
the EEPROM. After a successful write cycle this bit is cleared by the EEPROM.
Bits 3 and 2(“Block Protect Select”) are used to define the area of memory that should be
protected against any write access. We will not use any protection in our lab, so just set the
two bits to ‘00’.
Bit 7 (“Write Protect Enable”) allows us to disable any write access into the Status
Register. For our Lab we will leave this bit cleared all the time (normal operation).

13 - 54 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_4: EEPROM via McBSP

Instruction Register
The AT25128/256 utilizes an 8-bit instruction register. The list of instructions and their op-
eration codes are contained in the next slide. All instructions, addresses and data are trans-
ferred with the MSB first and start with a high-to-low CS transition.

EEPROM AT25256
Instruction Register:

Instruction Description Code


WREN Write Enable 0000 0110

WRDI Write Disable 0000 0100

RDSR Read Status 0000 0101


Register
WDSR Write Status 0000 0001
Register
READ Read Data 0000 0011

WRITE Write Data 0000 0010

13 - 42

Before we can start our Lab procedure, we need to discuss these instructions in little more
detail.

The “Write Enable (WREN)” command must be applied to the EEPROM to open
the Write Enable Latch (WEN) prior to each WRITE and WDSR instruction. The command
is an 8-clock SPI- sequence, as shown on the next slide (Slide 13-43):

F2833x - Multichannel Buffered Serial Port 13 - 55


Lab Exercise 13_4: EEPROM via McBSP

EEPROM AT25256
Write – Enable (WREN) Timing:

© Atmel Corporation; Datasheet AT25256 (doc0872.pdf) – 2005; Page 10

13 - 43

The “RDSR” instruction allows the Status Register to be read. The Status Register may be
read any time. It is recommended to use this instruction to check the “Write In Progress”
(/RDY) bit before sending a new instruction to the EEPROM. This is also possible to read
the Status Register continuously.

EEPROM AT25256
Read Status Register (RDSR) Timing:

© Atmel Corporation; Datasheet AT25256 (doc0872.pdf) – 2005; Page 10

13 - 44

13 - 56 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_4: EEPROM via McBSP

The “READ” instruction is used to read data out of the EEPROM. The address range of
the AT25256 is from 0 to 0x7FFF. After the first 8 - bit (instruction code), the address is
transmitted as a 16 - bit address. As shown in Slide 13-45, the cycle is finished with the de-
activation of the /CS signal (high). However, if /CS stays active (low) and the master applies
another 8 clock pulses, an internal address counter is incremented with each READ
instruction.

EEPROM AT25256
Read (READ) Timing:

© Atmel Corporation; Datasheet AT25256 (doc0872.pdf) – 2005; Page 11

13 - 45

EEPROM AT25256
Write (WRITE) Timing:

© Atmel Corporation; Datasheet AT25256 (doc0872.pdf) – 2005; Page 11

13 - 46

F2833x - Multichannel Buffered Serial Port 13 - 57


Lab Exercise 13_4: EEPROM via McBSP

The “WRITE” instruction is used to write data into the EEPROM. The instruction is
terminated by a rising edge at signal chip select (/CS) high. At this point the internal self -
timed write cycle actually starts, at the end of which the “Write In Progress”(/RDY) bit of
the Status Register is reset to 0.

Procedure

Open Project, Modify Source File

1. If not still open from Lab13_3, re-open the project Lab13.pjt in C:\DSP2833x\Labs.
2. Open the file “Lab13_1.c” and save it as “Lab13_4.c”
3. Remove the file “Lab13_3.c” from the project and add “Lab13_4.c” to it. Note:
optionally you can also keep “Lab13_3.c” in the project, but exclude it from build.
Use a right mouse click on file “Lab13_3.c”, select “File Specific Options”; in
category “General” enable “Exclude from Build”.
4. At the beginning of file “Lab13_4.c” we can simplify our coding by adding some
useful macros:
#define WRITE_BUTTON GpioDataRegs.GPADAT.bit.GPIO17 // PB1
#define READ_BUTTON GpioDataRegs.GPBDAT.bit.GPIO48 // PB2
#define CS_EEPROM GpioDataRegs.GPADAT.bit.GPIO11 //CS - EEPROM
// Instruction Register Definitions for EEPROM
#define WREN 0x06 // Write Enable
#define WRDI 0x04 // Write Disable
#define RDSR 0x05 // Read Status Register
#define WRSR 0x01 // Write Status Register
#define READ 0x03 // Read Command
#define WRITE 0x02 // Write Command

5. Remove all lines (Prototypes, Function calls and Function definitions) for functions
“AIC23_init()” , “McBSP_A_TX_isr()” and “SPIA_Init()”. We do not need these
functions in this lab. Also remove the global variables “volume”, fsin” and
“sine_table”, including the DATA_SECTION statement for “sine_table”.
6. Next, change the interrupt enable lines. For the IER register, enable the INT1 line
only. Remove the PIE - interrupt enable line for McBSP-A (register PIEIER6). The
only active interrupt in lab 13_4 is the CPU - Timer 0 interrupt service.
7. Inspect and change function “Gpio_select()”. Delete the setup for GPIO16, 18, 19, 20,
21, 22, 23, 58 and 59 as SPI-A or McBSP-A signals. Instead, initialize GPIO24, 25
and 26 to their McBSP-B - function. Set the direction of GPIO9 (LD1), GPIO11 (/CS-
EEPROM), GPIO34 (LD3) and GPIO49 (LD4) to output. Make sure, that lines
GPIO17 and GPIO48 are initialized as inputs, because they are used as push-button
lines. Finally in register GPADAT, set the data level for GPIO11 to 1, because this is
the passive level for the chip select line (/CS) of the EEPROM.

13 - 58 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_4: EEPROM via McBSP

8. Rename the function “McBSPA_Init()” to “McBSPB_Init()” and change the code of


this function. The best way is to remove all old lines and code new lines. Please keep
the “EALLOW” - statement at the beginning and the “EDIS” - statement at the end of
the function code:
• Register SPCR1:
• Enable clock-stop mode (CLKSTP) with ½ cycle clock delay
• Enable receiver (RRST)
• Register SPRC2:
• Set Free-Run (FREE) in a break event
• Enable transmitter (XRST)
• Enable sample rate generator (GRST)
• Release frame logic from reset (FRST)
• Register PCR:
• Valid transmit data on rising edge of clock (CLKXP)
• Receive data sampled on rising edge of clock (CLKRP)
• McBSP is master in SPI (CLKXM)
• McBSP-clock derived from LSPCLK (SCLKME)
• Transmit frame sync generated internally (FSXM)
• Transmit frame sync pulses are active low(FSXP)
• Register SRGR1:

• Set CLKG frequency to 1 MBit/s. (CLKGDV)


• Register SRGR2:
• Select LSPCLK as input clock source (CLKSM)
• Generate frame sync when DXR is copied into XSR (FSGM)
• Register XCR1:
• Select 1 word per frame (XFRLEN1)
• Select 8 bit per word (XWDLEN1)
• Register XCR2:
• Select Single Phase Transmit (XPHASE)
• No Data delay between sync and first data bit (XDATDLY)
• Register RCR1:
• Select 1 word per frame (RFRLEN1)
• Select 8 bit per word (RWDLEN1)
• Register RCR2:
• Select Single Phase Receive (RPHASE)
• No Data delay between sync and first data bit (RDATDLY)

F2833x - Multichannel Buffered Serial Port 13 - 59


Lab Exercise 13_4: EEPROM via McBSP

Next we have to prepare some access functions to the EEPROM. Recall that the access to
this device is controlled by a sequence of serial commands (see Slide 13-42).
10. Write a function “McBSP_B_EEPROM_Read_Status()”. As the name indicates,
we will use this function to read the current value from the EEPROM status register
(see Slide 13-41). The bit “/RDY” is important. If a previous command has not
completed (/RDY =1), we cannot apply another one to the EEPROM. Here is the
required function code:

int McBSP_B_EEPROM_Read_Status(void)
{
unsigned int k;
CS_EEPROM = 0; // activate /CS of EEPROM
McbspbRegs.DXR1.all = RDSR; // read status register command
while (McbspbRegs.SPCR1.bit.RRDY == 0); // wait for end of SPI - cycle
k=McbspbRegs.DRR1.all; // dummy read to release receiver

McbspbRegs.DXR1.all = 0; // dummy data to drive 8 more SPICLK


while (McbspbRegs.SPCR1.bit.RRDY == 0); // wait for end of SPI - cycle
k=McbspbRegs.DRR1.all; // read status , LSB is WIP
CS_EEPROM = 1; // deactivate /CS of EEPROM
return (k);
}

Add a function prototype at the beginning of “Lab13_4.c”.


Note: in this function and in all other functions of this lab we apply “while”-loops to
wait until a certain condition becomes true. This is a first and simple approach to
communicate with the device. However, there is a big problem with such a technique,
since the program will stall, if the condition never becomes true. So please do not use
such a technique in a real application! Instead, use timeout wait - loops or interrupt
service routines in such events. If you have spare laboratory time, you can try to
improve your project in such a way, after you have a first running example.
11. Write a new function “McBSP_B_EEPROM_Write_Enable()”. Later we will use
this function to enable a write instruction into the EEPROM. Such a preceding step is
necessary for all write accesses. Add:
void McBSP_B_EEPROM_Write_Enable(void)
{
volatile int dummy;
CS_EEPROM = 0; // activate /CS of EEPROM
McbspbRegs.DXR1.all = WREN; // write enable command
while (McbspbRegs.SPCR1.bit.RRDY == 0); // wait for end of cycle
dummy = McbspbRegs.DRR1.all; // dummy read to clear RX
CS_EEPROM = 1; // deactivate /CS of EEPROM
}

Also add a function prototype for this function at the beginning of “Lab13_4.c”.

13 - 60 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_4: EEPROM via McBSP

12. Write a new function “McBSP_B_EEPROM_Write()”. This will be the function to


write a new 8-bit pattern into an EEPROM-address. Add:
void McBSP_B_EEPROM_Write(int address,int data)
{
volatile int dummy;
CS_EEPROM = 0; // activate /CS of EEPROM
McbspbRegs.DXR1.all = WRITE; // send write code
while (McbspbRegs.SPCR2.bit.XRDY == 0); // wait for end of cycle
McbspbRegs.DXR1.all = (address>>8); // write upper address byte
while (McbspbRegs.SPCR2.bit.XRDY == 0); // wait for end of cycle
McbspbRegs.DXR1.all = address; // write lower address byte
while (McbspbRegs.SPCR2.bit.XRDY == 0); // wait for end of cycle
McbspbRegs.DXR1.all = data; // send data
while (McbspbRegs.SPCR2.bit.XRDY == 0); // wait for end of cycle
dummy = McbspbRegs.DRR1.all; // dummy read to clear receiver
while (McbspbRegs.SPCR1.bit.RRDY == 0);
dummy = McbspbRegs.DRR1.all;
CS_EEPROM = 1; // deactivate /CS of EEPROM
}

Add a function prototype at the beginning of “Lab13_4.c”.


13. Write a new function “McBSP_B_EEPROM_Read()”. This will be the function to
read an 8 - bit data from an EEPROM - address. Add:
int McBSP_B_EEPROM_Read(int address)
{
int data;
CS_EEPROM = 0; // activate /CS of EEPROM
McbspbRegs.DXR1.all = READ; // Read op-code
while (McbspbRegs.SPCR2.bit.XRDY == 0);
McbspbRegs.DXR1.all = address>>8; // upper byte of read address
while (McbspbRegs.SPCR2.bit.XRDY == 0);
McbspbRegs.DXR1.all = address; // lower byte of read address
while (McbspbRegs.SPCR2.bit.XRDY == 0);
McbspbRegs.DXR1.all = 0x00; // send dummy data
while (McbspbRegs.SPCR2.bit.XRDY == 0);
data = McbspbRegs.DRR1.all; // Clear receive flag
while (McbspbRegs.SPCR1.bit.RRDY == 0);
data = McbspbRegs.DRR1.all; // Read data from memory
CS_EEPROM = 1; // deactivate /CS of EEPROM
return(data);
}

Add a function prototype at the beginning of “Lab13_4.c”.


Now we are ready to add function calls to write into or to read from the EEPROM into
our main-loop.
14. In the function “main()” just before we enter the endless while(1)-loop, add code to
check if bit “/RDY” of the EEPROM status - register is zero. Use the function
“McBSP_B_EEPROM_Read_Status()” to read the current status byte. Continue into
the while(1)-loop only if “/RDY” is zero. If it is not zero, repeat the status check.

F2833x - Multichannel Buffered Serial Port 13 - 61


Lab Exercise 13_4: EEPROM via McBSP

15. In the endless while(1)-loop of “main()”, just after the 100 milliseconds wait
construction based on CPU-Timer 0 and the service - instructions for the watchdog,
add new code to write or to read the EEPROM.

Write into EEPROM - Address 0x0040:


Recall, that we would like to execute a write access at address 0x0040, if button PB1
(GPIO17) is pushed (this line is zero, if the button is pressed down). If this is true:

• Call function “McBSP_B_EEPROM_Write_Enable()”.

• Wait until EEPROM status bit “WEN” = 1. Use function


“McBSP_B_EEPROM_Read_Status” to get the latest status.

• Call function “McBSP_B_EEPROM_Write()” to write data to the EEPROM.


The first parameter is the internal EEPROM - Address (for example 0x0040), the
second parameter is the data. For data we will use the current value of the Hex-
Encoder device (GPIO15…GPIO12), which inputs a value between 0 and 15.

• Wait until EEPROM status - bit “/RDY” is zero. Use the function
“McBSP_B_EEPROM_Read_Status()” to get the latest status.

• Note: At the end of this sequence you should also add some code lines to make
sure that the second execution of a write sequence is only possible, after button
PB1 has been released. Since the watchdog is active, you cannot simply put a
wait-loop here!

Read from EEPROM - Address 0x0040:


Finally we have to add some code to read EEPROM - address 0x0040, if button PB2
(GPIO48) has been pushed (this line is zero, if the button is pressed down). If this is
true:

• Call the function “McBSP_B_EEPROM_Read()” and store the return value in a


new local unsigned integer variable “data_read”.

• Copy bit 2 of “data_read” to LED LD4 (GPIO49), bit 1 to LED LD3(GPIO34)


and bit 0 of “data_read” to LED LD1 (GPIO9).

Build, Load and Run


16. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

17. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

13 - 62 F2833x - Multichannel Buffered Serial Port


Lab Exercise 13_4: EEPROM via McBSP

18. Verify that in the debug perspective the window of the source code “Lab13_3.c” is
high-lighted and that the blue arrow for the current Program Counter position is placed
under the line “void main(void)”.

19. Perform a real time run.

Scripts  Realtime Emulation Control  Run_Realtime_with_Restart


20. Turn the 4-Bit Hex-Encoder to a known state. Hint: Use a Watch window and monitor
GPIO15…GPIO12.

21. Now press button PB1. The Encoder value is written into EEPROM - Address 0x0040.
22. Now press button PB2. The bits 2…0 of the returned value from EEPROM address
0x0040 should be displayed at LEDs LD4, LD3 and LD1. It should correspond to the
status of GPIO12, GPIO13 and GPIO14 which was written into the EEPROM by the
last write command.
23. Stop the Realtime Run:
Scripts  Realtime Emulation Control  Full Halt
24. Close Code Composer Studio and switch off the Peripheral Explorer Board. After a
few seconds re-power the board and start Code Composer Studio. Download the
project into the DSP, run it and push the read button PB2 first. Now the LEDs LD4,
LD3 and LD1 should display the last value that has been stored in EEPROM-address
0x0040 before the power has been switched off. (An EEPROM is non - volatile
memory that retains the information when power supply has been switched off).

END of Lab-Exercise 13_4

F2833x - Multichannel Buffered Serial Port 13 - 63


Optional Exercise (EEPROM and SCI):

Optional Exercise (EEPROM and SCI):


If your Laboratory time permits, you can try to combine Lab13_4 (EEPROM) with one of
the exercises from chapter 9 (SCI - module). The task is to store a whole message, which is
transmitted by a host to the F2833x via RS232. If PB2 is pushed, the message, which is
stored inside the F2833x, must be sent back to the host.

13 - 64 F2833x - Multichannel Buffered Serial Port


F2833x Flash Programming

Introduction
So far we have used the internal volatile memory (L1 - SARAM) of thee F2833x to store the
code for our examples. Before we could execute the code we used Code Composer Studio to
load it into L1 - SARAM (“File”  “Load Program”). This is fine for projects in a
development and debug phase where there are frequent changes to parts and components of
the software. However, when it comes to production versions with a standalone embedded
control unit based on the F2833x, we no longer have the option to download our control code
using Code Composer Studio. Imagine a control unit for an automotive braking system,
where you have to download the control code first when you hit the brake pedal (“Do you
really want to brake? ...”).
For standalone embedded control applications, we need to store our control code in NON-
Volatile memory. This way it will be available immediately after system power-up. The
question is: what type of non-volatile memory is available? There are several physically
different memories of this type: Read Only Memory (ROM), Electrically Programmable
Read Only Memory (EPROM), Electrically Programmable and Erasable Read Only Memory
(EEPROM) and Flash-Memory. In the case of the F28335, we can add any of the above
types of memory to the control unit using the external interface (XINTF).
The F2833x is also equipped with an internal Flash memory of 256K x 16 bits. This is quite
a large amount of memory and more than sufficient for our lab exercises!
Before we can go to modify one of our existing lab solutions to start up out of Flash
memory, we have to go through a short explanation of how to use this memory. This module
also covers the boot sequence of the F2833x - what happens when we power on the F2833x?
This chapter also covers the password feature of the F2833x code security module. This
module is used to embed dedicated portions of the F2833x memory in a secure section with a
128 bit-password. If the user does not know the correct combination that was programmed
into the password section, any access to the secured areas will be denied! This is a security
measure to prevent reverse-engineering.
At the end of this lesson we will do a lab exercise to load one of our existing solutions into
the internal Flash memory.

CAUTION: Please do not upset your teacher by programming the password area! Be
careful, if you program the password by accident the device will be locked forever! If you
decide to make your mark at your university by locking the device with your own password,
be sure to have passed all your exams first.

F2833x - Flash Programming 14 - 1


Module Topics

Module Topics
F2833x Flash Programming............................................................................................................ 14-1
Introduction ................................................................................................................................... 14-1
Module Topics ............................................................................................................................... 14-2
F2833x Start-up Sequences ........................................................................................................... 14-3
F2833x Flash Memory Sectors...................................................................................................... 14-5
Flash Speed Initialization.............................................................................................................. 14-5
Flash Configuration Registers ...................................................................................................... 14-8
Flash Programming Procedure..................................................................................................... 14-9
CCS Flash Plug-In ...................................................................................................................... 14-11
Code Security Mode .................................................................................................................... 14-12
Lab Exercise 14: Standalone Project ......................................................................................... 14-16
Objective ................................................................................................................................. 14-16
Procedure ................................................................................................................................ 14-17
Open Files, Create Project File ............................................................................................... 14-17
Project Build Options .............................................................................................................. 14-18
Add Additional Source Code Files ......................................................................................... 14-18
Modify Source Code to Speed up Flash memory ................................................................... 14-18
Build project ........................................................................................................................... 14-19
Verify Linker Results: The “.map” - File................................................................................ 14-20
Use CCS integrated Flash Programming ................................................................................ 14-20
Shut down CCS and Restart FLASH - Code .......................................................................... 14-21

14 - 2 F2833x - Flash Programming


F2833x Start-up Sequences

F2833x Start-up Sequences


There are 16 different options to start the F2833x out of power- on. The options are hard-
coded by 4 GPIO-Inputs (GPIO 87, 86, 85 and 84). The 4 pins are sampled during power-on.
Depending on their status, one of the following options is selected:

GPIO87 GPIO86 GPIO85 GPIO84 Mode

1 1 1 1 Jump to Flash 0x33FFF6

1 1 1 0 SCI-A Boot loader

1 1 0 1 SPI-A Boot loader

1 1 0 0 I2C-A Boot loader

1 0 1 1 eCAN-A Boot loader

1 0 1 0 McBSP-A Boot loader

1 0 0 1 Jump to XINTF x16

1 0 0 0 Jump to XINTF x32

0 1 1 1 Jump to OTP

0 1 1 0 Parallel GPIO – Boot loader

0 1 0 1 Parallel XINTF – Boot loader

0 1 0 0 Jump to SARAM 0x000000

0 0 1 1 Jump “to check boot mode”

0 0 1 0 Jump to Flash, without ADC –


calibration

0 0 0 1 Jump to SARAM, without ADC –


calibration

0 0 0 0 SCI – A boot loader, without ADC -


calibration

On the F28335ControlCard, the four GPIOs are pulled high by resistors R3, R4, R5 and R14
(47 kOhm each) to code “1111” (FLASH). The Peripheral Explorer Board offers only one
other selection for the boot mode: a closed header J3 allows to pull-down GPIO84 to select

F2833x - Flash Programming 14 - 3


F2833x Start-up Sequences

“1110” (SCI-A Boot loader). The following slide shows the sequence that takes place when
we start from Flash.

Startup Sequence from Flash Memory

0x30 0000 _c_int00 “rts2800_ml.lib”


FLASH (256Kw)

0x33 FFF6 LB
5
_c_int00 “user” code sections
Passwords (8w) main ( )
{
……
3 ……
……
0x3F F000 Boot ROM (8Kw) }
Boot Code
0x3F F9CE
{SCAN GPIO}
2
BROM vector (32w)
0x3F FFC0 0x3F F9CE
1

RESET 14 - 2

1. RESET-address is always defined in address 0x3F FFC0. This is part of TI’s internal
BOOT-ROM. This address is loaded into the program counter (PC).
2. The BOOT-ROM code performs a basic initialization of the CPU and selects the
boot-code sequence or calculates the entry point address.
3. If GPIO pins 87 to 84 are pulled high “1111” and a jump to address 0x33 FFF6 is
performed. This address is called “the Flash entry point”, which is an empty 2-word
memory space. One of our tasks in preparation to use the Flash is to add a jump
instruction to this two-word space. If we use a project based on the C language, we
have to jump to the C start-up function “c_int00”, which is part of the runtime
library “rts2800_ml.lib”.

CAUTION: Do never exceed the two word memory space for this step.
Addresses 0x33 FFF8 to 0x33 FFFF are reserved for the password area!!
4. Function “c_int00” performs initialization routines for the C-environment and global
variables. For this module, we will have to place this function into a specific Flash
section.
5. At the very end, “c_int00” branches to our C-function called “main()”, which also
must be loaded into a flash section.

14 - 4 F2833x - Flash Programming


F2833x Flash Memory Sectors

F2833x Flash Memory Sectors


TMS320F28335 Flash Memory Map
Address Range Data & Program Space
0x30 0000 – 0x30 7FFF Sector H; 32K x 16
0x30 8000 – 0x30 FFFF Sector G; 32K x 16
0x31 0000 – 0x31 7FFF Sector F; 32K x 16
0x31 8000 – 0x31 FFFF Sector E; 32K x 16
0x32 0000 – 0x32 7FFF Sector D; 32K x 16
0x32 8000 – 0x32 FFFF Sector C; 32K x 16
0x33 0000 – 0x33 7FFF Sector B; 32K x 16
0x33 8000 – 0x33 FF7F Sector A; (32K-128) x 16
0x33 FF80 – 0x33 FFF5 Program to 0x0000 when using
Code Security Mode !
0x33 FFF6 – 0x33 FFF7 Flash Entry Point; 2 x 16
0x33 FFF8 – 0x33 FFFF Security Password; 8 x 16

14 - 3

The 256k x 16 bit Flash is divided into 8 groups called “sectors”. Each sector can be
programmed independently from the others. Please note that the highest 128 addresses of
sector A (0x33FF80 to 0x33 FFFF) are not available for general purpose. Lab 14 will use
sections A and D.

Flash Speed Initialization


To derive the highest possible speed for the execution of our code we have to initialize the
number of wait states that are added when the Flash area is accessed. When we start the
F2833x out of RESET, the number of wait states defaults to 16. Wait states are additional
clock cycles, that extend the FLASH - access period. For our tiny lab exercises, this
extension is of no significance, but when you work on a real-world project, where computing
power is so important, it would be a shame not to make best use of these wait states. So let us
assume that our lab examples are ‘real’ projects and that we want to use the maximum
frequency for the Flash. But why do we not initialize the wait states down to zero? Well, the
number of wait states is related to the operational speed of the FLASH memory. According
to the data-sheet of the F2833x there is a limit for the minimum number of wait states. For
the current silicon revision of the F2833x this limit is set to 5 for a 150MHz device.

F2833x - Flash Programming 14 - 5


Flash Speed Initialization

Basic Flash Operation


 Flash is arranged in pages of 128 addresses
 Wait states are specified for consecutive accesses within a page,
and random accesses across pages
 OTP has random access only
 Must specify the number of SYSCLKOUT wait-states
 Reset defaults are maximum values!
 Flash configuration code must not run from Flash memory!
15 12 11 8 7 4 3 0
FBANKWAIT
@ 0x00 0A86 reserved PAGEWAIT reserved RANDWAIT

FOTPWAIT 15 4 3 0

@ 0x00 0A87 reserved OTPWAIT

*** Refer to the F2833x datasheet for detailed numbers ***


For 150 MHz, PAGEWAIT = 5, RANDWAIT = 5, OTPWAIT = 8
For 100 MHz, PAGEWAIT = 3, RANDWAIT = 3, OTPWAIT = 5
14 - 4

There are two bit-fields in the “FBANKWAIT” register that are used to specify the number
of wait states – PAGEWAIT and RANDWAIT. Consecutive page accesses are performed
within an area of 128 addresses whereas a sequence of random accesses is performed in any
order of addresses. So how fast is the F2833x running out of Flash or, in computer language:
How many millions of instructions (MIPS) is the F2833x doing?
Answer:
The F2833x executes one instruction (a 16-bit word) in 1 cycle. Adding the 5 wait states we
end up with:
1 instruction / 6 cycles * 150MHz = 25 MHz.
For a one-cycle instruction machine like the F2833x, the 25 MHz translate into 25MIPS.
This is pretty slow compared to the original system frequency of 150 MHz! Is this all we can
expect from Texas Instruments? No! The hardware solution is called a “pipeline”, which is
shown in next slide!
Instead of reading only one 16-bit instruction from Flash code memory, Texas Instruments
has implemented a 64-bit access – reading up to 4 instructions in 1+5 cycles. This leads to
the final estimation of the speed of the internal Flash:
4 instructions / 6 cycles * 150 MHz = 100 MHz.

Using the Flash code Pipeline, the real Flash speed is 100 MIPS!
To use the Flash pipelining code fetch method we have to set bit “ENPIPE” to 1 to enable
pipeline operations. By default after RESET, this feature is disabled.

14 - 6 F2833x - Flash Programming


Flash Speed Initialization

Speeding Up Code Execution in Flash:


Flash Pipelining (for code fetch only)

16

16 or 32
64 dispatched
64 F2833x Core
decoder unit
Aligned 2-level deep
64-bit fetch buffer
fetch
Flash Pipeline Enable
0 = disable (default)
1 = enable

FOPT @ 0x00 0A80


15 1 0
reserved ENPIPE

14 - 5

F2833x - Flash Programming 14 - 7


Flash Configuration Registers

Flash Configuration Registers


There are some more registers to control the timing and operation modes of the F2833x
internal Flash memory. For our lab exercise and most of the ‘real’ F2833x applications, it is
sufficient to use the default values after RESET.
Texas Instruments provides an initialization function for the internal Flash, called
“InitFlash()”. This function is part of file “DSP2833x_SysCtrl.c” of the Peripheral Register
Header Files that we have already used in our previous labs. We will use this function in our
coming lab exercise.

Other Flash Configuration Registers


Address Name Description
0x00 0A80 FOPT Flash option register
0x00 0A82 FPWR Flash power modes registers
0x00 0A83 FSTATUS Flash status register
0x00 0A84 FSTDBYWAIT Flash sleep to standby wait register
0x00 0A85 FACTIVEWAIT Flash standby to active wait register
0x00 0A86 FBANKWAIT Flash read access wait state register
0x00 0A87 FOTPWAIT OTP read access wait state register

 FPWR: Save power by putting Flash/OTP to ‘Sleep’ or ‘Standby’


mode; Flash will automatically enter active mode if a Flash/OTP
access is made
 FSTATUS: Various status bits (e.g. PWR mode)
 FSTDBYWAIT: Specify number of cycles to wait during wake-up
from sleep to standby
 FACTIVEWAIT: Specify number of cycles to wait during wake-up
from standby to active

Defaults for these registers are often sufficient – See “TMS320F2833x System
Control and Interrupts Reference Guide,” SPRUFB0, for more information
14 - 6

14 - 8 F2833x - Flash Programming


Flash Programming Procedure

Flash Programming Procedure


The procedure to load a portion of code into the Flash is not as simple as loading a program
into the internal RAM. Recall that Flash is non-volatile memory. Flash is based on a floating
gate technology. To store a binary 1 or 0 this gate must load / unload electrons. The term
“Floating Gate” means this is an isolated gate, with no electrical connections. Two effects
are used to force electrons into this gate: ‘Hot electron injection’ or ‘electron tunnelling’
performed by a charge pump on board of the F2833x.
But how do we get the code into the internal Flash?
The F2833x itself will take care of the Flash programming procedure. Texas Instruments
provides the code to execute the sequence of actions. The Flash Utility code can be applied
using two basic options:
1. Code Composer Studio integrated tool
 Tools  On Chip Flash
2. Download both the Flash Utility code and the Flash Data via one of the boot loader
options of the F2833x.
For our lab we will use the CCS-Tool.
Please note that the Flash Utility code must be executed from a SARAM portion of the
F2833x.

Flash Programming Basics


 The DSP CPU itself performs the flash programming
 The CPU executes Flash utility code from RAM that reads the
Flash data and writes it into the Flash
 We need to get the Flash utility code and the Flash data into RAM

FLASH CPU

Flash Emulator JTAG


Utility
Code RAM
RS232 SCI

SPI
Bootloader

I2C
ROM

Flash
eCAN
Data
GPIO

XINTF TMS320F2833x 14 - 7

The steps “Erase” and “Program” to program the Flash are mandatory; “Verify” is an option
but is highly recommended.

F2833x - Flash Programming 14 - 9


Flash Programming Procedure

Flash Programming Basics


 Sequence of steps for Flash programming:

Algorithm Function
1. Erase - Set all bits to zero, then to one
2. Program - Program selected bits with zero
3. Verify - Verify flash contents

 Minimum Erase size is a sector


 Minimum Program size is a bit!
 Important not to lose power during erase step:
If CSM passwords happen to be all zeros, the
CSM will be permanently locked!
 Chance of this happening is quite small! (Erase
step is performed sector by sector)
14 - 8

Flash Programming Utilities


 Code Composer Studio Plug-in (uses JTAG)
 Third-party JTAG utilities
 SDFlash JTAG from Spectrum Digital (requires SD emulator)
 Signum System Flash utilities (requires Signum emulator)
 BlackHawk Flash utilities (requires Blackhawk emulator)
 SDFlash Serial utility (uses SCI boot)
 Gang Programmers (use GPIO boot)
 BP Micro programmer
 Data I/O programmer
 Build your own custom utility
 Use a different ROM bootloader method than SCI
 Embed flash programming into your application
 Flash API algorithms provided by TI

* TI web has links to all utilities (http://www.ti.com/c2000)


14 - 9

14 - 10 F2833x - Flash Programming


CCS Flash Plug-In

CCS Flash Plug-In


The Code Composer Studio Flash Plug-in is called from:
 Tools  On Chip Flash
It opens with the following window:

Code Composer Studio Flash Plug-In

14 - 10

First verify that the OSCCLK is set to:

• 30MHz and PLLCR – value to 10 for a F28335ControlCard @ 30MHz or


• 20MHz and PLLCR – value to 10 for a F28335ControlCard @ 20MHz
The resulting SYSCLKOUT frequency is either 150 or 100MHz. Please make sure to use
the correct numbers, which are equivalent to the physical set up of your
F28335ControlCard.

NEVER use the buttons “Program Password” or “LOCK”!


Leave all 8 entries for Key 0 to Key 7 filled with “FFFF”.
On the top right-hand side, we can exclude some of the sectors from being erased.
The lower right side is the Operation part of the window. First we have to specify the name
of the projects out-file. The Plug-In extracts all the information needed to program the Flash
from this COFF- File.
Before you start the programming procedure, it is highly recommended that you inspect the
linker map-file (*.map) in the “Debug”-Subfolder. This file provides a statistical view of the
usage of the different Flash sections by your project. Verify that all sections are used as
expected.

F2833x - Flash Programming 14 - 11


Code Security Mode

Code Security Mode


Before we continue with our next lab, let us first discuss the Code Security feature of the
F2833x. As mentioned earlier in this module, dedicated areas of memory are password
protected. This is valid for memory L0, L1, L2, L3, OTP and Flash.

Code Security Module (CSM)


 Access to the following on-chip memory is restricted:
0x000A80 Flash Registers

0x008000 L0 SARAM (4Kw)


0x009000 L1 SARAM (4Kw)
0x00A000 L2 SARAM (4Kw)
0x00B000 L3 SARAM (4Kw)

Dual
0x300000 Mapped
FLASH (256Kw)
128-Bit Password
0x340000
0x380400 OTP (1Kw)
0x3F8000 L0 SARAM (4Kw)
0x3F9000 L1 SARAM (4Kw)
0x3FA000 L2 SARAM (4Kw)
0x3FB000 L3 SARAM (4Kw)

 Data reads and writes from restricted memory are only


allowed for code running from restricted memory
 All other data read/write accesses are blocked:
JTAG emulator/debugger, ROM boot loader, code running in
external memory or unrestricted internal memory 14 - 11

Once a password is applied, a data read or write operation from/to restricted memory
locations is only allowed from code in restricted memory. All other accesses, including
accesses from code running from external or unrestricted internal memories as well as JTAG
access attempts are denied.
As mentioned earlier, the password is located in address space 0x33 FFF8 to 0x33 FFFF and
has a field size of 128-bits. The 8 key registers (Key0 to Key7) are used to allow an access to
a locked device. All you need to do is to write the correct password sequence in Key 0 -7
(address space 0x00 0AE0 – 0x00 0AE7).
The password area filled with 0xFFFF in all 8 words is equivalent to an unsecured device.

The password area filled with 0x0000 in all 8 words locks the device FOREVER!

14 - 12 F2833x - Flash Programming


Code Security Mode

CSM Password

0x300000

FLASH (256Kw) CSM Password


Locations (PWL)
0x33FFF8 128-Bit Password
0x33FFF8 - 0x33FFFF

 128-bit user defined password is stored in Flash

 128-bit KEY registers are used to lock and unlock


the device
 Mapped in memory space 0x00 0AE0 – 0x00 0AE7
 Registers “EALLOW” protected
14 - 12

CSM Registers
Key Registers – accessible by user; EALLOW protected
Address Name Reset Value Description
0x00 0AE0 KEY0 0xFFFF Low word of 128-bit Key register
0x00 0AE1 KEY1 0xFFFF 2nd word of 128-bit Key register
0x00 0AE2 KEY2 0xFFFF 3rd word of 128-bit Key register
0x00 0AE3 KEY3 0xFFFF 4th word of 128-bit Key register
0x00 0AE4 KEY4 0xFFFF 5th word of 128-bit Key register
0x00 0AE5 KEY5 0xFFFF 6th word of 128-bit Key register
0x00 0AE6 KEY6 0xFFFF 7th word of 128-bit Key register
0x00 0AE7 KEY7 0xFFFF High word of 128-bit Key register
0x00 0AEF CSMSCR 0xFFFF CSM status and control register
PWL in memory – reserved for passwords only
Address Name Reset Value Description
0x33 7FF8 PWL0 user defined Low word of 128-bit password
0x33 7FF9 PWL1 user defined 2nd word of 128-bit password
0x33 7FFA PWL2 user defined 3rd word of 128-bit password
0x33 7FFB PWL3 user defined 4th word of 128-bit password
0x33 7FFC PWL4 user defined 5th word of 128-bit password
0x33 7FFD PWL5 user defined 6th word of 128-bit password
0x33 7FFE PWL6 user defined 7th word of 128-bit password
0x33 7FFF PWL7 user defined High word of 128-bit password
14 - 13

F2833x - Flash Programming 14 - 13


Code Security Mode

Locking and Unlocking the CSM

 The CSM is locked at power-up and reset


 To unlock the CSM:
 Perform a dummy read of each password in
the Flash
 Write the correct passwords to the key
registers
 New Flash Devices (PWL are all 0xFFFF):
 When all passwords are 0xFFFF – only a
read of the PWL is required to bring the
device into unlocked mode

14 - 14

CSM Caveats
 Never program all the PWL’s as 0x0000
 Doing so will permanently lock the CSM
 Flash addresses 0x337F80 to 0x337FF5,
inclusive, must be programmed to 0x0000 to
securely lock the CSM
 Remember that code running in unsecured
RAM cannot access data in secured memory
 Don’t link the stack to secured RAM if you have
any code that runs from unsecured RAM
 Do not embed the passwords in your code!
 Generally, the CSM is unlocked only for debug
 Code Composer Studio can do the unlocking

14 - 15

14 - 14 F2833x - Flash Programming


Code Security Mode

CSM Password Match Flow

Device permanently locked


Start Is PWL = Yes
CPU access is limited –
all 0s? device cannot be debugged
or reprogrammed
No
Flash device
secure after Yes
reset or runtime Is PWL =
all Fs?
No
Do dummy read of PWL Write password to KEY registers
0x33 7FF8 – 0x33 7FFF 0x00 0AE0 – 0x00 0AE7
(EALLOW) protected

Device unlocked
Correct Yes
password? User can access on-
chip secure memory
No
14 - 16

CSM C-Code Examples


Unlocking the CSM:
volatile int *PWL = &CsmPwl.PSWD0; //Pointer to PWL register file
volatile int i, tmp;

for (i = 0; i<8; i++) tmp = *PWL++; //Dummy reads of PWL locations

asm (” EALLOW”); //KEY regs are EALLOW protected


CsmRegs.KEY0 = PASSWORD0; //Write the passwords
CsmRegs.KEY1 = PASSWORD0; //to the Key registers
CsmRegs.KEY2 = PASSWORD2;
CsmRegs.KEY3 = PASSWORD3;
CsmRegs.KEY4 = PASSWORD4;
CsmRegs.KEY5 = PASSWORD5;
CsmRegs.KEY6 = PASSWORD6;
CsmRegs.KEY7 = PASSWORD7;
asm (” EDIS”);

Locking the CSM:


asm(” EALLOW”); //CSMSCR reg is EALLOW protected
CsmRegs.CSMSCR.bit.FORCESEC = 1; //Set FORCESEC bit
asm (”EDIS”);

14 - 17

F2833x - Flash Programming 14 - 15


Lab Exercise 14: Standalone Project

Lab Exercise 14: Standalone Project


Lab 14: Load an application into Flash
 Use Solution for Lab6 to begin with
 Modify the project to use internal Flash for code
 Add “DSP2833x_CodeStartBranch.asm” to branch
from Flash entry point ( 0x33 FFF6) to C - library
function “_c_int00”
 Add TI - code to set up the speed of Flash
 Add a function to move the speed-up code from
Flash to SARAM Adjust Linker Command File
 Use CCS plug-in tool to perform the Flash
download
 Disconnect emulator and re-power the board!
 Code should be executed out of Flash
 For details see procedure in textbook!

14 - 18

Objective

The objective of this laboratory exercise is to practice working with the F2833x internal
Flash Memory. Let us assume your task is to prepare one of your previous laboratory
solutions to run as a stand-alone solution, direct from Flash memory after powering up the
F2833x. You can select any of your existing solutions, but to keep it easier for your
supervisor to assist you during the debug phase let us take the “binary counter” (Lab 6) as
the starting point.
What do we have to modify?
In Lab 6 the code was loaded by CCS via the JTAG-Emulator into L1-SARAM after a
successful build operation. The linker command file “28335_RAM_lnk.cmd” took care of
the correct connection of the code sections to physical memory addresses of L1-SARAM.
Obviously, we will have to modify this part. Instead of editing the command file, we will use
another one (“F28335.cmd”), also provided by Texas Instruments header file package.
In addition, we will have to fill in the Flash entry point address with a connection to the C
environment start function (“c_int00”). Following a RESET, the Flash memory itself
operates with the maximum number of wait states – our code should reduce this number of
wait states to gain the highest possible speed for Flash operations. Unfortunately we cannot
call this speed-up function when it is still located in Flash – we will have to copy this
function temporarily into any code SARAM before we can call it.
Finally we will use Code Composer Studio’s Flash Programming plug in tool to load our
code into Flash.

14 - 16 F2833x - Flash Programming


Lab Exercise 14: Standalone Project

Please recall the explanations about the Code Security Module in


this lesson, be aware of the password feature all the time in this lab
session and do NOT program the password area!
There are several things to take into account in this lab session, so as usual, let us use a
procedure to prepare the project.

Procedure

Open Files, Create Project File


1. Create a new project, called Lab14.pjt in C:\DSP2833x\Labs.

2. Open the file “Lab6.c” from C:\DSP2833x_V4\Labs\Lab6 and save it as “Lab14.c” in


C:\DSP2833x_V4\Labs\Lab14.
3. Define the size of the C system stack. In the project window, right click at project
“Lab14” and select “Properties”. In category “C/C++ Build”, “C2000 Linker”, “Basic
Options” set the C stack size to 0x400.

Link some of the source code files, provided by Texas Instruments, to the project:
4. In the C/C++ perspective, right click at project “Lab14” and select “Link Files to
Project”. Go to folder “C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\source” and
link:

• DSP2833x_GlobalVariableDefs.c
From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\source link:
• DSP2833x_PieCtrl.c
• DSP2833x_PieVect.c
• DSP2833x_DefaultIsr.c
• DSP2833x_CpuTimers.c
• DSP2833x_SysCtrl.c
• DSP2833x_CodeStartBranch.asm
• DSP2833x_ADC_cal.asm
• DSP2833x_usDelay.asm
From C:\tidcs\c28\dsp2833x\v131\DSP2833x_headers\cmd link:

• DSP2833x_Headers_nonBIOS.cmd
From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\cmd link:

• F28335.cmd
Exclude the file “F28335_RAM_lnk.cmd from the project

F2833x - Flash Programming 14 - 17


Lab Exercise 14: Standalone Project

Project Build Options


5. We have to extent the search path of the C-Compiler for include files. Right click at
project “Lab13” and select “Properties”. Select “C/C++ Build”, “C2000 Compiler”,
“Include Options”. In the box: “Add dir to #include search path”, add the following
lines:

C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include

Note: Use the “Add” Icon to add the new paths:

Close the Property Window by Clicking <OK>.

Add Additional Source Code Files


6. To add the machine code for the Flash entry point at address 0x33 FFF6, we have to
add an assembly instruction “LB _c_int00” and to link this instruction exactly to the
given physical address. Instead of writing our own assembly code, we can make use of
another of TI’s predefined functions (“code_start”), which is part of the source code
file “DSP2833x_CodeStartBranch.asm”.
From C:\tidcs\c28\dsp2833x\v131\DSP2833x_common\source we have already linked
to our project:

• DSP2833x_CodeStartBranch.asm
If you open the linker command file “F28335.cmd”, you will find a label “code_start”
linked to “BEGIN” which is defined at address 0x33 FFF6 in code memory page 0.

Modify Source Code to Speed up Flash memory


7. Open file “Lab14.c” to edit.
In “main()”, after the function call “InitSysCtrl()”, we have to add the code to speed-
up the Flash memory.
This will be done by the function “InitFlash()”. However, as mentioned earlier, this
code must run out of SARAM. When we finally run the program from Flash and the
F2833x reaches this line, all code is still located in Flash. This means that before we
can call “InitFlash()”, the F2833x has to copy it from FLASH into SARAM. Standard
ANSI-C provides a memory copy function “memcpy(*dest,*source, number)” for this
purpose, the function prototype being in the file “string.h”.

14 - 18 F2833x - Flash Programming


Lab Exercise 14: Standalone Project

What do we use for “dest” (destination address), “source” (source address) and
“number” (number of elements to copy)?
Again, the solution can be found in the file “DSP2833x_SysCtrl.c”. Open it and look
at the beginning of this file. You will find a “#pragma CODE_SECTION” – line that
defines the dedicated code section “ramfuncs” and connects the function “InitFlash()”
to it. The symbol “ramfuncs” is used in the file “F28335.cmd” to connect it to physical
memory “FLASHD” as load-address and to memory “RAML0” as execution address.
The task of the linker command file “F28335.cmd” is it to provide the physical
addresses for the rest of the project. The symbols “LOAD_START”, “LOAD_END”
and “RUN_START” are used to define these addresses symbolically as
“_RamfuncsLoadStart”, “_RamfuncsLoadEnd” and “_RamfuncsRunStart”.
Add the following line to your code:
memcpy(&RamfuncsRunStart, &RamfuncsLoadStart,
&RamfuncsLoadEnd - &RamfuncsLoadStart);
Add a call to the function “InitFlash()”, now available in RAML0:
InitFlash();
At the beginning of Lab14.c, add a function prototype for “InitFlash()”. Also declare
the symbols used as parameters for “memcpy()” as externals:
extern unsigned int RamfuncsLoadStart;
extern unsigned int RamfuncsLoadEnd;
extern unsigned int RamfuncsRunStart;

Build project
8. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild Active Project (Alt +Shift + P)


If the build was successful you should get 0 Errors, 0 Warnings and 0 Infos:

F2833x - Flash Programming 14 - 19


Lab Exercise 14: Standalone Project

Verify Linker Results: The “.map” - File


9. Before we actually start the Flash programming, it is always good practice to verify
the used sections of the project. This is done by inspecting the linker output file
“lab14.map”.
10. Open file “lab14.map” in the sub-folder “..\Debug”
In ‘MEMORY CONFIGURATION’ column ‘used’ you will find the amount of
physical memory that is used by your project.
Verify that only the following five lines from PAGE 0 are used:
Name origin length used unused attr
RAML0 00008000 00001000 0000001f 00000fe1 RWIX
FLASHD 00320000 00008000 0000001f 00007fe1 RWIX
FLASHA 00338000 00007f80 00000729 00007857 RWIX
BEGIN 0033fff6 00000002 00000002 00000000 RWIX
ADC_CAL 00380080 00000009 00000007 00000002 RWIX

The number of addresses used in FLASHA might be different in your lab session.
Depending on how efficient your code was programmed by yourself, you will end up
with more or less words in this section.
In the SECTION ALLOCATION MAP, you can see how the different portions of our
projects code files are distributed throughout the physical memory sections. For
example, the “.text” - entry shows all the objects that were concatenated into section
“FLASHA”.
The entry-point “codestart” connects the object “CodeStartBranch.obj” to physical
address 0x3F FFF6 and occupies two words.

Use CCS integrated Flash Programming


11. The next step is to program the machine code into the internal Flash. As mentioned in
this lesson there are different ways to accomplish this step. The easiest way is to use
the “Debug Active Project” feature of Code Composer Studio.
If there are FLASH based sections part of the project, they will be erased and
programmed automatically!

Perform:  Target  Debug Active Project


If everything went as expected you should see these status messages:

14 - 20 F2833x - Flash Programming


Lab Exercise 14: Standalone Project

Congratulations!
Your code has been stored into FLASH – memory!
In the “Debug” – Perspective open the disassembly window and enable “Show Source”

The blue arrow points the beginning of main. The address in the first column shows that the
code has been loaded into a physical FLASH section (in the example above to address
0x33840B).

Shut down CCS and Restart FLASH - Code


12. Close your Code Composer Studio session.
13. Disconnect the power from the Peripheral Explorer Board.
14. Verify that Peripheral Explorer Board jumper J3 (“SCI-BOOT GPIO84”) is open.
15. Reconnect Peripheral Explorer Board to power supply.

Your code should be executed immediately out of Flash, showing the


LED - binary counter at LEDs LD1…LD4.

F2833x - Flash Programming 14 - 21


Lab Exercise 14: Standalone Project

Blank page.

14 - 22 F2833x - Flash Programming


F2833x Boot ROM

Introduction
In Chapter 14 we discussed the option of starting our embedded control program directly
from the internal Flash memory of the F2833x. We also looked briefly into other options for
starting the code execution. We saw that it is also possible to start up from M0 - SARAM,
OTP and that we can select a ‘boot load’ operating mode that engages a serial or parallel
download of the control code before it is actually executed.
In Chapter 15 we will take a closer look into what is going on in these different modes and
into the sequence of activities that are performed by the F2833x boot firmware before the
first instruction of your program is reached. This chapter will help you to understand the
start-up procedures of the F2833x and the power-on problems of an embedded system in
general.
We start with a summary of the 16 options to start the F2833x after a RESET, followed by a
look into the firmware structure inside the F2833x Boot-ROM. This includes some lookup
tables for mathematical operations, a generic interrupt vector table and the code that is used
to select one of the six start options.
Because we have already dealt with the Flash start option in Chapter 14, we can now focus
on the serial boot loader options. Five options are available: Serial Communication Interface
(SCI), Serial Peripheral Interface (SPI), Inter Integrated Circuit (I2C), Controller Area
Network (CAN) used for motor vehicles and Multi Channel Buffered Serial Port (McBSP).
All five interfaces were discussed in detail in Chapters 9, 10, 11, 12 and 13. If you have
finished the lab exercises of some of these five modules successfully, you should be able to
develop your own code to download code from a PC as host into the SARAM of the F2833x
and start it from there.
A typical application for the serial download of new code into the F2833x is a field update of
the internal Flash memory that contains the control code for the embedded system. It would
be much too expensive to use the JTAG - Emulator to download the new code. Instead,
Texas Instruments offers a Flash API that uses exactly the same SCI boot load option to
transmit the new code and/or data into the F2833x. This API - a portion of code that will be
part of your project will take care of the code update. For more details refer to
“TMS320F2833xFlash API v2.10”, document number: SPRC539 on TI’s website.
Another typical application is the use of the SPI boot load option. In this case, an external
serial SPI-EEPROM of Flash holds the actual code. Before it is executed on the F2833x, it is
downloaded into the F2833x. This is a useful option for members of the TMS320C34x -
family, which do not have any internal non-volatile memory at all.
Finally, we will discuss a parallel boot load option that uses some GPIO lines to download
code and/or data into the F2833x.

F2833x - Boot ROM 15 - 1


Module Topics

Module Topics
F2833x Boot ROM ........................................................................................................................... 15-1
Introduction ................................................................................................................................... 15-1
Module Topics ............................................................................................................................... 15-2
F2833x Memory Map .................................................................................................................... 15-3
Direct start of code execution ................................................................................................... 15-3
Start of a boot loader protocol................................................................................................... 15-3
F2833x Reset Boot Loader ............................................................................................................ 15-4
Timeline for Boot Loader .............................................................................................................. 15-5
Boot - ROM Memory Map ............................................................................................................. 15-7
SINE / COSINE Lookup Tables ............................................................................................... 15-7
Normalized Square Root Table ............................................................................................... 15-10
Normalized ArcTan Table ...................................................................................................... 15-10
Rounding and Saturation Table............................................................................................... 15-10
Min / Max Table ..................................................................................................................... 15-10
Exp(x) Table ........................................................................................................................... 15-10
Floating-point normalized ArcTan Table................................................................................ 15-10
Floating-point Exp(x) Table ................................................................................................... 15-10
Boot Loader Code ................................................................................................................... 15-10
F2833x Vector Table .............................................................................................................. 15-11
Boot Loader Data Stream ........................................................................................................... 15-12
Boot Loader Data Stream Example ........................................................................................ 15-13
Boot Loader Transfer Function ............................................................................................... 15-14
Init Boot Assembly Function ....................................................................................................... 15-15
SCI Boot Load ............................................................................................................................. 15-16
SCI Hardware Connection ...................................................................................................... 15-16
SCI Boot Loader Function ...................................................................................................... 15-17
Parallel Boot Loader................................................................................................................... 15-18
Hardware Connection ............................................................................................................. 15-18
F2833x Software Flow............................................................................................................ 15-19
Host Software Flow ................................................................................................................ 15-20
SPI Boot Loader .......................................................................................................................... 15-21
SPI Boot Loader Data Stream ................................................................................................. 15-22
SPI Boot Loader Flowchart .................................................................................................... 15-22
Lab 15_1: Serial Boot Loader SCI-A ......................................................................................... 15-25
Objective ................................................................................................................................. 15-25
Procedure ................................................................................................................................ 15-25
Open Project ........................................................................................................................... 15-25
Build, Load and Run ............................................................................................................... 15-26
Change Hardware set up ......................................................................................................... 15-26
Generate download data stream .............................................................................................. 15-27
Download Image into the target .............................................................................................. 15-29

15 - 2 F2833x - Boot ROM


F2833x Memory Map

F2833x Memory Map


To begin with, let us recall the F2833x memory map.

Direct start of code execution


We have a choice of directly starting our program from fixed code entry points in the
following memory sections:

• FLASH
• OTP
• M0-SARAM or
• XINTF - Zone 6

TMS320F2833x Memory Map


Data Program
0x000000 M0 SARAM (1Kw) 0x010000 reserved
0x000400 M1 SARAM (1Kw) 0x100000
0x000800 XINTF Zone 6 (1Mw)
0x000D00 PIE Vectors 0x200000
XINTF Zone 7 (1Mw)
(256 w) 0x300000
0x000E00 reserved
PF 0 (6Kw) FLASH (256Kw) Dual Mapped:
0x002000 L0, L1, L2, L3
0x004000 0x33FFF8 PASSWORDS (8w)
XINTF Zone 0 (4Kw) 0x340000
0x005000 reserved
PF 3 (4Kw) 0x380080
0x006000 ADC calibration data CSM Protected:
PF 1 (4Kw) reserved 0x380090
0x007000 reserved L0, L1, L2, L3,
PF 2 (4Kw) 0x380400 FLASH, ADC CAL,
0x008000 User OTP (1Kw)
L0 SARAM (4Kw) 0x380800 OTP
0x009000 reserved
L1 SARAM (4Kw) 0x3F8000
0x00A000 L0 SARAM (4Kw)
L2 SARAM (4Kw) 0x3F9000
0x00B000 L1 SARAM (4Kw)
L3 SARAM (4Kw) 0x3FA000
0x00C000 L2 SARAM (4Kw) DMA Accessible:
L4 SARAM (4Kw) 0x3FB000
0x00D000 L3 SARAM (4Kw) L4, L5, L6, L7,
L5 SARAM (4Kw) 0x3FC000
0x00E000 reserved XINTF Zone 0, 6, 7
L6 SARAM (4Kw) 0x3FE000
0x00F000 Boot ROM (8Kw)
L7 SARAM (4Kw)
0x010000 0x3FFFC0 BROM Vectors (64w)
0x3FFFFF
Data Program 15 - 2

The options are hard-coded by 4 GPIO-lines (87, 86, 85 and 84). The 4 pins are always
sampled during power-on. Depending on the status one of the options is selected and the
code is executed immediately.

Start of a boot loader protocol


Instead of starting customer code directly after reset, we can engage a serial or parallel
communication protocol between the F2833x and a host (e.g. a PC) or between the F2833x
and an external non-volatile memory device. Such a communication link can be used (a) to
download the control code before it is actually executed or (b) to update the control code by
a new revision.
In addition to the 4 direct start options for code execution, we have 7 more options to open a
serial or parallel communication protocol after power-on as shown on Slide 15-3:

F2833x - Boot ROM 15 - 3


F2833x Reset Boot Loader

Boot Loader Options

GPIO pins
Boot Mode
87 86 85 84
1 1 1 1 jump to FLASH address 0x33 FFF6
0 1 0 0 jump to M0 SARAM address 0x00 0000
0 1 1 1 jump to OTP address 0x38 0400
1 0 0 1 jump to XINTF 16 address 0x10 0000
1 0 0 0 jump to XINTF 32 address 0x10 0000
1 1 1 0 boot load code to on-chip memory via SCI - A port
1 1 0 1 boot load code to on-chip memory via SPI - A port
1 1 0 0 boot load code to on-chip memory via I2C - A port
1 0 1 1 boot load code to on-chip memory via eCAN - A port
1 0 1 0 boot load code to on-chip memory via McBSP - A port
0 1 1 0 boot load code to on-chip memory via GPIO (parallel)
0 1 0 1 boot load code to on-chip memory via XINTF (parallel)

15 - 3

F2833x Reset Boot Loader


The next two slides summarize the RESET options of the F2833x.

Reset – Bootloader
0x3FF9CE: Boot loader sets:
Reset OBJMODE = 1
OBJMODE = 0 AMODE = 0 AMODE = 0
ENPIE = 0 INTM = 1

Boot determined by
state of GPIO pins
Reset vector fetched from
Boot ROM GPIO 87, 86, 85, 84
0x3F FFC0

Direct Code Entry Points Start Boot loader code


M0SARAM 0x000000 SCI - A SPI - A
FLASH 0x33FFF6 I2C - A eCAN - A
OTP 0x380400 McBSP - A
XINTF 0x100000 XINTF (parallel)GPIO (parallel)

15 - 4

15 - 4 F2833x - Boot ROM


Timeline for Boot Loader

Timeline for Boot Loader


1. RESET-address is always 0x3F FFC0. This is part of Texas Instruments internal
ROM.
Before we continue, let us inspect this part of the memory. In Code Composer
Studio, open a memory window and enter the address 0x3F FFC0:

This is a direct view of the ROM-vector table at the end of this memory section.
Address 0x3FFFC0 is loaded with the start address of the RESET-vector
(0x3FF9CE); the following entries are vectors for interrupt INT1 (0x000042), INT2
(0x000044) and so on.
2. The F2833x reads the RESET-vector from the table and loads its program counter
(PC) with this 32-bit value. If you perform a RESET in Code Composer Studio, the
disassembly window will pop up and the green arrow will point to the first machine
code instruction at address 0x3FF9CE, which is the first instruction of the boot code.
Here basic initialization tasks are performed and the type of the boot sequence is
selected.

F2833x - Boot ROM 15 - 5


Timeline for Boot Loader

3. Next, still as part of the boot code function, the execution entry point is determined
by the status of the four pins (GPIO87...84).
In Code Composer Studio, if you use “single step over (F10)” from RESET a few
times, you can inspect the sequence. If all four GPIOs (87...84) are ‘1’ (in case of the
Peripheral Explorer Board leave jumper J3 “SCI-boot 84” open), the FLASH-entry
point is selected. After a few hits of function key F10 you will reach this entry point:

4. If one of the serial or parallel boot loading options is selected, another part of the
boot code function is executed to establish a standard communication protocol for
the pre-selected channel. We will have a closer look into these communication
protocols in later slides. In case of the Peripheral Explorer Board we can close
jumper J3 “SCI-boot 84” to select the “SCI-A boot loader”. But before we will do
that, we need to discuss the part of the communication host side.

Here is a graphical summary of the code flow after a RESET:

Reset Code Flow - Summary


0x00 0000 0x00 0000
M0 SARAM (1Kw)

0x38 0400 XINTF Zone 6


OTP (1Kw) (x16 / x32)
0x10 0000
0x30 0000
FLASH (256Kw)
0x33 FFF6

Execution Entry
0x3F E000 Boot ROM (8Kw) Point Determined
Boot Code By GPIO Pins
0x3F F9CE
• •
• •

BROM vector (64w)


RESET 0x3F FFC0 0x3F F9CE Bootloading
Routines
(SCI-A, SPI-A, I2C,
eCAN-A, McBSP-A
GPIO, XINTF)
15 - 5

15 - 6 F2833x - Boot ROM


Boot - ROM Memory Map

Boot - ROM Memory Map


Before we go into the boot load options let us have a closer look into the partitioning of the
boot-ROM area. The size of the area is 8k x 16- bit and it is mapped both into code and data
memory, using a unified memory map.

F2833x BOOT-ROM Memory Map


Address Range Function Format
0x3FE000 – 0x3FE501 IQ - Math sine/cosine table 641 x 32 bit; I2Q30
0x3FE502 – 0x3FE711 IQ - Math normalized inverse 264 x 32 bit; I3Q29
0x3FE712 – 0x3FE823 IQ - Math normalized sqrt 137 x 32 bit; I2Q30
0x3FE824 – 0x3FE9E7 IQ - Math normalized arctan 226 x 32 bit; I2Q30
0x3FE9E8 – 0x3FEB4F IQ – Math round / saturation 180 x 32 bit; I2Q30
0x3FEB50 – 0x3FEBC7 IQ – Math min / max table 60 x 32 bit; I31Q1 – I1Q31
0x3FEBC8 – 0x3FEBDB IQ – Math exp(x) table 10 x 32 bit; I1Q31
0x3FEBDC – 0x3FF0DD FPU sine/cosine table 641 x 32 bit; float
0x3FF0DE – 0x3FF261 FPU normalized arctan 194 x 32 bit; float
0x3FF262 – 0x3FF275 FPU exp(x) table 10 x 32 bit; float
0x3FF276 – 0x3FF34B reserved
0x3FF34C – 0x3FF9ED Boot Loader Functions F2833x machine code
0x3FF9EE – 0x3FFFB8 reserved
0x3FFFB9 – 0x3FFFBF ROM version and
0x3FFFC0 – 0x3FFFFF Reset and Interrupt vectors 32 x 32 bit address
15 - 6

SINE / COSINE Lookup Tables


IQ-Math - Table
The ROM offers two different sine/cosine-tables; one for fixed-point math (IQ-numbers) and
one for floating-point numbers (32-bit IEEE float format).
Since the look-up tables for sine and cosine are very useful tools in mathematic
computations, we should inspect them now:
 View  Memory
Let’s begin with the first 1282 addresses (0x3F E000 to 0x3F E501). This area includes an
IQ-Math sine/cosine look-up table and consists of 641 32-bit numbers in I2Q30-format. The
first 512 numbers are for a 360-degrees unit circle with an increment angle of 360/512 =
0.703 degree. The remaining 128 values are a repetition of the first 90-degree quarter.
To visualize the sine/cosine-values open a memory window and set up the properties to 32 -
bit signed integer and Q-value to 30:

F2833x - Boot ROM 15 - 7


Boot - ROM Memory Map

Numbers are in “IQ-Format” with 2 Integer and 30 Fractional Bits. CCS uses the binary
content of the memory to display it in the correct format:

Compare: sin (1* 360/512) = 0.012271538285719926079408261951003


sin (2* 360/512) = 0.024541228522912288031734529459283

15 - 8 F2833x - Boot ROM


Boot - ROM Memory Map

Floating-Point sine/cosine - Table


The floating-point look-up table at address 0x3FEBDC consists also of 640 entries for 5
quarters of sine-values, but now in IEEE 754 single precision floating point format. To
inspect this region, change the memory windows start address to 0x3FEBDC and the data
type to “32-bit Float”:

You should always remember that there are these two tables available in the ROM. If you
need to calculate trigonometric numbers, all you have to do is to set a pointer at the
beginning of these memory arrays. In your control code you can then easily access
sine/cosine-values.

Normalized Inverse Table


Another section of the Boot-ROM includes a lookup table for the Newton-Raphson inverse
algorithm. It spans 528 addresses (0x3F E502 to 0x3F E711) and covers 264 32-bit numbers
in I3Q29-Format.

F2833x - Boot ROM 15 - 9


Boot - ROM Memory Map

Normalized Square Root Table


From address 0x3F E712 to 0x3F E823 137 32-bit numbers are stored as a look-up table for
estimates of the Newton-Raphson square root algorithm. Data format is I2Q30.

Normalized ArcTan Table


A lookup table for the iterative estimation of the Normalized Arc Tangent follows from 0x3F
E824 to 0x3F E9E7 in I2Q30-format.

Rounding and Saturation Table


The memory area 0x3F E9E8 to 0x3F EB4F is used for rounding and saturation subroutines
of Texas Instrument library function, like IQ-math or digital motor control libraries (dmclib).
The format is also of I2Q30.

Min / Max Table


A section with minimum and maximum fixed point numbers follows from address 0x3F
EB50 to 0x3F EBC7. This array is used to define the number ranges from I31Q1 to I1Q31.

Exp(x) Table
A table for coefficients to calculate y = exp(x) using a Taylor series follows at address
0x3FEBC8. The numbering system is I1Q31.

Floating-point normalized ArcTan Table


A floating-point normalized arcos-tangents table in 32-bit float format is available from
address 0x3F F0DE.

Floating-point Exp(x) Table


A table for coefficients to calculate y = exp(x) using a Taylor series follows at address
0x3FF262. The numbering system is single precision floating point.

Boot Loader Code


The memory space 0x3FF34C - 0x3FF9ED is used for the boot loader machine code. When
the F2833x is coming out of RESET this code will be executed first. As mentioned earlier it
derives the actual entry point or the boot loader option from the status of four input pins.

15 - 10 F2833x - Boot ROM


Boot - ROM Memory Map

F2833x Vector Table


The very last 64 addresses are reserved for 32 Entries of 32-bit address information for
interrupt service routine entry points. The layout is shown at the following slide. Each
interrupt core line is hard linked to its individual entry in this memory area. In the case where
an interrupt is acknowledged by the F2833x, the assigned 32-bit-information (shown in the
next slide as “Content”) is used as the entry-point for the dedicated interrupt service routine.
Because we cannot change the content of this TI-ROM, we have to use the fixed entry points
in M0-SARAM (0x00 0042 to 0x00 007F) to place a 32-bit assembly branch instruction into
our dedicated interrupt service routines. If we come out of RESET, all interrupts are
disabled, so we don’t have to do anything. If we decide to use interrupts, which is a wise
decision for embedded control, we can use M0-SARAM as vector table - or better - we use
the Peripheral Interrupt Expansion (PIE) Unit - see Chapter 6.

F2833x BOOT-ROM Vector Table


Vector Address Content Vector Address Content
RESET 0x3F FFC0 0x3F FC00 RTOSINT 0x3F FFE0 0x00 0060
INT1 0x3F FFC2 0x00 0042 reserved 0x3F FFE2 0x00 0062
INT2 0x3F FFC4 0x00 0044 NMI 0x3F FFE4 0x00 0064
INT3 0x3F FFC6 0x00 0046 ILLEGAL 0x3F FFE6 0x00 0066
INT4 0x3F FFC8 0x00 0048 USER 1 0x3F FFE8 0x00 0068
INT5 0x3F FFCA 0x00 004A USER 2 0x3F FFEA 0x00 006A
INT6 0x3F FFCC 0x00 004C USER 3 0x3F FFEC 0x00 006C
INT7 0x3F FFCE 0x00 004E USER 4 0x3F FFEE 0x00 006E
INT8 0x3F FFD0 0x00 0050 USER 5 0x3F FFF0 0x00 0070
INT9 0x3F FFD2 0x00 0052 USER 6 0x3F FFF2 0x00 0072
INT10 0x3F FFD4 0x00 0054 USER 7 0x3F FFF4 0x00 0074
INT11 0x3F FFD6 0x00 0056 USER 8 0x3F FFF6 0x00 0076
INT12 0x3F FFD8 0x00 0058 USER 9 0x3F FFF8 0x00 0078
INT13 0x3F FFDA 0x00 005A USER 10 0x3F FFFA 0x00 007A
INT14 0x3F FFDC 0x00 005C USER 11 0x3F FFFC 0x00 007C
DLOGINT 0x3F FFDE 0x00 005E USER 12 0x3F FFFE 0x00 007E

15 - 7

F2833x - Boot ROM 15 - 11


Boot Loader Data Stream

Boot Loader Data Stream


The following two slides show the structure of the incoming data stream to the boot loader.
The basic structure is the same for all the boot loaders and is based on the F2833x hex utility
tool. The tool is en executable file called “hex2000.exe
(C:\CCStudio_v3.3\C2000\cgtools\bin)” and is used to convert the project’s out-file from
“COFF”- format to the necessary hex-format.
The first 16-bit word in the data stream is known as the key value. The key value is used to
tell the boot loader the width of the incoming stream: 8 or 16 bits. Note that not all boot
loaders will accept both 8 and 16-bit streams. The SPI boot loader is 8-bit only. Please refer
to the detailed information on each loader for the valid data stream width. For an 8-bit data
stream, the key value is 0x08AA and for a 16-bit stream it is 0x10AA. If a boot loader
receives an invalid key value, then the load is aborted. In this case, the entry point for the
Flash memory will be used.

Boot Loader Data Stream Structure


1 0x10AA : Key for memory width = 16 bit
2-9 Reserved for future use
10 Entry Point PC[22:16]
11 Entry Point PC[15:0]
12 Block Size (words); if 0 then end of transmission
13 Destination Address of block ; Addr[31:16]
14 Destination Address of block ; Addr[15:0]
15 First word of block

N Last word of block


N+1 Block Size (words)
N+2 Destination Address of block ; Addr[31:16]
N+3 Destination Address of block ; Addr[15:0]

15 - 8

The next eight words are used to initialize register values or otherwise enhance the boot
loader by passing values to it. If a boot loader does not use these values then they are
reserved for future use and the boot loader simply reads the value and then discards them.
Currently, only the SPI boot loader uses one word to initialize a register value.
The next 10th and 11th words comprise the 22-bit entry point address. This address is used to
initialize the PC after the boot load is complete. This address is most likely the entry point of
the program downloaded by the boot loader.

15 - 12 F2833x - Boot ROM


Boot Loader Data Stream

The twelfth word of the data stream is the size of the first data block to be transferred. The
size of the block is defined for both 8 and 16-bit data stream formats as the number of 16-bit
words in the block. For example, to transfer a block of twenty 8-bit data values from an 8-bit
data stream, the block size would be 0x000A to indicate ten 16-bit words.
The next two words tell the loader the destination address of the block of data. Following the
size and address will be the 16-bit words that make up the corresponding block of data.
This pattern of block size/destination address repeats for each block of data to be transferred.
Once all the blocks have been transferred, a block size of 0x0000 signals to the loader that
the transfer is complete. At this point, the loader will return the entry point address to the
calling routine, which in turn will clean up and exit. Execution will then continue at the entry
point address as determined by the input data stream contents.

Boot Loader Data Stream Example


Next is an example of a boot loader data stream that is used to load two blocks of data into
two different memory locations of the F2833x. Five words (1,2,3,4,5) are loaded into address
0x3F 9010 and two words are loaded into address 0x3F 8000.

Boot Loader Data Stream Example


10AA ; Key for 16-Bit memory stream
0000
0000
0000
0000
0000
0000
0000
0000
003F ; PC – starting point after load is complete: 0x3F 8000
8000
0005 ; 5 words in block 1
003F
9010 ; First block is loaded into 0x3F 9010
0001 ; first data word
0002
0003
0004
0005 ; last data
0002 ; Second block is two words long
003F ; Second block is loaded into 0x3F 8000
8000
7700 ; first data
7625 ; last data
0000 ; next block zero length = end of transmission 15 - 9

F2833x - Boot ROM 15 - 13


Boot Loader Transfer Function

The next flowchart illustrates the basic process a boot loader uses to determine whether 8-bit
or 16-bit data stream has been selected, transfer that data, and start program execution. This
process occurs after the boot loader detects the valid boot mode selected by the state of the
GPIO pins.
The loader compares the first value sent by the host against the 16-bit key value of 0x10AA.
If the value fetched does not match then the loader, it will read a second value. This value
will be combined with the first value to form a word. This will then be checked against the 8-
bit key value of 0x08AA. If the loader finds that the header does not match either the 8-bit or
the 16-bit key value, or if the value is not valid for the given boot mode then the load will
abort. In this case the loader will return the entry point address for the flash to the calling
routine.

F2833x Boot Loader Transfer Procedure


Read first word(W1)

No
W1 = Read second word
0x10AA? lower 8 bit
Yes

16bit data size W2:W1= No


Format Error
0x08AA?
Read Entry Point
Yes
Read BlockSize(R)
8bit data size
Yes
R = 0?
No
Read BlockAddress
Return and Jump
Transfer R words from to Entry Point
source to destination
15 - 10

15 - 14 F2833x - Boot ROM


Init Boot Assembly Function

Init Boot Assembly Function


The first routine of the Boot-ROM that is called after RESET is the InitBoot assembly
routine. This routine initializes the device for operation in F2833x object mode. Next it
performs a dummy read of the Code Security Module (CSM) password locations. If the CSM
passwords are erased (all 0xFFFFs), then this has the effect of unlocking the CSM.
Otherwise, the CSM will remain locked and this dummy read of the password locations will
have no effect. This can be useful if you have a new device that you want to boot load.
After the dummy read of the CSM password locations, the InitBoot routine calls the
SelectBootMode function. This function will then determine the type of boot mode desired
by the state of specific GPIO pins. Once the boot is complete, the SelectBootMode function
passes back the EntryAddr to the InitBoot function. InitBoot then calls the ExitBoot routine
that then restores CPU registers to their reset state and exits to the entry address that was
determined by the boot mode.

F2833x Init Boot Function


RESET
Init Boot

Initialize C28x:
OBJMODE = 1
AMODE = 0
M0M1MAP = 1 Dummy Read Call
DP = 0 CSM passwords BootModeSelect
OVM = 0
SPM = 0
SP = 0x00 0400
ExitBoot

15 - 11

F2833x - Boot ROM 15 - 15


SCI Boot Load

SCI Boot Load


SCI Hardware Connection

The SCI boot mode asynchronously transfers code from SCI-A to the F2833x. It only
supports an incoming 8-bit data stream and follows the same data flow as outlined before.

Note:
It is important to understand that if you want to connect a PC via its serial COM-port to an
F2833x, you will need to have a RS-232 transceiver interface between the F2833x and the
PC to generate the necessary voltages. Fortunately the F28335ControlCard provides such a
transceiver, a Texas Instruments MAX2332. If you connect the F2833x directly to the two
PC-COM lines you will eventually destroy the F2833x!
If you are not sure about the hardware set up, ask your teacher before you continue with the
laboratory exercise at the end of this chapter!

F2833x SCI Boot Loader Function

RS 232
F2833x TxD 2 TxD
e.g.
SCI-A Host/ e.g.
Texas RS 232
RxD PC‘s COM1
Instruments RxD
3
MAX3221

15 - 12

15 - 16 F2833x - Boot ROM


SCI Boot Load

SCI Boot Loader Function


The flowchart for the SCI interface is shown in Slide 15-13 (below).

F2833x SCI Boot Function


SCI Boot
Enable SCI-A Clock Echo auto baud
Set LSPCLK to /4 character

Enable SCI-A Tx and


Rx - Pin Read KeyValue

Setup SCI-A:
1 stop,8 data ,no parity No
No loopback Valid Key? FLASH
Disable SCI-A INT
Disable SCI-A FIFO
Yes
Prime SCI-A baud rate
register
Start Boot Load
Enable Autobaud Sequence
detection

Yes
Autobaud
Lock ?
No
15 - 13

The F2833x communicates with the external host device by communication through the SCI-
A Peripheral. The auto baud feature of the SCI port is used to lock baud rates to the host. For
this reason, the SCI loader is very flexible and the user can select a number of different baud
rates to communicate with the DSP.
After each data transfer, the DSP will echo back the 8-bit character received to the host. In
this manner, the host can perform checks that each character was received correctly by the
DSP.
At higher baud rates, the slew rate of the incoming data bits can be affected by transceiver
and connector performance. While normal serial communications may work well, this slew
rate may limit reliable auto-baud detection at higher baud rates (typically beyond 100 k
baud) and cause the auto-baud lock feature to fail.

F2833x - Boot ROM 15 - 17


Parallel Boot Loader

Parallel Boot Loader


Hardware Connection
The parallel general purpose I/O (GPIO) boot mode asynchronously transfers code from
GPIO0 to GPIO15 to internal or XINTF memory. Each value can be 16 bits or 8 bits wide
and follows the same data flow as outlined in the data stream structure.

F2833x parallel Boot Loader (GPIO)

GPIO - 26
C28x GPIO - 27 Host/ e.g.
GPIO
PC‘s COM1
16

GPIO15...GPIO0

1: F28x indicates: “ready to receive”


2: Host signals “data active at GPIO-B”
3: F28x indicates “read is complete”
4: Host acknowledges “cycle completed”
5: F28x indicates: “ready for more data”
GPIO26

GPIO27

1 2 3 4 5 6
15 - 14

The F2833x communicates with the external host device by polling/driving the GPIO26 and
GPIO27 lines. The handshake protocol shown in Slide 15-14(above) must be used to
successfully transfer each word via GPIO0...GPIO15. This protocol is very robust and allows
for a slower or faster host to communicate with the F2833x device.
If the 8-bit mode is selected, two consecutive 8-bit words are read to form a single 16-bit
word. The most significant byte (MSB) is read first followed by the least significant byte
(LSB). In this case, data bytes are read from GPIO0...GPIO7 only.
The DSP first signals to the host that the DSP is ready to start a data transfer by pulling the
GPIOD27 pin low. The host load then initiates the data transfer by pulling the GPIOD26 pin
low. The complete protocol is shown in the Slide 15-14 (above).

15 - 18 F2833x - Boot ROM


Parallel Boot Loader

F2833x Software Flow

Slide 15-15 shows a flowchart for the Parallel GPIO boot loader inside the F2833x. After
parallel boot has been selected at RESET, GPIO0...GPIO15 are initialized as an input port.
The two handshake lines GPIO26 and GPIO27 are initialized as input and output
respectively.
Next, the first character is polled from GPIO0...GPIO15. If it is a valid 8-bit (0x08AA) or
16-bit (0x10AA) key, the procedure continues to read eight more reserved words and
discards them. Next, the code entry point and all following blocks are polled according to the
diagram at Slide 15-14.
If all blocks are received successfully, the routine jumps to the entry point address that was
received during the boot load sequence.

F2833x GPIO Boot Function


GPIO Boot

Read and discard


8 reserved words
Initialize GPIO
GPIO0…15 = input
GPIO27 = input
GPOI26 = output Read Entry Point

Read KeyValue
( 8 or 16 Bit size) Call Parallel Copy Data

Yes
Valid Key?
Jump
Entry Point
No

FLASH

15 - 15

F2833x - Boot ROM 15 - 19


Parallel Boot Loader

Host Software Flow


Slide 15-16 (below) shows the transfer flow from the Host side. The operating speed of the
F2833x and Host are not critical in this mode as the host will wait for the F2833x and the
F2833x will in turn wait for the host. In this manner the protocol will work with both a host
running faster and a host running slower than the F2833x.

Host GPIO Boot Function


Start Download

F28x ack? No
No
F28x ready? (GPIO26=1)
(GPIO26=0)
Yes
Yes
Deactivate GPIO27 =1
Load data

Signal that data avail.


GPIO27 =0
Yes
More Data?

No

End Download

15 - 16

First, the host waits for a handshake signal (GPIO26) to be activated (= 0) by the F2833x.
Next, the host has to load the next character onto its parallel output port. The host then
acknowledges a valid character by activating (=0) the signal that is connected to the F2833x
GPIO27 input line.
The F2833x has now all the time it requires to read the data from GPIO0…GPIO15. Once
this has been performed, the F2833x deactivates its output line GPIO26 to inform the host
that the transfer cycle is completed.
The host acknowledges this situation by deactivating its handshake line (GPIO27). If the
algorithm has more data to transmit to the F2833x, the procedure is repeated once more. If
not, the download is finished.

15 - 20 F2833x - Boot ROM


SPI Boot Loader

SPI Boot Loader


The SPI loader expects an 8-bit wide SPI-compatible serial EEPROM device to be present
on the SPI pins as shown in Slide 15-17. The SPI boot loader does not support a 16-bit data
stream.

F2833x SPI Boot Loader Function

SPI – MOSI (GPIO16) Serial EEPROM


DIN
F2833x SPI – SOMI (GPIO17)
DOUT
SPI - A SPI – CLK (GPIO18) CLK
SPI – STE (GPIO19) /CS

Note:
(1) SPI – loader is 8bit only, it EEPROM – Types:
does not support 16bit data
Atmel: AT25C256; see chapter 13
stream Xicor: X25256
(2) EEPROM data stream must ST: M95080
start at address 0x0000 and others

15 - 17

The SPI boot ROM loader initializes the SPI module to interface to a serial SPI EEPROM.
Devices of this type include, but are not limited to, the Microchip M95080 (1K x 8), the
Xicor X25320 (4Kx8) and Xicor X25256 (32Kx8). At the Peripheral Explorer Board, the
interface SPI-A is used for the control channel of the audio codec AIC23B, so we cannot
experiment directly with the SPI-A boot loader. To do so, we would have to add an external
EEPROM to the hardware. Again, ask you teacher, if your university classroom equipment
has been enhanced.
An SPI boot loader is widely used in real world projects. Therefore let us discuss the
software flow.
The SPI boot ROM loader initializes the SPI with the following settings: FIFO enabled, 8-bit
character, internal SPICLK master mode and talk mode, clock phase = 0, polarity = 0 and
slowest baud rate.
If the download is to be preformed from an SPI port on another device, then that device must
be set up to operate in slave mode and mimic a serial SPI EEPROM. Immediately after
entering the SPI Boot function, the pin functions for the SPI pins are set to primary function
and the SPI is initialized. The initialization is done at the slowest speed possible. Once the

F2833x - Boot ROM 15 - 21


SPI Boot Loader

SPI is initialized and the key value read, the user could specify a change in baud rate or low
speed peripheral clock.

SPI Boot Loader Data Stream

The following slide (Slide 15-18) shows the sequence of 8-bit data expected by the Boot
Loader.

F2833x SPI Boot Loader Data Stream

Byte Content
1 LSB = 0xAA ( Key for 8bit transfer)
2 MSB = 0x08 ( Key for 8bit transfer)
3 LSB = LSPCLK value
4 MSB = SPIBRR value
5-18 reserved
19 Entry Point [23:16]
20 Entry Point [31:24]
21 Entry Point [7:0]
22 Entry Point [15:8]
23 ... Blocks of data: block size/destination/data as shown

15 - 18

SPI Boot Loader Flowchart


The flowchart is shown in Slide 15-18 and Slide 15-19. The data transfer is performed in
“burst” mode from the serial SPI EEPROM. The transfer is carried out entirely in byte mode
(SPI at 8 bits/character). A step-by step description of the sequence now follows:

1) The SPI-A port is initialized


2) The GPIO19 pin is now used as a chip-select for the serial SPI EEPROM

15 - 22 F2833x - Boot ROM


SPI Boot Loader

3) The SPI-A outputs a read command to the serial SPI EEPROM


4) The SPI-A interface sends the serial SPI EEPROM address 0x0000; that is,
the host requires that the EEPROM must have the downloadable package
starting at internal address 0x0000 of the EEPROM.
5) The next word fetched must match the key value for an 8-bit data stream
(0x08AA). The most significant byte of this word is the byte read first and
the least significant byte is the next byte fetched. This is true of all word
transfers on the SPI. If the key value does not match then the load is aborted
and the entry point for the Flash (0x3F 7FF6) is returned to the calling
routine.
6) The next two bytes fetched can be used to change the value of the low speed
peripheral clock register (LOSPCP) and the SPI Baud rate register
(SPIBRR). The first byte read is the LOSPCP value and the second byte read
is the SPIBRR value. The next seven words are reserved for future
enhancements. The SPI boot loader reads these seven words and then
discards them.
7) The next two words makeup the 32-bit entry point address where execution
will continue after the boot load process is complete. This is typically the
entry point for the program being downloaded through the SPI port.
8) Multiple blocks of code and data are then copied into memory from the
external serial SPI EEPROM through the SPI port. The blocks of code are
organized in the standard data stream structure presented earlier. This is
done until a block size of 0x0000 is encountered. At that point in time, the
entry point address is returned to the calling routine that then exits the boot
loader and resumes execution at the address specified.

F2833x - Boot ROM 15 - 23


SPI Boot Loader

F2833x SPI Boot Function


SPI - Boot
Read KeyValue

Enable SPI clock


Set LSPCLK to 4
Valid No
FLASH
Enable SPI pin – Key?
functionality ( 0x08AA
Yes
)
Read LSPCLK value
Setup SPI:
8-bit character
Internal SPI-clock
SPI-Master
Slowest baud rate (0x7F) No
Requested
Relinquish from RESET
LSPCLK =
2?
Set chip enable
GPIO-F3 = 1 Yes Change LSPCLK

Send Read Command


To EEPROM
Address = 0x0000
C
15 - 19

F2833x SPI Boot Function (cont.)


C

Read SPIBRR value

Requested No
SPIBRR =
0x7F?

Change SPIBRR
Yes

Read 7 reserved words

Read Entry Point Read Data Blocks Jump EntryPoint

15 - 20

15 - 24 F2833x - Boot ROM


Lab 15_1: Serial Boot Loader SCI-A

Lab 15_1: Serial Boot Loader SCI-A


Objective

The objective of this laboratory exercise is to practice using the F2833x internal serial boot
loader options. In Chapter 9 we discussed the SCI-interface of the F2833x and experimented
with some transmit and receive laboratory examples. Let us now use the SCI-A interface to
download control code on power ON from a host into the internal RAM of the F2833x and
execute this code after the download is completed. This is a typical scenario for distributed
control systems, in which a master-node sends control code to slave-nodes.

Lab15_1: SCI – A boot loader


• Use Lab6 (“binary counter”) as starting point
• Change the Hardware Boot Sequence from FLASH to
SCI -A (close Jumper J3)

• Use a SCI – connection to your PC:

• Use tool “hex2000.exe” to generate download stream


• Use a PC terminal program to download code
15 - 21

Again we will use our solution from Lab 6, the binary counter at LEDs LD1…LD4, as a
starting point.

Procedure

Open Project
1. Open your project “Lab6.pjt” from C:\DSP2833x_V4\Labs\Lab6.
2. Open the file “Lab6.c”, save it in “C:\DSP2833x_V4\Labs\Lab6” as “Lab15.c”.
3. Exclude file “Lab6.c” from Build
4. Open the file “Lab15.c” to edit.

F2833x - Boot ROM 15 - 25


Lab 15_1: Serial Boot Loader SCI-A

Although there is no need to change the control code of Lab15.c, we should generate a
considerably slower frequency for the control code. Remember, that in Lab14 we have
programmed the binary counter code, running at 100 milliseconds time steps into the
FLASH of the F2833x. Now, to be able to distinguish between the FLASH-code
(which should not be active in Lab15) and the RAM-downloaded code, the simplest
way is to change the step size of our control code from 100 milliseconds to 1 second.
Also, recall that the watchdog unit is active. In “main()”, change the code-section to
wait for the next control step into:

while(CpuTimer0.InterruptCount < 10)


{
EALLOW;
SysCtrlRegs.WDKEY = 0x55; // service WD #1
EDIS;
}
CpuTimer0.InterruptCount = 0;

Build, Load and Run


5. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

6. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

7. Perform a real time run.

Target  Run

Verify that the control code (binary counter at LD1…LD4) is now running at a step size of 1
second. If this is true, we have a working code example, which can be used to extract the
necessary download modules.
Verify that the file “Lab6.out” exists in subdirectory ‘\Debug’, and that it is up to date.

Change Hardware set up


8. Close Code Composer Studio and switch off the power supply of the Peripheral
Explorer Board.
9. Close jumper J3 (“SCI-BOOT 84”) at the Peripheral Explorer Board. This will select
the SCI-A boot loader option of the F2833x.

15 - 26 F2833x - Boot ROM


Lab 15_1: Serial Boot Loader SCI-A

10. Connect the Peripheral Explorer Board SCI-A (header J12) with a serial COM-channel
of your PC. Plug in the serial cable provided to header J12 making sure the red wire
aligns with the Rx pin on the peripheral explorer kit.

11. Re-power ON the Peripheral Explorer Board. The binary counter code at LEDs
LD1…LD4 should not run.

Generate download data stream


12. Texas Instruments provides a very useful tool, called “hex2000.exe”, to convert data
from COFF-format (“Lab6.out”) into any other format, including binary images, Intel-
hex file format and many others. We can use this tool to generate the data stream
accordingly to the serial download format, which we discussed at the beginning of this
chapter. Unfortunately, this tool is available as a command line version only. If you
recall the old days from Microsoft-DOS, you should be familiar with the command
line window control. As a modern-day student, you are probably too young for such
cryptic syntax, so here is an explanation of what to do:

• In Windows-XP or Windows-Vista, open a command line window (“cmd.exe”).


• In this window, enter the path to the location of file “Lab6.out”. The actual path
depends on your PC-installation. Note: use the Windows-Explorer to locate the
location on your PC. On my computer it is:
cd C:\DSP2833x_V4\labs\Lab6\Debug

F2833x - Boot ROM 15 - 27


Lab 15_1: Serial Boot Loader SCI-A

• To start the “hex2000” - tool, first search the harddisk location of the file
“hex2000.exe”

• Next, using the Windows Explorer, copy the file “hex2000.exe” into the direc-
tory of your project, e.g. C:\DSP2833x_V4\labs\Lab6\Debug.

• Now enter the following command as a single line into the command window:
hex2000 -b -boot -sci8 -e=codestart -o=test.bin Lab6.out

Here is an explanation of what we did:


The tool “hex2000.exe” used the input file “Lab6.out” to generate a new output file
“test.bin”. Both the name “test” and extension “bin” are arbitrary and used just as examples.
The switch “-b” told the tool to perform a binary extraction. The switches “-boot” and “-
sci8” have been used to generate a file structure according the boot loader sequence for SCI-
mode. The option “-e =codestart” has been used to specify the start address after the
download sequence is completed. We used the symbol “codestart” from file
“DSP2833x_CodeStartBranch.asm”.
The screenshot above tells us that the tool has generated binary sections for

• the codestart - section (codestart)

15 - 28 F2833x - Boot ROM


Lab 15_1: Serial Boot Loader SCI-A

• the default machine-code section (.text)


• a section for functions with different Load and Run-addresses (ramfuncs)
• a section for global initialization constants (.cinit)
• a section for constant variables (.econst)
Verify, that you have a new file “test.bin” in your “Debug”-directory!

Download Image into the target


13. For this step we need a serial terminal program running under windows. If you still
use XP, you can use the program “Windows-HyperTerminal”. Under Windows-Vista,
there is no such a tool. However, there are a few similar freeware tools available, such
as “Hercules” (www.HW-group.com)
• Open your terminal program and enter the following initial parameters:
o 9600 bit/s
o 8 data bits
o no parity bit
o 1 stop bit
o no hardware handshake or flow control
Here is an example for “Hercules”:

• Next, send a single character ‘A’, which is used for auto baud rate detection in
the serial boot loader code of the F2833x. The F2833x will immediately respond
with an echo of ‘A’ to indicate successful auto baud rate detection.

F2833x - Boot ROM 15 - 29


Lab 15_1: Serial Boot Loader SCI-A

• Finally, send the file “test.bin” to the F2833x. Right mouse click in “Hercules”,
select “Send File” and browse to the location of “test.bin”. Do not worry about
the strange output, the F2833x echoes back all bytes and since we are
transmitting a binary image, only a few of them are printable:

• At the end of the download sequence, the boot-loader code will branch directly
into the code entry point “codestart”; our downloaded control code is running!

END of Lab15_1

15 - 30 F2833x - Boot ROM


F2833x FLASH - API

Introduction
In Chapter 14 we discussed the option to start our embedded control program directly from
the F2833x internal Flash memory. Another important task of a real-world project is to
update parts of the internal FLASH whilst the control code is still running in FLASH
memory.
Texas Instruments provides an “Application Programmers Interface” (API) - library for such
purposes. The API is free for download from Texas Instruments website (www.ti.com).
There are different versions of this library, depending on the type of device. For the F2833x,
the literature number is “SPRC539” and for the F2823x it can be found under “SPRC665”.
For the laboratory exercise at the end of this chapter it is necessary that you have installed
the correct library on your PC. The default installation path is either:
C:\tidcs\c28\Flash28_API\Flash28335_API_V210\ or
C:\tidcs\c28\Flash28_API\Flash28332_API_V210
If the library is not already present on your PC, download the corresponding latest archive
file from the website, unzip and install it on your PC.
Here is a block diagram that shows the execution flow, when FLASH - API - algorithms are
involved. Method “C” shows the embedded code solution, which we will discuss and
perform a lab exercise later in this chapter.

F2833x - FLASH - API 16 - 1


Module Topics

Module Topics
F2833x FLASH - API ...................................................................................................................... 16-1
Introduction ................................................................................................................................... 16-1
Module Topics ............................................................................................................................... 16-2
F2833x FLASH - API Installation ................................................................................................. 16-3
F2833x FLASH API Fundamentals ............................................................................................... 16-4
Erase ......................................................................................................................................... 16-4
Program..................................................................................................................................... 16-5
Verify ........................................................................................................................................ 16-5
General Guidelines ....................................................................................................................... 16-6
FLASH - API Checklist ................................................................................................................. 16-7
Step1: Modify Flash2833x_API_Config.h ............................................................................... 16-8
Step 2: Include Flash2833x_API_Library.h ............................................................................. 16-8
Step 3: Include the appropriate Flash API library ..................................................................... 16-9
Step 4: Initialize PLL Control Register (PLLCR) ..................................................................... 16-9
Step 5: Check PLL Status for Limp Mode Operation ............................................................... 16-9
Step 6: Copy the Flash API functions to Internal SARAM .................................................... 16-10
Step 7: Initialize Flash_CPUScaleFactor ................................................................................ 16-10
Step 8: Initialize the Callback Function Pointer...................................................................... 16-10
F2833x FLASH - API Reference ................................................................................................. 16-11
Data Type Conventions........................................................................................................... 16-11
API Function Naming Conventions ........................................................................................ 16-11
FLASH - API - Functions ....................................................................................................... 16-12
Files included with the API..................................................................................................... 16-12
Lab 16: Use of FLASH - API...................................................................................................... 16-13
Objective ................................................................................................................................. 16-13
Procedure ................................................................................................................................ 16-14
Open Project ........................................................................................................................... 16-14
Build project ........................................................................................................................... 16-18
Verify Linker Results - The map - File ................................................................................... 16-18
Use CCS integrated Flash Program Tool ................................................................................ 16-19
Close CCS & Restart the Peripheral Explorer Board .............................................................. 16-20

16 - 2 F2833x - FLASH - API


F2833x FLASH - API Installation

F2833x FLASH - API Installation


The F2833x FLASH - API function library can be downloaded free of charge from the Texas
Instruments website. It supports FLASH programming via embedded function calls, as
shown as path ‘C’ in Slide 16-2. All functions can be integrated into the code of an existing
project.

TMS320F2833x FLASH Load Options

16 - 2

FLASH – API - Installation

1. Download from: www.ti.com:


• F2833x: “SPRC539”
• F2823x: “SPRC665”

2. Default Installation path:


• C:\tidcs\c28\FLASH28_API\

3. Read included documentation


• “Flash2833x_API_Readme.pdf”

16 - 3

F2833x - FLASH - API 16 - 3


F2833x FLASH API Fundamentals

F2833x FLASH API Fundamentals


The Flash Application Program Interface (Flash API) consists of functions that the client
application calls to perform flash specific operations. The flash array and One Time Pro-
grammable (OTP) block on the device are managed via CPU execution of algorithms in the
Flash API library. Texas Instruments provides API functions to erase, program and verify the
flash array as briefly described here:

FLASH – API – Fundamentals


Erase:
• Pre - Compact
• ensure that no bits are over erased
• Pre – Condition
• set all bits to ‘0’ to allow an even erase
• Erase
• set all memory bits to ‘1’ ( = Erased state)
• Post – Conditioning
• ensure that no bits are left in “over – erased”
Program:
• program selected bits from ‘1’ to ‘0’

Verify:
• CPU read to compare FLASH and image

16 - 4

Erase
Erase operates on the flash array only. The One Time Programmable (OTP) block cannot be
erased once it has been programmed. The Erase function is used to set the flash array con-
tents to all 1’s (0xFFFF). The erase operation includes the following steps:
• Pre-compact all sectors. This step is to make sure no bits are in an over-erased or
“depleted” state before attempting the sector erase. Depletion can occur as a result of
stopping the erase function before its post-condition or compaction step can com-
plete. Even with this step, halting the erase function before it completes is not rec-
ommended.
• Pre-condition or “clear” the sector to be erased. This step programs all of the bits in
the sector to 0 to allow for an even erase across the sector.
• Erase the sector. This step removes charge from the bits in the sector until all of the
bits within the sector are erased.
• Post-condition or compact the sector that was erased. This step makes sure no bits
are left in an over-erased (or depleted) state.

16 - 4 F2833x - FLASH - API


F2833x FLASH API Fundamentals

The smallest amount of memory that can be erased at a particular time is a single sector.
Some traditional algorithms, such as those for the 240x family, require that the flash be pre-
conditioned or “cleared” before it is erased. The Flash API erase function for the F2833x
includes the flash pre-conditioning and a separate “clear” step is not required.

The flash array and OTP block are in an erased state (all 0xFFFF) when the device is shipped
from the factory.

Program

The program function operates on both the flash array and the OTP block. This function is
used to put application code and data into the flash array or OTP. The program function can
only change bits from a 1 to a 0. Bits cannot be moved from a 0 back to a 1 by the program-
ming function. For this reason, flash is typically in an erased state (all 0xFFFF) before call-
ing the programming function. The programming function operates on a single 16-bit word
at a time.

To protect the flash or OTP and allow for user flexibility, the program operation will not at-
tempt to program any bit that has previously been programmed. For example, a flash or OTP
location can be programmed with 0xFFFE and later the same location can be programmed
with 0xFFFC without going through an erase cycle. During the second programming call, the
program operation will detect that bit 0 was already programmed and will only program bit
1.

Verify
The erase and program functions perform verification with voltage margin as they execute.
The verify function provides a second check via a CPU read that can be run to verify the
flash contents against the reference value. The verify function operates on both the flash ar-
ray and OTP blocks.

To integrate one of the Flash APIs into your application you will need to follow the steps
described in this chapter.

For a detailed description of all API - functions please refer to document “FLASH
2833x_API_Readme.pdf” (part of SPRC539.zip).

F2833x - FLASH - API 16 - 5


General Guidelines

General Guidelines
Here is a list of general rules that should be followed, when using the FLASH - API:
1. Install the latest and correct version of the FLASH - API. For the F28335, the literature
number is “SPRC539”. The default location of the package is:
“C:\tidcs\c28\Flash28_API”.
2. Execute the Flash API code from zero-wait state internal SARAM memory.
3. Configure the API for the correct CPU frequency of operation.
4. Follow the Flash API checklist in section 5 of “FLASH 2833x_API_Readme.pdf” to
integrate the API into an application.
5. Initialize the PLL control register (PLLCR) and wait for the PLL to lock before calling
an API function.
6. Initialize the API callback function pointer (Flash_CallbackPtr). If the callback function
is not going to be used then it is best to explicitly set the function pointer to NULL.
Failure to initialize the callback function pointer can cause the code to branch to an
undefined location. Carefully review the API restrictions for the callback function,
interrupts, and watchdog described in Section 15 of “FLASH 2833x_API_Readme.pdf”.
There is also a list what should be not done:
7. Do not execute the Flash APIs from the flash or OTP. If the APIs are stored in flash or
OTP memory, they must first be copied to internal SARAM before they are executed.
8. Do not execute any interrupt service routines (ISRs) that can occur during an erase, pro-
gram or depletion recovery API function from the flash or OTP memory blocks. Until
the API function completes and exits the flash and OTP are not available for program
execution or data storage.
9. Do not execute the API callback function from flash or OTP. When the callback function
is invoked by the API during the erase, program or depletion recovery routine the flash
and OTP are not available for program execution or data storage. Only after the API
function completes and exits do the flash and OTP become available.
10. Do not stop the erase, program or depletion recovery functions while they are executing
(for example, do not stop the debugger within API code, do not reset the part, etc).
11. Do not execute code or fetch data from the flash array or OTP while the flash and/or
OTP is being erased, programmed or during depletion recovery.

Sounds pretty complicated, doesn’t it? Well, since we are students we can keep it simple
(first). Later, when we have a functional framework, we can implement a more detailed solu-
tion.

16 - 6 F2833x - FLASH - API


FLASH - API Checklist

FLASH - API Checklist


Here is the sequence of steps required to use parts of the FLASH - API Library code:

FLASH – API Checklist

Project Preparation:
1. Modify file “Flash2833x_API_Config.h”
2. Include Flash2833x_API_Library.h in source – code
3. Add FLASH-API – library to your project

Source - Code Modification:


4. Initialize PLL and wait for lock
5. Make sure, that PLL is not in “limp” – mode
6. Copy all API – functions from FLASH into SARAM
7. Initialize global variable “Flash_CPUScaleFactor”
8. Initialize callback – pointer “Flash_CallbackPtr”
9. Call API - functions

16 - 5

A called API - Function will perform the following actions:

FLASH – API function

A called FLASH – API – function will perform:

1. A disable of the Watchdog – Timer


2. A check of the registers CLASSID/PARTID
• Addresses 0x0882 and 0x380090)
3. A check of the content of 0x3FFFB9
• API – version versus silicon - revision
4. Start of the selected operation and:
• Disables and restores interrupts around time critical sections
• Invokes the callback – function
5. It returns an success - or error code

16 - 6

F2833x - FLASH - API 16 - 7


FLASH - API Checklist

Step1: Modify Flash2833x_API_Config.h


Modify file “Flash2833x_API_Config.h” to be found in the include directory of each API, to
match your specific target. Set the corresponding line to ‘1’:

#define FLASH_F28335 1
#define FLASH_F28334 0
#define FLASH_F28332 0

Uncomment the line corresponding to the CPU Clock rate (SYSCLKOUT) in nanoseconds at
which the API functions will run. This is done by removing the leading // in front of the re-
quired line. Only one line should be uncommented. The file lists a number of commonly oc-
curring clock rates. If your CPU clock rate is not listed, then provide your own definition
using the examples as a guideline.
For example: Suppose the final CPU clock rate will be 150 MHz. This corresponds to a
6.667 ns cycle time. If there is no line present for this clock speed, so you should insert your
own entry and comment out all other entries:

#define CPU_RATE 6.667L // for a 150MHz


SYSCLKOUT
//#define CPU_RATE 10.000L // for a 100MHz
SYSCLKOUT
//#define CPU_RATE 13.330L // for a 75MHz
SYSCLKOUT
//#define CPU_RATE 20.000L // for a 50MHz
SYSCLKOUT
//#define CPU_RATE 33.333L // for a 30MHz
SYSCLKOUT
//#define CPU_RATE 41.667L // for a 24MHz
SYSCLKOUT
//#define CPU_RATE 50.000L // for a 20MHz
SYSCLKOUT
//#define CPU_RATE 66.667L // for a 15MHz
SYSCLKOUT
//#define CPU_RATE 100.000L // for a 10MHz
SYSCLKOUT

The CPU clock rate is used during the compile phase to calculate a scale factor for your op-
erating frequency. This scale factor will be used by the Flash API functions to properly scale
software delays that are VITAL to the proper operation of the API. The formula found at the
bottom of the Flash2833x_API_Config.h file provides this calculation:

#define SCALE_FACTOR 1048576.0L*( (200L/CPU_RATE) ) // IQ20

Step 2: Include Flash2833x_API_Library.h


The file “Flash2833x_API_Library.h” is the main include file for the Flash API and should
be included in any application source - code file that interfaces to the Flash API.

#include "FLASH2833x_API_Library.h"

16 - 8 F2833x - FLASH - API


FLASH - API Checklist

Also, include the search path to this header - file into the project C/C++ build options. In the
“C/C++” perspective, right click on the active project, select “properties”, C2000 compiler,
Include Options and add:

C:\tidcs\c28\Flash28_API\Flash28335_API_V210\include

Step 3: Include the appropriate Flash API library


The appropriate Flash API library must also be linked to your project.

By default, the symbol “ <>” stands for “C:\tidcs\c28”

F28335: <>\Flash28_API\Flash28335_API_V210\lib\Flash28335_API_V210.lib
F28334: <>\Flash28_API\Flash28334_API_V210\lib\Flash28334_API_V210.lib
F28332: <>\Flash28_API\Flash28332_API_V210\lib\Flash28332_API_V210.lib

The Flash APIs have been compiled with the large memory model (-ml) option. The small
memory model option is not supported. For information on the large memory model refer to
the TMS320C28x Optimizing C/C++ Compiler User’s Guide (literature #SPRU514).

The F2833x Flash APIs have been compiled using the “--float_support=fpu32” floating point
option. Only object files compiled as such can be linked to the APIs.

Step 4: Initialize PLL Control Register (PLLCR)


It is vital that the API functions be run at the correct clock frequency. To achieve this, the
calling application must initialize the PLLCR register before calling any of the API func-
tions. To change the PLLCR, follow the flow outlined in the device appropriate System Con-
trol and Interrupts Reference Guide. Following this flow is important in order to make sure
that the PLL is not operating in limp mode before changing the PLLCR register. As part of
this initialization, the calling application must guarantee that the PLL has had enough time to
lock to the new frequency before making API calls. To do this the application can monitor
the PLLLOCKS bit in the PLLSTS register. When this bit is set it indicates that the PLL has
completed locking and the CPU is running at the specified frequency.

The best way to follow these requirements for setting up the PLL is to call function “Init-
SysCtrl()”, provided by Texas Instruments in file “DSP2833x_SysCtrl.c”.

Step 5: Check PLL Status for Limp Mode Operation


The API functions contain time-critical code with software delay loops that must execute to
meet specific timing requirements. For this reason, the device must be operating at the cor-
rect CPU frequency before the Flash API functions are called. If the input clock to the device
has gone missing, the PLL will enter what is called limp mode operation and the CPU will be
clocked at a much lower frequency. When this happens the device is reset and the
MCLKSTS bit will be set in the PLLSTS register. If this bit is set, the API functions should
not be called.

F2833x - FLASH - API 16 - 9


FLASH - API Checklist

Refer to the device appropriate TMS320x2833x System Control and Interrupts Reference
Guide for more information on the missing clock detection logic of the F2833x devices.

Step 6: Copy the Flash API functions to Internal


SARAM
If the Flash API functions are stored in flash or OTP, then the calling application must first
copy the required code into SARAM before making any calls into the API. The following
sequence describes how to accomplish this copy:

• Link the linker command file “F28335.cmd” to your project


• This linker command file defines 3 symbols:
o Load address start: Flash28_API_LoadStart
o Load address end: Flash28_API_LoadEnd
o Run address start: Flash28_API_RunStart
• Use the symbols in a copy loop, such as:
Uint16 * pSourceAddr;
Uint16 * pDestAddr;
Uint16 i;
pSourceAddr = &Flash28_API_LoadStart;
pDestAddr = &Flash28_API_RunStart;
for(i=0;i<(&Flash28_API_LoadEnd- &Flash28_API_LoadStart);
i++)
{
*pDestAddr++ = *pSourceAddr++;
}

Step 7: Initialize Flash_CPUScaleFactor


“Flash_CPUScaleFactor” is a global 32-bit variable defined by the Flash API functions. The
Flash API functions contain several delays that are implemented as software delays. The cor-
rect timing of these software delays is vital to the proper operation of the API functions. The
32-bit global variable “Flash_CPUScaleFactor” is used by the API functions to properly
scale these software delays for a particular CPU operating frequency (SYSCLKOUT).

Flash_CPUScaleFactor = SCALE_FACTOR;

Step 8: Initialize the Callback Function Pointer


A callback function is one that is not invoked explicitly by the user’s application; rather the
responsibility for its invocation is delegated to the API function by way of the callback func-
tion's address. The callback function can be used whenever the application must process cer-
tain information itself at some time in the middle of the execution of an API function. For
example, if the system has an external watchdog that must be serviced or if status needs to be
sent by way of a communications port, this can be done by the user inserting code within the
callback function.

16 - 10 F2833x - FLASH - API


The variable “Flash_CallbackPtr” is global function pointer used to specify the callback
function to be used by the Flash API. The Flash API functions will call the callback function
at safe times during the program, erase, verify and depletion recovery algorithms. To use the
callback function, the calling application must first initialize the function pointer
Flash_CallbackPtr before calling any API function. If the callback feature is not going to
be used, then set the pointer to NULL. When Flash_CallbackPtr is NULL the API will not
make a call to any function.

Flash_CallbackPtr = NULL;

F2833x FLASH - API Reference


Data Type Conventions
The following data type definitions are defined in Flash2833x_API_Library.h:
#ifndef DSP28_DATA_TYPES
#define DSP28_DATA_TYPES
typedef int int16;
typedef long int32;
typedef long long int64;
typedef unsigned int Uint16;
typedef unsigned long Uint32;
typedef unsigned long long Uint64;
typedef float float32;
typedef long double float64;
#endif

API Function Naming Conventions


The F2833x API function names are of the following form:

Flash<device>_<operation>(args)

Where
<device> is 28335, 28334, 28332
<operation> is the operation being performed such as Erase, Program, Verify

For example:
Flash28335_Program(args)

is the F28335 Program function.

The API function definitions for the F2833x API libraries are compatible. For this reason the
file
Flash2833x_API_Library.h includes macro definitions that allow a generic function call to
be used in place of the device specific function call.

Flash_<operation>(args)

F2833x - FLASH - API 16 - 11


F2833x FLASH - API Reference

The use of these macros is optional. They have been provided to allow easy porting of code
between the devices.

FLASH - API - Functions


The following API - Functions are available:

Generic Function F28335 API Function


Flash_ToggleTest Flash28335_ToggleTest
Flash_Erase Flash28335_Erase
Flash_Program Flash28335_Program
Flash_Verify Flash28335_Verify
Flash_DepRecover Flash28335_DepRecover
Flash_APIVersion Flash28335_APIVersion
Flash_APIVersionHex Flash28335_APIVersionHex

All functions use a structure “FLASH_ST”. This structure is used to pass information back
to the calling routine by the Program, Erase and Verify API functions. This structure is de-
fined in Flash2833x_API_Library.h:

typedef struct {
Uint32 FirstFailAddr;
Uint16 ExpectedData;
Uint16 ActualData;
}FLASH_ST;

For the parameter list of all API - functions please refer to the documentation file
“Flash2833x_API_Readme.pdf”.

Files included with the API


In a typical installation, <base> = c:\tidcs\c28\Flash28_API

API Library:
<base>\Flash28335_API_V210\lib\Flash28335_API_V210.lib

API Include Files:


<base>\Flash28335_API_V210\include\Flash2833x_API_Library.h
<base>\Flash28335_API_V210\include\Flash2833x_API_Config.h

Documentation:
< base >\Flash28335_API_V210\doc

Example:
< base >\Flash28335_API_V210\example

16 - 12 F2833x - FLASH - API


Lab 16: Use of FLASH - API

Lab 16: Use of FLASH - API


Objective
The objective of this laboratory exercise is to practice using the F2833x FLASH - API
library. Here is what we will do:

• We will run a small amount of control code direct from FLASH - A. The main - loop
of this control code will permanently read a data memory variable
“FLASH_Voltage_A0“, located in FLASH - section B, and display the four most
significant bits (bit 11…bit 8) of “FLASH_Voltage_A0” on four LEDs
(LD4…LD1).

Lab16: Use of FLASH – API


• Run stand alone control code from FLASH – A
• “main()” - loop reads value “FLASH_Voltage_A0” from
FLASH-B and display the four most significant bits at LEDs
LD4…LD1.

• CPU – Timer 0 will start an ADC conversion of channel


ADCINA0 (potentiometer VR1) each 50 milliseconds.

• The ADC interrupt service will store the result of the


conversion in SARAM - variable “Voltage_A0”

• If button PB1 is pushed, FLASH – B variable


“FLASH_Voltage_A0” is updated with “Voltage_A0”
using FLASH – API functions “Erase”, “Program” and
“Verify”.
16 - 7

• ADC channel ADCINA0, started by CPU - Timer 0 every 50 milliseconds, will


convert the value from potentiometer “VR1” of the Peripheral Explorer Board into a
local 12 - bit - variable “Voltage_A0”. The CPU-Timer 0 - Interrupt service will
perform the software - start of the ADC; the ADC - Interrupt service will update
“Voltage_A0”

• If we push button “PB1” of the Peripheral Explorer Board, we start another part of
the control code. We will call our function “Update_FLASHB()” to update the
FLASH-B - variable “FLASH_Voltage_A0“ with the current value from
“Voltage_A0”. This function includes some API - Function calls from the Texas
Instruments FLASH-API.

F2833x - FLASH - API 16 - 13


Lab 16: Use of FLASH - API

• After a successful update of FLASH-B, our code will perform a warm reset to re-
start the code. To do so, you have to set the boot-sequence to “Boot to FLASH”. On
the “Peripheral Explorer Board”, make sure that jumper J3 (“SCI_BOOT 84) is
open!

• Note: The provided test function “Update_FLASHB()” is intended to be used in


experimental student laboratories only, it does not cover error - handling or timeout
monitoring. For a real product version you can easily extend the functionality of this
example; all code sequences are based on Texas Instruments API - Functions. To
keep the first example simple, we will use basic API - features only.

Procedure

Open Project
1. For convenience, open the project “Lab16.pjt” from C:\DSP2833x_V4\Labs\Lab16. If
you create your own project, you have to add the provided files from
C:\DSP2833x_V4\Labs\Lab16 manually.
2. From “C:\DSP2833x_V4\Labs\Lab14” open the file “Lab14.c”, save it in
“C:\DSP2833x_V4\Labs\Lab16” as “Lab16.c” and add “Lab16.c” to your project.
3. Open the file “Lab16.c” to edit.

• At the beginning of “Lab16.c”, add two macros to define the push-buttons PB1
and PB2:
#define START GpioDataRegs.GPADAT.bit.GPIO17 // Button PB1
#define STOP GpioDataRegs.GPBDAT.bit.GPIO48 // Button PB2

• Also at the beginning of “main()”, add an external function prototype for


function “Update_FLASHB()”. This function is defined in file
“Lab16_FLASH_API.c”, which will be inspected shortly. Add:
extern void Update_FLASHB(int);

• Since we will use the ADC, we will also call function “InitAdc()”, which is
defined in the file “DSP2833x_ADC.c”. Add a 2nd additional external function
prototype:
extern void InitAdc(void);

• Third, add another external function prototype:


extern void display_ADC(unsigned int);
This function, defined in the provided source code file “Display_ADC.c”, will
be used to convert the four most significant bits of an input value into a “light-
beam” at the four LEDs LD1…LD4.

• Next, add a prototype for the local ADC interrupt service routine. Add:
interrupt void adc_isr(void);

• Finally add two global variables:

16 - 14 F2833x - FLASH - API


Lab 16: Use of FLASH - API

unsigned int Voltage_A0;


extern unsigned int FLASH_Voltage_A0;
The variable “FLASH_Voltage_A0” is already defined in the file
“Lab16_FLASH_DATA.c”; therefore we need the “extern” keyword.
4. Edit function “main()” of file “Lab16.c”:

• Delete the variable “counter” and the code in the endless while(1)-loop of
“main()”, which is related to “counter”.

• Next, add a line to re-load the entry for the ADC in the PIE -vector table with
the name of our own interrupt service function. Search for line of code, which
we used to reload TINT0 and add:
PieVectTable.ADCINT = &adc_isr;

• Change the function call to “ConfigCpuTimer()” from a 100 milliseconds to a 50


milliseconds period.

• After the function call to “ConfigCpuTimer()”, add a new call to the function
“InitAdc()”. This function, provided by Texas Instruments, will switch the ADC
- module to a default standby mode. Add:
InitAdc();

• Next, add the initialization for the ADC sequencer unit.


For register “ADCTRL1”:
o set acquisition window to 8 clocks (ACQ_PS)
o set clock prescaler CPS to “divide by 1”
o select single run mode (CONT_RUN)
o select cascaded mode (SEQ_CASC)
For register “ADCTRL2”:
o enable interrupt (INT_ENA_SEQ1)
For register “ADCCTRL3”:
o Set bit fields “ADCCLKPS” to select HSPCLK / 8
Set “MAXCONV” to convert 1 channel
Set channel selector “CONV00” to convert ADCINA0

• Next, add a line to enable also PIE-interrupt 1.6 (ADC). Note: PIE-interrupt 1.7
(Timer 0) is also active; keep its enable command line in your code. Add:
PieCtrlRegs.PIEIER1.bit.INTx6 = 1;

F2833x - FLASH - API 16 - 15


Lab 16: Use of FLASH - API

5. Edit the endless while(1) - loop of function “main()”:

• At the beginning of this loop, add a call to the function “display_ADC(0);”. This
will switch OFF all four LEDs LD1…LD4.

• Next, wait for 100 milliseconds

• Next update the LEDs by a 2nd function call


“display_ADC(FLASH_Voltage_A0);”. This will update the LEDs with the
value from the global variable “FLASH_Voltage_A0”

• Next, wait for another 100 milliseconds, before you clear the Timer 0 interrupt
counter and before you service the watchdog. The whole new code snippet looks
like:
display_ADC(0);
while(CpuTimer0.InterruptCount < 2);
display_ADC(FLASH_Voltage_A0);
while(CpuTimer0.InterruptCount < 4);
CpuTimer0.InterruptCount = 0;
EALLOW;
SysCtrlRegs.WDKEY = 0x55;
EDIS;

• Finally, we have to add code that samples button “PB1”. In the event of an
active button (pushed down = 0), we have to call our FLASH re-programming
function “Update_FLASHB(Voltage_A0)”. After returning from this call, the
new data values are programmed into FLASH and we have to start the F2833x
with a reset. The question is: how can we cause a reset by an instruction? One
answer is: the watchdog control register does the trick. If we intentionally violate
the watchdog control register security bits (WDCHK2…0) by writing 000 into
this bit-field, we cause a reset. The whole code snippet look like this:
if (START == 0) // START Button is pressed down (zero)
{
Update_FLASHB(Voltage_A0);
EALLOW;
SysCtrlRegs.WDCR = 0; // force a “warm” - RESET
while(1); // line is never reached
}

6. Change CPU - Timer 0 Interrupt Service Routine


When we enter the FLASH - API functions, the hardware interrupts are still active and
must be serviced. The problem is that we cannot execute code from FLASH, when we
re-program it. This includes the Interrupt Service Functions. The solution is to copy
the ISRs from FLASH to RAM at the beginning of the code execution. We have used
a similar principle for function “InitFlash()”. All we need is a connection of the RAM
runtime functions to section “ramfuncs”. In front of function “cpu_timer0_isr()”, add:
#pragma CODE_SECTION(cpu_timer0_isr, "ramfuncs");
To start the ADC, add a line in the function “cpu_timer0_isr()” to force a software
start:
AdcRegs.ADCTRL2.bit.SOC_SEQ1 = 1; // start ADC by SW
16 - 16 F2833x - FLASH - API
Lab 16: Use of FLASH - API

At the end of “Lab16.c” add a new interrupt function “adc_isr()”.


Again, use a pragma - statement to assign this function to a RAM run - time location
#pragma CODE_SECTION(adc_isr, "ramfuncs");
In this function, read the ADC result, store it in the global variable “Voltage_A0” and
clear the ADC for the next conversion. The whole function is:
interrupt void adc_isr(void)
{
Voltage_A0 = AdcRegs.ADCRESULT0>>4;
AdcRegs.ADCTRL2.bit.RST_SEQ1 = 1; // Reset SEQ1
AdcRegs.ADCST.bit.INT_SEQ1_CLR = 1; // Clear INT SEQ1 bit
PieCtrlRegs.PIEACK.all = PIEACK_GROUP1; // Acknowledge PIE
}

7. Inspect and adjust the header file “Flash2833x_API_Config.h”. This file defines a few
macros. Make sure to have those macros active that correspond to your
F28335ControlCard. There are two versions out, a 20MHz (100MHz SYSCLKOUT)
and a 30MHz (150MHz SYSCLKOUT) version. The following snippet is for a
F28335 running at external 30MHz clock speed:
#define FLASH_F28335 1
#define FLASH_F28334 0
#define FLASH_F28332 0
#define CPU_RATE 6.667L // for a 150MHz CPU (SYSCLKOUT)
//#define CPU_RATE 10.000L // for a 100MHz CPU (SYSCLKOUT)

8. Inspect the provided file “Lab16_FLASH_DATA.c”. This file defines a new global
variable “FLASH_Voltage_A0”. The “DATA_SECTION” directive connects the
variable to a linker symbol “myFlashConstants”.
#ifdef __cplusplus
#pragma DATA_SECTION("myFlashConstants")
#else
#pragma DATA_SECTION(FLASH_Voltage_A0,"myFlashConstants");
#endif
volatile unsigned int FLASH_Voltage_A0;

9. Inspect the provided linker command file “Lab16.cmd”.


SECTIONS
{
myFlashConstants : > FLASHB PAGE =1
Flash28_API:
{
-lFlash28335_API_V210.lib(.econst)
-lFlash28335_API_V210.lib(.text)
} LOAD = FLASHD,
RUN = RAML0,
LOAD_START(_Flash28_API_LoadStart),
LOAD_END(_Flash28_API_LoadEnd),
RUN_START(_Flash28_API_RunStart),
PAGE = 0

F2833x - FLASH - API 16 - 17


Lab 16: Use of FLASH - API

First, this file connects the section “myFlashConstants” to physical FLASH-B memory
block (0x330000). Second, it connects section “Flash28_API” to a load address in
FLASH- D block (0x320000) and to run-address RAML0 (0x8000). It also defines
symbols “Flash28_API_LoadStart”, “Flash28_API_RunStart” and
“Flash28_API_LoadEnd”, which are used in the next source file (see procedure step
11). All memory blocks (FLASHB, FLASHD, and RAML0) are defined in the default
linker command file “F28335.cmd”.
10. Inspect the source code file “Lab16_FLASH_API.c”. This file is an example on how
to use the FLASH-API - functions. Note: Again, this is an example just for student
exercises and not for real production code. It does not cover any error situations, as
you can see in the rather sparse function “Error()” at the end of this file.
The function “Update_FLASHB()” basically performs the following steps:
(1) It checks, whether the F2833x is in “Limp”-Mode (clock has been lost). If
so, the function just returns (which is one point to be improved for
production code)
(2) If not in limp - mode, it copies all FLASH-API - functions from FLASHD
into RAML0.
(3) Next, it checks the correct FLASH-API - version
(“Flash_APIVersionHex()”).
(4) If the version is correct, it erases FLASHB by function call to
“Flash_Erase(SECTORB, &Flash_Status)”.
(5) It programs new data into section FLASHB by function call
“Flash_Program(&FLASH_Voltage_A0,&new_value,1,&Flash_Status)”.
Now let us finish the lab exercise!

Build project
11. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

Verify Linker Results - The map - File


12. Before we actually start the Flash programming, it is always good practice to verify
the used sections of the project. This is done by inspecting the linker output file
“lab16.map”
13. Open the file “lab16.map” in the sub-folder ..\Debug
In the “MEMORY CONFIGURATION” column "used" you will find the amount of
physical memory that is used by your project.
Verify that only the following five lines from PAGE 0 are used:

16 - 18 F2833x - FLASH - API


Lab 16: Use of FLASH - API

Name origin length used unused attr


RAML0 00008000 00001000 0000055f 00000aa1 RWIX
FLASHD 00320000 00008000 0000055f 00007aa1 RWIX
FLASHA 00338000 00007f80 000007f3 0000778d RWIX
BEGIN 0033fff6 00000002 00000002 00000000 RWIX
ADC_CAL 00380080 00000009 00000007 00000002 RWIX

The number of addresses used in FLASHA and FLASHD might be different in your
lab session. Depending on how efficiently you programmed your code, you will end
up with more or less words in this section.
Verify that in PAGE1 section FLASHB has been allocated:
Name origin length used unused attr
FLASHB 00330000 00008000 00000001 00007fff RWIX

In the SECTION ALLOCATION MAP you can see how the different portions of our
project’s code files are distributed into the physical memory sections. For example, the
.text - entry shows all the objects that were concatenated into FLASHA.
Entry symbol “codestart” connects the object “CodeStartBranch.obj” to physical
address 0x33 FFF6 and occupies two words.

Use CCS integrated Flash Program Tool


14. Perform  Target  Debug Active Project
The FLASH based sections of the project will be erased and programmed
automatically!

F2833x - FLASH - API 16 - 19


Lab 16: Use of FLASH - API

Close CCS & Restart the Peripheral Explorer Board


15. Close your Code Composer Studio session.
16. Disconnect power from the Peripheral Explorer Board.
17. Verify that Peripheral Explorer Board Jumper J3 (“SCI-BOOT GPIO84”) is open

Test Application
18. Re-connect the Peripheral Explorer Board to the power supply. The code should run
immediately after power on. If this is you first test of “Lab16” and FLASH-B has not
been used so far, e.g. variable “FLASH_Voltage_A0” is still programmed with
0xFFFF, the four LEDs LD1…LD4 should blink simultaneously at 100 milliseconds
intervals.
19. Turn potentiometer VR1 into its middle position. Next push PB1 shortly. This push
should start the FLASH - programming sequence and program the new voltage into
FLASHB. The LED - blinking should stop for approximately 1 second. After that
programming time, the code should start again, now showing the new value in
FLASHB.
20. If you power OFF and ON again, the code should immediately show the value, which
was stored in FLASHB, before powering OFF the tool.
21. Re-Start Code Composer Studio and connect to the target.
22. To test code in FLASH, we can also apply a symbolic test strategy.

• Reload project “Lab16.pjt”.

• Perform “Go main” and Run (F8)

• Inspect variables “FLASH_Voltage_A0” and “Voltage_A0”.

• LEDs LD1...LD4 are toggled between “0000” and the corresponding values in
bit 11 to bit 8 of “FLASH_Voltage_A0”

END of Lab16.

16 - 20 F2833x - FLASH - API


IQ - Math Library

Introduction
In Chapter 4 we discussed the differences between fixed-point and floating-point processors
and the influence of hardware support for the computing time of numerical mathematics. In
Lab 4 we also benchmarked the performance of the F2833x for fixed-point and floating-
point implementations.
The good thing with a Digital Signal Controller, such as the F2833x is that we can decide
whether to generate fixed-point code or floating-point machine code, because the hardware
of this device supports both worlds. There are not that many controllers in the market, which
give us such flexibility!
However, the C2000 family of Digital Signal Controller includes also some other members
without the additional support of a floating-point unit. There is one other member, the
TMS320F28035, which has an additional hardware "Control Law Accelerator" (CLA),
which is also based on floating-point hardware. But for all other members of the C2000 -
family, for example the F281x and the F280x groups, we cannot rely on a floating-point
hardware.
In Lab 4 we also realized, that the use of a floating-point library always leads to an extended
execution time for each mathematical instruction, which involves floating-point data type
variables. For a real-time control application, this extended calculation time is not very
welcome. And, to make it worse, real-time applications are quite often very cost sensitive, so
that a floating -point controller is out of the question.
The question is: Is there a better solution for mathematical tasks running on a controller
without hardware support for floating-point variables?
Probably, you can guess the answer. In the case of the Texas Instruments C2000 - family
there is.
The solution is called "IQ-Math" -library (IQ = "Integer - Quotient"). This library is based
purely on the F28x 32-bit fixed-point hardware unit. The "IQ-Math" solution takes advantage
of the internal 64-bit resolution of the F28x fixed-point hardware-module. The word
"library" might sound like a common C-compilers collection of supporting functions, but the
IQ-Math library is different. All "functions" of that library are not "called" like any other
library function. Instead, an optimized set of a few machine code lines is directly placed into
the translation sequence of the machine code. For such functions the term "intrinsic" is used.
The advantage is a very short execution time, because at execution time there is no function
call, no return, no context save and context restore. Of course, the code size will grow
slightly. However, all IQ-Math functions are optimized and consist of only a few words.
The current version (version 1.5a) of Texas Instruments “IQ-Math” - Library can be found in
literature number “SPRC087” at www.ti.com.

F2833x - IQ-Math 17 - 1
Module Topics

Module Topics
IQ - Math Library ........................................................................................................................... 17-1
Introduction ................................................................................................................................... 17-1
Module Topics ............................................................................................................................... 17-2
The “IQ”-Format .......................................................................................................................... 17-3
Which IQ-Format is best? ............................................................................................................. 17-5
How do use IQ-Math? ................................................................................................................... 17-6
Standard ANSI - C 16-Bit Mathematics ................................................................................... 17-7
Standard ANSI - C 32-Bit Mathematics ................................................................................... 17-8
32-Bit IQ - Math Approach....................................................................................................... 17-9
IQ - Math Library Functions ....................................................................................................... 17-13
IQ- Math Application: Field Orientated Control ....................................................................... 17-14
Benchmark of IQ - formats ..................................................................................................... 17-17
Benchmark Results ................................................................................................................. 17-20
IQ - Math summary ..................................................................................................................... 17-20
Lab 17: IQ - Math based low - pass filter .................................................................................. 17-21
Objective ................................................................................................................................. 17-21
Procedure ................................................................................................................................ 17-22
Install IQMath ......................................................................................................................... 17-22
Open Project ........................................................................................................................... 17-23
Build, Load and Run ............................................................................................................... 17-23
Add code for ADC - Initialization .......................................................................................... 17-24
Build, Load and Run ............................................................................................................... 17-25
Add a sampling buffer ............................................................................................................ 17-26
Build, Load and Run ............................................................................................................... 17-27
Add the low - pass filter code ................................................................................................. 17-28
MATLAB Filter Coefficient Calculation ................................................................................ 17-30
Final Build, Load and Run ...................................................................................................... 17-32
Benchmark IQ-Math and Floating-Point Filter code .............................................................. 17-33
Summary ................................................................................................................................. 17-35

17 - 2 F2833x - IQ-Math
The “IQ”-Format

The “IQ”-Format
We have already discussed different number systems, such as floating-point, fixed-point and
binary fractions in Chapter 4. To continue with Chapter 17, you should review Chapter 4
first.
Let us start with the summary of binary fractions. In this number system we "split" a binary
number in an integer ('I') part and a fractional ('Q' - quotient) part. This split is an imaginary
one; we "read" a binary number just in a different way and we do all our mathematics based
on this interpretation of a pure binary number.
Note: The "binary point", shown in Slide 17-2, is just an interpretation; there is no hardware
unit, which will split the binary number in two parts.
Because we do not need a special hardware unit to support this number system, we can use
any fixed-point microcontroller to operate with this system (see Chapter 4). However, only
the F28x - family offers an optimized machine code set to operate on IQ - numbers. And,
even better, the CPU of this family is able to operate with a 64-bit internal resolution for 32-
bit numbers. This 64-bit resolution is based on a concatenation of two internal 32-bit
registers (ACC and P). It will reduce the size of truncation errors to the region of 2-32 and
less.
Based on this special F28x IQ - fixed point machine code set, we can qualify the IQ-Math
library to be comparable to a solution based on floating-point hardware. Therefore, Texas
Instruments calls this library rightly "a virtual floating-point library".

Fractional Representation
31 0
S IIIIIIII fffffffffffffffffffffff
32 bit mantissa

.
-2I + 2I-1 + … + 21 + 20 2-1 + 2-2 + … + 2-Q

“IQ” – Format
“I” ⇒ INTEGER – Fraction
“Q” ⇒ QUOTIENT – Fraction

Advantage ⇒ Precision same for all numbers in an IQ format


Disadvantage ⇒ Limited dynamic range compared to floating point

17 - 2

Now, if the separation in an integer and a fractional part of a binary number is just an inter-
pretation, we can easily shift this separation point to another location, left or right. What will
be the result? What is the advantage in shifting this binary point?

F2833x - IQ-Math 17 - 3
The “IQ”-Format

The answer is, we can adjust our number system to have a more dynamic range of the num-
bers, or we can optimize our number system to give a higher resolution. The term "higher
resolution" means that we can reduce the step size between two consecutive numbers in a
selected IQ-format. The term "dynamic range" refers to the difference between the most
negative and most positive member of a given IQ-scale.

The next slide (Slide 17-3) gives an example, how a 4-bit number can be used in four differ-
ent IQ-Formats:

IQ – Range and Resolution


4-bit number:
Format Most Most Resolution
Negative Positive (step size)
I1Q3 1.000 0.111 0.001
-1 +0.875 0.125
I2Q2 10.00 01.11 00.01
-2 +1.75 0.25
I3Q1 100.0 011.1 000.1
-4 +3.5 0.5
I4Q0 1000 0111 0001
-8 +7 1

• Trade - Off between Range and Resolution


• Note: Integer Format (I4Q0) is a subset of IQ-Math
17 - 3

Depending on the requirements of an application and its control code, we can optimize the
number system. If we need more dynamic range, we would prefer more integer bits. If we
should need more resolution, a format with more fractional bits would make sense. This de-
cision must be made by the software designer. In most cases it is a trade-off between range
and resolution, you cannot get both high dynamic range and high resolution!

The decision, which IQ-Format shall be used for a given task, is one of the most important
decisions, which must be made by the programmer of a control task. At the end of this chap-
ter, we will inspect a real-world application with a benchmark to select the proper IQ-format.

Note: The last line in Slide 17-3, which shows the I4Q0 - Format, is nothing more than the
standard signed integer format for a 4-bit number in 2's-complements. Therefore we can
state, that the format "signed integer" is just a subset of a more general IQ - number system!

Of course, in real-world, we do not operate on 4-bit numbers; the typical size for a control
application is either 16-bit or even 32-bit numbers. For simplification, we used a 4-bit exam-
ple in Slide 17-3.

17 - 4 F2833x - IQ-Math
Which IQ-Format is best?

Which IQ-Format is best?


The IQ-number selection is not a static one. The software engineer can decide which part of
a code solution should be executed on IQ-Format 'A' and which one on format 'B'.

Example: A software - project might be based by default on I8Q24 - numbers, which gives
all numbers a dynamic range of -128…+127.999 and a resolution of 2-24. If, for some reason,
at a certain point in the control code this dynamic range is not sufficient, we can easily
change the number system to another system, for example into I12Q20. Of course, we have
to take into account the reduced resolution for that part of the code.

Texas Instruments offers a wide range of libraries, free to download, which are based on IQ-
Math. All libraries feature an interface to language C, e.g. you can call any of these IQ-
Functions like a common C - function. Please note that all these IQ-functions are "intrinsic"
as discussed at the beginning of this chapter. The prototypes of the functions expect input
data in a certain IQ-Format, such as "I1Q15" or "I8Q24" and so on. Return values are also
delivered in such a format. It is your responsibility to adjust your input- and output-variables
to the expected data format. With the help of the previous slides you should now be able to
understand these requirements.

The next slide (Slide 17-4) shows a set of libraries, offered by Texas - Instruments Libraries;
most of them are based on IQ-Math:

F28x Signal Processing Libraries


Signal Processing Libraries & Applications Software Literature #
ACI3-
ACI3-1: Control with Constant V/Hz SPRC194
ACI3-
ACI3-3: Sensored Indirect Flux Vector Control SPRC207
ACI3-
ACI3-3: Sensored Indirect Flux Vector Control (simulation) SPRC208
ACI3-
ACI3-4: Sensorless Direct Flux Vector Control SPRC195
ACI3-
ACI3-4: Sensorless Direct Flux Vector Control (simulation) SPRC209
PMSM3-
PMSM3-1: Sensored Field Oriented Control using QEP SPRC210
PMSM3-
PMSM3-2: Sensorless Field Oriented Control SPRC197
PMSM3-
PMSM3-3: Sensored Field Oriented Control using Resolver SPRC211
PMSM3-
PMSM3-4: Sensored Position Control using QEP SPRC212
BLDC3-
BLDC3-1: Sensored Trapezoidal Control using Hall Sensors SPRC213
BLDC3-
BLDC3-2: Sensorless Trapezoidal Drive SPRC196
DCMOTOR: Speed & Position Control using QEP without Index SPRC214
Digital Motor Control Library (F/C280x) SPRC215
Communications Driver Library SPRC183
DSP Fast Fourier Transform (FFT) Library SPRC081
DSP Filter Library SPRC082
DSP Fixed-
Fixed-Point Math Library SPRC085
DSP IQ Math Library SPRC087
DSP Signal Generator Library SPRC083
DSP Software Test Bench (STB) Library SPRC084
C28x FPU Fast RTS Library SPRC664
C2833x C/C++ Header Files and Peripheral Examples SPRC530

Available from TI Website ⇒ http://www.ti.com/c2000


http://www.ti.com/c2000
17 - 4

F2833x - IQ-Math 17 - 5
How do use IQ-Math?

How do use IQ-Math?


Implementing complex digital control algorithms on a Digital Signal Controller (DSC), or
any other DSP capable processor, typically we come across the following issues:

• Algorithms are typically developed using floating-point math


• Floating-point devices are more expensive than fixed-point devices
• Converting floating-point algorithms to a fixed-point device is very time consuming
• Conversion process is one way and therefore backward simulation is not always
possible

The diagram below illustrates a typical development scenario in use today:

So how do we really use all this fraction stuff?


The Fixed-Point Development Dilemma

Natural development
Simulation
Platform starts with simulation in
Takes many days/weeks (i.e. MatLab) floating-point
to convert (one way
process)

Can be easily ported


Fixed-Point Floating-Point
Algorithm Algorithm
to floating-point
(ASM, C, C++) (C or C++) device

Floating-Point DSP
Fixed-Point DSP

17 - 5

The design may initially start with a simulation (i.e. MATLAB) of a control algorithm,
which typically would be written in floating-point math (C or C++). This algorithm can be
easily ported to a floating-point device. However, because of the commercial reality of cost
constraints, most likely a 16-bit or 32-bit fixed-point device would be used in many target
systems.

The effort and skill involved in converting a floating-point algorithm to function using a 16-
bit or
32-bit fixed-point device is quite significant. A great deal of time (many days or weeks)
would be needed for reformatting, scaling and coding the problem. Additionally, the final
implementation typically has little resemblance to the original algorithm. Debugging is not
an easy task and the code is not easy to maintain or document.

17 - 6 F2833x - IQ-Math
How do use IQ-Math?

Standard ANSI - C 16-Bit Mathematics


If the processor of your choice is a 16-bit fixed-point and you do not want to include a lot of
library functions in your project, a typical usage of binary fractions is shown next. We
assume that the task is to solve the equation Y = MX + B. This type of equation can be found
in almost every mathematical approach for digital signal processing.

Traditional 16-bit “Q” Math Approach


y = mx + b

s Q15 M
ss Q30
s Q15 X
sssssssssssss Q15 s Q15 B
Align Binary
<< 15 Point For Add
ss Q30

sI Q30

Align Binary
>> 15 Point For Store
ssssssssssssI Q15 s Q15 Y

in C: Y = ((i32) M * (i32) X + (i32) B << Q) >> Q;

17 - 6

The diagram shows the transformations, which are needed to adjust the binary point in
between the steps of this solution. We assume that the input numbers are in I1Q15-Format.
After M is multiplied by X, we have an intermediate product in I2Q30-format. Before we
can add variable B, we have to align the binary point by shifting b 15 times to the left. Of
course we need to typecast B to a 32-bit long first to keep all bits of B. The sum is still in
I2Q30-format. Before we can store back the final result into Y we have to right shift the
binary point 15 times.
The last line of the slide shows the equivalent syntax in ANSI-C. “i32” stands for a 32-bit
integer, usually called ‘long’. ‘Q’ is a global constant and gives the number of fractional bits;
in our example Q is equal to 15.
The disadvantage of this Q15 - approach is its limitation of only 16 bits. A lot of projects for
digital signal processing and digital control will not be able to achieve stable behavior due to
the lack of either resolution or dynamic range.
The F28x as a 32-bit processor can do better - we just have to expand the scheme to 32-bit
binary fractions!

F2833x - IQ-Math 17 - 7
How do use IQ-Math?

Standard ANSI - C 32-Bit Mathematics


The next diagram is an expansion of the previous scheme to 32-bit input values. Again, the
task is to solve equation Y = MX +B. In the following example the input numbers are in an
I8Q24-format.

Traditional 32-bit “Q” Math Approach


y = mx + b

I8 Q24 M
I16 Q48
I8 Q24 X
ssssssssssssssssssI8 Q24 I8 Q24 B
Align Decimal
<< 24 Point for Add
ssssI8 Q48

I16 Q48

Align Decimal
>> 24 Point for Store
sssssssssssssssssI16 Q24 I8 Q24 Y

in C: Y = ((i64) M * (i64) X + (i64) B << Q) >> Q;


Note: Requires support for 64-bit integer data type in compiler 17 - 7

The big problem with the translation into ANSI-C code is that we do not have a 64-bit
integer data type! Although the last line of the slide looks pretty straight forward, we can’t
apply this line to a standard C-compiler!
What now?
The rescue is the internal hardware arithmetic (Arithmetic Logic Unit and 32-bit by 32-bit
Hardware Multiply Unit) of the F28x. These units are able to deal with 64-bit intermediate
results in a very efficient way. Dedicated assembly language instructions for multiply and
add operations are available to operate on the integer part and the fractional part of the 64-bit
number.
To be able to use these advanced instructions, we have to learn about the F28x assembly
language in detail. Eventually your professor offers an advanced course in F28x assembly
language programming -
OR, just use Texas Instruments “IQ-Math”-library, which is doing nothing more than using
these advanced assembly instructions!

17 - 8 F2833x - IQ-Math
How do use IQ-Math?

32-Bit IQ - Math Approach


The first step to solve the 64-bit dilemma is to refine the last diagram for the 32-bit solution
of Y = MX + B. As you can see from the next slide, the number of shift operations is
reduced to 1. Again, the C-line includes a 64-bit ‘long’, which is not available in standard C.

32-bit IQmath Approach


y = mx + b

I8 Q24 M
I16 Q48
I8 Q24 X
Align Decimal
Point Of Multiply
>> 24
sssssssssssssssssI16 Q24

I8 Q24 B

I8 Q24 I8 Q24 Y

in C: Y = ((i64) M * (i64) X) >> Q + B;

17 - 8

The “IQ”-Math approach ‘redefines’ the multiply operation to use the advantages of the
internal hardware of the C28x. As stated, the F28x is internally capable of handling 64-bit
fixed-point numbers with dedicated instruction sets. Texas Instruments provides a collection
of intrinsic functions, one of them to replace the standard multiply operation by an
_IQmpy(M,X) -line. Intrinsic means, we do not ‘call’ a function with a lot of context save
and restore; instead the machine code instructions are directly included in our source code.
As you can see from the next slide the final C-code looks much better now without the
cumbersome shift operations that we have seen in the standard C approach.
AND: The execution time of the final machine code for the whole equation Y = MX + B
takes only 7 cycles; with a 150MHz F2833x, this translates into 46 nanoseconds!

F2833x - IQ-Math 17 - 9
How do use IQ-Math?

IQmath Approach
Multiply Operation

Y = ((i64) M * (i64) X) >> Q + B;

Redefine the multiply operation as follows:


_IQmpy(M,X) == ((i64) M * (i64) X) >> Q

This simplifies the equation as follows:


Y = _IQmpy(M,X) + B;

C28x compiler supports “_IQmpy” intrinsic; assembly code generated:


generated:
MOVL XT,@M
IMPYL P,XT,@X ; P = low 32-bits of M*X
QMPYL ACC,XT,@X ; ACC = high 32-bits of M*X
LSL64 ACC:P,#(32-Q) ; ACC = ACC:P << 32-Q
; (same as P = ACC:P >> Q)
ADDL ACC,@B ; Add B
MOVL @Y,ACC ; Result = Y = _IQmpy(M*X) + B
; 7 Cycles

17 - 9

Let us have a closer look to the assembly instructions used in the example above.
The first instruction ‘MOVL XT,@M’ is a 32-bit load operation to fetch the value of M into
a temporary register ‘XT’.
Next, ‘XT’ is multiplied by another 32-bit number taken from variable X (‘IMPYL
P,XT,@X’). When multiplying two 32-bit numbers, the result is a 64-bit number. In the case
of this instruction, the lower 32-bit of the result are stored in a register ‘P’.
The upper 32 bits are stored with the next instruction (‘QMPYL ACC,XT,@X’) in the
‘ACC’ register. ‘QMPYL’ is doing the same multiplication once more but keeps the upper
half of the result only. At the end, we have stored all 64 bits of the multiplication in the
register combination ACC:P.
What follows is the adjustment of the binary point. The 64-bit result in ACC:P is in I16Q48-
fractional format. Shifting it 32-24 times to the left, we derive an I8Q56-format. The
instruction ‘ADDL ACC,@B’ uses only the upper 32 Bits of the 64-bit, thus reducing our
fractional format from I8Q56 to I8Q24 - which is the same format as we use for B and all
our variables!
The whole procedure takes only 7 cycles!

17 - 10 F2833x - IQ-Math
How do use IQ-Math?

The next slide compares the different approaches. The IQ-Math library also defines a new
data type ‘_iq’ to simplify the definition of fractional data. If you choose to use C++ the
floating-point equation and the C++ equation are identical! This is possible due to the
overload feature of C++. The floating-point multiply operation is overloaded with its IQ-
Math replacement - the code looks ‘natural’.

IQmath Approach
It looks like floating-point!

float Y, M, X, B;
Floating-Point
Y = M * X + B;

long Y, M, X, B;
Traditional
Fix-Point Q Y = ((i64) M * (i64) X + (i64) B << Q)) >> Q;

“IQmath” _iq Y, M, X, B;

In C Y = _IQmpy(M, X) + B;

“IQmath” iq Y, M, X, B;

In C++ Y = M * X + B;

“IQmath” code is easy to read!


17 - 10

This technique opens the way to generate a unified source code that can be compiled in a
floating-point representation as well as into a fixed-point output solution. No need to
translate a floating-point simulation code into a fixed-point implementation - the same source
code can serve both worlds.

F2833x - IQ-Math 17 - 11
How do use IQ-Math?

IQmath Approach
GLOBAL_Q simplification
User selects “Global Q” value for the whole application
GLOBAL_Q
based on the required dynamic range or resolution, for example:
GLOBAL_Q Max Val Min Val Resolution
28 7.999 999 996 -8.000 000 000 0.000 000 004
24 127.999 999 94 -128.000 000 00 0.000 000 06
20 2047.999 999 -2048.000 000 0.000 001

#define GLOBAL_Q 18 // set in “IQmathLib.h” file


_iq Y, M, X, B;
Y = _IQmpy(M,X) + B; // all values are in Q = 18
The user can also explicitly specify the Q value to use:
_iq20 Y, M, X, B;
Y = _IQ20mpy(M,X) + B; // all values are in Q = 20
17 - 11

IQmath Provides Compatibility Between Floating-


Point and Fixed-Point
1) Develop any mathematical function
Y = _IQmpy(M, X) + B;

2) Select math type in IQmathLib.h


#if MATH_TYPE == IQ_MATH #if MATH_TYPE == FLOAT_MATH

3) Compiler automatically converts to:


Y = (float)M * (float)X + (float)B;

Fixed-Point Floating-Point
Math Code Math Code
Compile & Run Compile & Run
on Fixed-Point on Floating-Point
F282xx F283xx *

All “IQmath” operations have an equivalent floating-point operation

* Can also compile floating-point code on any floating-point compiler (e.g., PC, Matlab, fixed-point w/ RTS lib,
17 -etc.)
12

17 - 12 F2833x - IQ-Math
IQ - Math Library Functions

IQ - Math Library Functions


The next two slides summarize the existing library functions of IQ-Math.

IQmath Library: Math & Trig Functions


Operation Floating-Point “IQmath” in C “IQmath” in C++
type float A, B; _iq A, B; iq A, B;
constant A = 1.2345 A = _IQ(1.2345) A = IQ(1.2345)
multiply A*B _IQmpy(A , B) A*B
divide A/B _IQdiv (A , B) A/B
add A+B A+B A+B
substract A-B A-B A–B
boolean >, >=, <, <=, ==, |=, &&, || >, >=, <, <=, ==, |=, &&, || >, >=, <, <=, ==, |=, &&, ||
trig sin(A),cos(A) _IQsin(A), _IQcos(A) IQsin(A),IQcos(A)
and sin(A*2pi),cos(A*2pi) _IQsinPU(A), _IQcosPU(A) IQsinPU(A),IQcosPU(A)
power asin(A),acos(A) _IQasin(A),_IQacos(A) IQasin(A),IQacos(A)
functions atan(A),atan2(A,B) _IQatan(A), _IQatan2(A,B) IQatan(A),IQatan2(A,B)
atan2(A,B)/2pi _IQatan2PU(A,B) IQatan2PU(A,B)
sqrt(A),1/sqrt(A) _IQsqrt(A), _IQisqrt(A) IQsqrt(A),IQisqrt(A)
sqrt(A*A + B*B) _IQmag(A,B) IQmag(A,B)
exp(A) _IQexp(A) IQexp(A)
saturation if(A > Pos) A = Pos _IQsat(A,Pos,Neg) IQsat(A,Pos,Neg)
if(A < Neg) A = Neg

Accuracy of functions/operations approx ~28 to ~31 bits 17 - 13

IQmath Library: Conversion Functions

Operation Floating-Point “IQmath” in C “IQmath” in C++


iq to iqN A _IQtoIQN(A) IQtoIQN(A)
iqN to iq A _IQNtoIQ(A) IQNtoIQ(A)
integer(iq) (long) A _IQint(A) IQint(A)
fraction(iq) A – (long) A _IQfrac(A) IQfrac(A)
iq = iq*long A * (float) B _IQmpyI32(A,B) IQmpyI32(A,B)
integer(iq*long) (long) (A * (float) B) _IQmpyI32int(A,B) IQmpyI32int(A,B)
fraction(iq*long) A - (long) (A * (float) B) _IQmpyI32frac(A,B) IQmpyI32frac(A,B)
qN to iq A _QNtoIQ(A) QNtoIQ(A)
iq to qN A _IQtoQN(A) IQtoQN(A)
string to iq atof(char) _atoIQ(char) atoIQ(char)
IQ to float A _IQtoF(A) IQtoF(A)
IQ to ASCII sprintf(A,B,C) _IQtoA(A,B,C) IQtoA(A,B,C)

IQmath.lib > contains library of math functions


IQmathLib.h > C header file
IQmathCPP.h > C++ header file
17 - 14

F2833x - IQ-Math 17 - 13
IQ- Math Application: Field Orientated Control

IQ- Math Application: Field Orientated Control


The next slides are just to demonstrate the ability of “IQ-Math” to solve advanced numeric
calculations in real time. The example is taken from the area of digital motor control. We
will not go into the details of the control scheme and we will not discuss the various options
to control an electrical motor. If you are a student of an electrical engineering degree you
might be familiar with these control techniques. Eventually your university also offers
additional course modules with this topic. The field of motor and electrical drive control is
quite dynamic and offers a lot of job opportunities.
The next slide is a block diagram of a control scheme for an alternating current (AC)
induction motor. These types of motors are based on a three-phase voltage system. Modern
control schemes are introduced these days to improve the efficiency of the motor. One
principle, called “Field Orientated Control”, incorporates “Space Vector Modulation”, a
voltage modulation technique to drive an inverter, which is quite popular today. In fact this
theory is almost 70 years old now, but in the past it was impossible to realize a real time
control due to the lack of computing power. Now with a controller like the F2833x, it can be
implemented!

AC Induction Motor Example


One of the more complex motor control algorithms

 Sensorless, ACI induction machine direct rotor flux control


 Goal: motor speed estimation & alpha-axis stator current estimation
17 - 15

The core control system consists of three digital PID-controllers, one for the speed control of
the motor (“PID_REG3 SPD”), one to control the torque (“PID_REG3 IQ”) and one for the
flux (“PID_REG3 ID”). Between the control loops and the motor two co-ordinate
transforms are performed (“PARK” and “I_PARK”).
Let us have a look into a standard C implementation of the PARK transform, which converts
a 3-D vector to a 2-D vector. For now, it is not necessary to fully understand this transform,
just have a look into the mathematical operations involved.

17 - 14 F2833x - IQ-Math
IQ- Math Application: Field Orientated Control

All variables are data type “float” and the functions included are:
• Six multiply operations,
• Two trigonometric function calls,
• An addition and
• A subtraction.
This code can easily be compiled by any standard C compiler and downloaded into a
simulation or into any processor, for example the F2833x. It will work, but it will not be the
most efficient way to use the F2833x because it will involve floating-point library function
calls that will consume a considerable amount of computing time.

AC Induction Motor Example


Park Transform – floating-point C code

#include “math.h”

#define TWO_PI 6.28318530717959


void park_calc(PARK *v)
{
float cos_ang , sin_ang;
sin_ang = sin(TWO_PI * v->ang);
cos_ang = cos(TWO_PI * v->ang);

v->de = (v->ds * cos_ang) + (v->qs * sin_ang);


v->qe = (v->qs * cos_ang) - (v->ds * sin_ang);
}

17 - 16

With the “IQ-Math” library we can improve the code for the C28x, as shown at the next
slide. Of course, we have to replace all float function calls by “IQ-Math” intrinsic functions.

F2833x - IQ-Math 17 - 15
IQ- Math Application: Field Orientated Control

All variables are now of data type “_iq”, the sine and cosine function calls are replaced by
their intrinsic replacements as well as the six multiply operations.
The constant “TWO_PI” will be converted into the standard IQ-format with the conversion
function “_IQ( )”. This way the number 6.28 will be translated into the correct fixed-point
scale before it is used during compilation.
The resulting code will be compiled into a much denser and faster code for the C28x. Of
course, a little bit of coding is still needed to convert an existing floating-point code into the
“IQ-Math” C- code.
Fortunately, the structure of the two program versions is identical, which helps to keep a
development project consistent and maintainable, for both the floating-point and the fixed-
point implementations.

AC Induction Motor Example


Park Transform - converting to “IQmath” C code

#include “math.h”
#include “IQmathLib.h”
#define TWO_PI _IQ(6.28318530717959)
6.28318530717959
void park_calc(PARK *v)
{
float
_iq cos_ang , sin_ang;
sin_ang = _IQsin(_IQmpy(TWO_PI
sin(TWO_PI * v->ang);, v->ang));
cos_ang = _IQcos(_IQmpy(TWO_PI
cos(TWO_PI * v->ang);, v->ang));

v->de = _IQmpy(v->ds , cos_ang)


(v->ds * cos_ang) + _IQmpy(v->qs
+ (v->qs * sin_ang); , sin_ang);
v->qe = _IQmpy(v->qs , cos_ang)
(v->qs * cos_ang) - _IQmpy(v->ds
- (v->ds * sin_ang); , sin_ang);
}

17 - 17

17 - 16 F2833x - IQ-Math
IQ- Math Application: Field Orientated Control

Benchmark of IQ - formats
The complete AC-induction motor system was coded using "IQ-Math". Based on analysis of
coefficients in the system, the largest coefficient had a value of 33.3333. This indicated that a
minimum dynamic range of 7bits (+/-64 range) was required. Therefore, this translated to a
GLOBAL_Q value of 32-7 = 25(Q25). Just to be safe, the initial simulation runs were
conducted with GLOBAL_Q = 24 (Q24) value.

AC Induction Motor Example


GLOBAL_Q = 24, system stable

IQmath: speed IQmath: current

Floating-Point: speed Floating-Point: current

17 - 18

Slide 17-18 compares the results for a floating-point code and an I8Q24-code. The left hand
side diagrams show the speed response of the motor to reach a set point. The left hand side
diagrams are the measurement results in one of the three phase currents each.
We can say that the results are almost identical; there is no difference in the control loop for
a floating-point controller and an I8Q24 fixed-point device. The reason for this similarity is
shown at the next slide (Slide 17-19).
In the computation region of numbers, which are used in this first test, the resolution (or
precision) of fixed-point and floating-point is equal - and so are the results!

F2833x - IQ-Math 17 - 17
IQ- Math Application: Field Orientated Control

What’s Happening Here?


Equal Precision in the Computation Region

Floating-Point:

+∞ 0 -∞

Same precision as I8Q24


I8Q24 Fractions:

+∞ 0 -∞

In the region where these particular computations occur, the


precision of single-precision floating-point just happens to equal
the precision of the I8Q24 format.
So, both produce similar results!

17 - 19

Next, the whole AC induction motor solution was investigated for stability and dynamic
behavior by changing the global Q value. With a 32-bit fixed-point data type we can modify
the fractional part between 0 bit (“Q0”) and 31 bits (“Q31”). The following slide shows the
results for an I5Q27 - math system:

AC Induction Motor Example


GLOBAL_Q = 27, system unstable

IQmath: speed

IQmath: current

17 - 20

The system becomes unstable with spikes in the speed response, because of the reduced
dynamic range and resulting overflows in the numbering scale.

17 - 18 F2833x - IQ-Math
IQ- Math Application: Field Orientated Control

The next slide (Slide 17-21) shows the results for an I16Q16 - solution. Here the system
becomes unstable, because of the limited resolution of a step size of the numbers.

AC Induction Motor Example


GLOBAL_Q = 16, system unstable

IQmath: speed

IQmath: current

17 - 21

All the results are summarized below. As you can see, there is an area, in which all tests led
to a stable operating mode of the motor. The two other areas showed an increasing degree of
instability, caused by either not enough dynamic range in the integer part or not enough
fractional resolution of the numbering system.

AC Induction Motor Example


Q stability range

Q range Stability Range


Q31 to Q27 Unstable
(not enough dynamic range)

Q26 to Q19 Stable

Q18 to Q0 Unstable
(not enough resolution, quantization problems)

The developer must pick the right GLOBAL_Q value!

17 - 22

F2833x - IQ-Math 17 - 19
IQ - Math summary

Benchmark Results
Here is a summary of the results for the control code of a "field orientated control" (FOC) of
an AC - induction motor:
AC Induction Motor Example
Performance comparisons

Benchmark C28x C C28x C C28x C


floating-point floating-point IQmath
std. RTS lib fast RTS lib v1.4d
(150 MHz) (150 MHz) (150 MHz)
B1: ACI module cycles 401 401 625
B2: Feedforward control cycles 421 371 403
B3: Feedback control cycles 2336 792 1011
Total control cycles (B2+B3) 2757 1163 1414
% of available MHz used 36.8% 15.5% 18.9%
(20 kHz control loop)

Notes: C28x compiled on codegen tools v5.0.0, -g (debug enabled), -o3 (max. optimization)
fast RTS lib v1.0beta1
IQmath lib v1.4d
17 - 23

IQ - Math summary
IQmath Approach Summary
“IQmath”
IQmath” + fixed-
fixed-point processor with 32-
32-bit capabilities =
 Seamless portability of code between fixed and floating-
point devices
 User selects target math type in “IQmathLib.h” file
 #if MATH_TYPE == IQ_MATH
 #if MATH_TYPE == FLOAT_MATH
 One source code set for simulation vs. target device
 Numerical resolution adjustability based on application
requirement
 Set in “IQmathLib.h” file
 #define GLOBAL_Q 18
 Explicitly specify Q value
 _iq20 X, Y, Z;
 Numerical accuracy without sacrificing time and cycles
 Rapid conversion/porting and implementation of algorithms

IQmath library is freeware - available from TI DSP website


http://www.ti.com/c2000
http://www.ti.com/c2000 17 - 24

17 - 20 F2833x - IQ-Math
Lab 17: IQ - Math based low - pass filter

Lab 17: IQ - Math based low - pass filter


Before we start this lab exercise, you should inspect your solution from Lab 7-9 “Sine Wave
PWM signal at ePWM1A” (see Chapter 7). In this exercise we already used some IQ-Math
functions. Based on the discussion in Chapter 17 you should be able to better understand the
details of the calculations, performed in Lab 7-9.

Objective
The objective of this laboratory exercise is to practice using the F2833x and its IQ-Math
library.
The hardware diagram of this exercise is shown below (Slide 17-25). We will write code to
calculate an FIR-Filter with low-pass characteristics, send our samples through the filter and
compare the results in graphical form.

Lab17: IQ – Math FIR - Filter


ePWM1 ADC
TB Counter ADCINA0 RESULT0
Compare FIR Filter
Action Qualifier
connector
wire

ePWM2 triggering ADC on period


match using SOC A trigger every data
20µs (50 kHz) memory
ePWM2
pointer rewind

CPU copies
result to
buffer during
...

ADC ISR

Display
using CCS

17 - 25

The procedure steps of the exercise are listed in Slide 17-26:

F2833x - IQ-Math 17 - 21
Lab 17: IQ - Math based low - pass filter

Lab17: IQ – Math FIR - Filter


Objective:
1. Generate a symmetrical 2 kHz PWM signal with 25%
duty cycle
2. Measure the signal with ADC at a 50 kHz sample rate
3. Store the ADC results in a circular result buffer
4. Compute the ADC results in a digital finite impulse
response (FIR) filter with low-pass characteristics. The
Filter is calculated by IQ-Math functions
5. Plot the graphs of the filtered and unfiltered signal with
Code Composer Studios graph tool
6. Compare the results

17 - 26

Procedure

Install IQMath
If not already installed on your PC, you will have to install the IQMath library now. The
default installation path is "C:\tidcs\c28\IQmath":

If this library is not available on your PC, you will have to install it first. If you are in a
classroom and you do not have administrator installation rights, ask your teacher for
assistance. You can find the installation file under number "sprc087.zip" in the utility part of
this CD-ROM or at the Texas Instruments Website (www.ti.com).

17 - 22 F2833x - IQ-Math
Lab 17: IQ - Math based low - pass filter

Open Project
1. For convenience, open the provided project “Lab17.pjt” from
C:\DSP2833x_V4\Labs\Lab17.
2. Open the file “Lab17.c” to edit. In the function “Setup_ePWM1A()”, change the
frequency of the square wave signal at ePWM1A from 1 kHz to 2 kHz and set the
pulse width (duty cycle) to 25%.
3. In function “cpu_timer0_isr()”, delete the code to change the duty cycle (register
CMPA). For Lab17 we will use a static or permanent pulse width of 25%.

Build, Load and Run


4. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

5. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

6. Verify that in the debug perspective the window of the source code “Lab17.c” is high-
lighted and that the blue arrow for the current Program Counter position is placed un-
der the line “void main(void)”.

7. Perform a real time run.

Target  Run

8. Use an oscilloscope to measure and verify the 2 kHz-output signal at ePWM1A. Con-
nect your oscilloscope to the Peripheral Explorer Board Header J6-1.

F2833x - IQ-Math 17 - 23
Lab 17: IQ - Math based low - pass filter

Add code for ADC - Initialization


9. At the end of file “Lab17.c”, add the new function “void Setup_ADC(void)”. Also,
define a function prototype at the beginning of “Lab17.c”. In the function “main()”,
add a call to “Setup_ADC()”, immediately after the call to “Setup_ePWM1A()”.

In function “Setup_ADC()”, add the following initialization sequence:


• Call function “InitAdc()”. Because this function is defined in the file
“DSP2833x_Adc.c”, we also have to add an external function prototype at the
beginning of “Lab17.c”.
• In register “ADCTRL1”:
o Select “Cascaded Sequencer Mode”
o Select “No continuous Run”
o Set prescaler “CPS” to zero
• In register “ADCTRL2”:
o disable the ePWM_SOCA_SEQ1 start-option (we will use software
start)
o disable the ePWM_SOCB_SEQ start-option
o disable the ePWM_SOCB_SEQ2 start option
o Enable SEQ1 interrupts with every end of sequence (EOS)
o Set the ADC-clock to HSPCLK / 6. Note: HSPCLK has been initialized
in function “InitSysCtrl()” to SYSCLK/2. For a 150 MHz device the re-
sulting ADC clock will be 12.5 MHz.
• In register “ADCMAXCONV”:
o Set the number of conversions to “1 conversion per start”
• In register “ADCCHSELSEQ1”:
o set field “CONV00” to convert channel ADCINA2

10. In Step 9 we have enabled the ADC to request an interrupt at the end of a conversion.
To get this interrupt into the CPU, we also must enable the PIE - unit switch for the
ADC and we must provide an interrupt-service routine.

• In function “main()”, locate the line, in which we enabled bit 7 of register


PIEIER1. Add a second line to enable also bit 6 of register PIEIER1, which con-
trols the ADC interrupt line:

PieCtrlRegs.PIEIER1.bit.INTx6 = 1;

• Locate the line, in which we loaded variable “PieVectTable” with the address of
function “cpu_timer0_isr()”. Now add a second line to load the address of an in-
terrupt service routine (e.g. “adc_isr()”) for the ADC:

PieVectTable.ADCINT = &adc_isr;

• At the beginning of file “Lab17.c”, add a function prototype for the new func-
tion:

interrupt void adc_isr(void);

• At the end of file “Lab17.c”, add the new interrupt service function:

17 - 24 F2833x - IQ-Math
Lab 17: IQ - Math based low - pass filter

interrupt void adc_isr(void)


{
}

We will fill in the code lines in “adc_isr()” in procedure Step 9.

11. To start the ADC we will use our time-base, the CPU-Timer 0. In file “Lab17.c” this
timer is still initialized to 100 microseconds from an earlier lab. For the new exercise,
we would like to use a sample frequency of 50 kHz or a period of 20 microseconds.
Change the line to initialize the CPU-timer 0 to:

ConfigCpuTimer(&CpuTimer0,150,20);

In the function “cpu_timer0_isr()”, which is triggered by Timer 0 once every 20 mi-


croseconds, add a line to start the ADC by software:

AdcRegs.ADCTRL2.bit.SOC_SEQ1 = 1;

12. In the function “adc_isr()”, which will be triggered at the end of each conversion, add
the following 3 lines to re-initialize the ADC for the next conversion:

AdcRegs.ADCTRL2.bit.RST_SEQ1 = 1; // Reset SEQ1


AdcRegs.ADCST.bit.INT_SEQ1_CLR = 1; // Clear INT SEQ1 bit
PieCtrlRegs.PIEACK.all = 1; // Acknowledge interrupt to PIE

Now we should have completed the framework, which consists of a 2 kHz - signal at
ePWM1A, a sampling time base of 50 kHz, generated by CPU-Timer 0 and an ADC,
which is triggered by CPU-Timer0 to sample channel ADCINA2. The end of conver-
sion will trigger the interrupt service routine “adc_isr()”. Before we go on to read and
store the ADC results in a buffer, let us perform a test, to verify that this framework
actually works:

Build, Load and Run


13. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)


and watch the tools run in the build window. If you get errors or warnings debug as
necessary.

14. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

15. Verify that in the debug perspective the window of the source code “Lab11_1.c” is
high-lighted and that the blue arrow for the current Program Counter position is placed
under the line “void main(void)”.

F2833x - IQ-Math 17 - 25
Lab 17: IQ - Math based low - pass filter

13. Set a breakpoint in the function “adc_isr()” and run the program (F8). If everything
works as expected, the breakpoint should be hit:

Resume a few times the run of the code (F8). The breakpoint should be hit periodical-
ly. This proves that our framework is functional.

Remove the breakpoint and run the code. If your oscilloscope is still connected to
ePWM1A, it should still show the 2 kHz - signal from procedure step 5. Finally, halt
the code ( Target  Halt).

Add a sampling buffer


14. Because our computation will be done based on IQ-Math, we need to include the IQ -
Math function prototypes. At the beginning of file “Lab17.c”, add a line to include the
IQ-Math header file:

#include "IQmathLib.h"

15. Also at the beginning of file “Lab17.c”, add a macro to define the size of our data buf-
fer, a macro to define the value of 3.0 in default IQ-format, and the data buffer itself
as a global variable:

#define AdcBufLen 50
#define AdcFsVoltage _IQ(3.0) // ADC full scale voltage
_iq AdcBuf[AdcBufLen]; // ADC results buffer

16. In interrupt service function “adc_isr()”:

• Add a static unsigned integer variable “index” and initialize it with zero.
• Read the current sample and store it in array “AdcBuf”:

AdcBuf[ibuf] = _IQmpy(AdcFsVoltage, _IQ16toIQ( (_iq)AdcRegs.ADCRESULT0));

This line needs an explanation (from right to left). First we read the latest sample from
the ADC. The result register format is 16 bit, but the result data are in bits 15 to 4 (left
justified). We “interpret” these numbers as an unsigned value between +1 and 0; the
term is “binary fractions” or “per-unit”. Next, we convert this I16Q16 - number into
the default IQ - format (function “_IQ16toIQ()” ). Finally this percentage number is
multiplied by the full scale value of 3.0.

• Increment variable “index” and reset it to 0, if it exceeds AdcBufLen.

17 - 26 F2833x - IQ-Math
Lab 17: IQ - Math based low - pass filter

The whole ISR should now look like this:

17. From location C:\tidcs\c28\IQmath\v15a\lib link the IQ-Math library to your project:

IQmath.lib

Now it is time to perform a test, whether our sampling system is able to fill the result
buffer. Using a wire, connect the Peripheral Explorer Board Header J6-1 (ePWM1A)
to Header J13-4 (ADCINA2).

Build, Load and Run


18. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

19. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

20. Verify that in the debug perspective the window of the source code “Lab17.c” is high-
lighted and that the blue arrow for the current Program Counter position is placed un-
der the line “void main(void)”.

21. Perform a real time run.

Target  Run

22. Open a Graph - Window (Tools  Graph  Single Time) and enter the following
properties:

F2833x - IQ-Math 17 - 27
Lab 17: IQ - Math based low - pass filter

The graph should display the sampled data, e.g. the waveform of the 2 kHz signal with
25% pulse width:

Add the low - pass filter code


23. At this point it is time to add the low pass filter code. For convenience, the source
code file “Filter.c” has been provided. Include this file into the project (right click on
the file and unmark the option “Exclude from Build”).

17 - 28 F2833x - IQ-Math
Lab 17: IQ - Math based low - pass filter

24. Open and inspect file “Filter.c”. This file contains an IQ-Math N-tap single-sample
FIR filter function (“IQssfir()”). It calculates:
𝑁𝑁−1

𝑦𝑦(𝑘𝑘) = � 𝑎𝑎(𝑛𝑛) ∗ 𝑥𝑥(𝑘𝑘 − 𝑛𝑛)


𝑛𝑛 =0

The code of function “IQssfir()” is based on some basic IQ-Math functions. It is just a
simple filter example, and completely un-optimized. The goal with the code was clarity
and simplicity, not efficiency. The filtering is done from last tap to first tap. This allows
more efficient delay chain updating. The array ‘x’ contains the latest N samples, which
are used in the next calculation of y(k). The array ‘a’ contains the filter coefficients and
defines the transfer function of the filter.
25. At the beginning of “Lab17.c”, add a function prototype:
extern _iq IQssfir(_iq*, _iq*, Uint16);
26. Also at the beginning of “Lab17.c”, add 3 new global variables:
_iq AdcBufFiltered[AdcBufLen]; // filtered ADC results buffer
_iq xBuffer[5] = {0,0,0,0,0}; // filter sample buffer
_iq coeffs[5] = {_IQ(0.0357), _IQ(0.2411), _IQ(0.4465), _IQ(0.2411),
_IQ(0.0357)};
All variables are of type “_iq”, which is a signed 32-bit number with default IQ-format.
To inspect or change this default IQ-format, open the file “IQmathLib.h” and search for
the definition of constant “GLOBAL_Q”:

F2833x - IQ-Math 17 - 29
Lab 17: IQ - Math based low - pass filter

MATLAB Filter Coefficient Calculation


The filter coefficient values, shown above as initialization values for variable “coeffs”,
are derived from a MATLAB - filter design tool called “fdatool”. The Filter parameters
are:

• FIR - Low pass - Filter 4th order

• Sampling Frequency: 50 kHz

• Corner Frequency: 300 Hz

• Window: Hamming

The resulting filter coefficients are shown next:

17 - 30 F2833x - IQ-Math
Lab 17: IQ - Math based low - pass filter

27. In the function “adc_isr()”, immediately after the store instruction for the latest ADC-
result, add code to update the filter sample buffer and call the filter function “IQssfir()”:
xBuffer[0] = AdcBuf[index];
AdcBufFiltered[index] = IQssfir(xBuffer, coeffs, 5);
The whole interrupt service routine “adc_isr()” should now look like:

Also, at the beginning of “Lab17.c”, add an external prototype for the function
“IQssfir()”:
extern _iq IQssfir(_iq*, _iq*, Uint16);

F2833x - IQ-Math 17 - 31
Lab 17: IQ - Math based low - pass filter

Final Build, Load and Run


28. Click the “Rebuild Active Project ” button or perform:

Project  Rebuild All (Alt +B)

29. Load the output file in the debugger session:

Target  Debug Active Project

and switch into the “Debug” perspective.

30. Verify that in the debug perspective the window of the source code “Lab17.c” is high-
lighted and that the blue arrow for the current Program Counter position is placed un-
der the line “void main(void)”.

31. Run the code:

Target  Run

Then stop the execution (Target  Halt).

32. Open a Graph - Window (Tools  Graph  Dual Time) and enter the following
properties:

17 - 32 F2833x - IQ-Math
Lab 17: IQ - Math based low - pass filter

The top graph should display the sampled 2 kHz - signal and the bottom graph shows the
output of the low-pass filter, stored in buffer “AdcBufFiltered”.

Benchmark IQ-Math and Floating-Point Filter code


Since the F2833x is able to run floating-point code and fixed-point code, we can test the
filter code of this exercise, based on floating-point machine code or fixed-point code. The
fixed-point code will be done in IQ-Math.
33. Open the file “IQmathLib.h” and verify that the macro “MATH_TYPE” is set to
“IQ_MATH”:

This macro will tell the compiler to use IQ-Math instructions for the compilation of
function “IQssfir()”.
34. Rebuild, reload and run the project.
Open the graph window shown in procedure Step 32 and verify that it still shows the
same two graphs.
Set a breakpoint at the instruction “y = y + _IQmpy(*a--, *x);” in the file “Filter.c”,
open the disassembly window, right mouse click into it and select “Show Source”:

F2833x - IQ-Math 17 - 33
Lab 17: IQ - Math based low - pass filter

Verify that the compiler has actually used IQ - machine code instructions. Look for the
instructions “IMPYL”, “QMPYL” and “LSL64”. This code will run on any C2000
family member without floating-point hardware, e.g. F280x, F281x or F2823x devices.
35. Now change the macro “MATH_TYPE” in file “IQmathLib.h” from “IQ_MATH” to
“FLOAT_MATH”.

36. Rebuild, reload and run the project.


Open the graph window shown in procedure Step 32 and verify that it still shows the
same two graphs.
Run the code until it hits the breakpoint in the file “Filter.c” and inspect again the
“Disassembly Window”:

Now the compiler has generated floating-point machine code! Instructions “MOV32”
and “MPYF32” are using the floating-point hardware unit of the F28335.

17 - 34 F2833x - IQ-Math
Lab 17: IQ - Math based low - pass filter

Summary
Code written in IQ-Math can be compiled for a fixed-point target (MATH_TYPE =
IQ_MATH) or for a floating-point target (MATH_TYPE = FLOAT_MATH). All we
have to do is to change one single line in the header-file!
This is an exciting feature of the C2000 - family, because we don’t have to modify a
single line of code, when we move from a floating-point device to a fixed-point device
or vice versa.

F2833x - IQ-Math 17 - 35
Lab 17: IQ - Math based low - pass filter

blank page

17 - 36 F2833x - IQ-Math
F2833x Digital Motor Control
Introduction
In this module, we will look into an application that is not usually considered to be the
domain of Digital Signal Processors: real-time control of electrical motors. In the old days,
the control of speed and torque of electrical motors was performed using purely analog
technology. Since the appearance of microprocessors, more and more control units have been
designed digitally, using the advantages of digital systems. This improves the degree of
efficiency and allows the implementation of more advanced control schemes, thanks to
increased real-time computing power. It is a natural progression to use the internal hardware
computing units of a DSP to transfer the calculation from a standard microprocessor to a
DSP. This way, we can implement more advanced algorithms in a given time period.

However, to use a digital controller for motor control, the system needs a little more than
computing power. The output signals of the digital controller to the power electronic are
usually generated as pulse width modulated signals (PWM). It would be most cost-effective
if the controller could be equipped with an internal PWM-unit. To control the operation of
the motor we need to do some measurements for currents and voltages – analogue to digital
converters (ADC) will be helpful as well. A typical unit to perform a position/speed
measurement is an optical encoder; quite often, we build in a Quadrature Encoder (QEP).
Recalling all parts of the F2833x we discussed in this Teaching - CD, you can imagine that
the F2833 is an ideal device for Digital Motor Control (DMC).
The chapter will not go into the fine details of electrical motors and drives. Instead, it will
give you a sense of what needs to be done to use the F2833x to control the motor of a
vacuum cleaner or the motor of an electrical vehicle. To fully understand these principles, it
requires many more classes at university. If you are on a course of electrical engineering that
focuses on drives and power engineering, you might be familiar with most of the technical
terms. If not, see this chapter as a challenge for you to open up another application field for a
Digital Signal Controller.
Chapter 18 is based on a Texas Instruments Presentation “TIs C2000 Real-Time MCU for
Digital Motor Control“(August 2009). Depending on the laboratory equipment at your
university, you might be offered the chance to attend a laboratory session to build a working
solution for such a motor control.

F28333x - Digital Motor Control 18 - 1


Module Topics

Module Topics
F2833x Digital Motor Control ........................................................................................................ 18-1
Introduction ................................................................................................................................... 18-1
Module Topics ............................................................................................................................... 18-2
Basics of Electrical Motors ........................................................................................................... 18-3
Motor Categories ...................................................................................................................... 18-3
Asynchronuous Motor .............................................................................................................. 18-4
Synchronuous Motors: BLDC and PMSM ............................................................................... 18-5
Motor Control Principles .............................................................................................................. 18-6
Trapezoidal Control .................................................................................................................. 18-6
Scalar Control (“V/f”) ............................................................................................................... 18-6
Field Oriented Control (FOC) ................................................................................................... 18-7
FOC Coordinate Transform (Clarke / Park).............................................................................. 18-9
FOC Measurement of Motor Position and Speed ..................................................................... 18-9
Advantages of Vector Control ................................................................................................ 18-10
FOC Step By Step ................................................................................................................... 18-10
3-Phase Power Switches ............................................................................................................. 18-11
Sine PWM VSI Control .......................................................................................................... 18-12
Space Vector PWM VSI Control ............................................................................................ 18-13
FOC Control Schematics ............................................................................................................ 18-14
Field Oriented ACI control ..................................................................................................... 18-14
Field Oriented Brushless DC control ...................................................................................... 18-15
Field Oriented PMSM control................................................................................................. 18-16
F2833x Features for Motor Control ........................................................................................... 18-17
Software .................................................................................................................................. 18-17
IQ – Math Functions ............................................................................................................... 18-18
Real-time Debug (RTDX)....................................................................................................... 18-19
Texas Instruments Digital Motor Control Library ...................................................................... 18-20
Software Modules ................................................................................................................... 18-20
The Application Framework ................................................................................................... 18-21
Texas Instruments DMC Solutions ......................................................................................... 18-22
Example: PMSM Framework ...................................................................................................... 18-23
Build Level 1 .......................................................................................................................... 18-23
Build Level 2 .......................................................................................................................... 18-24
Build Level 3 .......................................................................................................................... 18-25
Build Level 4 .......................................................................................................................... 18-25
Build Level 5 .......................................................................................................................... 18-26
Build Level 6 .......................................................................................................................... 18-26
Power Factor Correction (PFC) .............................................................................................. 18-27
C2000 Motor Control Hardware ................................................................................................ 18-28
Summary...................................................................................................................................... 18-30
Motor Control Development Kit.................................................................................................. 18-30

18 - 2 F28333x - Digital Motor Control


Basics of Electrical Motors

Basics of Electrical Motors


Motor Categories
In order to classify the different electrical motors families, we can distinguish motors driven
by direct current (DC) and motors driven by an alternating current (AC). DC motors are the
most popular ones: both stators and rotors carry an excitation created by coils or windings in
which DC current circulates. In order to ensure the motor rotation by commutating the
windings, brushes are permanently in contact with the rotor.

Common Motors & C2000 Applicability


Motor Type Torque Curve Applications Strengths Weaknesses

Universal T Power Tools, Cheap, Simple Low reliability


Vacuums, Control Poor torque and
Fans limited control
Low
S
DC Brushed T Power Tools, Cheap, Simple Low reliability, EMI,
Battery Control Noisy, Feedback
S
Operated required
Stepper Printers, Constant Control complexity
T torque, Precise can vary; Speed
Automation
position control,
High speed
control or High
Load
Control
S

AC – Asynch White Goods, Low cost, Poor at low speeds,


Complexity
T
Pumps, Fans Efficient at fixed Feedback (f,i) and (generally)
AC Induction
speeds, complex control for
S high efficiency
AC – Synch Automation, Efficient, Demanding control
Traction, reliable, smooth for highest
BLDC T
Precision, operation; efficiency; High
PMSM Growth
White Goods Combustible Historically
IPM S environments; expensive but
High torque prices dropping
Reluctance Traction, White Low cost, highly Complex control to
High
T
Goods reliable eliminate noise and
SR (still not widely torque ripple
S used)

Under the classification of AC motors, we have synchronous motors and asynchronous


motors; both motor types are induction machines.
Asynchronous machines require a sinusoidal voltage distribution on the stator phases in
order to induce current on the rotor, which is not fed by any currents nor carries any
magnetic excitation.
Synchronous motors are usually called “Brushless DC Motors” (BLDC) but can also be
called “Permanent Magnet Synchronous Motors” (PMSM) depending on their construction
and the way they are being controlled. In this type of motor, we have one sinusoidal or
trapezoidal excitation on the stator and one constant flux source on the rotor (usually a
magnet).

F28333x - Digital Motor Control 18 - 3


Basics of Electrical Motors

Asynchronuous Motor

Asynchronous Motor: ACI


1.50
Phase currents
1.00
ia ib ic
Rotor rotation
ia A` Ω 0.50

Rotor flux 0.00


1 24 47 70 93 116 139 162 185 208 231 254 277 300 323 346

Ω R = s.Ω
-0.50

C B -1.00

Im -1.50

Stator flux ~
ΩS ω I
c Current Phasors ωt
~
C 120o I
a
B` ` Re
A Aluminum bar
~
I
b
Theory of Operation:
– Rotor placed in a moving magnetic field (flux) will have current induced – which produces another magnetic field
– The interaction of these two magnetic fields produces the rotational torque
• Stator flux is variably controlled by feeding current
• Rotor flux is induced by the stator flux
• Rotor and Stator rotate at different speeds = Asynchronous
• Angle between rotor and stator flux can be regulated to determine torque
• Rotor position is never known

18 - 4 F28333x - Digital Motor Control


Basics of Electrical Motors

Synchronuous Motors: BLDC and PMSM

Synchronous Motors: BLDC & PMSM


A` Rotor field
φ ω 120. f
C Rotor speed (rad/s) : Ω = gives (r.pm)
N p p
f : AC supply frequency (Hz)
B p : motor poles
N

S
C` Stator field
S
B`
A BLDC Back EMF
PMSM Back EMF

Theory of Operation:
– Fixed rotor flux (magnetic field) and a produced stator flux
– The interaction between the two fields produces a torque which will cause the motor to rotate
• Stator flux is variably controlled by feeding current
• Rotor flux is constant by permanent magnets or current fed coils
• Rotor rotation is at same frequency as supplied excitation = Synchronous
• Angle between rotor and stator flux can be regulated to determine torque
• Rotor position can be measured or estimated

Which Synchronous? BLDC vs. PMSM


Continuous States = More Complex
Back EMF of BLDC Motor
Back EMF of PMSM
ea
ωt
ea eb ec
eb
ωt
ωt
ec
ωt

1 2 3 4 5 6 1 CONTINUOUS
• BLDC Motors • PMSM Motors
– Easier to control (6 Trapezoidal states) – More complex control (continuous 3Ph Sine Wave)
– Torque ripple at commutations – No torque ripple at commutation
– Better for lower speed – Higher max achievable speed
– Noisy – Low noise
– Doesn’t work with distributed winding – Work with low-cost distributed winding
– Not as efficient, lower Torque – Higher efficiency, higher Torque
– Lower cost – Higher cost

F28333x - Digital Motor Control 18 - 5


Motor Control Principles

Motor Control Principles


Trapezoidal Control

Trapezoidal Control (BLDC only) - Simple


ea Trapezoidal Step by Step
ωt
1. Sample the System
eb – Position: Hall sensors (3 Square wave
outputs correspond to rotor position)
– 3 Ph Voltages (sensorless)
ωt – Current through a shunt (optional)
ec 2. Calculate
ωt – Speed = Frequency of positions
3. Estimations (Sensorless)
– Voltage Back EMF easily gives position
1 2 3 4 5 6 1 of rotor
4. Regulate the Loop
Trapezoidal Control – Simple proportional PID speed control
+ Fed with direct current – Optional Current/Voltage Monitor
+ Stator Flux commutation only each 60º (1-6) 5. Stimulate the System
+ Two phases ON at the same time – Simple PWM trapezoidal patterns (1-6)
– Torque ripple at commutations
– Communication at high speed difficult
– Noisy
– Doesn’t work with distributed winding

Scalar Control (“V/f”)

V/f Control (ACI or PMSM) – Simple


Model:
MAXIMUM
TORQUE VOLTAGE Rs Ls Rr/s Lr

V Φm Lm R(s)
NOMINAL
TORQUE I m = (Vm / 2π f L m )
TORQUE Φ m = (Vm / 2π f)
Vo
At low speed: Rs is no longer
negligible: Vm < V
LOW SPEED NOM SPEED SPEED A large portion of energy is now
wasted.

+ Simple Proportional Control: Three sine waves feeding the motor


+ Position information not required (optional) Torque oscillation
generates uncontrolled
– Poor dynamic performance current overshoot:
TORQUE
– Torque delivery not optimized for all speeds
TIME

18 - 6 F28333x - Digital Motor Control


Motor Control Principles

The V/Hz regulation scheme is the simplest one that can be applied to an asynchronous mo-
tor. The goal is to work in an area where the rotor flux is constant (Volts proportional to
speed).
In practical solutions, the speed sensor is optional as the control is tuned to follow a prede-
fined “speed-profile versus load table”, assuming the load characteristics are known in ad-
vance.
Obviously, this type of control bases itself on the steady electrical characteristics of the ma-
chine and assumes that we are able to work with a constant flux in the complete speed range
the application targets. This is why this type of control does not deliver a good dynamic per-
formance and a good transient response time; the V/Hz profile is fixed and does not take into
account conditions other than those seen in a steady state. The second point is the problem at
startup of AC induction motors, which cannot deliver high torques at zero speed; in this case,
the system cannot maintain a fixed position. In practice for low speed, we need to increase
the delivered voltage to the stator compared to the theoretical V/Hz law.

Field Oriented Control (FOC)


Instead of using a pure sine wave shaped modulation of the PWM stage, in recent years the
space vector theory has demonstrated some improvements for both the output crest voltage
and the harmonic copper loss. The maximum output voltage based on the space vector theory
is 1.155 times larger than the conventional sinusoidal modulation. This makes it possible to
feed the motor with a higher voltage than the simpler sub-oscillation modulation method.
This modulator enables higher torque at high speeds, and a higher efficiency. Torque
distortion is also reduced.
The space vector PWM technique implemented into the existing TI DMC library reduces the
number of transistor commutations. It therefore improves EMI behavior.

F28333x - Digital Motor Control 18 - 7


Motor Control Principles

FOC Control (ACI or PMSM) – Complex


A`
q=90°
C F Maintain
N
the ‘load
B
angle’ at
90°
C`
S F
B`
A Torque = Cross Product of Fields
Maximized when Sin q = 1 = 90 Degrees
Field Orientation
+ Reduced torque ripple
+ Better dynamic response
Measure & Control
+ Good performance at lower speeds Torque, Flux
Angle, Speed
- Need to measure angle between rotor and stator
- Requires independent control of flux and torque in real-time

A typical characteristic of FOC - PWM command strategy is that the envelope of the
generated signal is carrying the first and the third harmonics. We can interpret this as a
consequence of the special PWM sequence applied to the power inverters. Literature also
mentions the third harmonic injection to boost out the performance we get out of the DC bus
capacitor. This third-harmonic exists in the phase to neutral voltage but disappears in the
phase-to-phase voltage.

18 - 8 F28333x - Digital Motor Control


Motor Control Principles

FOC Coordinate Transform (Clarke / Park)

FOC: Torque & Flux Deduced from Currents


a 3PH α Clarke Q Park
MATH MATH
MEASURE
CURRENTS
Currents TRANSFORM Transformation TRANSFORM Transformation

Is ωstator
Is Is D
Iq
π/2 Id
2π/3 Torque Component Flux Component
2π/3
β
b
c 2π/3
Ια t
Torque Component
IQ
ic ia ib t

t Flux Component
Ιβ t ID
t

Two phase orthogonal Rotating


Three phase reference frame reference frame
reference frame

FOC Measurement of Motor Position and Speed

FOC: Angle & Speed are Measured or Estimated

ACI
– Measured
• Tachometer: Square wave output proportional to speed
– Estimations
• Angle estimated from Integral of Sinusoidal Back EMF Voltage with closed
loop voltage compensation
• Speed estimated from Estimated Flux, measured current, and motor model

PMSM
– Measured
• Encoder: 2 Square waves give position, speed calculated by change over time
• Resolver: SIN + COS waves give position, speed calculated by change over
time
– Estimations
• Angle estimated from Integral of Sinusoidal Back EMF Voltage with Sliding
Mode Observer technique
• Speed calculated from change in angle over time

F28333x - Digital Motor Control 18 - 9


Motor Control Principles

Advantages of Vector Control

Why FOC? Performance Comparison


FOC

FOC
• System responds faster to changes in set point or load change
• Minimum speed at full load is now essentially zero
• Starting torque is increased
• Very little torque ripple
• Reduces Cost
• Optimally size motor for the task at hand
• Current controlled, so the inverter can be optimized

FOC Step By Step

FOC: Step By Step


Measure & Control
1. Sample the System
Torque, Flux
– Current
– Voltage (Sensorless) Angle, Speed
– Speed (ACI Sensored)
– Speed & Position/Angle (PMSM Sensored)
2. Transform sampled data and calculate useful quantities
– Measure Currents  Use Clarke/Parke Transform  Torque & Flux
– ACI Sensored
• Measure Speed + Torque & Flux Components  Angle
– ACI Sensorless
• Measure Voltage + Stator Current (Clarke)  Angle Estimation
• Angle Estimation + Stator Current (Clarke)  Speed Estimation
– PMSM Sensored
• Measured Speed and Measured Angle
– PMSM Sensorless
• Measured Voltage + Stator Current (Clarke)  Angle Estimation
• Angle Estimation  Speed Estimation
3. Regulate the Loop
– PID techniques are most common; Controls to a reference value
– Regulate speed, position/angle, current, flux and maximize torque
4. Stimulate the System
– Inverse transforms of Park and Clarke
– PWM Pattern generation to drive the voltage/current source

18 - 10 F28333x - Digital Motor Control


3-Phase Power Switches

3-Phase Power Switches


As we saw in the previous basic diagrams, we need to apply three 120° phase shifted excita-
tion signals to the power circuitry of the motor. As you have seen in Chapter 7 (“PWM”), a
PWM signal can be used to modulate sinusoidal signals. With three independent switching
pattern streams and six power switches, we can deliver the necessary phase voltages to gen-
erate the required torque imposed by the load. The goal is to build the correct conduction
sequences in the IGBTs to deliver sinusoidal currents to the motor to transform it to a me-
chanical rotation.
This is traditionally achieved by comparing a three-phase sinusoidal waveform with a trian-
gular carrier. In the digital world, on the DSP processor, we compute a sinusoidal command
and apply it to the PWM units that generate the appropriate PWM outputs usually connected
to gate drivers of the IGBTs from the inverter.
Basically we are “chopping” a DC voltage, carried by the DC bus capacitor, in order to build
the appropriate voltage shapes for the stator phases, with the goal of having a good efficiency
during this energy conversion process. This is a power electronics concern: we need to mi-
nimize the noise introduced by these conducting sequences and source of harmonics.

Controlling the 3PH Voltage Source Inverter (VSI)

Upper & lower


devices can not
be turned on
simultaneously
(dead band)
PWM signal is
applied between
gate and source
+

DC bus
capacitor − Three phase
outputs which
go to the motor
terminals

Power
Switching
Devices

F28333x - Digital Motor Control 18 - 11


3-Phase Power Switches

Sine PWM VSI Control

Traditional (Old) Sine PWM VSI Control

 Inputs
 Triangular Switching Frequency (5-25 kHz typically)
 Sine wave = Carrier Trying to match (V or I Reference, 0-1000 Hz typically)
 Image not to scale; Typically 100s of triangle periods in each Sine wave
 Output
 When they cross, you switch the PWM

18 - 12 F28333x - Digital Motor Control


3-Phase Power Switches

Space Vector PWM VSI Control

Space Vector PWM VSI Control


Theory: A special switching sequence of the upper three power devices of a
VSI results in 3 pseudo-sinusoidal currents in the stator phases.
Calculate the appropriate duty cycle – every period - needed to
generate a given stator reference voltage.
q

V120 (010) V60 (011)V0 (100)


S2
Van*
S3

θ S1
V180 (110) 0 (111) 0 (000)
0 d
S4 S6

Zero Vectors (000) & (111)


S5

V240 (100) V270 (101)

For review of the calculations,


please see detailed theory in
SVGEN documentation from DMC
Library (SPRC080 or SPRC125).

SVPWM Benefits vs Traditional Sine PWM

• 15% boost in torque


• 30% less switching losses (higher efficiency)
• 30% reduced EMI due to fewer transistor commutations
• Reduced harmonic copper losses
• Capacitor reduction
– The use of smaller DC link capacitor will introduce DC bus ripple
– Controllers with processing overhead can digitally compensate for the
ripple on the DC bus, allowing for a greater ripple limit
– This smaller capacitor size can reduce system cost

F28333x - Digital Motor Control 18 - 13


FOC Control Schematics

FOC Control Schematics


Field Oriented ACI control
The overall system for implementation of the 3-phase ACI control unit is shown in the next
slide. The ACI motor is driven by the conventional voltage-source inverter. The F2833x is
generating six pulse width modulation (PWM) signals by means of space vector PWM
technique for six power- switching devices in the inverter. In a “sensored” measurement
mode, a tachometer or resolver is used to feedback speed and position. By contrast, in a
“sensorless” measurement mode, two input currents of the PMSM (ia and ib) are measured
from the inverter and they are sent to the F2833x via two analog-to-digital converters
(ADCs).

ACI System for FOC


MCU
+ DC Bus
Tx PWM1
Timers PWM2
Serial coms
and PWM PWM3
R (UART) PWM4
Compare
x PWM5
Units
PWM6
PWM1 PWM3 PWM5 AC Induction
SIMO
Motor
Capture CAP/QEP
SOMI SPI
CLK Serial coms Unit
STE

ADCIN0 PWM2 PWM4 PWM6


ADCIN1 CAP/QEP
ADC

Shunt Tacho
resistor Or
Resolver

ADCIN2
ADCIN3 Signal
Conditioning

Sensor is removed with sensorless FOC

18 - 14 F28333x - Digital Motor Control


FOC Control Schematics

Field Oriented Brushless DC control

BLDC System – Sensored, Trapezoidal


Back EMF of BLDC

ea

eb
MCU
+ DC Bus ec
Tx PWM1
Serial Timers PWM2
and PWM PWM3
Rx (UART) PWM4
Compare PWM5
Units PWM6
PWM1 PWM3 PWM5 Three-phase
SIMO SPI BLDC machine
Capture CAP1
SOMI (Synch CAP2
CLK Unit CAP3
Serial)
STE
CAP1
PWM2 PWM4 PWM6 CAP2
ADC ADCIN0 CAP3

DC Shunt
0 / 120 / 240 deg
position
information
(e.g., Hall
Signal sensors )
Conditioning

BLDC System – Sensorless, Trapezoidal


Back EMF of BLDC

ea
MCU
DC Bus eb
+
Tx PWM1 ec
Serial coms Timers PWM2
and PWM PWM3
Rx (UART) PWM4
Compare PWM5
Units PWM6
PWM1 PWM3 PWM5 Three-phase
SIMO BLDC machine
SOMI SPI Capture
CLK Serial coms Unit
STE
ADCIN1
ADC
ADCIN2 PWM2 PWM4 PWM6 No
ADCIN3

ADCIN0
sensors !
DC Shunt
ADCIN1 Phase
Signal ADCIN2
ADCIN3 Voltage
Conditioning Meas

F28333x - Digital Motor Control 18 - 15


FOC Control Schematics

Field Oriented PMSM control

PMSM System – FOC/Vector


Back EMF of PMSM
MCU 1.50

DC Bus 1.00 ea eb ec
+ 0.50

Tx PWM1 0.00
1 24 47 70 93 116 139 162 185 208 231 254 277 300 323 346
ωt
Timers PWM2 -0.50
Serial coms
and PWM PWM3 -1.00

Rx (UART) PWM4 -1.50


Compare
PWM5
Units
PWM6
PWM1 PWM3 PWM5
SIMO QEP1
SOMI SPI Capture
QEP2
CLK Serial coms Unit
CAP3
STE
QEP1
ADCIN0 PWM2 PWM4 PWM6 QEP2
ADC ADCIN1 CAP3 (index)
Encoder
Shunt Optional
resistor

Signal
Conditioning

Sensor is removed with sensorless FOC

18 - 16 F28333x - Digital Motor Control


F2833x Features for Motor Control

F2833x Features for Motor Control


Software

Software for Real-Time Controllers

Header Files Foundation Libraries CCS Debug Tools


– Init routines and functions – Math primitives – Real-time Debug
– Named bit fields – Signal Processing – Graphical Analysis
– Peripheral Examples – Floating-point – DSP/BIOS RTOS and
– Control Law Accelerator scheduler
CCS v4 Sample Projects and – Flash API – Plug-ins and add-ons
Workspaces – IQMath
– Eclipse-based code editor and 3rd Party Tools
debugger
Device Evaluation
–Tool kit demonstration
Application
Application Libraries Debug and
– Modeling and Simulation
– Digital Motor Control – Debug tools
workspaces show how to set Development
– Digital Power
Productization
– Emulators
up watch windows and graphs
for real-time analysis
– General Purpose GUI ready System Examples
for customization – Robust Modular Frameworks
– Multiple Digital Power
Demonstration GUIs Conversion Types
– Peripheral Explorer – Multiple Motor Types
– Renewable Energy Kit – Power Line Communication
– Digital Power Kits
3rd Party Resources
– Diagram-based code
generation
– Software libraries

10/28/2009 28

C2000 Software for DMC Concept

Methodology
- Highest precision & most numerically accurate
- Modular libraries (C source) for easiest re-use and customization
- Removal of fixed point scaling and saturation burden
- Easiest to tune for your custom motor
- Documentation: DMC theory, software, BOM, schematics

Customers can self serve and achieve high productivity!

Achieved by
- IQMath
- Application Frameworks: DMC Library & Incremental Build
- Partner Tools for simulation, GUI programming, and auto code gen

F28333x - Digital Motor Control 18 - 17


F2833x Features for Motor Control

IQ – Math Functions

IQMath
• Library and Compiler Intrinsic
– Move your decimal point to where you need it
– Write in floating point, compiler does all the work

• Start-up, tuning, and debug effort are reduced


– Change numerical range on the fly, global or local
– Tune for best resolution and dynamic range
– Remove quantization effects
– Scaling and saturation are a thing of the past
– Better integration with simulation and code gen tools
– Single source set to move between fixed and floating point
processors
– Easy re-use and re-tuning for new systems

IQmath: Choose your decimal


Range or Resolution?
Based On The Required Dynamic Range Or Resolution
31 0
S I I I I I I I I I I I I I I I I . Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q (Q15)
GLOBAL_Q Max Val Min Val Resolution
28 7.999 999 996 -8.000 000 000 0.000 000 004
24 127.999 999 94 -128.000 000 00 0.000 000 06
20 2047.999 999 -2048.000 000 0.000 001

The user selects a “Global Q” value for the entire application:


#define GLOBAL_Q 24 // set in “IQmathLib.h” file
_iq Y, M, X, B;
Y = _IQmpy(M,X) + B; // all values are in I8Q24
The user can also explicitly specify the IQ value to use:
_iq20 Y, M, X, B;
Y = _IQ20mpy(M,X) + B; // all values are in I12Q20

18 - 18 F28333x - Digital Motor Control


F2833x Features for Motor Control

Probably one of the most important advantages of programming in IQMaths is the ability to
switch from a fixed-point environment to the floating-point processor world. When the
programmer uses a conditional compilation technique, based on “#if – else – end if”
directives, the same C code can be used for fixed-point and floating-point translation.

IQMath: One source set from Simulation to Production

Simulation
Or IQMath
Algorithm

Y = _IQmpy(M, X) + B;
Configure Math Type In IQmath Header File
#if MATH_TYPE == IQ_MATH #if MATH_TYPE == FLOAT_MATH
Automatically Converts To:

Y = (float)M * (float)X + (float)B;


Fix-Point Math Code Floating-Point Math Code

Compiler Intrinsic Compile & Run


Run On On any Floating-Point
F28x Fixed-Point Device

Gives Up And Down Code Mobility

Real-time Debug (RTDX)


Real-time Debug (RTDX)
Control systems must be debugged while running!
 Halt in non-critical code for debug while time-critical interrupts
Real-time

continue to be serviced
Debug

 Access memory and registers without stopping the processor


 Implemented in silicon, not by a software debug monitor
 No CPU cycles required

 RTDX always available, real-time debug on customer returns

Halt and single step non-time critical code Time-critical interrupts


are still serviced.

Main() function() Interrupt void ISR_1()


{ { {
…… …… ………
} } }

F28333x - Digital Motor Control 18 - 19


Texas Instruments Digital Motor Control Library

Texas Instruments Digital Motor Control Library


Software Modules

Texas Instruments Digital Motor Control (DMC) Library is available free of charge and
can be downloaded from the Texas Instruments website. It consists of a number of useful
functions for motor control applications. Among those functions, there are pure motor con-
trol modules (Park and Clark transforms, Space Vector PWM etc) as well as traditional
control modules (PID controller, ramp generator etc) and peripherals drivers (for PWM,
ADC and others).
Based on this DMC library, Texas Instruments has developed a number of application
notes for different types of electrical motors. All applications examples are specially de-
signed for the C2000 platform and come with a working example of the corresponding
software, background information and documentation.
One branch of this library is dedicated to the F2833x and takes advantage of the 32-bit IQ-
Math data format.
The following slide shows the software modules available for the C2000 family:

DMC Library
Blocks are Modular C functions
- Variables as Inputs, Variables as Outputs
- Library of Source Code
- Most are IQ based, tune to your stability needs!
Multi-page
Documentation
& Theory of
Operation for
each module

Other Libraries Available


- FFT (32-bit Complex & Real)
- Filters (FIR, IIR)
- QMath (Trig, SQRT, INV, LOG, DIV)
- IQMath Virtual Floating Point
(Conversion, Arithmetic, Trig, Math)
- Signal Generation (Sine, Ramp, Trapezoidal)
- Digital Power

18 - 20 F28333x - Digital Motor Control


Texas Instruments Digital Motor Control Library

The Application Framework


All Digital Motor Control Library solutions are based on are based on a framework system,
shown in the following slide. Although the modules are written in optimized IQMath code,
all of them can be accessed using a C language interface.

Application Frameworks

Connect the Blocks Complete Solutions from TI


- Tie output variables to input variables in C code - 20+ Motor Type and Control Technique Specific Solutions
- Yellow = Transforms - DC, BLDC, ACI, PMSM, SR, Stepper
- Pink = Control - Sensored or Sensorless, V/Hz or Vector/FOC
- Green = Peripheral - Download Includes
ex: Instead of user configuring all ePWM registers, the - CCStudio IDE Workspace and Project
FC_PWM_DRV module uses variable inputs from - Source Code
SVGEN_DQ to create the proper PWM register - Documentation
settings for proper duty cycle and pattern generation - System Overview
- Control Theory of Operation
- Software Flow Diagram
- Hardware Configuration
- Step by Step Instructions
- Screen Captures
- Verification & Debug Techniques
- Incremental Build Methodology
- Step by Step System Verification

Connect Blocks In C:
// Connect SVGEN Block: This module abstracts all the PWM
svgen_dq1.Ualpha = ipark1.Alpha; registers. Does all the work for you –
svgen_dq1.Ubeta = ipark1.Beta; every period – based on the changing
// Execute SVGEN Block:
duty cycle calculations from SVGEN
svgen_dq1.calc(&svgen_dq1); and your system frequency. You don’t
even need to write to the peripheral
registers!

What the user has to do is simply to select the correct blocks, to define the variables for input
and output lines of the corresponding blocks and to connect these “lines” by passing
variables. All modules are supplied with a dedicated documentation file.
For example, the file “pid_reg3.pdf” explains the interface and the background of the PID-
controller:

All functions are coded for 32-bit variables in IQ-Math-format. The functions are used as
instances of a predefined object class, based on a structure definition in a header file.

F28333x - Digital Motor Control 18 - 21


Texas Instruments Digital Motor Control Library

Texas Instruments DMC Solutions


Texas Instruments offers a set of more than 20 complete solutions for different types of
motors, switching and control techniques, all based on this application framework.

Application Frameworks, Hardware,


and Application Notes
C2000
MOTOR TYPE CONTROL FEEDBACK SOLUTION
STEPPER Microstepping Sensorless SPRAAU7
DC Speed & Position Sensored SPRC177, SPRC214
V/F Sensored SPRC130, SPRC194
ACI FOC Sensored SPRC077, SPRC207
FOC Sensorless SPRC078, SPRC195, SPRC922
BLDC Trapezoidal Sensored SPRC175, SPRC213
Trapezoidal Sensorless SPRC176, SPRC196
V/F Sensored SPRC129, SPRC210
FOC - Resolver Sensored SPRC178, SPRC211
PMSM FOC Sensored SPRC179, SPRC212
FOC Sensorless SPRC128, SPRC197, SPRC922,
TMDS1MTRPFCKIT, TMDS2MTRPFCKIT

SWITCHED Two Quadrant Sensorless SPRA600


RELUCTANCE
OTHER DMC Library: SPRC080, SPRC215
Designing High Performance DMC: SPRT528

These solutions follow a simple principle for testing the software, accessing the power drives
and closing the control loop: an incremental build methodology. The basic idea is to define a
macro and to use a conditional compilation (called: “Build Level”) to include more and more
modules into the final machine code. Such a technique is very helpful when the user tests a
motor drive system for the very first time.
The following slides explain this sequential method with the example of a PMSM Field
Oriented Control System.

18 - 22 F28333x - Digital Motor Control


Example: PMSM Framework

Example: PMSM Framework


Build Level 1
Build Level 1 is used to verify the target independent modules, such as PWM frequency,
duty cycles and updates of the PWM unit. The motors are disconnected at this level. Two
software modules “RAMP_GEN” and “RAMP_CNTL” are used to stimulate the PWM
system via the inverse PARK module and the Space Vector Generator module.

Incremental Build Methodology


Dual Sensorless FOC PMSM Example

An oscilloscope is used to monitor the shape of the PWM signals and the pulses series
generated by the SVGEN module.

F28333x - Digital Motor Control 18 - 23


Example: PMSM Framework

Build Level 2

Incremental Build Methodology


Dual Sensorless FOC PMSM Example

Incremental Build Methodology


Dual Sensorless FOC PMSM Example

Connect IQmath Blocks In C: Watch/Modify Variables In Real-Time:


// Connect Park Block:
PARK.theta_p = RAMP_GEN.mp_out;
PARK.d = CLARKE.d;
PARK.q = CLARKE.q;
// Execute Park Block:
_IQparkPU(&PARK);
// Result in PARK.D and PARK.Q

18 - 24 F28333x - Digital Motor Control


Example: PMSM Framework

Build Level 3

Incremental Build Methodology


Dual Sensorless FOC PMSM Example

Build Level 4

Incremental Build Methodology


Dual Sensorless FOC PMSM Example

F28333x - Digital Motor Control 18 - 25


Example: PMSM Framework

Build Level 5

Incremental Build Methodology


Dual Sensorless FOC PMSM Example

Build Level 6

Incremental Build Methodology


Dual Sensorless FOC PMSM Example

18 - 26 F28333x - Digital Motor Control


Example: PMSM Framework

Power Factor Correction (PFC)

MIPS leftover…integrate digital PFC!

We achieve PFC by controlling the


duty cycle such that the rectified
input current is made to follow the
rectified input voltage while
providing load and line regulation .

Why add Power Factor Correction?

Why: In an AC-Rectifier, the 3-phase inverter stage and the motor act
as a non-linear load and will draw harmonic currents from the line.
These harmonics result in losses and such currents can distort the
line voltage.
Some countries and regulatory bodies limit the distortion to the line
a product can inject (see IEC 61000-3-2).
How: Generate an intermediate DC Bus from an AC source while
drawing a sine wave input current that is exactly in phase with the
line voltage
A PFC stage has become an integral part of most power supply
designs…usually done with a standalone PFC chip…why not have
the MCU control this digitally!

F28333x - Digital Motor Control 18 - 27


C2000 Motor Control Hardware

C2000 Motor Control Hardware


To start an exploration for motor control, based on C2000 controllers, Texas Instruments
offers a set of low cost tools:

controlSTICK: Low Cost Evaluation


$39 Kit includes
• Simple USB memory stick form
factor evaluation tool
•Piccolo F28027
•Onboard USB JTAG emulation
•Header pins provides access to
most Piccolo pins
•11 example projects explain most
Piccolo peripherals
•Jumpers and patch cords to easily
connect pins together
•USB extension cable
•Code Composer Studio V3.3 with
32KB code size limit
•Complete hardware documentation
•Gerbers, schematics, etc

controlCARD: Modular, Robust, Standard


controlCARD
• Low cost, small form factor
• Standard DIMM interface
– Includes analog I/O, digital I/O, and
JTAG signals available at DIMM Pin compatible across
interface
• Robust design
the C2000 family!
– Noise filter at ADC input pins
– Ground plane
– Isolated UART communication
– Supply pin decoupling
• All life support circuitry
– Clock, Power Supply, LDO, etc
• Multiple versions available
– Piccolo F28027
– Piccolo F28035
– Delfino F28335
– Delfino C28436
– F2808
– F28044
– $49-69

18 - 28 F28333x - Digital Motor Control


C2000 Motor Control Hardware

A set of base boards allows the user to go deeper into different application areas, such as
Digital Power Supply or Digital Motor Control.

controlKIT: controlCARD + base board


Device Evaluation Application Development
Experimenter’s Kit - Flash Digital Power
TMDXDOCK28027 Experimenter’s Kit
TMDXDOCK28035 TMDSDCDC2KIT
TMDSDOCK2808 $229
TMDSDOCK28335
$79-$159 Digital Power
Developer’s Kit
TMDSDCDC8KIT
Experimenter’s Kit - RAM $325
TMDXDOCK28343
TMDXDOCK28346-168
$189
AC/DC Developer’s Kit
TMDSACDCKIT
$695
Peripheral Explorer
TMDSPREX28335
$179 Resonant DC/DC
Developer’s Kit
TMDSRESDCKIT
$229
controlKITs Include
• controlCARD + Base Board Renewable Energy
• CCStudio IDE v3.3 32KB code size limit
Developer’s Kit
• Example Software with lab document
TMDSENRGYKIT
• Power Supply and Cables
$349
Developer’s Package Sensorless FOC DMC +
• Schematics (source and .PDF files) PFC Developer’s Kit
• Bill of materials (BOM) TMDS1MTRPFCKIT 1 Motor
• Gerber files to freely use or modify TMDS2MTRPFCKIT 2 Motor
• Pin-out table showing all key signals $369/$399
• DIMM100 pin/socket mechanical details

For Digital Motor Control the following package includes all you need to experiment with
PMSM motors.

Sensorless FOC and PFC Developer’s Kit

$399 Motor Control


and PFC Kit Includes
 Piccolo F28035 controlCARD
 Sensorless Sinusoidal SVPWM based
Field Oriented Control
 Single or Dual Axis Operation
 Integrated Digital Power Factor
Correction
 Hardware Features
 100W 2 phase interleaved power
factor correction stage
 2 x 60 W motor driver stages
based on TI DRV8402 motor
driver chips
 On board isolated XDS100
JTAG emulation
 Software Lab Projects
No external
 Standalone PFC emulator required!
 Dual Axis TMDS2MTRPFCKIT(2 motors)
 Single Axis + PFC TMDS1MTRPFCKIT(1 motor)
11/1/2009
 Dual Axis + PFC (coming soon)

F28333x - Digital Motor Control 18 - 29


Summary

Summary

Benefits of C2000 for Motor Control


AC
Input
Bridge DC link Power
Motor Load
• High energy efficiency via advanced
Rectifier Converter
Control
• Variable speed Real-time control
MOSFET
I and V Sense Driver I Sense • Better dynamic and transient control

Isolation Products • Overall System performance


optimization
Resolver • High Level of Integration
Power High
Accuracy Driver
• Provides Control and Supervision
Supply
ADC’s
LDO C28xTM MCU and Buffer Optical
Controller DAC’s encoder
PFC
SVS
PWM
Level-
Shifter • Quicker Return on Investment
Hall effect
• Portfolio of compatible devices from
lowest cost to highest performance
• Long term SW and tools compatibility
• System Cost Optimization
Network 4-20mA ADC DAC
interface interface Data line Interface Interface
• Low System Cost
• Integrated OSC, Watchdogs
4-20mA loop CAN
Ethernet
RS232
+/- 10V +/- 10V • Analog Comparators
RS485
• Fault Detection
• Limited life support
• No external GPIO filters needed

Motor Control Development Kit


The Digital Motor Control Kit “TMDS2MTRPFCKIT” is an ideal target to experiment with
control loops for electrical motors.
This kit comes with a set of documentation, including all the software that is needed to build
software projects as described in this Chapter. You can also download this software from the
Texas Instruments website (www.ti.com):

• Search for literature number “sprc922.zip” to obtain the board specific software
• Search for literature number “sprc675.zip” to get the software baseline for this kit
• Search for literature number “SPRUGQ1” to get the Quick Start Guide for the
board.

18 - 30 F28333x - Digital Motor Control


TI

C28x™ Digital Power Supply Workshop

Workshop Guide and Lab Manual

C28xdps
Revision 1.1
May 2008
Technical Training
Organization
Workshop Topics

Important Notice
Texas Instruments and its subsidiaries (TI) reserve the right to make changes to their products or to
discontinue any product or service without notice, and advise customers to obtain the latest version of
relevant information to verify, before placing orders, that information being relied on is current and
complete. All products are sold subject to the terms and conditions of sale supplied at the time of order
acknowledgment, including those pertaining to warranty, patent infringement, and limitation of liability.

TI warrants performance of its semiconductor products to the specifications applicable at the time of sale in
accordance with TI’s standard warranty. Testing and other quality control techniques are utilized to the
extent TI deems necessary to support this warranty. Specific testing of all parameters of each device is not
necessarily performed, except those mandated by government requirements.

Customers are responsible for their applications using TI components.

In order to minimize risks associated with the customer’s applications, adequate design and operating
safeguards must be provided by the customer to minimize inherent or procedural hazards.

TI assumes no liability for applications assistance or customer product design. TI does not warrant or
represent that any license, either express or implied, is granted under any patent right, copyright, mask
work right, or other intellectual property right of TI covering or relating to any combination, machine, or
process in which such semiconductor products or services might be or are used. TI’s publication of
information regarding any third party’s products or services does not constitute TI’s approval, warranty or
endorsement thereof.

Copyright © 2008 Texas Instruments Incorporated

Revision History
January 2008 – Revision 1.0
May 2008 – Revision 1.1

Mailing Address
Texas Instruments
Training Technical Organization
7839 Churchill Way
M/S 3984
Dallas, Texas 75251-1903

2 C28x Digital Power Supply Workshop


Workshop Topics

Workshop Topics
Workshop Topics.........................................................................................................................................3
Workshop Outline .......................................................................................................................................4
1 – Introduction to Digital Power Supply Design.......................................................................................5
What is a Digital Power Supply?............................................................................................................5
Why use Digital Control Techniques?....................................................................................................6
Peripherals used for Digital Power Supply Design...............................................................................10
Development Tools and Software ........................................................................................................12
Lab1: Exploring the Development Environment.......................................................................................16
2 – Driving the Power Stage with PWM Waveforms ................................................................................24
Open-Loop System Block Diagram......................................................................................................24
Generating PWM using the ePWM Module.........................................................................................25
Power Stage Topologies and Software Library Support.......................................................................28
Lab2: PWM Generation / Open-Loop Control .........................................................................................32
3 – Controlling the Power Stage with Feedback.......................................................................................42
Closed-Loop System Block Diagram ...................................................................................................42
ADC Module Block Diagram...............................................................................................................43
Digital Control of Power Converter .....................................................................................................43
High-Resolution PWM Benefits...........................................................................................................46
Soft Start – Starting the Loop ...............................................................................................................47
Lab3: Closed-Loop Control ......................................................................................................................48
4 – Tuning the Loop for Good Transient Response ..................................................................................57
Digital Power Supply Control Theory ..................................................................................................57
Intuitive Loop Tuning – “Visually without Math” ...............................................................................59
Active Load Feature of the Power EVM ..............................................................................................63
Lab4: Tuning the Loop..............................................................................................................................64
Multi-Loop Control ..............................................................................................................................71
5 – Summary and Conclusion ...................................................................................................................73
Review of Workshop Topics and Exercises .........................................................................................73
TI Digital Power Products ....................................................................................................................74
C2000 Digital Signal Controller Family...............................................................................................75
UCD9xxx Digital Power Controller Family .........................................................................................80
Where to Find More Information .........................................................................................................81

C28x Digital Power Supply Workshop 3


Workshop Outline

Workshop Outline
Workshop Outline
1. Introduction to Digital Power
Supply Design
Š Lab: Exploring the Development Environment
2. Driving the Power Stage with PWM
Waveforms
Š Lab: PWM Generation / Open-Loop Control
3. Controlling the Power Stage with
Feedback
Š Lab: Closed-Loop Control
4. Tuning the Loop for Good Transient
Response
Š Lab: Tuning the Loop
5. Summary and Conclusion

4 C28x Digital Power Supply Workshop


1 – Introduction to Digital Power Supply Design

1 – Introduction to Digital Power Supply Design


Introduction to Digital Power Supply Design

‹ What is a Digital Power Supply?


‹ Why use Digital Control
Techniques?
‹ Peripherals used for Digital Power
Supply Design
‹ Development Tools and Software

What is a Digital Power Supply?


What is Digital Power?
Generic Power System Block Diagram

Vin

Controller PWM Switches LC Vout


(Compensator) (FETs) Network

The controller block is what differentiates between a digital


power system and a conventional analog power system

C28x Digital Power Supply Workshop 5


1 – Introduction to Digital Power Supply Design

Why use Digital Control Techniques?


Why Digital Control Techniques?
Controller PWM Power Elec.
Analog
or
Digital ?? Sensor(s)

Analog Controller Digital Controller


‹ High bandwidth ‹ Insensitive to environment (temp, drift,…)
+ ‹ High resolution ‹ S/w programmable / flexible solution
‹ Easy to understand / use ‹ Precise / predictable behavior
‹ Historically lower cost ‹ Advanced control possible (non-linear, multi-variable)
‹ Can perform multiple loops and “other” functions

‹ Component drift and aging / unstable ‹ Bandwidth limitations (sampling loop)


‹ Component tolerances ‹ PWM frequency and resolution limits
‹ Hardwired / not flexible ‹ Numerical problems (quantization, rounding,…)

‹ Limited to classical control theory only ‹ AD / DA boundary (resolution, speed, cost)


‹ CPU performance limitations
‹ Large parts count for complex systems
‹ Bias supplies, interface requirements

Benefits of Digital Control


V I Filter V PFC VI DC/DC V I V I
Output
Bridge
8 4

5 1 Traditional Analog
Inrush/ DC/DC
DC/DC Current/Load
Current/Load Power Supply
Hot-plug PFC Control Converter
Converter Sharing
Sharing
Control Control
Control Control
Control „ Multiple chips for
Interface Multi-mode
Multi-mode control
Power control
Power control
Circuit „ Micro-controller for
Monitor Supervisory
Supervisory
MCU
MCU Housekeeping
Housekeeping supervisory
(MCU)
(MCU?) Circuits
Circuits
„ Dedicated design
Aux P/S To Host

Eliminate Components
Filter V PFC DC/DC V Output
Bridge Reduce Manufacturing Cost

Better Performance Across Corners

One Design, Multiple Supplies

Failure Prediction
Aux P/S
One Device, Multiple DC Outputs

Variable DC Output
Digital controller enables multi-threaded applications

6 C28x Digital Power Supply Workshop


1 – Introduction to Digital Power Supply Design

Analog Control System


e C P
R
+ Σ (controller) (plant)
Y
-
“Analog Computation”
Differential equations
C2 C

C1
R
Energy
R2 R
Storage
R
Elements
R1
L

d 3 y (t ) d 2 y (t ) dy(t )
+ k2 + k1 +k 0 y (t ) = f (t )
R2 ⎛ 1 + R1C1s ⎞ 3
dt 2
C ( s) = ⎜ ⎟ dt dt
R1 ⎜⎝ 1 + R2C2 s ⎟⎠ Differential equations
1st, 2nd, 3rd,…order

Need to find: Laplace Transform


R1, R2, C1, C2

Digital Control System


E Cd U D-A P
R
+ Σ (controller) ZOH (plant) Y
-
A-D
S&H

Difference equation C

U(n) = a2 ⋅U(n − 2) + a1 ⋅U(n −1) + Energy


R
Storage
b2 ⋅ E(n − 2) + b1 ⋅ E(n −1) + b0 ⋅ E(n) Elements
L
whereK E(n) = R(n) − Y (n)

d 3 y (t ) d 2 y (t ) dy(t )
Need to find: 3
+ k2 + k1 +k 0 y (t ) = f (t )
dt dt 2 dt
a1, a2, b0, b1, b2 Differential equations
1st, 2nd, 3rd,…order
Laplace Transform
OR
Z Transform

C28x Digital Power Supply Workshop 7


1 – Introduction to Digital Power Supply Design

Time Sampled Systems

Digital Processor

- Control
A-D Σ Law
D-A
+
Ref

y(t) y(n) u(n) u(t)


sample
period
T

t t t t
Continuous Discrete
time signal time signal

Processor Bandwidth
y(n)

TSAMPLE

Processor Control Code Control Code Control

Sam ple Freq (=PW M) Sa mple Period


(kHz ) (ns )
100 10000
300 3333
500 2000
700 1429
1000 1000
1500 667
2000 500

8 C28x Digital Power Supply Workshop


1 – Introduction to Digital Power Supply Design

Time Division Multiplexing (TDM)


y(n)
TSAMPLE

Processor 1 Control Code (C1) Control Code Control

Processor 2 Control Code (C2) Control Code Control

Processor 3 Control Code (C3) Control Code Control

Single CPU C1 C2 C3 C1 C2 C3 C1 C2 C3

Digitally Controlled Power Supply

DAC
(PWM)

DSC
ADC
“Plant”

0110101100
1011011101
0010100111
“High fidelity”
Translation boundary

C28x Digital Power Supply Workshop 9


1 – Introduction to Digital Power Supply Design

System Mapping
PFC – 3ph Interleaved
VO UT
F280xx Vin

Ch1
DSP ADC
Ch2
32 bit core
12 bit
60~100
(80nS)
MHz Ch16

1A
ePWM1 1B
2A Phase-Shifted Full Bridge
ePWM2 2B
3A VIN V OUT
ePWM3 3B

8A
ePWM8 8B

Peripherals used for Digital Power Supply Design


TMS320F280x
TM

Code security
High Performance DSP (C28x Core)
ƒ 100MIPS performance
64Kw Flash 18Kw 4Kw ƒ Single cycle 32 x32-bit MAC (or dual 16 x16 MAC)
+ 1Kw OTP RAM Boot ePWM
ROM ƒ Very Fast Interrupt Response
ƒ Single cycle read-modified-write
eCAP
Memory Bus Memory Sub-System
eQEP
Fast program execution out of both RAM and
12-bit ADC Flash memory
Peripheral Bus

Interrupt Management ƒ 85 MIPS with Flash Acceleration Technology


Watchdog
ƒ 100 MIPS out of RAM for time-critical code

TM
100 MIPs C28x 32-bit DSP Control Peripherals
32x32-bit CAN 2.0 B Up to 6 ePWM, 4 eCAP, and 2 eQEP
R‚M‚W
Multiplier Atomic Ultra-Fast 12-bit ADC
I2C
ALU ƒ 6.25 MSPS throughput
32-bit
SCI ƒ Dual sample&holds enable simultaneous sampling
Timers (3)
32-bit ƒ Auto Sequencer, up to 16 conversions w/o CPU
SPI
Real-Time Register
File
Communications Ports
JTAG GPIO
Multiple standard communication ports provide
simple interfaces to other components

Datasheet available at: http://www-s.ti.com/sc/ds/tms320f2808.pdf

10 C28x Digital Power Supply Workshop


1 – Introduction to Digital Power Supply Design

Efficient 32-bit Processor Capability


Interrupt Management C28xTM DSP Core
ƒ Single-cycle 32-bit multiplier makes
TM
C28x 32-bit DSP computationally intensive control
32x32 bit R‚M‚W algorithms more efficient
Multiplier Atomic
ALU
ƒ Three 32-bit timers support multiple
32-bit control loops / time bases
Timers (3)
32-bit ƒ Single cycle read-modified-write in any
Real-Time
Register memory location and 32-bit registers
JTAG
File improve control algorithm efficiency
ƒ Real-time JTAG debug shortens
# Instructions vs PWM development cycle
PWM freq. PWM per. Processor MIPS ƒ Fast & flexible interrupt management
(kHz) (μs) 100 150 significantly reduce interrupt latency
50 20.0 2000 3000
100 10.0 1000 1500
200 5.0 500 750 TPWM
250 4.0 400 600
300 3.3 333 500 PWM
500 2.0 200 300
750 1.3 133 200 CPU Control Code spare Control Code spare Control

1000 1.0 100 150


MIPS = Million Instruction Per Second

ePWM “DAC” Capability


ePWM Control Peripherals
Event
Time-Base Trig. Trip EPWMxA ePWM
Zone EPWMxB
Qualifier

& Int.
ƒ Number of channels scalable
Action

Counter Dead PWM and resources allocated per


Compare Band Chop channel
ƒ Two independent PWM outputs
per module
ƒ Dedicated time-base timer
PWM effective resolution (CPU=100MHz) ƒ Two independent compare
PWM Standard PWM HR-PWM registers
(kHz) bits % bits % ƒ Multi-event driven waveform
50 11.0 0.05 17.0 0.0007 ƒ Trip zones and event interrupts
100 10.0 0.10 16.0 0.0015 ƒ F2808 offers 6 modules
150 9.4 0.15 15.4 0.0022 ƒ Provides ePWM DAC capability
250 8.6 0.25 14.7 0.0037 for DPS
500 7.6 0.50 13.7 0.0075 ƒ Switching can be programmed
750 7.1 0.75 13.1 0.0112 as Asymmetric or Symmetric
1000 6.6 1.00 12.7 0.0150 PWM
ƒ High-Resolution PWM mode

C28x Digital Power Supply Workshop 11


1 – Introduction to Digital Power Supply Design

12-bit ADC Capability


SYSCLK
Control Peripherals
ADC Prescaler

Fast & Flexible


8 ADC Analog S/H
Inputs MUX A 12-bit 16-Channel ADC
12-bit Result
Registers
ADC
Module 16 words
ƒ 12.5 MSPS throughput
8 ADC Analog S/H
Inputs MUX B
ƒ Dual sample/hold enable
simultaneous sampling or
Start of sequencing sampling modes
Conversion Auto Sequencer
ƒ Analog input: 0V to 3V
ƒ 16 channel, multiplexed inputs
ADC Utilization:
ƒ Auto Sequencer supports up to 16
# Channels (“Loops”) vs. PWM frequency
conversions without CPU
MSPS = 3 MSPS = 6.25
PWM # Channels PWM # Channels
intervention
(kHz) (kHz) ƒ Sequencer can be operated as two
125 24 125 50
250 12 250 25
independent 8-state sequencers or
500 6 500 13 as one large 16-state sequencer
750 4 750 8
1000 3 1000 6 ƒ Sixteen result registers (individually
addressable) to store conversion
values

Development Tools and Software


Code Composer Studio
CPU
Menus or Icons Help Window

Project Manager:
¾Source & object files
¾File dependencies
¾Compiler, Assembler &
Linker build options

Full C/C++ & Assembly


Debugging:
¾C & ASM Source
¾Mixed mode
¾Disassembly (patch)
¾Set Break Points
¾Set Probe Points

Editor:
¾Structure Expansion

Status Watch Window Graph Memory Window


Window Window

12 C28x Digital Power Supply Workshop


1 – Introduction to Digital Power Supply Design

Software Library Approach


CNTL CNTL Buck E HR E

2P2Z 3P3Z Single P


W
Buck P
W
Ref Ref DRV M Single M
FB
Uout
FB
Uout DRV
Duty H EPWMnA Duty H EPWMnA
W W
Control 2-pole / 2-zero Control 3-pole / 3-zero
Buck Single Output High Resolution Buck
IIR-FILT IIR-FILT
2P2Z 3P3Z EPWM1A PFC E
MPIL E
EPWM1B 2PHIL P
P W
f f DRV W DRV M
EPWM2A
M
Duty EPWMnA
In Out In Out EPWM2B H
H Adj W EPWMnB
2nd order IIR filter 3rd order IIR filter Duty W
Power Factor 2-phase
Multi-Phase Interleaved Interleaved
SinGen1 SGenHP1
E IBM
HHB P E
Freq F req DRV W FB P EPWMnA

Gain Out Gain Out


M DRV W
EPWMnB
M
EPWMnA
Offset Offset Duty H In
EPWM(n+1)A
W EPWMnB H
D elLL
Sine Wave generator High precision Sine Gen W EPWM(n+1)B
Half H-Bridge D elRL

IBM method Full Bridge


SSartSEQ
INV
PSFB E
SQ R EPWMnA Ch0
DRV P
ADC
A
D Ch1
W
EPWMnB Ch3
In Out
Delay
M DRV C
Ch4
Phase
EPWM(n+1)A
Slope Out H H
Inverse Square function Llegdb
Rslt
T arget W EPWM(n+1)B W
Rlegdb

Soft Start and Sequencing Phase Shifted Full Bridge Analog-Digital Converter driver

Modular Software Architecture


“Signal Net” based module connectivity

f1
Net1
In 1A
O ut1
Net5
In4A
f4
Net2
In 1B Net6 Net8
In4B Out4
Net7
In4C
f2
In 2A O ut2
f5
Net3

In5A Out5 Net9

f3
Net4 In 3A O ut3

Initialization time
Run time - ISR
// pointer & Net declarations
Int *In1A, *In1B, *Out1, *In2A,... ; Execute the code
Int Net1, Net2, Net3, Net4,...
f1
// “connect” the modules f2
In1A=&Net1; In1B=&Net2; In2A=&Net3; In3A=&Net4; // inputs f3
Out4=&Net8; Out5=&Net9; // outputs f4
Out1=&Net5; In4A=&Net5; // Net5
Out2=&Net6; In4B=&Net6; // Net6
f5
Out3=&Net7; In4C=&Net7; In5A=&Net7; // Net7

C28x Digital Power Supply Workshop 13


1 – Introduction to Digital Power Supply Design

Peripheral Drivers
CPU dependency only:
• Math / algorithms Depends on:
• Per-Unit math (0-100%) • PWM frequency
• Independent of Hardware • System clock frequency
E
BUCK P
CNTL DRV W
2P2Z M
Vref Ref Duty
Out In H EPWM1A
(Q15) (Q15) W
Fdbk

ADC
SEQ1 A
DRV D
Vout Rslt0
C
ADC_A0
(Q15)
H ADC_A1
W ADC_A2
// pointer & Net declarations
int *CNTL_Ref1, *CNTL_Fdbk1, *CNTL_Out1; ADC_A3
int *BUCK_In1, *ADC_Rslt1;
int Vref, Duty, Vout;

// “connect” the modules Depends on:


CNTL_Ref1 = &Vref; • # ADC bits (10 / 12 ?)
CNTL_Out1 = &Duty; BUCK_In1 = &Duty;
CNTL_Fdbk1 = &Vout; ADC_Rslt1 = &Vout; • Unipolar, Bipolar ?
• Offset ?

Dual Buck Example


BG ISR
Start / Stop trigger
Single Power Stage
Voltag e E

S-start / SEQ
Contro ller BUCK P Vin Vout1
W
CNTL
DRV M
2P2Z
V ref1 H
Ref Uout DutyCmd 1 Duty W EPWM1A DRV B uck
FB
400 kHz
400 kHz
A
ADC D
DRV C

H
Vout1 rslt0 W Ch0

400 kHz

Single Power Stage


Voltag e E

S-start / SEQ
Contro ller BUCK P Vin Vo ut2
W
CNTL
DRV M
2P2Z
V ref2 H
Ref Uout DutyCmd 2 Duty W EPWM2A DRV B uck
FB
400 kHz
400 kHz
A
ADC D
DRV C

H
Vout2 rslt0 W Ch1

400 kHz

14 C28x Digital Power Supply Workshop


1 – Introduction to Digital Power Supply Design

Software Block Execution


BG ISR
(400 kHz)

SStartSeq
Context Save
Comms
ADC_DRV (1)

CNTL_2P2Z(1) Loop-1

BUCK_DRV (1)

ISR body
ADC_DRV (2)

CNTL_2P2Z(2) Loop-2
Other....
BUCK_DRV (2)

Context
Restore

C28x Digital Power Supply Workshop 15


Lab1: Exploring the Development Environment

Lab1: Exploring the Development Environment


¾ Objective

The objective of this lab exercise is to demonstrate the topics discussed in this module and
become familiar with the operation of Code Composer Studio (CCS). Steps required to build and
run a project will be explored. The project will generate various PWM waveforms which will be
viewed using the CCS graphical capabilities. The slider feature in CCS will be used to adjust the
duty, phase, and dead-band values of the waveforms. Additionally, the Digital Power software
framework, associated files, and library modules will be used.

Lab1: Exploring the Development Environment

‹ Navigate CCS features


‹ Understand DPS library structure
‹ Generate and visualize PWM waveforms
TI PowerTrain
PTD08A010W Active Volt
SW1 Phase Links
10A module Load LEDs Meter
ƒ Current meas.
ƒ Temp meas
ƒ Over Current Prot.
ƒ Over Current Flag
ƒ No Heat-sink needed

controlCard 2808

¾ Project Overview

The PWMexplore project makes use of the “C-background/ASM-ISR” framework. This


framework will be used throughout all the lab exercises in this workshop. It uses C-code as the
main supporting program for the application, and is responsible for all system management tasks,
decision making, intelligence, and host interaction. The assembly code is strictly limited to the
ISR, which runs all the critical control code and typically this includes ADC reading, control
calculations, and PWM updates.

The key framework C files used in this project are:

PWMexplore-Main.c – this file is used to initialize, run, and manage the application. This is
the “brains” behind the application.

PWMexplore-DevInit.c – this file is responsible for a one time initialization and


configuration of the F280x device, and includes functions such as setting up the clocks, PLL,
GPIO, etc.

16 C28x Digital Power Supply Workshop


Lab1: Exploring the Development Environment

The ISR consists of a single file:

PWMexplore-ISR.asm – this file contains all time critical “control type” code. This file has
an initialization section (one time execute) and a run-time section which executes (typically) at
the same rate as the PWM timebase used to trigger it.

The Power Library functions (modules) are “called” from this framework. Library modules may
have both a C and an assembly component. In this lab exercise, six library modules (all PWM
waveform generators or drivers) are used. The C and corresponding assembly module names are:

C configure function ASM initialization macro ASM run-time macro

BuckSingle_CNF() BuckSingle_DRV_INIT n BuckSingle_DRV n

BuckDual_CNF() BuckDual_DRV_INIT n BuckDual_DRV n

MPhIL_CNF() MPhIL_DRV_INIT n, N MPhIL_DRV n, N

FullBridgePS_CNF() FullBridgePS_DRV_INIT n FullBridgePS_DRV n

FullBridgeIBM_CNF() FullBridgeIBM_DRV_INIT n FullBridgeIBM_DRV n

PFC2PhIL_CNF() PFC2PhIL_DRV_INIT n PFC2PhIL_DRV_INIT n

These blocks can also be represented graphically. This helps visualize the system software flow
and function input/output. The PWM driver modules used in Lab1 are:

C28x Digital Power Supply Workshop 17


Lab1: Exploring the Development Environment

¾ Lab Exercise Overview

The software in Lab1 has been configured so the user can quickly evaluate the 6 PWM driver
modules by viewing the output waveforms and interactively adjusting the duty, phase, and
deadband values. The graphing feature of CCS is used to visualize the waveform. The ADC
peripheral is configured to provide a “scope” capture function. The PWM outputs on the buck
EVM are directly connected to ADC inputs via zero ohm resistors. Collected data samples are
stored in four separate memory buffers, hence a simple 4-channel scope is realized. CCS can link
each memory buffer to a graph window and display the captured data. With the real-time feature
enabled, this data can be captured at high speed and streamed back via JTAG (at a slower rate) to
update the graph windows periodically (~200 ms update rate).

Since the PWM waveforms being sampled are essentially “square waves” (high speed edges) they
have been scaled down in frequency to approximately 10 kHz. This allows the ADC sampling to
better capture and display the edge transitions in the graph window during datalogging. As Lab1
is more for visual demonstration purposes, the high speed ISR code subroutine _ISR_Run has
been allocated to datalogging. The PWM driver macros are running at a much slower update rate
from subroutine _ISR_Pseudo, which is conveniently called directly from C. The PWM driver
macro instantiation convention however is still the same as in the more typical case where
_ISR_Run is used to execute all PWM updates and loop control. This will be the convention
used in Labs 2, 3 and 4 where an actual 2-channel buck stage will be controlled with high speed
PWM outputs.

The following diagram shows an example of how the Full Bridge Phase Shifted PWM module is
evaluated in this lab. This setup is essentially the same for all 6 cases, except the PWM driver
macro module is swapped and the appropriate sliders used to adjust the relevant timing are
selected.

18 C28x Digital Power Supply Workshop


Lab1: Exploring the Development Environment

¾ Procedure

Start CCS and Open a Project


1. Move the switch SW1 to the “on” position to power the 2-channel buck EVM board.

2. Double click on the Code Composer Studio icon on the desktop. Maximize Code
Composer Studio to fill your screen. Code Composer Studio has a Connect/Disconnect
feature which allows the target to be dynamically connected and disconnected. This will
reset the JTAG link and also enable “hot swapping” a target board. Connect to the target.

Click: Debug Æ Connect

The menu bar (at the top) lists File ... Help. Note the horizontal tool bar below the menu
bar and the vertical tool bar on the left-hand side. The window on the left is the project
window and the large right hand window is your workspace.

3. A project contains all the files and build options needed to develop an executable output
file (.out) which can be run on the DSP hardware. A project named Lab1.pjt has
been created for this lab exercise. Open the project by clicking:

Project Æ Open…

and look in C:\C28x_DPS\LABS\LAB1. This project (.pjt file) will invoke all the
necessary tools (compiler, assembler, linker) to build the project. It will also create a
folder that will hold immediate output files.

4. In the project window on the left, click the plus sign (+) to the left of Project. Now,
click on the plus sign next to Lab1.pjt. Click on the plus sign next to Source to see
the current source file list.

5. A GEL file can be used to create a custom GEL menu and automate steps in CCS. A
GEL file which will setup sliders has been created for this lab exercise. The slider will be
used to adjust the duty, phase, and dead-band values of the waveforms. Load the
PWMexplore.gel file by clicking:

File Æ Load Gel…

and look in C:\C28x_DPS\LABS\LAB1.

Device Initialization, Main, and ISR Files

Note: DO NOT make any changes to the source files – ONLY INSPECT

6. Open and inspect PWMexplore-DevInit.c by double clicking on the filename in the


project window. Notice that system clock, peripheral clock prescale, and peripheral
clock enables have been setup. Next, notice that the shared GPIO pins have been
configured.

C28x Digital Power Supply Workshop 19


Lab1: Exploring the Development Environment

7. Open and inspect PWMexplore-Main.c. Notice the background for(;;) loop and
the case statements. This is where each of the PWM configuration functions are called
for the 6 cases previously described. The case statement provides a convenient way to
showcase each PWM driver quickly and interactively for demonstration purposes.

8. Open and inspect PWMexplore-ISR.asm. Notice the _ISR_Init and


_ISR_Pseudo sections. This is where the PWM driver macro instantiation is done for
initialization and runtime, respectively. Optionally, you can close the inspected files.

Build and Load the Project


9. The top four buttons on the horizontal toolbar control code generation. Hover your
mouse over each button as you read the following descriptions:
Button Name Description
1 Compile File Compile, assemble the current open file
2 Incremental Build Compile, assemble only changed files, then link
3 Rebuild All Compile, assemble all files, then link
4 Stop Build Stop code generation
10. Code Composer Studio can automatically load the output file after a successful build. On
the menu bar click: Option Æ Customize… and select the
“Program/Project/CIO” tab, check “Load Program After Build”.

Also, Code Composer Studio can automatically connect to the target when started. Select
the “Debug Properties” tab, check “Connect to the target at
startup”, then click OK.

11. Click the “Rebuild All” button and watch the tools run in the build window. The
output file should automatically load.

12. Under Debug on the menu bar click “Reset CPU”, “Restart”, and then “Go
Main”. You should now be at the start of Main().

Debug Environment Windows


It is standard debug practice to watch local and global variables while debugging code. There
are various methods for doing this in Code Composer Studio, such as memory windows and
watch windows. Additionally, Code Composer Studio has the ability to make time (and
frequency) domain plots. This allows us to view waveforms using graph windows. We will
use two of them here: watch windows and graph windows.

13. Open the watch window to view the variables used in the project.

Click: View Æ Watch Window on the menu bar.

Click the “Watch 1" tab at the bottom of the watch window. In the empty box in the
"Name" column, type the symbol name “ConfigOption” and press enter on
keyboard. Next add the following other symbol names: “Duty1”, “Duty2”,

20 C28x Digital Power Supply Workshop


Lab1: Exploring the Development Environment

“Phase”, “DbLeft”, and “DbRight”. The watch window should look something
like:

14. Open and setup two dual time graph windows to plot the four data log buffers A, B, C
and D (ADC result registers). Click: View Æ Graph Æ Time/Frequency… and
set the following values:

Select OK to save the graph options.

Saving the Workspace Environment


The workspace contains all of the elements that make up the current Code Composer Studio
working environment. These elements include the project, project settings, configuration settings,
and windows such as watch window and graphs. A workspace can be saved in a workspace file
(*.wks) and reloaded at a later time. This is very useful for a subsequent Code Composer Studio
session, or if a problem occurs and the tools need to be reset.

15. Save the current workspace by naming it Lab1.wks and clicking:

File Æ Workspace Æ Save Workspace As…

C28x Digital Power Supply Workshop 21


Lab1: Exploring the Development Environment

and saving in C:\C28x_DPS\LABS\LAB1.

When needed, a workspace can be loaded by clicking:

File Æ Workspace Æ Load Workspace…

and looking in the saved location.

Using Real-time Emulation


Real-time emulation is a special emulation feature that allows the windows within Code
Composer Studio to be updated at up to a 10 Hz rate while the DSP is running. This not only
allows graphs and watch windows to update, but also allows the user to change values in
watch or memory windows, and have those changes affect the DSP behavior. This is very
useful when tuning control law parameters on-the-fly, for example.

16. Enable real-time mode by selecting:

Debug Æ Real-time Mode

17. A message box may appear. If so, select YES to enable debug events. This will set bit 1
(DGBM bit) of status register 1 (ST1) to a “0”. The DGBM is the debug enable mask bit.
When the DGBM bit is set to “0”, memory and register values can be passed to the host
processor for updating the debugger windows.
18. The graph windows should be open. In real-time mode, we would like to have our
window continuously refresh. Click:

View Æ Real-time Refresh Options…

and check “Global Continuous Refresh”. Use the default refresh rate of 100
ms and select OK. Alternately, we could have right clicked on each window individually
and selected “Continuous Refresh”.

Note: “Global Continuous Refresh” causes all open windows to refresh at the
refresh rate. This can be problematic when a large number of windows are open, as
bandwidth over the emulation link is limited. Updating too many windows can cause the
refresh frequency to bog down. In that case, either close some windows, or disable
global refresh and selectively enable “Continuous Refresh” for individual
windows of interest instead.

Run the Code – PWMexplore


19. Run the code by using the <F5> key, or using the Run button on the vertical toolbar, or
using Debug Æ Run on the menu bar. The top graph window should display two
PWM waveforms generated by the two BuckSingle macros.

20. In the watch window, the variable ConfigOption should be set to 1. This option or
case selects the BuckSingle macro (actually there are two of them) as the active wave-
form generator. Change the option to 2, and examine the waveforms for the BuckDual.

22 C28x Digital Power Supply Workshop


Lab1: Exploring the Development Environment

Next, try the other options. Below is a list of the active PWM driver macro for each se-
lected ConfigOption:

1 BuckSingle (uses 2 single buck modules)


2 BuckDual
3 MPhIL (Multi-Phase Interleaved)
4 FullBridgePS (Phase-shifted full bridge)
5 FullBridgeIBM (IBM method Full bridge)
6 PFC2PhIL (2 phase Interleaved PFC)

21. Select the BuckSingle again (ConfigOption = 1). Open sliders D1Slider,
D2Slider and TrigSlider by using GEL Æ PWM explore Sliders Æ and move
the sliders into the workspace area. The D1Slider and D2slider control the duty cycle of
each BuckSingle. The TrigSlider works by moving a trigger point similar to a trigger on
an oscilloscope, and permits the waveform to be viewed more conveniently. Note, when
adjusting the sliders the actual value in the watch window also changes. The value can
be changed by directly editing the watch window, but the slider position will not be up-
dated.
22. Next, select FullBridgePS (ConfigOption = 4). Open sliders PhaseSlider,
DbLSlider, and DbRSlider (GEL Æ PWM explore slidersÆ). The PhaseSlider
controls the phase relationship between the left and right legs of the full bridge. The
DbLslider and DbRSlider control the deadband of left leg and right leg, respectively.
23. Fully halting the DSP when in real-time mode is a two-step process. First, halt the proc-
essor by using Shift <F5>, or using the Halt button on the vertical toolbar, or by using
Debug Æ Halt. Then click Debug Æ Real-time Mode and uncheck the
“Real-time mode” to take the DSP out of real-time mode.

24. If time permits, evaluate the other PWM macro drivers. The D1Slider is used to adjust
duty in ConfigOptions 3, 5, and 6. The LLdelSlider (left-leg delay) and LRdelSlider
(right-leg delay) is used to adjust the delay between bottom falling edge to top rising edge
for left and right full bridge legs, respectively in ConfigOption 5.
25. Close Code Composer Studio and turn off the power (SW1) to the 2-channel buck EVM.

End of Exercise

C28x Digital Power Supply Workshop 23


2 – Driving the Power Stage with PWM Waveforms

2 – Driving the Power Stage with PWM Waveforms


Driving the Power Stage with PWM Waveforms

‹ Open-Loop System Block Diagram


‹ Generating PWM using the ePWM
Module
‹ Power Stage Topologies and
Software Library Support

Open-Loop System Block Diagram


Simple Open-Loop Diagram

Single Power Stage


E
HR P Vin1 Vout1
BUCK W
Watch Window DRV M

H
Duty1 Duty1 In W EPWMnA DRV Buck

Duty2
ADC A
D
Duty3 1CH
C
DRV
Duty1
H
slider Vfdbk Vout1 Rslt W Ch0

24 C28x Digital Power Supply Workshop


2 – Driving the Power Stage with PWM Waveforms

Generating PWM using the ePWM Module


Scaleable PWM Peripherals
Each peripheral module has the same structure

xSYNCI

SYNCI

EPWM1INTn EPWM1AO ‰ Resources allocated on a per channel basis


EPWM1
‰ Each channel (module) supports 2
EPWM1SOC
Module EPWM1BO

SYNCO independent PWM outputs (A&B)


xSYNCO

SYNCI ‰ # Channels easily scaleable – software reuse


EPWM2INTn
EPWM2
EPWM2AO
‰ Time-base synch feature for all channels
PIE EPWM2SOC
Module GPIO
EPWM2BO
Mux ‰ 6 modules (12 PWM outputs) on F2808
SYNCO
‰ Key features:
‰Phase & edge control
SYNCI ‰New counting modes
EPWM6INTn
EPWM6
EPWM6AO
‰Independent deadband
EPWM6SOC
Module EPWM6BO
‰Flexible trip-zones
TZ1n to TZ6n
SOC SYNCO
‰High frequency chopper mode
xSOC

VBus32
ADC
to ECAP1 module (sync in)

ePWM Module Block Diagram


T im e -B a s e (T B )
S yn c
T B PR D S h ad o w (16) C TR = Z E R O In / O u t
S e le ct E PW M xS Y N C O
T B P R D A c ti v e (1 6 ) CT R=CMP B M ux

D i sa b le d
S0 S1
C T R = PR D

T B CT L[ S Y N C O S E L ]
16
E P W M x S YN C I
C o u n ter T B CT L [S W F S Y N C]
UP / D W N T B C T L [ CN T L D E ] (so ft w a re f orce d sy nc)

(1 6 b i t)

TBC NT C TR =ZE R O
A c t iv e (1 6 ) C T R _ D ir

16

Ph a se
T B PH S A c ti v e ( 1 6 ) C T R = PR D
C o n tr o l
E P W M x IN T n
CT R=Z E RO
E v en t
T rig g e r &
CT R=CMPA EP W M xS O C A
In t e rr u p t
C o u n ter C o m p a r e (C C ) CT R=CMPB (E T )
EP W M xS O C B
C T R _ D ir

16
C TR =C M P A

A c tio n
Q ua l i fie r
16 (A Q )

C M P A A c ti ve ( 1 6 )
E PWM A E P W M xA O

C M P A S h ad o w (16) T rip
D ead PW M
Ban d Choppe r Z on e
(D B ) (P C ) ( TZ )
16 CT R=CMP B
E PWM B E P W M xB O
16

C M P B A c ti ve ( 1 6 ) E PW M xT Z I N T n

C M P B S h ad o w (16) T Z 1n to T Z 6 n
C TR =ZE R O

C28x Digital Power Supply Workshop 25


2 – Driving the Power Stage with PWM Waveforms

Module Sync and Phase Control

TBCTR
FFFFh
Master Module
Ext Sync In
(optional)
Master 600 600
TBPRD
Phase Reg En SyncIn
Φ = 0ο
EPWM1A

CNT=Zero
CNT=CMPB EPWM1B 0000
1 X
SyncOut CTR=Zero
(SycnOut)
time
TBCTR
FFFFh Φ2
Phase = 120o
Slave Module
Slave 600 600
TBPRD
Phase Reg En SyncIn
Φ=Ξ ο
EPWM2A 200 200
CNT=Zero TBPHS
CNT=CMPB EPWM2B
0000
2 X
SyncOut
SyncIn

time

Action Qualifier Module (AQ)


Key Features TBCTR = Period

‰ Multi event driven waveform generator TBCT R = Zero Action EPWMA

‰ Events drive outputs A and B independently. Qualifier


TBCTR = Co mpare A
‰ Full control on waveform polarity Module
TBCTR = Co mpare B (AQ) EPWMB
‰ Full transparency on waveform construction
‰ S/W forcing events supported SW force

‰ All events can generate interrupts & ADC SOC


TBCTR Directio n
Actions
Events
Nothi ng Clear Lo Set Hi Toggle

Zero Z Z Z Z
TBCTR
(ZRO) T
CMPA CA CA CA CA PRD
TBCTR (CAu) Period
T
(Up) CBu CBd
equals: CMPB CB CB CB CB CMPB
(CBu) T
CAu CAd
P P P P
CMPA
Period
(PRD) T ZRO
CMPA CA CA CA CA Zero
TBCTR (CAd) T
(Down)
equals: CMPB CB CB CB CB
(CBd) T
SW SW SW SW
S/W force
T

26 C28x Digital Power Supply Workshop


2 – Driving the Power Stage with PWM Waveforms

Simple Waveform Construction


TBCT R
T B PR D
val ue

Z P CB CA Z P CB CA Z P

EPWMA

Z P CB CA Z P CB CA Z P

EPWMB

TB CT R
TB PR D
v a lu e

CA CB CA CB

EPWMA

Z Z Z
T T T

EPWMB

Fault Management Support


Vin Vout1
‘2808

EPW M1A Iin I1


EPW M2A
Iin EPW M1A Bu ck # 1
Hi Z

TZ1
ShutDown
I2
CL2 Vout2
TZ2

TZ3
CL1 I1
Action on
Fault
I2
IsetC L1 EPW M2A Bu ck # 2
EPW M1B Hi Z
IsetC L2
EPW M2B
IsetSD
ECAP1

IsetS D

Iin
Trip Zones: I1 IsetCL1
IsetCL2
6 independent zones (TZ1~TZ6) I2
Force High, Low or HiZ on trip
One-time trip Æ catastrophic failure EPWM1A

Cycle-by-cycle Æ current limit mode


EPWM2A
TZ1~TZ6 can trigger interrupt

C28x Digital Power Supply Workshop 27


2 – Driving the Power Stage with PWM Waveforms

Power Stage Topologies and Software Library Support


Multi-Phase Interleaved (MPI)
E xt Syn c In
(o ptiona l)
Master
Phase Reg En SyncIn
Φ = 0ο EPWM1A
CNT=Zero
CNT=CMPB EPWM1B Vin
1 X
SyncOut

EPWM1A EPWM2A EPWM3A


Slave
Phase Reg En SyncIn
Φ = 120ο EPWM2A
CNT=Zero
CNT=CMPB EPWM2B

2 X Vout
SyncOut

EPWM1B EPWM2B EPWM3B


Slave
Phase Reg En SyncIn
Φ = 240ο
EPWM3A
CNT=Zero
CNT=CMPB EPWM3B

3 X
SyncOut

Switching Requirements – MPI


P P P
I I I

• Asymmetrical PWM case


• Complementary output
generated by dead-band unit
P CA CB
A
P CA P
• CMPB triggers ADC SOC
Pulse Center
EPW M1A INIT-time
Φ2=120
• Period (1,2,3)
• CAu Action (1,2,3)
• PRD Action (1,2,3)
P P
CA CB
A
CA
• Phase (2,3)
• PRD Interrupt (1)
EPW M2A
• CBu ADC SOC (1,2,3)
Φ3=240
• Dead-band
RUN-time
CB
A
CA P CA P • CMPA (1,2,3)
• CMPB (1,2,3)
EPW M3A

28 C28x Digital Power Supply Workshop


2 – Driving the Power Stage with PWM Waveforms

Half H-Bridge (HHB)

VDC_bus VOUT

Ext Sync In
(optional)
Master
EPWM1A
Phase Reg En SyncIn
Φ = 0ο
EPWM1A
CNT=Zero
CNT=CMPB EPWM1B

1 X
SyncOut

EPWM1B

Switching Requirements – HHB


CMPA CMPA
modulation modulation • Up/Down Count
range range
• Asymmetrical PWM
• dead-band on A only
• 50 % max Modulation
CA CB Z CA Z (controlled by CMPA)
A
EPWM1B INIT-time
• ZRO Action (A,B)
Z CB CA Z CA • CAd Action
A • CAu Action
• CBd ADC trigger
EPWM1A DBRED DBRED
• CBd ADC trigger
• DBRED
Compare A modulation range:
0 < CMPA < ( PRD – ½ x DBRED ) RUN-time
• CMPA
• CMPB (optional)

C28x Digital Power Supply Workshop 29


2 – Driving the Power Stage with PWM Waveforms

Phase Shifted Full Bridge (PSFB)

Ext Sync In

Master
(optional)
VDC_bus VOUT
Phase Reg En SyncIn
Φ = 0ο
EPWM1A

CNT=Zero
CNT=CMPB EPWM1B
EPWM1A EPWM2A
1 X
SyncOut

Slave
Phase Reg En SyncIn
Φ = Var EPWM2A
CNT=Zero
CNT=CMPB EPWM2B
EPWM1B EPWM2B
2 X
SyncOut

Switching Requirements – PSFB


Z
I
Z
I
Z
I
• Asymmetrical PWM
• Using dead-band module
• Phase (F ) is the control variable
• Duty fixed at ~ 50%
Z CB CA Z CB CA Z
• RED / FED control ZVS trans.
A A i.e. via resonance
EPWM1A RED
• CMPB can trigger ADC SOC
ZVS
transition

EPWM1B
Power
Phase
FED INIT-time
ZVS
transition
• Period (1,2)
Φ2 = variable
• CMPA (1,2) ~ 50%
• CAu action (1,2)
• ZRO action (1,2)
Z CB CA Z CB CA Z
A A • CBu trigger for ADC SOC

EPWM2A RED
RUN-time
• Phase (2) – every cycle
EPWM2B
Power
Phase FED
• FED / RED (1,2) – slow loop

30 C28x Digital Power Supply Workshop


2 – Driving the Power Stage with PWM Waveforms

Software Driver Module – PSFB

50% duty

PSFB E
EPWM1A
DRV P
W EPWM1B
M
Net1 phase EPWM1A llegdb
EPWM2A Left leg
H
Net2 llegdb dead-band
W EPWM2B
EPWM1B Power
Net3 rlegdb Phase
llegdb

Φ2 = phase
VDC_bus VOUT

EPWM1A EPWM2A

EPWM2A rlegdb
right leg
dead-band
Power
EPWM2B Phase
EPWM1B EPWM2B rlegdb

“Left leg” “Right leg”

Software Driver Module – PFC2PHIL

PFC E
2PHIL P EPWM1A
DRV W
M
Net1 Duty
H EPWM1B
Net2 Adj W
EPWM1A +/-
Adj

VDC_bus

+/-
EPWM1B Adj

EPWM1A EPWM1B
Φ = 180 ο

C28x Digital Power Supply Workshop 31


Lab2: PWM Generation / Open-Loop Control

Lab2: PWM Generation / Open-Loop Control


¾ Objective

The objective of this lab exercise is to demonstrate the topics discussed in this module and control
the buck output voltage using simple PWM duty cycle adjustments without feedback. Since this
implementation is open-loop without a requirement for high speed feedback, the ADC will be
used to measure various values for instrumentation purposes and will be displayed using CCS.
The PWM duty cycle will be adjusted using watch windows or sliders. The Digital Power
software framework, associated files, and library modules will be used.

Lab2: PWM Generation / Open-Loop Control


‹ Control Buck output voltage using simple PWM
duty cycle adjustment without feedback
‹ Use CCS watch window and slider button features
to conveniently adjust PWM duty cycle

Buck E
Vin
Buck-1 Vo ut1
P
Watch W indow Single W
DRV M

Dut y1 Duty1 In H EPWM-1A DRV


W
Dut y2
Buck E
P
Single W
DRV M
Vin Buck-2 Vo ut2
Duty1 In H EPWM-2A
W
Watch W indow
DRV
Vout1
Duty1 Duty 2 Vout1
Vout2 A
slider slider ADC D Vout2
Temp1 Casc Temp1
C
Temp2
Temp2 Seq Iout1
H
CNF Iout2
Iout1 W Vin
Iout2

¾ Project Overview

Lab exercises 2, 3, and 4 use the TwoChannel project. It makes use of the “C-background/ASM-
ISR” framework. In Lab1 various PWM waveforms were generated using the EPWM modules 3,
4, and 5. The PWM outputs on the workshop EVM were not connected to power stages, but were
looped back as inputs to the ADC. In lab exercises 2, 3, and 4 EPWMs 1 and 2 are used to drive
buck stages Channel 1 and Channel 2, respectively.

The key framework files used in this project are:

TwoChannel-Main.c – this file is used to initialize, run, and manage the application. This is
the “brains” behind the application.

TwoChannel-DevInit.c – this file is responsible for a one time initialization and


configuration of the F280x device, and includes functions such as setting up the clocks, PLL,
GPIO, etc.

32 C28x Digital Power Supply Workshop


Lab2: PWM Generation / Open-Loop Control

TwoChannel-ISR.asm – this file contains all time critical “control type” code. This file has
an initialization section that is executed one time by the C-callable assembly subroutine
_ISR_Init. The _ISR_Run routine executes at the same rate as the PWM timebase which is
used to trigger it.

The Power Library functions (modules) are “called” from this framework. Library modules may
have both a C and an assembly component. In this lab exercise, the following C and
corresponding assembly modules are used:

C configure function ASM initialization macro ASM Run time macro

BuckSingle_CNF() BuckSingle_DRV_INIT n BuckSingle_DRV n

ADC_CascSeqCNF() none none

The workshop Power EVM consists of two identical buck power stages. The input bus voltage
for both stages is 12V. Shown below is a diagram of the Power EVM and some key features.

Main Pwr (SW1) Load 2 Load 1 Active Load

12V In

DMM

DC Bus
(SW2)

V1/V2
Select
(SW3)

Buck 2 Buck 1 Comms

12V In DC power supply from plug pack

Main Pwr SW1 - Master power switch for entire EVM

DC Bus SW2 - Power switch for Vin to buck stages only and when off F2808 DIMM
controller card still operates (next to the DC bus switch is a resettable fuse)

Buck 1, 2 Buck power stage modules with temperature/current measurement and over
current protection

Load 1, 2 Load terminals and/or buck converter output - next to each terminal block is a
light bulb or “visual” load (these draw approx 250 mA hot)

C28x Digital Power Supply Workshop 33


Lab2: PWM Generation / Open-Loop Control

Active Load Software controlled switched load (connected to output of buck 1 only)

DMM Digital Multi-Meter (has a range of 0~20V, with resolution of 10 mV and is


used to measure output voltage of buck conterters)

V1/V2 Select SW3 - selects between output voltage of buck 1 and 2

Comms Serial communications UART (optional for user, not used in lab exercises)

The key signal connections between the F2808 Digital Signal Controller and the 2 buck stages are
listed in the table below. For reference a portion of the shematic is also given.

Signal Name Description Connection to F2808

EPWM-1A PWM Duty control signal for buck stage 1 GPIO-00

EPWM-2A PWM Duty control signal for buck stage 2 GPIO-02

VoutFB-1 Voltage feedback for buck stage 1 ADC-B0

VoutFB-2 Voltage feedback for buck stage 2 ADC-A0

Iout-1 Current monitor / measurement buck stage 1 ADC-B1

Iout-2 Current monitor / measurement buck stage 2 ADC-A1

Temp-1 Temperature monitor / measurement buck stage 1 ADC-B2

Temp-2 Temperature monitor / measurement buck stage 2 ADC-A3

Ifault-1 Over-Current flag, digital output from buck stage 1 GPIO-01

Ifault-2 Over-Current flag, digital output from buck stage 2 GPIO-03

34 C28x Digital Power Supply Workshop


Lab2: PWM Generation / Open-Loop Control

C28x Digital Power Supply Workshop 35


Lab2: PWM Generation / Open-Loop Control

¾ Lab Exercise Overview

The software in Lab2 has been configured to independently adjust the duty cycle of EPWM-1A
and EPWM-2A. “Net” variable names Duty1 and Duty2 have been declared and “connected”
to the inputs of BuckSingle_DRV macro. Using either the watch window or the appropriate
slider, Duty1 and Duty2 can be directly adjusted. Below is the system diagram for Lab2.

Buck E Buck-1 Vout1


P Vin
Watch Window Single W
DRV M

Duty1 Duty1 In H EPWM-1A DRV


W
Duty2
Buck E
P
Single W
DRV M
Vin Buck-2 Vout2
Duty1 In H EPWM-2A
W
Watch Window
DRV
Vout1
Duty1 Duty2 Vout1
Vout2 A
slider slider ADC D Vout2
Temp1 Casc Temp1
C
Temp2
Temp2 Seq Iout1
H
CNF Iout2
Iout1 W Vin
Iout2

In Lab2 (as well as lab exercises 3 and 4) the assembly ISR _ISR_Run routine is triggered by
EPWM1. This is where the BuckSingle_DRV macros are executed. Therefore, the PWM
update rate is equal to the PWM frequency. Since this system is running open-loop, there is not a
requirement for high speed feedback. As a result, the ADC function ADC_CascSeqCNF() is
called in the C background code during initialization, and the ADC measured values are only
used for instrumentation purposes. The update rate can be much slower with no need to be
synchronized to the PWM or ISR. The ADC values are read directly from the ADC result
registers (AdcMirror.ADCRESULTn) by the background C code.

A task state-machine has been implemented as part of the background code. Tasks are arranged
in groups (A1, A2, A3…, B1, B2, B3…, C1, C2, C3…). Each group is executed according to 3
CPU timers which are configured with periods of 1 ms, 4 ms, and 8 ms respectively. Within each
group (e.g. “B”) each task is run in a “round-robin” manner. For example, group B executes
every 4 ms, and there are 3 tasks in group B. Therefore, B1, B2, and B3 execute once every 12
ms. System dashboard measurements are conveniently done by group 3 tasks (i.e. B1 – voltage
measurement, B2 – current measurement, and B3 – temperature measurement).

36 C28x Digital Power Supply Workshop


Lab2: PWM Generation / Open-Loop Control

¾ Procedure

Open a CCS Project


1. Turn on the power (SW1) to the 2-channel buck EVM. Open Code Composer Studio and
maximize it to fill your screen.

2. A project named Lab2.pjt has been created for this lab exercise. Open the project by
clicking:

Project Æ Open…

and look in C:\C28x_DPS\LABS\LAB2.

3. Load the TwoChannel.gel file by clicking:

File Æ Load Gel…

and look in C:\C28x_DPS\LABS\LAB2.

Device Initialization, Main, and ISR Files

Note: DO NOT make any changes to the source files – ONLY INSPECT

4. Open and inspect TwoChannel-DevInit.c by double clicking on the filename in the


project window. Confirm that GPIO00 and GPIO02 are configured to be PWM outputs.

5. Open and inspect TwoChannel-Main.c. Notice the incremental build option 1 (i.e.
IB1). A section of code is shown here for convenience. Comments have been added in
italics. Note that the run-time macros are executed at the PWM rate of 300 kHz.
//=============================================================
#if (IB1) // Open loop - Channels 1,2
//=============================================================
#define prd 333 // Period count = 300 KHz @ 100 MHz
#define NumActvCh 2 // Number of Active Channels

// "Raw" (R) ADC measurement name defines


#define VoutR1 AdcMirror.ADCRESULT0 //
#define VoutR2 AdcMirror.ADCRESULT1 //
#define IoutR1 AdcMirror.ADCRESULT2 //
#define IoutR2 AdcMirror.ADCRESULT3 //
#define TempR1 AdcMirror.ADCRESULT4 //
#define TempR2 AdcMirror.ADCRESULT5 //
#define VinR AdcMirror.ADCRESULT6 //

The ChSel array is used as input by function ADC_CascSeqCNF. These values will be used by “B” tasks for dashboard
calculations, and shown in the Watchwindow.
// Channel Selection for Cascaded Sequencer
ChSel[0] = 8; // B0 - Vout1
ChSel[1] = 0; // A0 - Vout2
ChSel[2] = 9; // B1 - Iout1
ChSel[3] = 1; // A1 - Iout2
ChSel[4] = 10; // B2 - Temperature-1
ChSel[5] = 2; // A2 - Temperature-2

C28x Digital Power Supply Workshop 37


Lab2: PWM Generation / Open-Loop Control

ChSel[6] = 11; // B3 - Vin

The 3 configuration functions below are part of the Power Library.


BuckSingle_CNF(1, prd, 1, 0); // ePWM1, Period=prd, Master, Phase=Don't Care
BuckSingle_CNF(2, prd, 0, 0); // ePWM2, Period=prd, Slave, Phase=0
ADC_CascSeqCNF(ChSel, 2, 7, 1); // ACQPS=2, #Conv=7, Mode=Continuous
EPwm1Regs.CMPB = 2; // ISR trigger point
ISR_Init(); // ASM ISR init

Duty1 and Duty2 variables will directly control the buck duty cycle. Sliders will be used to quickly change these values.
Duty1 = 0x0;
Duty2 = 0x0;

// Module connection to "nets" done here


//----------------------------------------
// BUCK_DRV connections
Buck_In1 = &Duty1;
Buck_In2 = &Duty2;
#endif // (IB1)

6. Open and inspect TwoChannel-ISR.asm. Notice the _ISR_Init and _ISR_Run


sections. This is where the PWM driver macro instantiation is done for initialization and
run-time, respectively. The code is shown below for convenience. In Lab2, incremental
build option IB1 is used.
.if(IB1) ; Init time
BuckSingle_DRV_INIT 1 ; EPWM1A
BuckSingle_DRV_INIT 2 ; EPWM2A
.endif

.if(IB1) ; Run time


BuckSingle_DRV 1 ; EPWM1A
BuckSingle_DRV 2 ; EPWM2A
.endif

7. Optionally, you can close the inspected files.

Build and Load the Project


8. Click the “Rebuild All” button and watch the tools run in the build window. The
output file should automatically load.

9. Under Debug on the menu bar click “Reset CPU”, “Restart”, and then “Go
Main”. You should now be at the start of Main().

Setup Watch Window


10. Open the watch window to view the variables used in the project.

Click: View Æ Watch Window on the menu bar.

Click the “Watch 1” tab at the bottom of the watch window. In the empty box in the
"Name" column, type the symbol names from the following screen capture and be sure to
modify the “Type” and “Radix” as needed.

38 C28x Digital Power Supply Workshop


Lab2: PWM Generation / Open-Loop Control

The following table gives a description for the variable names:

Variable Description

VinMeas Voltage input measurement (i.e. DC bus) to each buck power stage

Vmeas Voltage output of each channel, 3 element array, zeroth element not used

Imeas Current output of each channel, 3 element array, zeroth element not used

TdegC Temperature of each power module, 3 element array, zeroth element not used

Duty1 Q15 value (0~7FFFh) for duty input to BuckSingle_DRV1

Duty2 Q15 value (0~7FFFh) for duty input to BuckSingle_DRV2

Note 7FFFh = 32,768 = 100% duty

Save the Workspace


11. Save the current workspace by naming it Lab2.wks and clicking:

File Æ Workspace Æ Save Workspace As…

and saving in C:\C28x_DPS\LABS\LAB2.

Run the Code – TwoChannel


12. Enable real-time mode by selecting:

Debug Æ Real-time Mode

13. A message box may appear. If so, select YES to enable debug events. This will set bit 1
(DGBM bit) of status register 1 (ST1) to a “0”. The DGBM is the debug enable mask bit.
When the DGBM bit is set to “0”, memory and register values can be passed to the host
processor for updating the debugger windows.

C28x Digital Power Supply Workshop 39


Lab2: PWM Generation / Open-Loop Control

14. Check to see if the windows are set to continuously refresh. Click:

View Æ Real-time Refresh Options…

and check “Global Continuous Refresh”.

15. Run the code by using the <F5> key, or using the Run button on the vertical toolbar, or
using Debug Æ Run on the menu bar.

16. Note that in the watch window all values should be ~ zero, except for temperature, which
should be approximately equal to room temperature of 25° C.
17. Turn on the 12-volt DC bus (SW2) on the 2-channel buck EVM and observe variable
VinMeas in the watch-window. It should now be approximately 12V.

18. Open sliders D1Slider and D2Slider by using GEL Æ 2-Channel Sliders Æ and
move the sliders into the workspace area. D1Slider and D2Slider are used to change
variables Duty1 and Duty2, respectively. Increase the value of Duty1 to approximately
2800 (decimal). Power stage buck 1 module output voltage should be approximately 1V
on the DMM. Be sure that SW3 on the EVM is positioned to select Ch1. With the load
resistor (1Ω) connected to terminal 1, the open-loop voltage for Channel 1 is
approximately given by:

1V 2800

2V 5600

3V 8400

19. Try the same adjustment on Duty2. Be sure SW3 on the EVM is positioned to select
Ch2. Note that Channel 2 buck is only lightly loaded with a lamp (2~3Ω) and hence a
slightly lower Duty2 value will give the same output voltage as in the Ch1 case.
20. Of general interest – during duty/voltage adjustments observe the various watch window
variables such as voltage, current and temperature. Vmeas should reflect approximately
the same value as the DMM display. The current measurement is not very precise as it is
designed to measure a range up to 15A. Hence at low current levels accuracy will be
quite poor. Temperature should track quite well and the channel supplying the most
power will show an observable temperature increase.
21. Turn off the 12-volt DC bus (SW2) on the 2-channel buck EVM. (Do not turn off the
main power SW1).
22. Fully halt the DSP in real-time mode. First, halt the processor by using Shift <F5>, or
using the Halt button on the vertical toolbar, or by using Debug Æ Halt. Then click
Debug Æ Real-time Mode and uncheck the “Real-time mode” to take the
DSP out of real-time mode.

23. In the project window right click on Lab2.pjt and select Close.

40 C28x Digital Power Supply Workshop


Lab2: PWM Generation / Open-Loop Control

24. Do Not Close Code Composer Studio or it will be necessary to setup the debug
environment windows again for the next lab exercise!

End of Exercise

C28x Digital Power Supply Workshop 41


3 – Controlling the Power Stage with Feedback

3 – Controlling the Power Stage with Feedback


Controlling the Power Stage with Feedback

‹ Closed-Loop System Block Diagram


‹ Analog-to-Digital Converter Module
‹ Digital Control of Power Converter
‹ High Resolution PWM Benefits
‹ Soft Start – Starting the Loop

Closed-Loop System Block Diagram


The “Closed-Loop”

E
Control “PWM” P
W
“2P2Z” DRV M Vin
Vset Ref Duty H
Uout In W Vout
FB
Power
Stage
A
“Loop” “ADC” D
DRV C
Feedback
H
Rslt W

42 C28x Digital Power Supply Workshop


3 – Controlling the Power Stage with Feedback

ADC Module Block Diagram


ADC Module Block Diagram
Analog MUX
ADCINA0
ADCINA1 Result MUX
MUX S/H
... A RESULT0
A
RESULT1
ADCINA7 12-bit A/D
S/H RESULT2
MUX Converter

...
ADCINB0
ADCINB1 MUX S/H Result
SOC EOC
...

B B Select RESULT15
ADCINB7 Autosequencer
MAX_CONV1
Ch Sel (CONV00)
Ch Sel (CONV01)
Ch Sel (CONV02)
Software Ch Sel (CONV03)
ePWM_SOC_A
ePWM_SOC_B ...
External Pin Ch Sel (CONV15)
(GPIO/XINT2_ADCSOC)
Start Sequence
Trigger

Digital Control of Power Converter


Digital Control of Power Converter
ΔVc
Vo
Power Converter

Vin C RL Vref _ adc


= Vo max ⋅ Kd

Kd
ΔD ΔVs

PWM ADC
Digital
Controller U(n) E(n) +
Gc(z)
+
Vr

U ( z ) B0 + B1 z −1 + B2 z −2
Gc ( z ) = =
E ( z ) 1 − A1 z −1 − A2 z −2

U (n) = B0 E ( n) + B1E (n − 1) + B2 E (n − 2) + A1U (n − 1) + A2U (n − 2)

C28x Digital Power Supply Workshop 43


3 – Controlling the Power Stage with Feedback

Digital Control of Power Converter


Steady State Limit Cycle
Vo levels (DPWM duty
ADC levels error bins
ratio steps)
Volt
ΔVc ΔVs +0010
ΔVs +0001
Vref 0000
ΔVc
-0001
steady state output,
limit cycle time

Vo levels (DPWM duty ADC levels


ratio steps) error bins
Volt ΔVc
ΔVs +0010
ΔVs +0001
Vref 0000
-0001
steady state output,
no limit cycle time

High Frequency PWM


V
TPWM
VSTEP

PWM T Sysclk
t t

PWM resolution = Log2 ( TPWM / TSysClk )

F2808 – SysClk = 100 MHz


PWM Freq Regular resolution High resolution
(kHz) (bits) (%) (bits) (%)
100 10.0 0.1 16.0 0.002
150 9.4 0.2 15.4 0.002
250 8.6 0.3 14.7 0.004
500 7.6 0.5 13.7 0.008
750 7.1 0.8 13.1 0.011
1000 6.6 1.0 12.7 0.015
1500 6.1 1.5 12.1 0.023
2000 5.6 2.0 11.7 0.030

44 C28x Digital Power Supply Workshop


3 – Controlling the Power Stage with Feedback

High Resolution PWM (HRPWM)


PWM Period

Regular
Device Clock PWM Step
(i.e. 100MHz)
(i.e. 10ns)

HRPWM divides a clock Calibration Logic tracks the


cycle into smaller steps number of Micro Steps per
ms ms ms ms ms ms
called Micro Steps clock to account for
(Step Size ~= 150ps) Calibration Logic variations caused by
Temp/Volt/Process

HRPWM
Micro Step (~150ps)

‹ Significantly increases the resolution of conventionally derived digital PWM


‹ Uses 8-bit extensions to Compare registers (CMPxHR) and Phase register
(TBPHSHR) for edge positioning control
‹ Typically used when PWM resolution falls below ~9-10 bits which occurs at
frequencies greater than ~200 kHz (with system clock of 100 MHz)
‹ Not all ePWM outputs support HRPWM feature (see device data manual)

Resolution Loss – Low Duty Utilization


TPWM
Max Duty

PWM Not Utilized

t
T SYSCL (10 ns)

0.8 1 1.2 1.8 2.5 3.3 5


Vin
14 94% 93% 91% 87% 82% 76% 64%
12 93% 92% 90% 85% 79% 73% 58%
10 92% 90% 88% 82% 75% 67% 50%
9 91% 89% 87% 80% 72% 63% 44%
8 90% 88% 85% 78% 69% 59% 38%
7 89% 86% 83% 74% 64% 53% 29%
6 87% 83% 80% 70% 58% 45% 17%

C28x Digital Power Supply Workshop 45


3 – Controlling the Power Stage with Feedback

High-Resolution PWM Benefits


Benefit of High Resolution PWM
Single Power Stage
Watch Window Voltage HR
E
P
Contro ller Vin1 Vo ut1
BUCK W
CNTL DRV M
2P2 Z
H
Vref Vref Ref Uout DutyCmd Duty W EPWMnA DRV Buck
FB
DutyCmd 1 MHz
1 MHz
ADC A
D
1CH
C
DRV
H
Vout rslt0 W Ch0

1 MHz

HiRes PWM (150ps) Regular PWM (10ns)

No Limit cycle Limit cycle problem

Edge control is precise Edge jumps around

Managing the “Closed-Loop”


Fault
Trip
Dead
Band

E
SSartSE Q
Vset “PWM” P
Control DRV
W
M
“2P2Z” Duty
Duty
Clamp H
Delay Ref In W
Uout
Slope Out
FB
Target
Open/Closed
Coeff set 3 Loop A
Coeff set 2 “ADC” D
CoeffCoeff
- B2 set 1 DRV C
Coeff - B 2
CoeffCoeff
- B1 - B2 Feedback
H
Coeff - B 1 Rslt W
CoeffCoeff
- B0 - B1
Coeff - B 0
CoeffCoeff
- A2 - B0
Coeff - A 2
CoeffCoeff
- A1 - A2
Coeff - A 1
Coeff - A1

46 C28x Digital Power Supply Workshop


3 – Controlling the Power Stage with Feedback

Simple User Interface Control


Supervisory - BG Control Engine(s)

Fault Trip
Dead Band
Open/Closed Loop Trip
Duty Clamp Zone

Vset
E
SSartSEQ
“PWM” P
Control DRV
W
M
“2P2Z”
Duty H
Delay Ref In W
Slope Out
Uout
FB
Target

Coeff set 3 “ADC”


A
D
Coeff set 2
Coeff - B2 set 1
Coeff Voltage DRV C
Coeff - B2
CoeffCoeff
- B1 - B2 Feedback H
Rslt
Coeficient Coeff - B1 W
CoeffCoeff
- B0 - B1
Tuning Coeff - B0
CoeffCoeff
- A2 - B0
Coeff - A2
CoeffCoeff
- A1 - A2
Coeff - A1
Coeff - A1

Vout Monitor
Duty Monitor

Soft Start – Starting the Loop


Soft-Start and Sequencing Multi Vout

C28x Digital Power Supply Workshop 47


Lab3: Closed-Loop Control

Lab3: Closed-Loop Control


¾ Objective

The objective of this lab exercise is to demonstrate the topics discussed in this module and
regulate the output voltage of a buck power stage using closed-loop feedback control realized in
the form of a software coded loop. Soft-start and shut-down management will be explored using
the CCS watch window and sliders. ADC management for high-speed feedback and slow
instrumentation will be utilized. The Digital Power software framework, associated files, and
library modules will be used.

Lab3: Closed-Loop Control


‹ Regulate the Buck output by using Voltage Mode Control (VMC) with
closed-loop feedback
‹ Soft-start and sequencing function used to ensure an “orderly”
voltage ramp-up/down
‹ Soft-start profile and target voltage is conveniently adjusted by using
the CCS watch window and slider buttons feature
SSta rtSE Q
Single Power Stage
E
Voltage HR P
Co ntroller Vin1 Vout1
BUCK W
CNTL DRV M
Delay 2 P2Z
Vref H
Slope Out Ref Uout Duty1 Duty W EPWMnA DRV Buck
Target FB

ADC A
D
1CH
C
DRV
Watc h W indow H
Vou t1 r slt0 W Ch0

Vsoft

SlewRate
Graph Wind ow
OnDelay D ataLog

Mem
In
Buffer

Vsoft
slid er

¾ Project Overview

The following Power Library modules will be used in this lab exercise. (Note: these are the same
library modules used in Lab2 exercise with the addition of other library modules).

C configure function ASM initialization macro ASM Run time macro

BuckSingle_CNF() BuckSingleHR_DRV_INIT n BuckSingleHR_DRV n

ADC_DualSeqCNF() ADC_NchDRV_INIT n ADC_NchDRV n

none ControlLaw_2P2Z_INIT n ControlLaw_2P2Z n

none DataLogTST_INIT n DataLogTST n

48 C28x Digital Power Supply Workshop


Lab3: Closed-Loop Control

Below is a description and notes for the Power Library modules used in this lab exercise.

BuckSingleHR_DRV This is the high resolution PWM version of BuckSingle used in Lab2.
The C configure function (BuckSingle_CNF) is applicable for both
high-resolution and non-high-resolution versions of macro.

ADC_NchDRV Reads 1st N ADC result registers every PWM cycle and stores to N
consecutive memory locations accessible by C. In Lab3, N=1 (i.e. a
single voltage is measured as feedback).

ControlLaw_2P2Z This is a 2nd order compensator realized from an IIR filter structure.
The 5 coefficients needed for this function are declared in the C
background loop as an array of longs. This function is independent of
any peripherals and therefore does not require a CNF function call.

DataLogTST Data logging function with time-stamp trigger input. Although not
needed in the application itself, it provides a convenient way to
visualize the output voltage in a CCS graph window. In Lab4 the data
logger will be useful in displaying an output voltage transient.

¾ Lab Exercise Overview

The software in Lab3 has been configured to provide closed-loop voltage control for Channel 1 of
the buck EVM. Additionally, datalogging of the output can be displayed in a CCS graph
window. Below is the system diagram for Lab3.

SStartSEQ
Buck E
Single P
W
Vin1 Vout1
CNTL HR M
Delay 2P2Z DRV
Vref H
Slope Out Ref Uout Duty1 In W EPWM1A DRV Buck
Target FB

Voltage
Controller ADC A
D
1CH
C Single Power Stage
DRV
Watch Window H
Vout1 rslt0 W ADC-B0

Vsoft

Graph Window
SlewRate

OnDelay DataLog

OffDelay Mem
In
Buffer

Vsoft
slider

C28x Digital Power Supply Workshop 49


Lab3: Closed-Loop Control

The closed-loop consists of only three modules – ADC_1ChDRV, CNTL_2P2Z, and


BuckSingleHR_DRV. When the code is runing these modules execute as in-line code (no
decision making) within the ISR_Run routine which is triggered at the PWM rate. To ensure
proper operation, Vref is kept at zero until a request is received to enable the output voltage. It is
important for a power supply to have a proper start-up and shut-down routine. This is managed
by the soft-start and sequencing code which executes in the main background C code
TwoChannel-Main.c. This code ensures that Vref can never have a step change, as direct
modification of Vref is not allowed. Vref can only be adjusted indirectly via a target value
request. This value will be reached at a given slew-rate. The slew-rate is programmable with
delay-on and delay-off time parameters which are useful for staggered sequencing of multiple
voltage rails.

In Lab3, the target voltage, slew-rate and delay-on/off parameters are conveniently modified via a
watch window. A slider can also be used to adjust the output target voltage by “connecting” it to
the Vsoft variable. The soft-start and sequencing code is “scaleable” and can manage multiple
voltage rails, for example 2, 3,…10 or more Vrefs. The interface to this code is via several
integer arrays and integer flags. The array index “n” is used to designate the channel number (i.e.
n=1 for channel 1, n=2 for channel 2,…etc.) Although in C an index of n=0 is valid, it is not used
here. Below is a summary of the arrays and their usage.

Desired output target voltage in Q15 format


Vsoft[n] e.g. Vsoft[2]=4000, set channel 2 output voltage to 4000 “units”
Enable (allow) voltage output to reach target value
ChannelEnable[n] e.g. ChannelEnable[3]=1, turn channel 3 “on”
e.g. ChannelEnable[2]=0, turn channel 2 “off”
Step size or rate at which the target voltage is ramped to
SlewStep[n] e.g. SlewStep[2]=15, increment or decrement by 15 units at every
call
Delay time to turn on from the “global” start command (StartUp=1)
OnDelay[n] e.g. OnDelay[3]=2000, start channel 3 after delay of 2000 “time
units”
Delay time to turn off from the “global” stop command (StartUp=0)
OffDelay[n] e.g. OffDelay[3]=1000, stop channel 3 after delay of 1000 “time
units”
Global turn on/off command. Used to synchronize/sequence all
StartUp channels
e.g. StartUp=1, global turn on command
e.g. StartUp=0, global turn off command

50 C28x Digital Power Supply Workshop


Lab3: Closed-Loop Control

¾ Procedure

Open a CCS Project


1. Code Composer Studio should still be running from the previous lab exercise. If not,
then it will be necessary to setup the debug environment from the previous lab exercise.

2. A project named Lab3.pjt has been created for this lab exercise. Open the project by
clicking:

Project Æ Open…

and look in C:\C28x_DPS\LABS\LAB3.

The TwoChannel.gel file and watch window should still be loaded from the previous lab.

Device Initialization, Main, and ISR Files

Note: DO NOT make any changes to the source files – ONLY INSPECT

3. Open and inspect TwoChannel-Main.c by double clicking on the filename in the


project window. Notice the incremental build option 2 (i.e. IB2). A section of code is
shown here for convenience. Comments have been added in italics.
//=====================================================================
#if (IB2) // Closed Loop Ch-1, with SoftStart using separate lib blocks
//=====================================================================
#define prd 400 // Period count = 250 KHz @ 100 MHz
#define NumActvCh 1 // Number of Active Channels

// "Raw" (R) ADC measurement name defines


#define VoutR1 AdcMirror.ADCRESULT0 //
#define VoutR2 AdcMirror.ADCRESULT8 //
#define IoutR1 AdcMirror.ADCRESULT9 //
#define IoutR2 AdcMirror.ADCRESULT10 //
#define TempR1 AdcMirror.ADCRESULT11 //
#define TempR2 AdcMirror.ADCRESULT12 //
#define VinR AdcMirror.ADCRESULT13 //

Soft-Start parameters for channel 1


OnDelay[1] = 0;
OffDelay[1] = 0;
Vsoft[1] = 10900; // 1.8 V
SlewStep[1] = 200;
Used for Scope feature via Graph window
DataLogTrigger = 980000;
ScopeGain = 1;
ScopeACmode = 0; // DC mode initially

ADC Sequencer 1 - VoutR1 used every PWM cycle


// Channel Selection for Sequencer-1
ChSel[0] = 8; // B0 - Vout1

ADC Sequencer 2 – Instrumentation only, round robin scheme


// Channel Selection for Sequencer-2
ChSel[8] = 0; // A0 - Vout2
ChSel[9] = 9; // B1 - Iout1
ChSel[10] = 1; // A1 - Iout2
ChSel[11] = 10; // B2 - Temperature-1

C28x Digital Power Supply Workshop 51


Lab3: Closed-Loop Control

ChSel[12] = 2; // A2 - Temperature-2
ChSel[13] = 11; // B3 - Vin

PWM and ADC configure functions


BuckSingle_CNF(1, prd, 1, 0); // ePWM1, Period=prd, Master, Phase=0
ADC_DualSeqCNF(ChSel, 1, 1, 1); // ACQPS=1, Seq1#Conv=1, Seq2#Conv=1
EPwm1Regs.CMPB = 193; // tCMPB1 - ISR trigger point
ISR_Init(); // ASM ISR init

// Lib Module connection to "nets"


//--------------------------------
// ADC1CH_DRV connections
ADC_Rslt = &Vfdbk;
// CNTL_2P2Z connections
CNTL_2P2Z_Ref1 = &VrefNetBus[1]; // point to Vref from SlewRate limiter
CNTL_2P2Z_Out1 = &Uout; // point to Uout
CNTL_2P2Z_Fdbk1 = &Vfdbk; // point to Vfdbk
CNTL_2P2Z_Coef1 = &Coef2P2Z[0]; // point to first coeff for Single Loop

// BUCK_DRV connections
Buck_In1 = &Uout;

Datalogger is an optional feature, not required for loop to run


// Data Logger connections, DLTST = DataLogTimeStampTrigger
DLTST_In1 = &Vfdbk;
DLTST_TimeBase1 = &ECap1Regs.TSCTR;
DLTST_TimeStampTrig1 = &DataLogTrigger;
DLTST_DcOffset1 = 0;
DLTST_Gain1 = ScopeGain;

Compare B event setup to trigger both Sequencer 1 & 2 simultaneously, note: Seq1 has priority
// Trigger ADC SOCA & B from EPWM1
//----------------------------------------
EPwm1Regs.ETSEL.bit.SOCASEL = ET_CTRU_CMPB; // SOCA on CMPB event
EPwm1Regs.ETSEL.bit.SOCBSEL = ET_CTRU_CMPB; // SOCB on CMPB event
EPwm1Regs.ETSEL.bit.SOCAEN = 1; // Enable SOC on A group
EPwm1Regs.ETSEL.bit.SOCBEN = 1; // Enable SOC on B group
EPwm1Regs.ETPS.bit.SOCAPRD = ET_1ST; // Trigger on every event
EPwm1Regs.ETPS.bit.SOCBPRD = ET_1ST; // Trigger on every event

#endif // (IB2)

4. Open and inspect TwoChannel-ISR.asm. Notice the _ISR_Init and _ISR_Run


sections. This is where the PWM driver macro instantiation is done for initialization and
run-time, respectively. The code is shown below for convenience. In Lab3, incremental
build option IB2 is used. Note the order for the run time macros – 1) measure feedback,
2) compensate, 3) update PWM. Also, the ADC is not run in continuous mode, but rather
in SOC trigger mode, and therefore needs to be reset every cycle.
.if(IB2) ; Init time
ADC_NchDRV_INIT 1 ; 1 Channel, N=1
ControlLaw_2P2Z_INIT 1
BuckSingleHR_DRV_INIT 1 ; EPWM1A
DataLogTST_INIT 1 ; 1 Channel Data logger
.endif

.if(IB2) ; Run time


ADC_NchDRV 1 ; 1 Channel, N=1 (Measure)
ControlLaw_2P2Z 1 (Compensate)
BuckSingleHR_DRV 1 ; EPWM1A (Update)
DataLogTST 1 ; 1 Channel Data logger
ADC_Reset:
MOVW DP,#ADCTRL2>>6 ; Reset ADC SEQ
MOV @ADCTRL2,#0x4101 ; RST_SEQ1=1, SOCA-SEQ1=1, SOCB-SEQ2=1
.endif

52 C28x Digital Power Supply Workshop


Lab3: Closed-Loop Control

5. Optionally, you can close the inspected files.

Build and Load the Project


6. Click the “Rebuild All” button and watch the tools run in the build window. The
output file should automatically load.

7. Under Debug on the menu bar click “Reset CPU”, “Restart”, and then “Go
Main”. You should now be at the start of Main().

Setup Watch Window and Graph


8. Another watch window will be opened in addition to the one used in the previous lab
exercise. Open the watch window to view the variables used in the project.

Click: View Æ Watch Window on the menu bar.

Click the “Watch 1” tab at the bottom of the watch window. In the empty box in the
"Name" column, type the symbol names from the following screen capture and be sure to
modify the “Type” and “Radix” as needed.

Note: ScopeGain, ScopeACmode, and ActiveLoad will be explained and used in the
next lab exercise.

C28x Digital Power Supply Workshop 53


Lab3: Closed-Loop Control

The following table gives a description for the variable names:

Variable Description

ChannelEnable Channel enable array

Vsoft Voltage target array

OnDelay DelayOn array

OffDelay DelayOff array

SlewStep Ramp step size array

StartUp Global turn-on/turn-off integer flag

9. Open and setup a time graph windows to plot the data log buffer (ADC result register).
Click: View Æ Graph Æ Time/Frequency… and set the following values:

Select OK to save the graph options.

Save the Workspace


10. Save the current workspace by naming it Lab3.wks and clicking:

File Æ Workspace Æ Save Workspace As…

and saving in C:\C28x_DPS\LABS\LAB3.

54 C28x Digital Power Supply Workshop


Lab3: Closed-Loop Control

Run the Code – TwoChannel


11. Enable real-time mode by selecting:

Debug Æ Real-time Mode

12. A message box may appear. If so, select YES to enable debug events. This will set bit 1
(DGBM bit) of status register 1 (ST1) to a “0”. The DGBM is the debug enable mask bit.
When the DGBM bit is set to “0”, memory and register values can be passed to the host
processor for updating the debugger windows.
13. Check to see if the windows are set to continuously refresh. Click:

View Æ Real-time Refresh Options…

and check “Global Continuous Refresh”.

14. Run the code by using the <F5> key, or using the Run button on the vertical toolbar, or
using Debug Æ Run on the menu bar.

15. Turn on the 12-volt DC bus (SW2) on the 2-channel buck EVM and observe variable
VinMeas in the watch-window. It should now be approximately 12V. Also the Graph
window should show a trace hovering at “0”.

16. In the watch window turn on Channel 1 output by setting ChannelEnable[1]=1.


Power stage buck 1 module output voltage should ramp quickly to ~1.8V (be sure that
SW3 on the EVM is positioned to select Ch1). Note that directly turning-on (enabling)
an individual channel ignores the OnDelay and OffDelay parameters since
synchronization to a global trigger is not utilized.

17. Open slider V1softSlider (GEL Æ 2-Channel Sliders Æ) and move the slider
into the workspace area. This slider is used to directly change Vsoft[1]. Increase the
value of Vsoft[1] to approximately 10900 (decimal). Power stage buck 1 module
output voltage should be approximately 1.8V. When you are done turn off Channel 1 by
setting ChannelEnable[1]=0.

18. Channel 1 can also be enabled by using the global turn-on flag – StartUp. In this case
OnDelay and OffDelay parameters are used. Both of these delays are set to zero by
default, but can be modified via the watch-window. For example, modify these values as
follows:

OnDelay[1]=1000

OffDelay[1]=2000

StartUp=1

This will trigger a global turn on and Channel 1 will start ramping up after 1000 time
units. Using StartUp=0 will trigger a global turn off and Channel 1 will ramp down
after 2000 time units.
19. The ramp-up and ramp-down rates can also be modified. In this lab code, up and down

C28x Digital Power Supply Workshop 55


Lab3: Closed-Loop Control

rates are the same and set by parameter SlewStep[1] for channel 1. The default value
in Lab3 is 200 units per step. Change it to 40 in the watch window and see the result.
Follow these steps:

SlewStep[1]=40

ChannelEnable[1]=1 Output should ramp up at slower rate

ChannelEnable[1]=0 Output should ramp down at slower rate

20. Turn off the 12-volt DC bus (SW2) on the 2-channel buck EVM. (Do not turn off the
main power SW1).
21. Fully halt the DSP in real-time mode. First, halt the processor by using Shift <F5>, or
using the Halt button on the vertical toolbar, or by using Debug Æ Halt. Then click
Debug Æ Real-time Mode and uncheck the “Real-time mode” to take the
DSP out of real-time mode.

22. In the project window right click on Lab3.pjt and select Close.

23. Do Not Close Code Composer Studio or it will be necessary to setup the debug
environment windows again for the next lab exercise!

End of Exercise

56 C28x Digital Power Supply Workshop


4 – Tuning the Loop for Good Transient Response

4 – Tuning the Loop for Good Transient Response


Tuning the Loop for Good Transient Response

‹ Digital Power Supply Control Theory


‹ Intuitive Loop Tuning – “Visually
without Math”
‹ Active Load Feature of the Power EVM
‹ Multi-Loop Control

Digital Power Supply Control Theory


The Digital Control System
Digital Processor
G(s)
r(t) e(kT) u(kT) c(t)
+ Controller DAC Actuator Process

D(z)

ADC Sensor

Advantages Considerations
• Immunity from environmental effects • Sample rate
• Advanced control strategies possible • Quantization
• Immunity from component errors • Ease of programming
• Improved noise immunity • Controller design
• Ability to modify and store control parameters • Cost
• Ability to implement digital communications • Processor selection
• System fault monitoring and diagnosis • Requires data converters
• Data logging capability • Numeric issues
• Ability to perform automated calibration

C28x Digital Power Supply Workshop 57


4 – Tuning the Loop for Good Transient Response

PID Control Review


u(t ) = K e(t) + K ∫ e(t ).dt + K de(t)
P I D dt
KP = Proportional gain
KP
Gc(s) KI = Integral gain
KD = Derivative gain
K
KI G ( s) = K + I + K s
C P s D
Usually written in “parallel” form:
e(t)
∫ e.dt + u(t)
⎛ ⎞
KD G ( s) = K ⎜⎜1 + 1 + T s ⎟⎟
C C ⎜ Ti s d ⎟
⎝ ⎠
de
KP = KC
dt
KI = KC/Ti
KD = KCT d

‹ Proportional term controls loop gain


‹ Integral action increases low frequency gain and
reduces/eliminates steady state errors
‹ Derivative action adds phase lead which improves
stability and increases system bandwidth

Tuning the Step Response


‹ Performance of the control loop can be determined from the
output response to a step change in load
‹ We will adjust PID coefficients to minimise deviation from
steady state and settling time of the output voltage

Steady state

Acceptable error

Peak deviation

Settling time

58 C28x Digital Power Supply Workshop


4 – Tuning the Loop for Good Transient Response

Intuitive Loop Tuning – “Visually without Math”


Loop Tuning – Good First Step

U (n) = B0 E (n ) + B1 E (n − 1) + B2 E (n − 2) + A1U (n − 1) + A2U (n − 2)

E(n-1) E(n-2)
-1 -1
E(n) Z Z

B0 X B1 X B2 X PRD-SF

U(n)
S X Duty

A2 X A1 X
-1 -1
Z Z
U(n-2) U(n-1)

PID – Intuitive / Interactive


We can also write the controller in transfer function form:

U(z) B0 + B1*z-1 + B2*z-2 B0z2 + B1*z + B2


------ = ------------------------- = ----------------------
E(z) 1 - z-1 z2 – z

Compare with the General 2P2Z transfer function:

U(z) B0 + B1*z-1 + B2*z-2 B0z2 + B1*z + B2


------ = --------------------------- = ----------------------
E(z) 1 + A1*z-1 + A2*z-2 z2 + A 1*z + A 2

We can see that PID is nothing but a special case of 2P2Z control where:

A1 = -1 and A2 = 0

Change PID coeff. “on fly” in back-ground loop


// Coefficient init
Coef2P2Z_1[0] = Dgain * 67108; // B2
Coef2P2Z_1[1] = (Igain - Pgain - Dgain - Dgain)*67108; // B1
Coef2P2Z_1[2] = (Pgain + Igain + Dgain)*67108; // B0
Coef2P2Z_1[3] = 0; // A2
Coef2P2Z_1[4] = 67108864; // A1
Coef2P2Z_1[5] = Dmax[1] * 67108; // Clamp Hi limit (Q26)
Coef2P2Z_1[6] = 0x00000000; // Clamp Lo

C28x Digital Power Supply Workshop 59


4 – Tuning the Loop for Good Transient Response

Control Law Computation

U (n) = B0 E (n ) + B1 E (n − 1) + B2 E (n − 2) + A1U (n − 1) + A2U (n − 2)

; e(n)=Vref-Vout
MOVU ACC,@Vref
SUBU ACC,*XAR2++
LSL ACC,#8 ; ACC=e(n) (Q24)
MOVL @VCNTL_DBUFF+4,ACC
U(n) ZAPA
; Voltage control law
DBUFF U(n-1) XAR7 A1 MOVL XT,@VCNTL_DBUFF+8 ; XT=e(n-2)
QMPYAL P,XT,*XAR7++ ; b2*e(n-2)
U(n-2) A2 MOVDL XT,@VCNTL_DBUFF+6 ; XT=e(n-1), e(n-2)=e(n-1)
QMPYAL P,XT,*XAR7++ ; ACC=b2*e(n-2), P=b1*e(n-1)
E(n) B0 MOVDL XT,@VCNTL_DBUFF+4 ; XT=e(n), e(n-1)=e(n)
QMPYAL P,XT,*XAR7++ ; ACC+=b1*e(n-1), P=b0*e(n)
E(n-1) B1 MOVL XT,@VCNTL_DBUFF+2 ; XT=u(n-2)
QMPYAL P,XT,*XAR7++ ; P=a2*u(n-2)
E(n-2) B2 MOVDL XT,@VCNTL_DBUFF ; XT=u(n-1), u(n-2)=u(n-1)
min QMPYAL P,XT,*XAR7++ ; ACC=a2*u(n-2)
ADDL ACC,P ; ACC=a2*u(n-2)+a1*u(n-1)
max LSL ACC,#(23-VCNTL_QF+8) ; (Q23)
ADDL ACC,ACC ; (Q24)
duty MOVL @VCNTL_DBUFF,ACC ; ACC=u(n)
; Saturate the result [min,max]
MINL ACC,*XAR7++
MAXL ACC,*XAR7++
; Duty Cycle Modulation
MOVL XT,ACC
QMPYL P,XT,*XAR7++ ;(Q0)
MOV *XAR3++,P

60 C28x Digital Power Supply Workshop


4 – Tuning the Loop for Good Transient Response

Type II Controller
Lo

V in Vout
COMPARATOR
+ Do Co

1 - DRIVER
s+ CONTROLLER
1 R2 C 2
G c (s ) = C1
R1C1 ⎛ C + C2 ⎞
s⎜⎜ s + 1 ⎟
⎝ R2C1C 2 ⎟⎠ C2 R2

R1
+

- REF

B o d e D ia g r a m
80

70

60
M a g n i tu d e ( d B )

50

40

R1 = 4.12kΩ 30

20

R2 = 124kΩ 10

C1 = 8.2 pF
-10

-20
0

C2 = 2.2nF
P has e (d eg )

-45

-90
2 3 4 5 6 7 8
10 1 0 10 10 10 10 1 0
Fr e qu enc y ( ra d / s e c )

Digital Type II Controller


Lo

Vin Vout

Do Co
B2 + B1z −1 + B0 z −2
Gc ( z ) = DRIVER
1 + A1z −1 + A0 z − 2

DIGITAL
PROCESSOR

CONTROLLER
B o d e D ia g r a m
1 00

80
M a g n itu d e ( d B )

60

40

B2 = 9.927 20

B1 = 0.03632 0

B0 = 9.891 -20
90

A1 = 1.339
P has e (deg )

45

A0 = 0.3391 0

-45

(Tustin’s transform, Ts = 1 us) -90


2 3 4 5 6 7 8
10 10 10 10 10 10 10
Fr e q u e n c y (r a d / s e c )

C28x Digital Power Supply Workshop 61


4 – Tuning the Loop for Good Transient Response

Type III Controller


Lo

Vin V out
COMPARATOR
+ Do Co

- DRIVER

⎛ 1 ⎞⎛ 1 ⎞
⎟⎜ s + ⎟
CONTROLLER
⎜s +
R1 + R3 ⎜⎝ R2C 2 ⎟⎠⎜⎝ (R1 + R3 )C3 ⎟⎠ C1
Gc (s ) =
R1 R3C1 ⎛ C1 + C 2 ⎞⎛ 1 ⎞
s⎜⎜ s + ⎟⎜ s + ⎟
R2C1C2 ⎟⎠⎜⎝ R3C3 ⎟⎠
C2 R2 C3 R3

R1
+

- REF

B o d e D ia g r a m
4 0

R1 = 4.12kΩ
M a g n it u d e ( d B )

3 0

R2 = 20.5kΩ 2 0

R3 = 150Ω 1 0

C1 = 0.22nF 0
4 5

C2 = 2.7nF
P h a s e (d e g )

C3 = 6.8nF
-4 5

-9 0
3 4 5 6 7
10 10 10 10 10
F re q u e n c y ( r a d /s e c )

Digital Type III Controller


Lo

Vin Vout

Do Co
B3 + B2 z −1 + B1 z −2 + B0 z −3
Gc ( z ) = DRIVER
1 + A2 z −1 + A1 z − 2 + A0 z −3

DIGITAL
PROCESSOR

CONTROLLER
B3 = 9.658 10 0
B o d e Dia g r a m

B2 = 9.158
M a g n itu d e ( d B )

80

B1 = 9.652 60

B0 = 9.164
40

20
A2 = 2.128 0

A1 = 1.397 90

A0 = 0.2689
P h as e (deg )

45

-4 5

(Tustin’s transform, Ts = 1 us) -9 0


3 4 5 6 7
10 10 10 10 10
F r e q u e n c y ( r a d /s e c )

62 C28x Digital Power Supply Workshop


4 – Tuning the Loop for Good Transient Response

Active Load Feature of the Power EVM


2-Channel Buck EVM

Active Volt
TI PowerTrain Phase Links
Load LEDs Meter
PTD08A010W
10A module
ƒ Current meas.
ƒ Temp meas
ƒ Over Current Prot.
ƒ Over Current Flag
ƒ No Heat-sink needed

2-Channel Buck EVM Schematic

C28x Digital Power Supply Workshop 63


Lab4: Tuning the Loop

Lab4: Tuning the Loop


¾ Objective

The objective of this lab exercise is to demonstrate the topics discussed in this module and tune
the closed-loop buck power stage for improved transient performance using visual “trial and
error” methods rather than a mathematical approach. The transient response will be modified by
interactively adjusting the system proportional (P), integral (I), and derivative (D) gains using
sliders. An active load circuit enabled by software will provide a repetitive step change in load.
The CCS graph window feature will be used to view the transient response in real-time. The
Digital Power software framework, associated files, and library modules will be used.

Lab4: Tuning the Loop


‹ Tune closed-loop Buck power stage for improved transient performance
using visual “trial and error” (rather than mathematical approach)
‹ The 2-channel Buck EVM has an active load circuit when enabled by software
provides a repetitive step change in load
‹ CCS graph window feature used to view the transient in real-time
Š Transient response can be modified directly until the desired improvement is
achieved by adjusting P, I, D sliders Fault
Trip
Coefficient “tuning” Dead
SSartSEQ Band
P I D Vset
E
“PWM” P
Delay Control DRV
W
M
“2P2Z” Duty
PID
Slope Out
Clamp Duty H
Mapping T arget
Ref In W
( 3 to 5 ) Uout
Coeff set 3 FB
Coeff set 2
CCS or GUI C oeffCoeff
- B2 set 1 Open/Closed
sliders Coeff - B2 Loop
OR CoeffCoeff
- B1 - B2
“ADC”
A
D
Coeff - B1
CoeffCoeff
- B0 - B1 DRV C
Im Coeff - B0 Feedback
CoeffCoeff
- A2 - B0 H
Pole / Zero Rslt
Coeff - A2 W
to Coef Map CoeffCoeff
- A1 - A2
(5 to 5) Coeff - A1 Graph Window
Coeff - A1
Re DataLog

Mem
In
Buffer
Pole / Zero
adjust GU I

¾ Project Overview

The software code used in Lab4 is exactly the same code as used in Lab3. All of the files and
build options are identical. The five coefficients to be modified are stored in the array
Coef2P2Z[n]. Directly manipulating these five coefficients independently by trial and error is
almost impossible, and requires mathematical analysis and/or assistance from tools such as
matlab, mathcad, etc. These tools offer bode plot, root-locus and other features for determining
phase margin, gain margin, etc.

To keep loop tuning simple and without the need for complex mathematics or analysis tools, the
coefficient selection problem has been reduced from five degrees of freedom to three, by
conveniently mapping the more intuitive coefficient gains of P, I and D to B0, B1, B2, A1, and
A2. This allows P, I and D to be adjusted independently and gradually. This method requires a
periodic transient or disturbance to be present, and a means to observe it while interactively
making adjustments. The data-logging feature introduced in Lab3 provides a convenient way to

64 C28x Digital Power Supply Workshop


Lab4: Tuning the Loop

observe the output transient while the built-in active load on the EVM can provide the periodic
disturbance.

The compensator block (macro) used is CNTL_2P2Z. This block has 2 poles and 2 zeros and is
based on the general IIR filter structure. The transfer function is given by:

U (z ) b0 + b1 z −1 + b 2 z −2
=
E (z ) 1 + a1 z −1 + a 2 z −2

The recursive form of the PID controller is given by the difference equation:

u (k ) = u (k − 1) + b0e(k ) + b1e(k − 1) + b 2e(k − 2)

where:

b0 = Kp '+ Ki '+ Kd '


b1 = − Kp '+ Ki '−2 Kd '
b 2 = Kd '

And the z-domain transfer funcion form of this is:

U (z ) b0 + b1 z −1 + b 2 z −2 b0 z 2 + b1 z + b 2
= =
E (z ) 1 − z −1 z2 − z

Comparing this with the general form, we can see that PID is nothing but a special case of
CNTL_2P2Z control where:

a1 = −1 and a 2 = 0

In the lab exercise, you will inspect the C code in which these coefficients are initialized.

¾ Lab Exercise Overview

In Lab3 the software has been configured to provide closed-loop voltage control for Ch1 of the
buck EVM and datalogging of the output which was displayed in a CCS graph window. Lab4
will additionally allow modification of the five coefficients associated with the 2nd order
CNTL_2P2Z compensator block. This modification will be done “on the fly” by using 3 sliders
(P, I and D) while the buck output is put under transient using an active load which is switched
periodically by the ECAP peripheral.

The following figure is the system diagram for Lab4.

C28x Digital Power Supply Workshop 65


Lab4: Tuning the Loop

P I D

Coeff.
PID
Mapping B2
(3 5) B1
B0
A2
Sliders
A1
SSartSEQ
Buck E
Single P
W
Vin1 Vout1
CNTL HR M
Delay 2P2Z DRV
Vref H
Slope Out Ref Uout Duty1 In W EPWM1A DRV Buck
Target FB

Voltage
Controller ADC A
D
1CH
C Single Power Stage
DRV
Watch Window H
Vout1 rslt0 W ADC-B0

Vsoft

Graph Window
SlewRate
1 ohm 1 ohm

OnDelay DataLog

OffDelay Mem
In DRV
Buffer

ECAP1
Vsoft Active Load
slider

The default coefficient settings chosen for Lab3 provide very poor performance (low gains).
Initially Lab4 will use the same settings. The control loop will be soft-stared to the target Vout
value, the same way it was done in Lab3. At this point, the active load will be enabled and a load
resistor of equal value to the static load will be switched in and out periodically.

In addition to the watch window variables discussed in Lab3, a few others will be used in the loop
tuning process. These include the P, I and D gains, active load enable, and CCS graph window
(scope control). The table below summarises these new variables.

Pgain Proportional gain; value adjustment : 0 ~ 1000

Igain Integral gain; value adjustment : 0 ~ 1000

Dgain Derivative gain; value adjustment : 0 ~ 1000

ActiveLoad Enable (value=1) / Disable (value=0) flag for the active load circuit

ScopeACmode Sets the CCS Scope (graph window) to operate in AC mode (i.e. removing the
DC component) and is useful for zooming into the transient only

ScopeGain Vertical gain adjustment for the CCS scope (much like a real oscilloscope)

66 C28x Digital Power Supply Workshop


Lab4: Tuning the Loop

¾ Procedure

Open a CCS Project


1. Code Composer Studio should still be running from the previous lab exercise. If not,
then it will be necessary to setup the debug environment from the previous lab exercise.

2. A project named Lab4.pjt has been created for this lab exercise. Open the project by
clicking:

Project Æ Open…

and look in C:\C28x_DPS\LABS\LAB4.

The TwoChannel.gel file, watch windows and graph window should still be loaded from
the previous lab.

Device Initialization, Main, and ISR Files

Note: DO NOT make any changes to the source files – ONLY INSPECT

3. Open and inspect TwoChannel-Main.c by double clicking on the filename in the


project window. This file is identical to the one used in Lab3. Notice the coefficient
initialization and P, I, and D mapping equation. A section of code is shown here for
convenience.

Pgain = 1; Igain = 1; Dgain = 5; // very "loose"

// Coefficient init for Single Loop


Coef2P2Z[0] = Dgain * 67108; // B2
Coef2P2Z[1] = (Igain - Pgain - Dgain - Dgain)*67108; // B1
Coef2P2Z[2] = (Pgain + Igain + Dgain)*67108; // B0
Coef2P2Z[3] = 0; // A2
Coef2P2Z[4] = 67108864; // A1 = 1 in Q26
Coef2P2Z[5] = Dmax[1] * 67108; // Clamp Hi limit (Q26)
Coef2P2Z[6] = 0x00000000; // Clamp Lo

(Note: 67108 = ~ 0.001 in Q26 format)

4. Optionally, you can close the inspected file.

Build and Load the Project


5. Click the “Rebuild All” button and watch the tools run in the build window. The
output file should automatically load.

6. Under Debug on the menu bar click “Reset CPU”, “Restart”, and then “Go
Main”. You should now be at the start of Main().

C28x Digital Power Supply Workshop 67


Lab4: Tuning the Loop

Save the Workspace


7. The watch windows and graph window were setup in the previous lab exercise. A
workspace needs to be saved to include the project for this lab exercise. Save the current
workspace by naming it Lab4.wks and clicking:

File Æ Workspace Æ Save Workspace As…

and saving in C:\C28x_DPS\LABS\LAB4.

Run the Code – TwoChannel


8. Enable real-time mode by selecting:

Debug Æ Real-time Mode

9. A message box may appear. If so, select YES to enable debug events. This will set bit 1
(DGBM bit) of status register 1 (ST1) to a “0”. The DGBM is the debug enable mask bit.
When the DGBM bit is set to “0”, memory and register values can be passed to the host
processor for updating the debugger windows.
10. Check to see if the windows are set to continuously refresh. Click:

View Æ Real-time Refresh Options…

and check “Global Continuous Refresh”.

11. Run the code by using the <F5> key, or using the Run button on the vertical toolbar, or
using Debug Æ Run on the menu bar.

12. Turn on the 12-volt DC bus (SW2) on the 2-channel buck EVM and observe variable
VinMeas in the watch-window. It should now be approximately 12V. Also the Graph
window should show a trace hovering at “0V”.

13. In the watch window turn on Channel 1 output by setting ChannelEnable[1]=1.


Power stage buck 1 module output voltage should ramp quickly to ~1.8V (be sure that
SW3 on the EVM is positioned to select Ch1).

14. Enable the active load circuit by setting variable ActiveLoad = 1 in the watch
window. To better view only the transient or AC component of the output voltage, set
the graph to AC mode by changing variable ScopeACmode = 1. This should put the
output waveform at the graph “zero” line. Optionally, set the scope gain higher by
changing variable ScopeGain = 4. If lab is working correctly, then the graph
window should look something like the following:

68 C28x Digital Power Supply Workshop


Lab4: Tuning the Loop

The negative going transient is when the extra load is switched in and the positive going
overshoot is when the extra load is removed.

15. Open the sliders for P, I and D adjustment (GEL Æ 2-Channel Sliders Æ)
Pgain_Slider, Igain_Slider and Dgain_Slider. Optionally, if you want to adjust the output
voltage via a slider, then open VsoftSlider, too. Move the sliders into the workspace
area.
16. By observing the transient in real time, gradually adjust each slider to get the best
transient response (i.e. least pertubation from the zero line). Gradual adjustment can be
best achieved by selecting the slider (mouse click) and then using the up/down arrows. A
large movement of the slider may cause the system to go unstable. A suggested
procedure is given below:
• Start with Igain first, increase gradually until the negative going transient flattens
out near the zero line
• Increase Pgain until some oscillation (2~3 cycles) occurs
• Increase Dgain to remove some of the oscillation
• Increase Igain again
• keep iterating very gradually until an acceptable transient is achieved – this may
look something like the graph shown below:

C28x Digital Power Supply Workshop 69


Lab4: Tuning the Loop

17. Reduce the scope vertical gain back to 1 (ScopeGain = 1) and set the graph back in
DC mode (ScopeACmode = 0). The voltage output response should look something
like this now:

18. With the active load still enabled, try shutting down Channel 1 output and then bringing it
back up under “soft” shut-down and start-up conditions. The closed loop should be
stable during the ramping even during the switching transients.
19. Turn off the 12-volt DC bus (SW2) on the 2-channel buck EVM. (Do not turn off the
main power SW1).
20. Fully halt the DSP in real-time mode. First, halt the processor by using Shift <F5>, or
using the Halt button on the vertical toolbar, or by using Debug Æ Halt. Then click
Debug Æ Real-time Mode and uncheck the “Real-time mode” to take the
DSP out of real-time mode.
21. Close Code Composer Studio and turn off the power (SW1) to the 2-channel buck EVM.

End of Exercise

70 C28x Digital Power Supply Workshop


Lab4: Tuning the Loop

Multi-Loop Control
Multi-Loop Control
Supervisory BG Control Engine(s)

Coef[1]
2 pole / ePWM
Loop-1 mgmt Vref[1]
2 Zero
Uout[1]
module
Ref Uout Duty PWM PWM-1
FB
Controller1 ADC
module ADC-1
Out In

Coef[2]
2 pole / ePWM
Loop-2 mgmt Vref[2]
2 Zero
Uout[2]
module
Ref Uout Duty PWM PWM-2
FB

Controller2 ADC
module ADC-2
Out In

Coef[N]
2 pole / ePWM
Loop-N mgmt Vref[N] 2 Zero
Uout[N]
module
Ref Uout Duty PWM PWM-N
FB

Controller N ADC
module ADC-N
Out In

Diag, slow ADC


module ADC -
adjustment. Out In
GenPurp

PFC (2PHIL) Software Control Flow


VpfcSetSlewed VpfcCntl VpfcOvp
1 kHz 100 kHz
1 kHz 100 kHz 100 kHz
SLEW CNTL PFC 100 kHz PFC E
PFC
LIMIT 2P2Z OVP ICMD CNTL 2PHIL P EPWM1A
385 V VpfcSet In Out Ref 2P2Z DRV W
Out In Out V1 M
VpfcSlewRate Incr Fdbk Out PfcIcmd Ref
V2 Out PfcDuty Duty
Vmon H
Voltage Fdbk EPWM1B
2 Adj W
Controller Vac
Current
Vboost Controller
Vboost
PfcShareAdj
VpfcSet
InvVavgSqr Ipfc
385 V

50 kHz 50 kHz 200 kHz 200 kHz 200 kHz


160 V AC Ipfc rslt0 IN0
FILT FILT
INV
BIQUAD LINE 2P2Z
SQR Vboost rslt1 IN1
RECT ADC A
50mS D
Out In Out In Out In Out In VacLine rslt2 SEQ1 IN2
C
DRV
Vavg rslt3 IN3
VacLineAvg VacLineRect VacLineFilt H
rslt4 W
IN4
BOX 50 kHz
rslt5 IN5
IphA CAR
AVG
100 Hz
IpfcAvgA Out In IpfcPhaseA
PFC HalfVref
BOX 50 kHz
ISHARE
CAR
Ia
PfcShareAdj Out AVG
Ib IpfcAvgB Out In IpfcPhaseB

IphB

C28x Digital Power Supply Workshop 71


Lab4: Tuning the Loop

DC-DC (ZVSFB) Software Control Flow

200 kHz
EPWM1A
200 kHz
200 kHz PSFB
SLEW 200 kHz
LIMIT
VoutSetSlewed CNTL Voltage
Controller I_FOLD
DRV EPWM1B
2P2Z
BACK EPWM2A
48 V VoutSet In Out Ref E
Out VdcCntl V Out PhaseCntl phase P EPWM2B
2 VoutSlewRate Incr Vout Fdbk I W
50 kHz M
Rv
V outSe t Fv PSFB H
48 V Ri DB W

Fi DRV
CNTL 200 ns DbAdjL llegdb
0V
2P2Z 180 ns DbAdjR rlegdb
12 A IoutSet Ref
100m s Out IdcCntl
Ipri Fdbk 200 kHz
200 kHz
Current Controller A
Ipri Ipri rslt0
ADC D IN0

SEQ2 C

Vout Vout rslt1 DRV H


IN1
W

CPU Bandwidth Utilization


MIPS = 100 # inst / us = 100 PWM (kHz) = 200
# TS = 4 # inst / time slice = 500 PWM (bits) = 9.0
S. rate = 200 Sampling period = 5.0 FW_Isr 200 kHz
IS R Rate Function / Activity # Cyc Tot. Cyc. Stats
All 200 kHz Context Save / Restore 32 292 % Util
200 kHz ISR Call / Return / Ack 24 58%
Every ISR call
200 kHz Time slice Mgmt 12
Context Save
200 kHz ADCSEQ2_DRV 14
200 kHz CNTL _2P2Z 1 (V loop ) 36 ADCSEQ2_DRV
200 kHz CNTL _2P2Z 2 ( I lo op) 36 CNTL_2P2Z(1)
200 kHz I_FOLD_BACK 25 CNTL_2P2Z(2)
ZVSFB_DRV
200 kHz ZVSFB_DRV 14
ADCSEQ1_DRV
200 kHz ADCSEQ1_DRV 57
FILT_2P2Z
200 kHz F ILT_2P2Z 35
AC_LINE_RECT
200 kHz AC_LINE_RECT 7

TS1 100 kHz PFC_OVP 25 117 % Util


100 kHz PFC_ICMD 30 82% Time Slice mgr
100 kHz CNTL _2P2Z 4 (I loop) 36 #Cyc. Rem.
100 kHz PFC2PHIL_DRV 26 91

TS2 50 kHz BOXCAR_AVG 1 42 145 % Util


50 kHz BOXCAR_AVG 2 42 87% 50 kHz 50 kHz 50 kHz 50 kHz
100 Hz PFC_ISHARE 15 #Cyc. Rem.
50 kHz Execution Pre-scaler(1:50) 10 63
1 kHz CNTL _2P2Z 3 (V loop ) 36
TS1 TS2 TS3 TS4
BOXCAR_AVG (1)
TS3 100 kHz PFC_OVP 25 117 % Util PFC_OVP PFC_OVP
BOXCAR_AVG (2)
100 kHz PFC_ICMD 30 82% PFC_ICMD PFC_ICMD FILT_BIQUAD
PFC_ISHARE
100 kHz CNTL _2P2Z 4 (I loop) 36 #Cyc. Rem. CNTL_2P2Z(4) CNTL_2P2Z(4) INV_SQR
ExecPS (1 :50)
100 kHz PFC2PHIL_DRV 26 91 PFC2PHIL_DRV PFC2PHIL_DRV
CNTL_2P2Z(3)
TS4 50 kHz F ILT_BIQUAD 46 124 % Util
50 kHz INV_SQR 78 83%
#Cyc. Rem.
84

BG Function / Activity # inst. Tot.Cyc. Stats


Comms + Supervisory 400 434 Int Ack
+ Soft-Start + Other ? Context restore
SLEW_LIMIT 1 17
SLEW_LIMIT 2 17
Return
% ISR utilization = 87%
Spare ISR MIPS = 12.6
BG loop rate (kHz ) / (us) = 29.0 34.4

72 C28x Digital Power Supply Workshop


5 – Summary and Conclusion

5 – Summary and Conclusion


Summary and Conclusion

‹ Review of Workshop Topics and


Exercises
‹ TI Digital Power Products
Š C2000 Digital Signal Controller
Family
Š UCD9xxx Digital Power Controller
Family
‹ Where to Find More Information

Review of Workshop Topics and Exercises


Workshop Topics and Exercises Review
‹ C28x DSC family provides ideal controller
for Digital Power Supply design
Š Scalable ePWM peripherals, ADC and fault
management support
Š Code Composer Studio, DPS Library and TI
Buck EVM
‹ Controlled Buck output voltage using
PWM waveform and duty cycle without
feedback
‹ Controlled Buck output using Voltage
Mode Control with feedback
‹ Tuned closed-loop Buck power stage
visually using CCS features

C28x Digital Power Supply Workshop 73


5 – Summary and Conclusion

TI Digital Power Products


TI Is The Right Digital Power Partner

TI solutions cover the spectrum of power applications

TMS320F282x
TMS320F281x
TMS320F283x
TMS320F280x
Flexibility

Fully Programmable,
Control Focused

UCD9111
UCD9112 UCD9220
UCD9240 Power-Optimized
Controllers

System Complexity

TI’s Digital Power Solutions Span the


Industry

Non-Isolated DC/DC POL Isolated DC/DC &


Offline AC/DC
• UCD91xx Single-Output Digital Controller • TMS320C2000 Digital Signal Controllers
• UCD92xx Multi-Output Digital Controller
• TMS320C2000 Digital Signal Controllers

DC/AC Inverters System Management


Only
• TMS320C2000 32-bit controller • UCD9080 Power Supply Sequencer
solutions for green energy (solar, wind, and Monitor
fuel cells) and UPS battery backup

74 C28x Digital Power Supply Workshop


5 – Summary and Conclusion

C2000 Digital Signal Controller Family


C2000 Family Roadmap

Future
r m ance Future
C28xxx
o C28xxx
Perf F283xx
300 MFLOPS
F282xx FPU, DMA
F282xx
150
150 MHz
MHz
F281x DMA
DMA
F281x
150
150 MHz n
ratio
MHz
88 Devices g Future
Devices
Inte C28xxx
F280x
F280xx
100 MHz
100MHz
150ps PWM
150ps PWM
F280xx
F280xx
60 MHz
60 MHz
150ps PWM
150ps PWM

TMS320F280xx Digital Signal Controllers

Code security High Performance Signal Processing


32-256 ƒ Up to 100 MHz performance
12-36 8KB
KB KB ƒ Single cycle 32 x32-bit MAC (or dual 16 x16 MAC)
Flash RAM Boot PWM
ROM ƒ Very Fast Interrupt Response
ƒ Single cycle read-modify-write
Event Capture
Memory Bus Memory Sub-System
QEP
Fast program execution out of both RAM and
12-bit ADC Flash memory
Peripheral Bus

ƒ 80 MIPS with Flash Acceleration Technology


Interrupt Management
Watchdog ƒ 100 MIPS out of RAM for time-critical code

C28xTM 32-bit DSC


Control Peripherals
CAN 2.0 B
Up to 16 PWM channels and 4 event captures
32x32-bit R‚M‚W 150 ps High-Resolution PWM
Multiplier Atomic I2C Ultra-Fast 12-bit ADC
ALU
32-bit ƒ 6.25 MSPS throughput
SCI
Timers (3) ƒ Dual sample&holds enable simultaneous sampling
32-bit
SPI ƒ Auto Sequencer, up to 16 conversions w/o CPU
Real-Time Register
JTAG File GPIO Communications Ports
Multiple standard communication ports provide
simple interfaces to other components

Datasheet available at: http://www-s.ti.com/sc/ds/tms320f2808.pdf

C28x Digital Power Supply Workshop 75


5 – Summary and Conclusion

F280xx Controller Portfolio


All Devices are 100% Hardware, Software & Pin Compatible

RAM 12-bit PWM/ CAP/ Communication


Flash
TMS320 MHz KB 16-ch
KB ADC Hi-Res. QEP Ports
F28015 60 32 12 267ns 10/4 2/0 SPI, SCI, I2C

F28016 60 32 12 267ns 10/4 2/0 SPI, SCI, CAN, I2C

F2801-60 60 32 12 267ns 8/3 2/1 2x SPI, SCI, CAN, I2C

F2802-60 60 64 12 267ns 8/3 2/1 2x SPI, SCI, CAN, I2C

F2801 100 32 12 160ns 8/3 2/1 2x SPI, SCI, CAN, I2C

F2802 100 64 12 160ns 8/3 2/1 2x SPI, SCI, CAN, I2C

F2806 100 64 20 160ns 16/4 4/2 4x SPI, 2x SCI, CAN, I2C

F2808 100 128 36 160ns 16/4 4/2 4x SPI, 2x SCI, 2x CAN, I2C

F2809 100 256 36 80ns 16/6 4/2 4x SPI, 2x SCI, 2x CAN, I2C

F28044 100 128 20 80ns 16/16 0 SPI, SCI, I2C

100-pin LQFP and u*BGA; Also available in -40 to 125 C and Automotive Q100

TMS320F283xx Digital Signal Controllers

Code security High Performance Signal Processing


128-512 ƒ Up to 150 MHz performance with 32-bit floating-
52-68 8KB
KB KB point unit
Flash RAM Boot PWM
ROM ƒ Six-channel DMA speeds data throughput
ƒ Very Fast Interrupt Response
Event Capture
Memory Bus Memory Sub-System
QEP
Fast program execution out of both RAM and
DMA 12-bit ADC Flash memory
Peripheral Bus

ƒ 120 MIPS with Flash Acceleration Technology


Interrupt Management
Watchdog ƒ 150 MIPS out of RAM for time-critical code

TM
C28x 32-bit DSC
Control Peripherals
CAN 2.0 B
Up to 16 PWM channels and 4 event captures
32x32-bit R‚M‚W 150 ps High-Resolution PWM
Multiplier Atomic I2C Ultra-Fast 12-bit ADC
ALU
32-bit ƒ 12.5 MSPS throughput
SCI
Timers (3) ƒ Dual sample&holds enable simultaneous sampling
32-bit
SPI ƒ Auto Sequencer, up to 16 conversions w/o CPU
Real-Time Floating-
JTAG Point Unit
McBSP Communications Ports
Multiple standard communication ports provide
simple interfaces to other components

Datasheet available at: http://www-s.ti.com/sc/ds/tms320f28335.pdf

76 C28x Digital Power Supply Workshop


5 – Summary and Conclusion

F283xx & F282xx Controller Portfolio


Flash RAM 12-bit PWM/ CAP/ Communication
TMS320 MHz FPU DMA
KB KB 16-ch ADC HRPW M QEP Ports
SPI, 3x SCI, I2C,
F28335 150 Yes 512 68 80 ns Yes 18/6 6/2 2x McBSP, 2x
CAN
SPI, 3x SCI, I2C,
F28334 150 Yes 256 68 80 ns Yes 18/6 4/2 2x McBSP, 2x
CAN
F28332 100 Yes 128 52 80 ns Yes 16/4 4/2 SPI, 2x SCI, I2C,
McBSP, 2x CAN
SPI, 3x SCI, I2C,
F28235 150 No 512 68 80 ns Yes 18/6 6/2 2x McBSP, 2x
CAN
SPI, 3x SCI, I2C,
F28234 150 No 256 68 80 ns Yes 18/6 4/2 2x McBSP, 2x
CAN
SPI, 2x SCI, I2C,
F28232 100 No 128 52 80 ns Yes 16/4 4/2
McBSP, 2x CAN

• 176-pin/ball LQFP/PBGA; 179-ball u*BGA; -40 to 125 C and Q100 in PBGA


• IQMath library provides software compatibility between floating-point and
fixed-point!

C2000 controlCARDs
F2808 F28335

only $59! only $69!

‹ New low cost single-board controllers perfect for initial


software development and small volume system builds.
‹ Small form factor (9cm x 2.5cm) with standard 100-pin DIMM
interface
‹ F28x analog I/O, digital I/O, and JTAG signals available at
DIMM interface
‹ Isolated RS-232 interface
‹ Single 5V power supply required
‹ controlCARDs available for 100MHz fixed-point
TMS320F2808, TMS320F28044, and 150 MHz
TMS320F28335 floating-point controller
‹ controlCARDs are available individually through TI distributors
and on the web:
Š Part Number: TMDSCNCD2808, TMDSCNCD28044,
TMDSCNCD28335

C28x Digital Power Supply Workshop 77


5 – Summary and Conclusion

Digital Power Experimenter Kit


DPEK
only $229! ‹ DPEK includes
Š 2-rail DC/DC EVM using TI
PowerTrain™ modules (10A)
Š On-board digital multi-meter and
active load for transient
response tuning
Š F2808 controlCARD
Š C2000 Applications Software CD
with example code and full
hardware details
Š Digital Power Supply Workshop
teaching material and lab
software
Š Code Composer Studio v3.3 with
code size limit of 32KB
Š 9VDC power supply
‹ DPEK available through TI
authorized distributors and on
the web
Š Part Number:TMDSDCDC2KIT

C2000 DC/DC Developer’s Kit


Only
$325!
‹ DC/DC Kit includes
Š 8-rail DC/DC EVM using TI
PowerTrain™ modules (10A)
Š F28044 controlCARD
Š C2000 Applications Software CD
with example code and full
hardware details
Š Code Composer Studio v3.3 with
code size limit of 32KB
Š 9VDC power supply
‹ Available through TI
authorized distributors and on
the web
Š Part Number: TMDSDCDC8KIT

78 C28x Digital Power Supply Workshop


5 – Summary and Conclusion

C2000 AC/DC Developer’s Kit


Only
‹ AC/DC Kit includes
$695! Š AC/DC EVM with interleaved PFC
and phase-shifted full-bridge
Š F2808 controlCARD
Š C2000 Applications Software CD
with example code and full
hardware details
Š Code Composer Studio v3.3 with
code size limit of 32KB
‹ AC/DC EVM features
Š 12VAC in, 80W/10A output
Š Primary side control
Š Synchronous rectification
Š Peak current mode control
Š Two-phase PFC with current
balancing
‹ AC/DC Kit available through TI
authorized distributors and on the
web
Š Part Number: TMDSACDCKIT

Emulation Solutions for C2000 Controllers

‹ BlackHawk USB2000 ‹ Spectrum Digital XDS510-LC


Controller only $299 only $249
Š Full CCS compatibility Š Full CCS compatibility
Š Bi-Color Status LED Š Supports SDFlash
(red/green) programming utility
Š 3.3/5.0 volt device I/O Š Supports XMLGUI for
Š Optional Isolation Adaptor for interfacing to ‘C’ – provides
$299 scripting capability
‹ http://www.blackhawk- ‹ http://www.spectrumdigital.com
dsp.com/Resellers.aspx

C28x Digital Power Supply Workshop 79


5 – Summary and Conclusion

VisSim Graphical Programming


for C2000
‹ Model based design for
simulation, code generation,
and interactive debugging
‹ Efficient code generation
near hand code quality
‹ Automatic code generation
for F28xx peripherals: ADC,
SCI, SPI, I2C, CAN, ePWM,
GPIO
‹ High speed target
acquisition for wave form
display on PC
‹ Watch ‘how to’ tutorials on
Visual Solutions web site
www.vissim.com

UCD9xxx Digital Power Controller Family


UCD9xxx Digital Power Controller Family

4 ind outputs
UCD9240 64 & 80 pin
Performance

UCD92xx 3 ind outputs


UCD9230
48 pin

2 ind outputs
UCD9220
32 pin

1 output, 2 phase
UCD9112 32 pin
UCD91xx

UCD9111 1 output, 1 phase


32 pin

Integration

80 C28x Digital Power Supply Workshop


5 – Summary and Conclusion

Where to Find More Information


Recommended Next Step:
One-day Training Course
TMS320C28x 1-Day Workshop Outline
- Workshop Introduction
- Architecture Overview
- Programming Development Environment
- Peripheral Register Header Files
- Reset, Interrupts and System Initialization
- Control Peripherals
- IQ Math Library and DSP/BIOS
- Flash Programming
Introduction to - The Next Step…
TMS320F2808
Design and
Peripheral Training

Recommended Next Step:


Multi-day Training Course
TMS320C28x Multi-day Workshop Outline
- Architectural Overview
- Programming Development Environment
- Peripheral Register Header Files
- Reset and Interrupts
- System Initialization
- Analog-to-Digital Converter
- Control Peripherals
- Numerical Concepts and IQmath
In-depth - Using DSP/BIOS
TMS320F2808 - System Design
Design and - Communications
Peripheral Training - Support Resources

C28x Digital Power Supply Workshop 81


5 – Summary and Conclusion

For More Information . . .


Internet
Website: http://www.ti.com

FAQ: http://www-k.ext.ti.com/sc/technical_support/knowledgebase.htm
Š Device information Š my.ti.com
Š Application notes Š News and events
Š Technical documentation Š Training
Enroll in Technical Training: http://www.ti.com/sc/training

USA - Product Information Center ( PIC )


Phone: 800-477-8924 or 972-644-5580
Email: support@ti.com
Š Information and support for all TI Semiconductor products/tools
Š Submit suggestions and errata for tools, silicon and documents

European Product Information Center (EPIC)


Web: http://www-k.ext.ti.com/sc/technical_support/pic/euro.htm

Phone: Language Number


Belgium (English) +32 (0) 27 45 55 32
France +33 (0) 1 30 70 11 64
Germany +49 (0) 8161 80 33 11
Israel (English) 1800 949 0107 (free phone)
Italy 800 79 11 37 (free phone)
Netherlands (English) +31 (0) 546 87 95 45
Spain +34 902 35 40 28
Sweden (English) +46 (0) 8587 555 22
United Kingdom +44 (0) 1604 66 33 99
Finland (English) +358(0) 9 25 17 39 48

Fax: All Languages +49 (0) 8161 80 2045

Email: epic@ti.com

Š Literature, Sample Requests and Analog EVM Ordering


Š Information, Technical and Design support for all Catalog TI
Semiconductor products/tools
Š Submit suggestions and errata for tools, silicon and documents

82 C28x Digital Power Supply Workshop

You might also like