Professional Documents
Culture Documents
Book DSP Frank Bormann PDF
Book DSP Frank Bormann PDF
Book DSP Frank Bormann PDF
Module 1: Introduction
1-1
Module Topics
CD – ROM Structure
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.
Lab6: “CPU-Timer 0 and Interrupts” - add a hardware timer to Lab5_1 and use an
interrupt service routine (hardware time base
framework)
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
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
– “Harvard” – Architecture:
» Two independent memory spaces for code and data
» Two memory bus systems for code and data
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.
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.
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
1-5
1 - 10 DSP2833x - Introduction
What is a Digital Signal Controller?
• 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:
A, B, Y: Internal register
F: Functional code
C: Carry – Bit
N: Negative – Bit
Z: Zero - Bit
1-7
DSP2833x - Introduction 1 - 11
What is a Digital Signal Controller?
control/
status
- Memory Manager - Bus Control
- logical / physical - Address & Data Bus – data
address Interface
- Instruction Queue
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?
2. our Desktop – PC is a?
2. Microcomputer
– Microcomputer = microprocessor (µP) + memory +
peripherals
– Example: your Desktop -PC
1-9
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:
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?
3. System on Chip
1 - 11
DSP2833x - Introduction 1 - 15
What is a Digital Signal Controller?
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?
1 - 13
Algorithm Equation
Convolution
1 - 14
DSP2833x - Introduction 1 - 17
What is a Digital Signal Controller?
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.
1 - 16
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?
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
1 - 19
1 - 20 DSP2833x - Introduction
What is a Digital Signal Controller?
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.
6%
12%
9%
Agere
14% Analog Devices
Freescale
Texas Instruments
Other
59%
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
3,2 2,8
4,6
Wireless
Consumer
9,1 Multipurpose
Computer
Wireline
Automotive
72,3 Relative
Source: www.forwardconcepts.com
1 - 22
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.
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.
1 - 25
The next Slide 1-26 illustrates the latest developments in the 32-bit real-time controller
family C28x:
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
1 - 26
DSP2833x - Introduction 1 - 25
TMS320F28x Application Areas
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
RFID Readers
DMA 2 QEP
Peripheral Bus
88 GPIO
C28xTM 32-bit DSC 16/32-bit
EMIF
32x32-bit RMW
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
3-1
Module Topics
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
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!
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
32-bit R-M-W
32x32 bit
Auxiliary Atomic FPU
Multiplier
Registers ALU 3 PIE
32-bit Interrupt
Register Bus Manager
Timers
CPU
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.
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.
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
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.
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).
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.
• 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)
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.
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)
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:
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.
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
CSM Protected:
L0, L1, L2, L3,
FLASH, ADC CAL,
OTP
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.
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
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.
2 - 14
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
F2833x - Architecture 2 - 17
Summary of TMS320F2833x Architecture
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.
CPU
window
Source
code
window
Status
window
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
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.
CPU
window
Source
code
window
Status
window
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-
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.
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.
Slide 3-5 reveals all peripheral units, which are populated at the Peripheral Explorer Board
(Texas Instruments part number: TMDSPREX28335).
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:
• 1 stereo audio codec AIC23B for line -in and headphone -out (connected via McBSP and
SPI)
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.
3-6
The step-by-step approach for Lab3 will show how to do the following:
• Watch Variables
• Use of Breakpoints
• View registers
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.
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).
Create a project
Let us now create our first project. Click on File New CCS Project and enter “Lab3”:
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”:
3 - 10
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:
• Go to category:
• C/C++ Build, C2000 Linker, Basic Options
• Set C system stack size: 0x400
3 - 12
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.
3 - 13
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:
3 - 14
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:
C – Compiler Sections
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
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:
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
Memory
Sections
0x00 0000 M0SARAM
(0x400)
.ebss
0x00 0400 M1SARAM
(0x400)
.stack
.text
3 - 17
Linking
Memory description
How to place Software
Sections into Memory
name.cmd
.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).
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.
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:
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!
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.
• Connect Target
• Load Program
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.
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.
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”:
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
• 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.
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.
• Monitor the variables of that code snippet and compare the results with your
expectations.
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 - 26
Run
Step Out
Halt
3 - 27
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.
• 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.
3 - 28
blue arrow:
blue and
current position
enabled dot:
of PC
active Breakpoint
3 - 29
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
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!
• 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’.
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:
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.
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.
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.
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!
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:
3 - 34
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:
3 - 35
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.
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!
3 - 38
By default, startup GEL – files defined in the target configuration file are automatically loaded
when a debug session is started.
OnReset(int nErrorCode)
{
C28x_Mode();
Unlock_CSM();
ADC_Cal();
}
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).
3 - 39
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
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”
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.
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”:
Save this file by clicking File Save as and type in: Lab3.c
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.
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
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:
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”).
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:
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
the start address of our project in RAM (a function called “c_int00”) and to start from this po-
sition.
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.
View Memory
Enter the address for variable k (“&k”) in the address box (top left corner box).
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:
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:
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).
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.
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
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
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):
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):
• 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.
4-4
In the following slides we will focus on the arithmetic numbering formats only.
• Mantissa (M):
23
−1 −2
M = 1 + m1 ⋅ 2 + m2 ⋅ 2 + ... + m23 ⋅ 2 − 23
= 1 + ∑ mi ⋅ 2−i
i =1
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
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:
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:
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
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!
Binary Numbers
01102 = (0*8)+(1*4)+(1*2)+(0*1) = 610
111102 = (1*16)+(1*8)+(1*4)+(1*2)+(0*1) = 3010
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:
Data Memory ?
Is there another (superior) numbering system? 4-7
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?
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
4-8
Four-Bit IQ - Multiplication
0100
. 1/2
x 1101
. x - 3/8
00000100
0000000
000100
11100
11110100 -3/16
Accumulator 11110100
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.
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
4 - 10
IQ - Examples
I1Q3 – Format:
3 0
S fff
Most negative decimal number: -1.0 = 1.000 B
4 - 11
IQ - Examples
I3Q1 – Format:
3 0
SII f
Most negative decimal number: -4.0 = 100.0 B
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
4 - 13
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
4 - 14
Now let us resume the failing Floating-Point example from the beginning of this module; IQ-
Math can do much better:
z = 10.000000240 (0x0A000004)
4 - 15
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:
½ 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
4 - 17
Procedure
• 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”:
2. Open the file “main.c” from project “Lab3” and save it as “lab4_1.c” in subfolder
“Lab4”:
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”:
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.
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)”.
• 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).
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.
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:
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 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.
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”.
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:
• 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!
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.
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…
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!
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).
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
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
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)
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
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
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;
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
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
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
5-7
5-8
5-9
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
SYSCLKOUT
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
Summary GPIO-Registers
The next two slides will summarize all registers of the GPIO-unit.
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
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
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
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.
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.
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
SysCtrlRegs.PCLKCR3
15 - 14 13 12 11 10 9 8 7-0
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
5 - 18
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!
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
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.
How do we clear the Watchdog counter register, before it overflows? Answer: By writing a
“valid key” or “good key” sequence into register WDKEY:
15 - 8 7-0
reserved WDKEY
5 - 21
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
Register: SysCtrlRegs.SCSR
15 - 3 2 1 0
5 - 23
IDLE off on on on
5 - 24
15 14 - 8 7-2 1-0
WDINTE reserved QUALSTDBY LPM0
* 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
Exit
Interrupt RESET GPIO Watchdog Any
or Port A Interrupt Enabled
Low Power XNMI Signal Interrupt
Mode
5 - 26
Register: SysCtrlRegs.GPIOLPMSEL
31 30 29 28 27 26 25 24
23 22 21 20 19 18 17 16
GPIO23 GPIO22 GPIO21 GPIO20 GPIO19 GPIO18 GPIO17 GPIO16
15 14 13 12 11 10 9 8
7 6 5 4 3 2 1 0
GPIO7 GPIO6 GPIO5 GPIO4 GPIO3 GPIO2 GPIO1 GPIO0
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”
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
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.
C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
and watch the tools run in the build window. If you get errors or warnings debug as ne-
cessary.
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)”.
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).
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.
Target Run
Our LED code should not work any more! This is a sign that the F2833x has been RESET by
a watchdog overflow.
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.
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!
Step 1
Step 2 Step 6
Step 3 Step 5
Step 4
5 - 32
Procedure
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.
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
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.
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!
5 - 33
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 - 35
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.
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.
Blank Page
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.
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
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 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.
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
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:
Execution Entry
0x3F E000 Boot ROM (8Kw) Point Determined
Boot Code By GPIO Pins
0x3F F9CE
• •
• •
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
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.
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.
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.
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
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.
INT1 1
INT2 0 F2833x
Core
INT14 1
7 6 5 4 3 2 1 0
INT8 INT7 INT6 INT5 INT4 INT3 INT2 INT1
6 - 10 F2833x - Interrupts
Maskable Interrupt Processing
7 6 5 4 3 2 1 0
INT8 INT7 INT6 INT5 INT4 INT3 INT2 INT1
6 - 13
F2833x - Interrupts 6 - 11
Peripheral Interrupt Expansion
INTM
INT10.x interrupt group 28x
IER
IFR
12 Interrupts
INT11.x interrupt group Core
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
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
INT10
INT11
6 - 16
F2833x - Interrupts 6 - 13
Peripheral Interrupt Expansion
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.
_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
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)
F2833x - Interrupts 6 - 15
F2833x CPU Timers
Timer Reload
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
PIE unit
TINT0
INT1.7 interrupt
28x Core Interrupt logic
INT1
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.
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.
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
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
Procedure
• 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.
C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include
6 - 20 F2833x - Interrupts
Lab 6: CPU Timer 0 Interrupt and 4 LEDs
and watch the tools run in the build window. If you get errors or warnings debug as ne-
cessary.
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)”.
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.
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
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.
Target Debug Active Project and switch into the “Debug” perspective.
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:
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
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!
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…
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
TBPRD
Asymmetrical
Waveform
Count Up Mode
TBCTR
TBPRD
Asymmetrical
Waveform
TBPRD
Symmetrical
Waveform
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
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;
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
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.
6 5-4 3 2 1-0
SWFSYNC SYNCOSEL PRDLD PHSEN CTRMODE
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
15 - 3 2 1 0
reserved CTRMAX SYNCI CTRDIR
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!
• 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
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
C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include
and watch the tools run in the build window. If you get errors or warnings debug as
necessary.
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)”.
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.
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
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
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
• 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
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.
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.
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.
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:
.. .. ..
TBPRD
CMPA Asymmetrical
CMPB Waveform
Count Up Mode
TBCTR
TBPRD
CMPA
CMPB
.. .. .. Asymmetrical
Waveform
.. .. .. ..
TBPRD
CMPA Symmetrical
CMPB Waveform
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:
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
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.
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.
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:
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
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
TBCTR
TBPRD
. .
. .
CA CB CA CB
↑ ↓ ↑ ↓
EPWMA
Z Z Z
T T T
EPWMB
7 - 21
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.
7 - 23
One-
One-Time S/W Force on Output B / A
0 = no action
1 = single s/w force event
7 - 25
“Continuous Force” will hold the line permanently in the selected state.
15 - 4 3-2 1-0
reserved CSFB CSFA
7 - 26
• 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
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) …
Result: The pulse width of your signal should change gradually between 100% and 0 %.
END of LAB 7_3
• Registers involved:
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
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.
Result: The pulse width of your pair of signals should change gradually between 100%
and 0 %.
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
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.
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
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.
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.
supply rail
7 - 31
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:
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
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.
7 - 34
The Dead Band Control Register combines the bit fields for switches S0 to S5:
Polarity Select
00 = active high
01 = active low complementary (RED)
10 = active high complementary (FED)
11 = active low
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 - 36
Procedure
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.
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):
EPWMxSYNCI EPWMxSYNCO
Period
Register EPWMxA
PWM Trip
Shadowed
Chopper Zone
SYSCLKOUT TBPRD . 15 - 0 EPWMxB
PCCTL . 10 - 0
TZy
TZSEL . 15 - 0
7 - 37
Purpose of Chopping
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.
EPWMxB
CHPFREQ
EPWMxA
EPWMxB
Programmable
Pulse Width
OSHT (OSHTWTH)
Sustaining
EPWMxA Pulses
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:
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 - 40
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
7 - 42
Procedure
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):
EPWMxSYNCI EPWMxSYNCO
Period
Register EPWMxA
PWM Trip
Shadowed
Chopper Zone
SYSCLKOUT TBPRD . 15 - 0 EPWMxB
PCCTL . 10 - 0
TZy
TZSEL . 15 - 0
7 - 43
7 - 45
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!
15 - 4 3-2 1-0
reserved TZB TZA
7 - 46
Register TZCTL is used to define the state of line ePWMxA and ePWMxB in case of an
over current signal.
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
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.
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.
7 - 49
Procedure
• 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.
6. Now push button PB1. Both ePWM1A and ePWM1B should be switched off (0V)
permanently.
• 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!
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);
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. 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
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:
TBPRD
CMPB
. . . . . . . .
CMPA
EPWMA
EPWMB
CTR = 0
CTR = PRD
CTRU = CMPA
CTRD = CMPA
CTRU = CMPB
CTRD = CMPB 7 - 51
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 - 52
15 14 - 12 11 10 - 8 7-4 3 2-0
SOCBEN SOCBSEL SOCAEN SOCASEL reserved INTEN INTSEL
7 - 54
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.
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).
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:
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 ( }).
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
Capture 1 Polarity
Register Select 1
CAP2POL
CAP2 . 31 - 0 ECCTL . 2
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.
Timer
Trigger
pin
Timestamp
Values
7 - 57
• 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.
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.
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
7 - 60
Upper Register:
CAP1 – 4 Load
on Capture Event
0 = disable
1 = enable
15 - 14 13 - 9 8
FREE_SOFT PRESCALE CAPLDEN
11110 = divide by 60
11111 = divide by 62
7 - 61
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.
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
7 - 62
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).
Upper Register:
Capture / APWM mode
0 = capture mode
1 = APWM mode
15 - 11 10 9 8
reserved APWMPOL CAP_APWM SWSYNC
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.
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.
15 - 8 7 6 5 4 3 2 1 0
reserved CTR=CMP CTR=PRD CTROVF CEVT4 CEVT3 CEVT2 CEVT1 reserved
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.
Procedure
• prescaler : divide by 1
• enable capture load results
• edge select: CAP1 - falling ; CAP2 - rising; CAP3 - falling; CAP4 - rising
• reset TSCTR on CAP4 - event
PieCtrlRegs.PIEACK.all = 8;
Ch. A
Ch. B
shaft rotation
7 - 66
(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 - 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
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
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
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.
Procedure
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.
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.
Module Topics
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
• 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.
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
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.
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
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.
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.
15 14 13 - 12 11 - 8 7
reserved RESET SUSMOD ACQ_PS CPS
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”
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).
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
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!
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
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.
15 - 8 7-6 5 4-1 0
reserved ADCBGRFDN ADCPWDN ADCCLKPS SMODE_SEL
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.
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
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.
15 - 12 11 - 8 7-4 3-0
ADCCHSELSEQ1 CONV03 CONV02 CONV01 CONV00
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:
ePWM
Time Base
Counter
ePWM
Output
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.
RESULT0 V1
RESULT1 V2
RESULT2 V3
RESULT3 I1
RESULT4 I2
RESULT5 I3
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.
ADCLO
GND
2) Subtract “1.5” from the digital result
#include “DSP2833x_Device.h”
#define offset 0x07FF
void main(void)
{
int16 value; // signed
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.
15 - 14 13 - 0
REF_SEL reserved
8 - 19
Structure Variable in C: AdcRegs.ADCREFSEL
8 - 20
8 - 21
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
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
• 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.
C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include
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”:
and watch the tools run in the build window. If you get errors or warnings debug as
necessary.
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)”.
Target Run
Result: All 4 LEDs should blink at a rate of 0.5 seconds on and off period.
• 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.ADCMAXCONV.all = ?; // 2 conversions
For register ADCCHSELSEQ1:
• 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;
AdcRegs.ADCTRL2.bit.RST_SEQ1 = 1;
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:
• Verify that the clock system is enabled (PCLKCR) for EPWM2 and ADC
Optional Lab8_2
Modify Lab 6 (“4-bit Counter”):
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”.
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).
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.
TX FIFO_15 TX FIFO_15
Transmitter-data Transmitter-data
buffer register buffer register
8 8
Receiver-data Receiver-data
buffer register buffer register
RX FIFO_0 RX FIFO_0
RX FIFO_15 RX FIFO_15
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
Addr/
Start LSB 2 3 4 5 6 7 MSB Parity Stop 1 Stop 2
Data
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’.
• 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
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-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.
9-6
Block of Frames
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
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
9 - 10
0 = receiver disabled
1 = receiver enabled
0 = transmitter disabled
1 = transmitter 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).
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!
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 %).
15 - 8 7 6 5-2 1 0
reserved TX reserved RX/BK TX
TXRDY
EMPTY INT ENA INT ENA
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.
1 = Receiver wakeup
condition detected
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.
7 6 5 4 3 2 1 0
TXFFINT
TXFFINT TXFFIENA TXFFIL4 TXFFIL3 TXFFIL2 TXFFIL1 TXFFIL0
CLR
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.
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
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.
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.
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.
Procedure
• 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.
• 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.
and watch the tools run in the build window. If you get errors or warnings debug as
necessary.
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
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:
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:
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.
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).
Procedure
SciaRegs.SCIFFTX.bit.TXINTCLR = 1;
That’s it.
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.
Procedure
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)
{
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:
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()”.
• 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”.
}
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:
#include <string.h>
That’s it.
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
clock
10 - 2
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
RX FIFO_15
SPIRXBUF.15-0
MSB LSB
SPIDAT.15-0 SPISOMI
SPITXBUF.15-0
TX FIFO_0
TX FIFO_15
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.
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
10 - 4
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
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
15-5 4 3 2 1 0
reserved
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).
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).
15-8 7 6 5 4-0
reserved reserved
10 - 9
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
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
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).
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
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”.
node 1 node 30
CAN_H
120 120
Ohm
Ohm
CAN_L
11 - 19
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
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.
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.
11 - 4
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:
• FlexRay®
o 10 Mbit/s
• FlexRay
• Time Triggered Protocol for fail safe applications;
• 10 Mbit/s; dual channel redundancy
• www.flexray.com
11 - 5
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.
11 - 7
• CAN-Version 2.0A
Standard • messages with 11-bit -
identifiers
• CAN-Version 2.0B
Extended • messages with 29-bit-
identifiers
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).
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
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.
11 - 11
11 - 12
11 - 13
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
11 - 15
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
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).
11 - 17
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
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
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.
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.
Rxd Txd
CAN Transceiver
SN65HVD23X
CAN_H
CAN_L
CAN - bus
11 - 20
11 - 21
The error management of a node is based on one of 3 states, in which a node operates:
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.
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
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.
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
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
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.
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).
32
Receive Buffer
Transmit Buffer
Control Buffer
Status Buffer
SN65HVD23x
3.3-V CAN Transceiver
.
. CAN Bus
11 - 30
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 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 - 32
CANME[31:16]
15 0
CANME[15:0]
CANMD[31:16]
15 0
CANMD[15:0]
11 - 33
CANTRS[31:16]
15 0
CANTRS[15:0]
CANTRR[31:16]
15 0
CANTRR[15:0]
11 - 34
CANTA[31:16]
15 0
CANTA[15:0]
CANAA[31:16]
15 0
CANAA[15:0]
CANRMP[31:16]
15 0
CANRMP[15:0]
CANRML[31:16]
15 0
CANRML[15:0]
CANRFP[31:16]
15 0
CANRFP[15:0]
11 - 37
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!
11 - 38
The F2833x CAN module is able to operate in one of two operating modes:
• 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!
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
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
TQ
11 - 43
TQ = BRP +1
BaseCLK
Note:
BaseCLK = SYSCLK / 2 for 283xx, 2803x devices
BaseCLK = SYSCLK for 281x, 280x and 2801x devices
11 - 44
11 - 45
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
11 - 47
15 6 5 4 3 2 1 0
11 - 48
reserved
15 0
reserved TEC
reserved
15 0
reserved REC
11 - 49
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
11 - 50
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
11 - 51
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
11 - 52
CANMIM[31:16]
15 0
CANMIM[15:0]
CANMIL[31:16]
15 0
CANMIL[15:0]
11 - 53
CANOPC[31:16]
15 0
CANOPC[15:0]
11 - 54
reserved
15 3 2 1 0
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
reserved
15 3 2 1 0
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
LNT[31:16]
15 0
LNT[15:0]
11 - 57
TOC[31:0]
11 - 58
31 30-29 28 16
15 0
LAMn[15:0]
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
31 16
MOTSn[31:16]
15 0
MOTSn[15:0]
CANLNT is a 32 bit timer that is clocked by the CAN – bit – time unit.
11 - 60
31 16
MOTOn[31:16]
15 0
MOTOn[15:0]
11 - 61
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
Message Identifier
Standard Frames : IDn[28:18] are used
Extended Frames : IDn[28:0] are used
11 - 63
11 - 64
11 - 65
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.
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:
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
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!
• 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.
Procedure
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:
• DSP2833x_Headers_nonBIOS.cmd
C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include
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.
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.
• 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
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
#if (CPU_FRQ_150MHZ)
and change the initialization values for BRPREG, TSEG1REG and TSEG2REG.
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.
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”.
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)”.
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.
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!
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.
• 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
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
• DSP2833x_Headers_nonBIOS.cmd
C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include
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.
• 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
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
#if (CPU_FRQ_150MHZ)
and change the initialization values for BRPREG, TSEG1REG and TSEG2REG.
Save and close file “DSP2833x_ECAN.c”.
and watch the tools run in the build window. If you get errors or warnings debug as
necessary.
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)”.
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.
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.
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!
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.
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
I2C TMP101
EPROM I2C
12 - 2
I2CXSR I2CDXR
TX FIFO
SDA
RX FIFO
I2CRSR I2CDRR
Clock
SCL
Circuits
12 - 3
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.
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.
The period of the master clock (TMASTER) is a multiple of the period of the I2C module clock:
100 MHz
10 MHz = ; IPSC = 14
( IPSC + 1)
• IPSC = 14
• ICCL = 95
• ICCH = 95
The following table give some more options for the I2C clock unit:
50 kHz 9 95 / 95 14 95 /95
400 kHz 9 10 / 5 14 10 / 5
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.
12 - 5
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.
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.
FDF XA 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.
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:
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.
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.
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.
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.
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).
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.
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.
7 6 5 4 3 2 1 0
reserved AAS SCD XRDY RRDY ARDY NACK AL
12 - 13
7 6 5 4 3 2 1 0
reserved reserved SCD XRDY RRDY ARDY NACK AL
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
I2caRegs.I2CCLKL
15 0
ICCL
I2caRegs.I2CCLKH
15 0
ICCH
12 - 17
15 - 10 9-0
reserved SAR
12 - 19
15 - 10 9-0
reserved OAR
12 - 20
15 0
ICDC
0x0000: The start value loaded to the internal data counter is 65536.
12 - 20
15 - 8 7-0
reserved DATA
12 - 21
7 6 5 4-0
TXFFINT TXFFINTCLR TXFFIENA TXFFIL
7 6 5 4-0
RXFFINT RXFFINTCLR RXFFIENA RXFFIL
12 - 23
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.
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:
At the Peripheral Explorer Board pins ADD0 and ADD1 are fixed to 0.
12 - 26
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
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:
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 - 29
The power-up/reset value of the Configuration Register is with all bits equal to 0.
Bus Idle:
Both SDA and SCL lines remain HIGH.
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.
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.
12 - 30
12 - 31
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:
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
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
C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include
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!
• Initialize the I2C module clock to 10MHz. If SYSCLKOUT is 150 MHz, set
Register I2CPSC to 14:
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).
• 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:
14. Install a wait loop until the 1st byte has been received from TMP100:
while(I2caRegs.I2CSTR.bit.RRDY == 0);
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;
and watch the tools run in the build output window. If you get errors or warnings de-
bug as necessary.
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.
The Variable “temperature” should display the current ambient temperature with a
resolution of 0.5 °C (the example above shows 29.0 °C).
Procedure
• 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.
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
and watch the tools run in the build output window. If you get errors or warnings de-
bug as necessary.
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)”.
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.
Variable “temperature” should display the current ambient temperature with a resolu-
tion of 1/16 °C (the example above shows 29.0625 °C).
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.
•
nd
M4 (green marker): 2 START Condition
Procedure
I2caRegs.I2CCNT = 2;
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)
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)”.
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).
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
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;
{
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).
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)”.
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).
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.
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.
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
CPU
RSR2 RSR1 MDRx
16 16
13 - 3
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):
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.
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
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”).
FS
D w6 w7 w0 w1 w2 w3 w4 w5 w6 w7
Frame
Word
13 - 6
A frame consists of multiple “words”. The number of words is programmable between 1 and
128 words.
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.
CLK
FS
D a1 a0 b7 b6 b5 b4 b3 b2 b1 b0
Word
Bit
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)
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.
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.
McBSP - clocking
McBSP - Clocking
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).
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).
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.
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
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.
McBSP Transmission
This section explains the fundamental process of transmission in the McBSP.
McBSP – Transmission
Transmission physical data path
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.
13 - 14
13 - 15
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.
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
13 - 20
13 - 22
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
13 - 27
In the next pages we will discuss the first external device of the Peripheral Explorer Board,
which is connected via McBSP - A:
“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:
Signals:
RHPOUT =
right headphone out
LHPOUT =
left headphone out
13 - 29
Description:
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).
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.
Switch OFF: LINE, MIC, ADC, DAC and OUT. Switch ON: OSC, CLK and OFF.
13 - 33
• Enable ADC High Pass Filter, Disable De - emphasis, disable DAC soft mute.
13 - 34
13 - 35
• Activate Interface
13 - 37
1= OFF, 0 = ON
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):
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:
• 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:
In preparation for Lab13_1, we can write a new function “SPIA_init()”, which covers the
initialization steps discussed above.
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.
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
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
Procedure
Now we are ready to code a new project for Lab13_1:
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
C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include
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!
• 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”.
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()”.
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
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:
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()”:
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:
• 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].
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)”.
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!
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
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”.
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)”.
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:
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!
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:
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
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.
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)”.
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:
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!
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.
13 - 39
Hardware Description:
The SPI - Interface of this device is connected to the F28335 - McBSP - channel B. The fol-
lowing schematic gives the hardware - details:
• 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.
Timing Diagram
The AT25256 has the following timing requirements:
EEPROM AT25256
Timing Diagram:
13 - 40
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.
EEPROM AT25256
Access Status Register:
7 6 5 4 3 2 1 0
WPEN 0 0 0 BP1 BP0 WEN /RDY
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:
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):
EEPROM AT25256
Write – Enable (WREN) Timing:
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:
13 - 44
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:
13 - 45
EEPROM AT25256
Write (WRITE) Timing:
13 - 46
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
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.
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
Also add a function prototype for this function at the beginning of “Lab13_4.c”.
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.
• 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!
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)”.
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).
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.
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
0 1 1 1 Jump to OTP
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
“1110” (SCI-A Boot loader). The following slide shows the sequence that takes place when
we start from Flash.
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 - 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.
FOTPWAIT 15 4 3 0
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.
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
14 - 5
Defaults for these registers are often sufficient – See “TMS320F2833x System
Control and Interrupts Reference Guide,” SPRUFB0, for more information
14 - 6
FLASH CPU
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.
Algorithm Function
1. Erase - Set all bits to zero, then to one
2. Program - Program selected bits with zero
3. Verify - Verify flash contents
14 - 10
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)
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!
CSM Password
0x300000
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
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
Device unlocked
Correct Yes
password? User can access on-
chip secure memory
No
14 - 16
14 - 17
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.
Procedure
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
C:\tidcs\C28\dsp2833x\v131\DSP2833x_headers\include
C:\tidcs\c28\DSP2833x\v131\DSP2833x_common\include
• 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.
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:
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.
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).
Blank page.
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.
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
• FLASH
• OTP
• M0-SARAM or
• XINTF - Zone 6
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.
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
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
15 - 4
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.
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.
Execution Entry
0x3F E000 Boot ROM (8Kw) Point Determined
Boot Code By GPIO Pins
0x3F F9CE
• •
• •
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:
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.
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.
15 - 7
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.
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.
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.
No
W1 = Read second word
0x10AA? lower 8 bit
Yes
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
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!
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
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.
GPIO - 26
C28x GPIO - 27 Host/ e.g.
GPIO
PC‘s COM1
16
GPIO15...GPIO0
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).
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.
Read KeyValue
( 8 or 16 Bit size) Call Parallel Copy Data
Yes
Valid Key?
Jump
Entry Point
No
FLASH
15 - 15
F28x ack? No
No
F28x ready? (GPIO26=1)
(GPIO26=0)
Yes
Yes
Deactivate GPIO27 =1
Load 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.
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
SPI is initialized and the key value read, the user could specify a change in baud rate or low
speed peripheral clock.
The following slide (Slide 15-18) shows the sequence of 8-bit data expected by the Boot
Loader.
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
Requested No
SPIBRR =
0x7F?
Change SPIBRR
Yes
15 - 20
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.
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.
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:
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.
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.
• 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
• 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.
• 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
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.
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
16 - 3
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.
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).
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.
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
16 - 5
16 - 6
#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:
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:
#include "FLASH2833x_API_Library.h"
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
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.
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”.
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.
Flash_CPUScaleFactor = SCALE_FACTOR;
Flash_CallbackPtr = NULL;
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)
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)
The use of these macros is optional. They have been provided to allow easy porting of code
between the devices.
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”.
API Library:
<base>\Flash28335_API_V210\lib\Flash28335_API_V210.lib
Documentation:
< base >\Flash28335_API_V210\doc
Example:
< base >\Flash28335_API_V210\example
• 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).
• 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.
• 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!
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
• 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);
• Next, add a prototype for the local ADC interrupt service routine. Add:
interrupt void adc_isr(void);
• 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;
• 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 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;
• 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 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
}
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;
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:
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.
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.
• LEDs LD1...LD4 are toggled between “0000” and the corresponding values in
bit 11 to bit 8 of “FLASH_Voltage_A0”
END of Lab16.
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
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:
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?
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:
F2833x - IQ-Math 17 - 5
How do use IQ-Math?
Natural development
Simulation
Platform starts with simulation in
Takes many days/weeks (i.e. MatLab) floating-point
to convert (one way
process)
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?
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
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?
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
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?
I8 Q24 M
I16 Q48
I8 Q24 X
Align Decimal
Point Of Multiply
>> 24
sssssssssssssssssI16 Q24
I8 Q24 B
I8 Q24 I8 Q24 Y
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
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;
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
Fixed-Point Floating-Point
Math Code Math Code
Compile & Run Compile & Run
on Fixed-Point on Floating-Point
F282xx F283xx *
* 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
F2833x - IQ-Math 17 - 13
IQ- Math Application: Field Orientated Control
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.
#include “math.h”
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.
#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));
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.
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
Floating-Point:
+∞ 0 -∞
+∞ 0 -∞
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:
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.
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.
Q18 to Q0 Unstable
(not enough resolution, quantization problems)
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
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
17 - 20 F2833x - IQ-Math
Lab 17: IQ - Math based low - pass filter
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.
CPU copies
result to
buffer during
...
ADC ISR
Display
using CCS
17 - 25
F2833x - IQ-Math 17 - 21
Lab 17: IQ - Math based low - pass filter
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%.
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)”.
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
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.
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:
• 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
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);
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:
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:
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).
#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
• Add a static unsigned integer variable “index” and initialize it with zero.
• Read the current sample and store it in array “AdcBuf”:
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.
17 - 26 F2833x - IQ-Math
Lab 17: IQ - Math based low - pass filter
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).
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)”.
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:
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
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
• Window: Hamming
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
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)”.
Target Run
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”.
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”.
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.
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
Asynchronuous Motor
Ω 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
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
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
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.
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.
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.
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
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
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
DC bus
capacitor − Three phase
outputs which
go to the motor
terminals
Power
Switching
Devices
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
θ S1
V180 (110) 0 (111) 0 (000)
0 d
S4 S6
Shunt Tacho
resistor Or
Resolver
ADCIN2
ADCIN3 Signal
Conditioning
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
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
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
Signal
Conditioning
10/28/2009 28
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
Achieved by
- IQMath
- Application Frameworks: DMC Library & Incremental Build
- Partner Tools for simulation, GUI programming, and auto code gen
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
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.
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:
continue to be serviced
Debug
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
Application Frameworks
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.
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.
An oscilloscope is used to monitor the shape of the PWM signals and the pulses series
generated by the SVGEN module.
Build Level 2
Build Level 3
Build Level 4
Build Level 5
Build Level 6
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!
A set of base boards allows the user to go deeper into different application areas, such as
Digital Power Supply or Digital Motor Control.
For Digital Motor Control the following package includes all you need to experiment with
PMSM motors.
Summary
• 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.
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.
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.
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
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
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
Vin
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
Failure Prediction
Aux P/S
One Device, Multiple DC Outputs
Variable DC Output
Digital controller enables multi-threaded applications
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
Difference equation C
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
Digital Processor
- Control
A-D Σ Law
D-A
+
Ref
t t t t
Continuous Discrete
time signal time signal
Processor Bandwidth
y(n)
TSAMPLE
Single CPU C1 C2 C3 C1 C2 C3 C1 C2 C3
DAC
(PWM)
DSC
ADC
“Plant”
0110101100
1011011101
0010100111
“High fidelity”
Translation boundary
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
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
TM
100 MIPs C28x 32-bit DSP Control Peripherals
32x32-bit CAN 2.0 B Up to 6 ePWM, 4 eCAP, and 2 eQEP
RMW
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
& Int.
Number of channels scalable
Action
Project Manager:
¾Source & object files
¾File dependencies
¾Compiler, Assembler &
Linker build options
Editor:
¾Structure Expansion
Soft Start and Sequencing Phase Shifted Full Bridge Analog-Digital Converter driver
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
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
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;
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
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
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
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.
controlCard 2808
¾ Project Overview
PWMexplore-Main.c – this file is used to initialize, run, and manage the application. This is
the “brains” behind the application.
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:
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:
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.
¾ Procedure
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.
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:
Note: DO NOT make any changes to the source files – ONLY INSPECT
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.
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().
13. Open the watch window to view the variables used in the project.
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”,
“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:
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:
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.
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.
Next, try the other options. Below is a list of the active PWM driver macro for each se-
lected ConfigOption:
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
H
Duty1 Duty1 In W EPWMnA DRV Buck
Duty2
ADC A
D
Duty3 1CH
C
DRV
Duty1
H
slider Vfdbk Vout1 Rslt W Ch0
xSYNCI
SYNCI
VBus32
ADC
to ECAP1 module (sync in)
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
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
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
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
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
2 X Vout
SyncOut
3 X
SyncOut
VDC_bus VOUT
Ext Sync In
(optional)
Master
EPWM1A
Phase Reg En SyncIn
Φ = 0ο
EPWM1A
CNT=Zero
CNT=CMPB EPWM1B
1 X
SyncOut
EPWM1B
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
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
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
PFC E
2PHIL P EPWM1A
DRV W
M
Net1 Duty
H EPWM1B
Net2 Adj W
EPWM1A +/-
Adj
VDC_bus
+/-
EPWM1B Adj
EPWM1A EPWM1B
Φ = 180 ο
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.
Buck E
Vin
Buck-1 Vo ut1
P
Watch W indow Single W
DRV M
¾ 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.
TwoChannel-Main.c – this file is used to initialize, run, and manage the application. This is
the “brains” behind the application.
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:
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.
12V In
DMM
DC Bus
(SW2)
V1/V2
Select
(SW3)
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)
Active Load Software controlled switched load (connected to output of buck 1 only)
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.
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.
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).
¾ Procedure
2. A project named Lab2.pjt has been created for this lab exercise. Open the project by
clicking:
Project Æ Open…
Note: DO NOT make any changes to the source files – ONLY INSPECT
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
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
Duty1 and Duty2 variables will directly control the buck duty cycle. Sliders will be used to quickly change these values.
Duty1 = 0x0;
Duty2 = 0x0;
9. Under Debug on the menu bar click “Reset CPU”, “Restart”, and then “Go
Main”. You should now be at the start of Main().
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.
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
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.
14. Check to see if the windows are set to continuously refresh. Click:
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.
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
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
...
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
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
PWM T Sysclk
t t
Regular
Device Clock PWM Step
(i.e. 100MHz)
(i.e. 10ns)
HRPWM
Micro Step (~150ps)
t
T SYSCL (10 ns)
1 MHz
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
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
Vout Monitor
Duty Monitor
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.
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).
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.
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
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.
¾ Procedure
2. A project named Lab3.pjt has been created for this lab exercise. Open the project by
clicking:
Project Æ Open…
The TwoChannel.gel file and watch window should still be loaded from the previous lab.
Note: DO NOT make any changes to the source files – ONLY INSPECT
ChSel[12] = 2; // A2 - Temperature-2
ChSel[13] = 11; // B3 - Vin
// BUCK_DRV connections
Buck_In1 = &Uout;
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)
7. Under Debug on the menu bar click “Reset CPU”, “Restart”, and then “Go
Main”. You should now be at the start of Main().
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.
Variable Description
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:
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:
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”.
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
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
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
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
Steady state
Acceptable error
Peak deviation
Settling time
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)
We can see that PID is nothing but a special case of 2P2Z control where:
A1 = -1 and A2 = 0
; 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
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 )
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
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 )
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
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
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.
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
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:
where:
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.
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.
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.
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)
¾ Procedure
2. A project named Lab4.pjt has been created for this lab exercise. Open the project by
clicking:
Project Æ Open…
The TwoChannel.gel file, watch windows and graph window should still be loaded from
the previous lab.
Note: DO NOT make any changes to the source files – ONLY INSPECT
6. Under Debug on the menu bar click “Reset CPU”, “Restart”, and then “Go
Main”. You should now be at the start of Main().
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:
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”.
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:
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:
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
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
IphB
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
TMS320F282x
TMS320F281x
TMS320F283x
TMS320F280x
Flexibility
Fully Programmable,
Control Focused
UCD9111
UCD9112 UCD9220
UCD9240 Power-Optimized
Controllers
System Complexity
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
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
100-pin LQFP and u*BGA; Also available in -40 to 125 C and Automotive Q100
TM
C28x 32-bit DSC
Control Peripherals
CAN 2.0 B
Up to 16 PWM channels and 4 event captures
32x32-bit RMW 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
C2000 controlCARDs
F2808 F28335
4 ind outputs
UCD9240 64 & 80 pin
Performance
2 ind outputs
UCD9220
32 pin
1 output, 2 phase
UCD9112 32 pin
UCD91xx
Integration
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
Email: epic@ti.com