Professional Documents
Culture Documents
From Matlab and Simulink To Real Time With Ti Dsps 1.2 PDF
From Matlab and Simulink To Real Time With Ti Dsps 1.2 PDF
with TI DSP’s
By:
Jacob Fainguelernt
From MATLAB and Simulink to Real-Time
with TI DSP’s
By:
Jacob Fainguelernt
Online:
< http://cnx.org/content/col10713/1.1/ >
CONNEXIONS
Control
1.1.1.2 Objectives
1.1.1.3 Level
Beginner; This is intended as the rst complete project using Matlab and Simulink.
It is suitable for students who have only limited exposure to Texas Instruments DSPs before.
1.1.1.4 Requirements
In developing this Laboratory, the following hardware and software were used:
1
2 CHAPTER 1. CONTROL
1.1.2 Simulation
1.1.2.1 Running the Vehicle Dynamics Simulation
6
Open VehicleDynamics.mdl .
Double click on the Vehicle Dynamics block. This models the equation of motion using Simulink Blocks.
Double click on the Engine Management block. This models the gas in horsepower out function of the
engine.
Change the shape of the Power Transfer Function. You may wish to change the gradient or make the
plateau wider. Run the model.
Go to the Website of an automobile manufacture, and obtain the actual engine power transfer function for
a real car. Run this in the model.
Replace the ramp generator input with a step function. This simulates someone stamping on the gas!
Run this model. This is the behavior that should be seen when the real-time model is run on the ezDSP
for F2812.
7 See the le at <http://cnx.org/content/m22943/latest/VehicleDynamicsF2812Simulation.mdl>
A list of available blocks will appear. Select Commonly used blocks. Highlight Subsystems. Drag-and-
drop two copies of this block into the model.
From the Simulink Library Browser, select Sources. Drag-and-drop the Ramp block onto the model.
Join the blocks as shown in the gure below. Change the names and add a title.
The ode45 solver is not suitable for use with DSP. Fixed Point Discrete is required.
The rst stage of the Engine Management Subsystem is a Gain block, which converts the Gas Pedal input
(0-100%) to 0-4000 rpm.
The second stage is a lookup table. This converts from rpm to hp.
From the Simulink Lookup Tables, drag-and-drop the Lookup Table block onto the model.
The values for the table can also be inserted as a table. Click on the Edit box.
The C28x operates in discrete-time; therefore the continuous integrator must be replaced by a Discrete
Time Integrator for DSP model implementation.
Select the Main tab. Change the Constant value to 0. Click on OK.
The ramp generator gently changes the Gas Pedal from 0% to 100%. This simulates smooth acceleration.
The Horsepower and Vehicle Speed are shown on the graphs.
For Matlab and Simulink to run correctly, you need to run the F2812 ezDSP.
Connect the F2812 hardware to the parallel port of the computer and turn on the supply to the board.
When the board is powered, the two green LED lights on the board will come on during self-test.
Start Code Composer Studio for F2812 ezDSP and use Debug -> Connect
A list of available blocks will appear. We are particularly interested in the Embedded Target for TI C2000
DSP. Click on this selection.
In the following sections we will select the building blocks for the DSP model shown in Figure 30.
From the C2000 Target Preferences, select F2812 ezDSP. Drag-and-drop the icon onto the new model.
Figure 1.26
To scale the ADC reading to the Gas Pedal 0 to 100% we will multiply the ADC input by 800 then divide
by 32768.
Figure 1.28
To scale the kph to the DAC output, we will multiply the kph input by 312.5. The Saturation block limits
the output to 200 kph.
To scale the kph to the DAC output, we will multiply the kph input by 312.5.
8
You may nd the nal model here .
The real-time model running on the ezDSP F2812 should now be behaving in the same way as the Simulation.
1.1.6 References
1. Spectrum Digital Incorporated, "eZdspTM F2812 Technical Reference" Rev. F, September 2003.
9
(http://c2000.spectrumdigital.com/ezf2812/docs/ezf2812_techref.pdf )
The Speed controller comprises two blocks (please refer to Figure 2):
1. This block compares the desired speed with the measured speed and generates a digital value propor-
tional to the DC value to be applied to the motor.
2. This block is implemented using a PWM signal generator and a Low Pass Filter as shown in Figure 3.
This method is described in . The output voltage, generated at the LPF output will be:
V = D · Vss (1.1)
Where:
V - Generated Voltage
Table 1.1
1.2.1.1 Setup
This demo is based on the Spectrum Digital eZdsp-F2812 that is connected to a DC Motor Kit through a
dedicated interface circuit. The setup is shown in Figure 5.
This circuit was designed as part of the demo that will be described in detail in chapter .
1. Signal Generator
2. Voltmeter
3. Oscilloscope.
4. Stroboscope
In this section we will identify the constants in the mathematical models of a DC motor and the tachome-
ter experimentally. The process consists of consists of two parts:
Measurement Equipment
• Signal Generator
• Voltmeter
• Oscilloscope.
• Stroboscope
The tachometer coecient and motor constant can be measured by generating a control voltage, using the
PWM block of the DSP, and measuring:
Figure 8 shows the model that will be used to generate the control voltage.
The PWM block will be congured to generate a PWM signal with a period of 4096 clock cycles of 75
MHz (please refer to Figure 9).
Measurement Procedure:
The ADC input voltage of the DSP should be in the range 0-3V, the therefore the tachometer output voltage
must be inverted and scaled down. This is done with the circuit shown in Figure 19. The gain of this circuit
is G = - 100/270 = - 0.37, i.e., inverting and attenuating approximately 1/3. The results obtained are shown
in Figure 10.
The measurement of the time constant will be obtained by generating a square pulse and measuring the
motor response to this stimulus. The principle of operation is shown in Figure 11; the experimental setup is
shown in Figure 12.
Measurement Procedure
The DC motor was modeled as a rst-order linear system where τrise = τfall ; however, the actual motor is
not linear (due to friction, for example), therefore the measured values were:
Table 1.2
We used the average of these readings, i.e., (0.13+0.23)/2 = 0.18 and rounded to 0.2 sec.
Ω(s) 1 Ω(s)
E(s) = Km 1+sτ m
⇔ E(s) = Km 1+1.2s (1.2)
1.2.3.1 Simulation
The speed control is a PID controller. A DC motor model (Figure 14) was created. The complete control
loop model is shown in Figure 15. Figure 16 shows the parameters chosen for the PID controller.
The connection between the eZDSP and the Motor Kit requires a dedicated interface circuit, implementing
the Low Pass Filter (used for the Digital to Analog conversion) and adapting the voltage levels at the eZDSP
(0 to 3V) to those of the DC Motor Kit (0-15V). The various signal types and their voltage range are shown
in .
The interface circuit contains two blocks. The rst is LPF with an amplier (shown in Figure 18),
connected between the PWM output and the servo amplier input. The second block is an attenuator
(shown in Figure 19) connected between the tachometer output and the Analog to Digital Input of the
eZDSP.
Procedure:
..\MATLAB\R2006b\toolbox\rtw\targets\tic2000\tic2000demos
• c2812speedcontrolDC.mdl
• runc2812speedcontrolDC.m
• runc2812speedcontrolDC.m
• Open the c2812speedcontrolDC.mdl model and save it as "DCMotorControlc2812.mdl"(please
14
refer to Figure 21 ).
6. Delete the selected blocks and replace them by the ADC block from Open the ADC block from the
C281x Chip support group from the C2000 Target Preferences, and connect is as follows:
7. Now the model is ready for real-time, we need however to update the MATLAB script le. Open the
Model Properties from File menu. Change the PostLoadFcn callback to runc2812speedcontrolIDC,
as shown:
8. The next step is to change the original PWM range (up to 64000) to the desired range (up to 4000).
Open the speddControlIDCLoop.m le with the MATLAB editor, an change on line 48 the command:
cycle = (double(pid).*100./64000);
to
cycle = (double(pid).*100./4000);
Please refer to the following picture:
12. You may change the speed of the motor using the slider in the right hand side and the Apply button.
1.2.5 References
1. "eZdspTM F2812 Technical Reference", Spectrum Digital, 2003
15
http://c2000.spectrumdigital.com/ezf2812/docs/ezf2812_techref.pdf
2. David M. Alter, " Using PWM Output as a Digital-to-Analog Converter on a TMS320F280x", TI
16
Application Report SPRAA88 , September 2008 http://www.ti.com/litv/pdf/spraa88a
This example was originally developed using the following hardware and software:
• MatLab R2008a
• Code Composer Studio (CCS) v3.3
• eZDSP-F2808 board.
15 http://c2000.spectrumdigital.com/ezf2812/docs/ezf2812_techref.pdf
16 http://www.ti.com/litv/pdf/spraa88a
17 This content is available online at <http://cnx.org/content/m22177/1.1/>.
18 See the le at <http://cnx.org/content/m22177/latest/ClassD.ppt>
19 See the le at <http://cnx.org/content/m22177/latest/eZDSPF2808_ClassD.mdl>
This block interfaces with the audio source, attenuates it DC component and limits the input voltage to the
ADC to the range 0 - 3.3V. The circuit contains also a DC-DC converter, for the DSP input buer.
The TMS320F2808, converts the analog signal to a pair of PWM signals that feed the output stage (Please
refer to section ). It operates with 100 MHz. The ADC samples the input signal at a 97.656.25 Ksps rate.
The ePWM, generates PWM signal with a period of 102.4 µs and duty cycle proportional to the input signal
level. The ePWM coupled with a D-Class output stage and a second order passive RLC lter, provides a
DAC equivalent.
The analog signal is converted to PCM values as shown in . The conversion is performed as described in
Table 1. The ADC operates in a sampling rate of 97.656 KHz (100 MHz/1024).
Vin < 0V 0
Vin
0 ≤ Vin < 3V 4096 ∗ 3 ,
Vin ≥ 3V 4095
Table 1.3
The process described in the previous section is executed in the Interrupt Service Routine (ISR). The ADC
conversion is triggered by the ePWM block when the PWM period starts (every 102.4 msecs). The ADC
generates an interrupt at the end of conversion. The interrupt service routine updates the PWM duty cycle
(CMPA value) on the value of this sample. The new duty cycle will be loaded in the beginning of the next
PWM period. The process is described in Figure 6.
This module contains the H-bridge, and a Low Pass Filter to remove high frequency components, leaving
only the audio-frequency content. This module basically implements a Digital to Analog Converter using a
PWM signal generator and a Low Pass Filter as shown in . This method is described in .
The basic conguration of a D-Class amplier is the Half-Bridge (H-Bridge) conguration. Two output
transistors operate as switches, driven by complementary PWM signals. One of the transistors is o (current
through it is close zero), while the remaining one is on (voltage across it is close to zero), keeping the power
dissipation very low.
The full-bridge Class D amplier comprises two half bridges, driven by synchronized PWM signals, having
two alternate conduction paths through the load, each one having a pair of transistor conducting while the
remaining pair is o.
1.3.3 Implementation
This section will describe the process of building a Simulink model for code generation according to descrip-
tion in chapter .
In the rst part the framework for interrupt handling will be created. The second section will describe
the creation of the Interrupt Service Routine.
1.3.3.1 Interrupt
1.
2.
3.
The Interrupt should be generated at the end of conversion of group A, (CPU Values=1 and PIE
Values=1) as shown in Figure 12.
4.
5.
20
6.
20 You may also change colors, and name the blocks as shown here.
1.
Figure 1.76
2.
The block should be congured to use channel 0 of module A, triggered by ePWMxA, and post an
interrupt at the end of conversion as shown:
(a) (b)
3.
(a)
(b)
79
(a)
(b)
80 CHAPTER 1. CONTROL
4.
5.
1.
• Use Oversampling
• Use the High-Resolution PWM
• Add Signal Processing (Filtering, Equalization, Gain Control) features to the amplier
1.3.5 References
1. "eZdspTM F2808 Technical Reference", Spectrum Digital, 2005
21
http://c2000.spectrumdigital.com/ezf2808/docs/2808_ezdspusb_techref_c.pdf
21 http://c2000.spectrumdigital.com/ezf2808/docs/2808_ezdspusb_techref_c.pdf
22 http://www.ti.com/litv/pdf/spraa88a
23 This content is available online at <http://cnx.org/content/m24360/1.2/>.
Variables Description
1.4.3 Simulation
The simulation process will be based on a simulation model for the PMS Motor.
Based on this model, the simulation will comprise ve steps as follows:
The diagram below highlights the modules used in the rst step. This rst incremental step conrms
operation of peripheral and target independent modules on forward control path and the code framework.
At this very rst stage the goal is to generate a sawtooth waveform with a varying frequency. This
waveform is an emulation of the rotor angle, which is then passed into the Park transformation allowing us
to check the correct computation of the Space Vector PWM needed for the Field Oriented Control.
Key Modules
• RMPCNTL (ramp control): this module used by the instantiation of the object rc1, structure for which
we can access each variable, controls the acceleration and deceleration rate of the speed command
speed_ref .This speed command is passed the input of the RMPCNTL module rc1.target_value. The
output of this module is called rc1.setpt_value which represents the frequency of the saw-tooth we
want to generate.This frequency information is then passed to the ramp generator module.
• RAMPGEN (ramp generator): to use this module, we instantiate an object rg1. The input of this
module is rg1.rmp_freq . The rotating angle we generate (saw-tooth waveform) is rg1.rmp_out. This
angle is then used for the Inverse PARK transformation.
• IPARK (Inverse Park Transformation): instance ipark1. Computed rotating angle is passed into the
ipark1.ang variable. The d and q inputs to the inverse Park transformation control the command
magnitude via the variables ipark1.de and ipark1.qe.
• SVGENDQ (Space Vector Generation): instance svgen_dq1. This module takes the output of the
IPARK module and calculates the modulation to be applied on the duty cycle of the three pairs of PWM
connected to the three phases inverter bridge (svgen_dq1.Ta, svgen_dq1.Tb and svgen_dq1.Tc).
• PWMGEN (Pulse Width Modulation Generation driver): this modules is the only one linked to the
DSP peripherals. Duty-cycles previously calculated are passed into the DSP PWM registers via the
instant pw1. PWMGEN takes care of the DSP PWM initialization (timer set-up, PWM polarity and
so on).
36
1. Run the PMS_Motor_data M-le. This le initializes the following variables:
%Mechanical system
%Electrical part
DC_voltage = 200;
encoder_resolution = 2000;
%PWM
freq_max=75e6;
%Controller
Ts=5e-5;
Vd Testing
1. Run the model and double-click the Stator Current and Rotor Speed scopes.
The purpose of this step is to simulate openloop operation with power-stage and motor connected and to
check out current sensing and feedback path.
• ILEG2DCBUSMEAS_VCON (current leg and DC bus measurement): This module initializes the
ADC to start automatic conversions of channels selected by the user on timer 1 underow. ADC
conversion results are automatically formatted and stored into dedicated variables.
• CLARKE (Clarke transform module): This module converts the measured current into CLARKE
coordinates in the reference frame (α, β ).
• PARK (Park Transformation): This module converts the (α, β) coordinates into two DC quantities.
38
• Open the PMS_Motor_level2 Simulink model.
Figure 1.94
Vd Testing
Figure 8: Open Loop Model
1. Run the model and double-click the Stator Current and Rotor Speed (same as previous section)
and Vd/Vq scopes.
Figure 1.95
1. Now you may change the values of Vd and Vq, and check how it inuences the graphs above.
The purpose of this step is to close the current loop and to set the PI regulators correctly to get a stable
system while the motor is still running in speed open-loop.
Key Modules:
In addition to the modules already used, we use the PI module:
• PIDREG3 (Proportional Integrator Derivative regulator): This module regulates the two currents id
and iq, generated in the Park module.
39
• Open the PMS_Motor_level3.mdl Simulink model.
Vd Testing
1. Run the model and double-click the Stator Current and Rotor Speed (same as previous section)
and Vd/Vq scopes.
For ease of use, the default PID parameters are already tuned. You can still play with them and observe
the results. Within the watch windows, the PID coecients are displayed for both iq and id. Using the
following picture will help you to interpret the variables.
During this step we will check the encoder feedback and we will align the calculated angle with the shaft
angle.
KEY MODULES:
In addition to the modules already used, we use:
• QEP (Quadrature encoder pulse module): instance qep1. This module initializes the QEP DSP unit.
This involves the associted timer (T2) set-up, the QEP DSP pins set-up and so on. Calling the
initialization routine of the QEP module, the dedicated DSP registers are automatically congured
with no waste of time for the user in reading through the documentation. This module outputs an
electrical angle stored into the qep1.theta_elec variable which is then passed into the speed calculator
module. The encoder mounted on the motor is a 2000 lines encoder. In addition to the traditional
QEP signals (QEP1 and QEP2), it provides an index pulse, which toggles every complete mechanical
round. This index is connected to the capture interrupt 3 of the DSP. In the corresponding served
interrupt, we clear the timer 2 counter ensuring to keep it between 0 and 8000: this way we have
a precise information on the rotor position. The QEP module also takes care of the capture unit
initialization.
• SPEED_MEAS_QEP (Speed measurement based on QEP information): instance speed1. Based
on system information (number of poles pairs for instance), this module outputs the motor speed
information.
40
• Open the PMS_Motor_level4 Simulink model.
1. Run the model and double-click the PWM dutycycles and Rotor Speed scopes.
Until now, the magnetic eld in the motor was generated without taking care of the shaft position. Even if
our motor is a synchronous motor, with no load and at load speed, it was easy to expect the shaft to start
and to catch the magnetic eld without problem. Now, if we want to close the speed loop, we need to know
the shaft angle at every moment. The shaft position is given by the encoder but we still have to align the
initial sensed position with the shaft.
For this, we use the Data Log module to display in real time the rmp_out variable (angle we used until
now to create the magnetic eld) and theta_elec (sensed angle).
The purpose of this step is to verify the speed regulator, close the speed loop and tune up the gains for the
speed regulator if necessary. All the modules previously described are used in this nal step.
During this build, the speed reference will be given to the DSP through a potentiometer placed on the
DMC 550 (R66). To start with, please put the potentiometer around its midle position.
The motor should have good response time now thanks to the speed closed loop. As usual the PID controller
is already tuned. Using the same graphical display we used during the lab 4 you can see the impact of the
PID parameters.
Since all the kits are dierent, the default settings for the current and speed PID may not be suitable
and the maximum command may be instable
Moving the speed potentiometer, you can appreciate the fast and smooth response time!
2.1.1.1 Objectives
• Design a model of LMS Noise Reduction for the Texas Instruments C6000 family of DSP devices using
MATLAB ® and Simulink®.
• Modify an existing Simulink demonstration model for use as a template.
• Run the project on the Texas Instruments DSK6713 with a microphone and computer loudspeakers /
headphones.
2.1.1.2 Level
Intermediate - Assumes prior knowledge of MATLAB and Simulink. It also requires a theoretical under-
standing of matrices and the LMS algorithm.
This laboratory was originally developed using the following hardware and software:
• MATLAB R2006b with Embedded Target for TI C6000 and the Signal Processing Toolbox.
• Code Composer Studio (CCS) v3.1
• Texas Instruments DSK6713 hardware.
• Microphone and computer loudspeakers / headphones.
109
110 CHAPTER 2. SIGNAL PROCESSING AND COMMUNICATION
2.1.2 Simulation
You will now start with a simple Simulink model and run it to see how it works.
The output from the LMS Filter starts at zero and grows slowly. Initially, some of the sine wave information
is lost as LMS Error.
The LMS Filter Weights all start at zero and take several iterations to reach their nal values.
The critical variable in the LMS Filter is the Step size (mu). This sets the rate of convergence of the LMS
lter.
Double-click on the LMS Filter block and change the Step size (mu) to 0.1
Run the model.
When the Step size (mu) is increased, LMS algorithm converges more quickly, but at the expense of
granularity the LMS Filter Output is not as smooth.
Figure 2.5: Input and LMS Filter Outputs for Step size (mu) = 0.1
Note that the lter weights (coecients) do not attain smooth values, as would be the case for smaller values
of Step size (mu).
Figure 2.6: LMS Filter Weights for Step size (mu) = 0.1
Part of the Acoustic Noise Algorithm is the delay. The delay should ideally be at least half a wavelength so
the two inputs to the LMS Filter have dierent random noise.
Experiment with dierent values of delay to see how it eects the operation of the LMS Filter.
Double-click on the LMS Block and change the Filter Size (number of Weights).
If the number of Weights is large, the algorithm will be slow to run.
If the number of Weights is too small, the lter will not remove the noise properly.
2.1.2.9 Summary
From practical experience, you should now know how to use LMS algorithm and how you can adjust the
Step size (mu), the lter delay and the number of weights to obtain optimum performance.
You will now apply this to building a real-time model.
Start Code Composer Studio for DSK6713 and use Debug -> Connect
Highlight Embedded Target for TI C6000 DSP then Audio. Click on Wavelet Denoising. We are
going to use this as our template.
For convenience, save the model to the MATLAB Work directory, where most models are stored.
Delete the Info box. Change the title to LMS Noise Reduction. You may also wish to move the DSK6713
icon to the left hand side.
Double-click on the function() box. The Wavelet Noise Reduction Algorithm model is now displayed.
Delete the blocks and connect the input directly to the output. Add a title.
Double-click on the blue box to the left marked DSK6713 ADC. The following screen will appear.
The DAC settings need to match those of the ADC. Check that it uses the same sampling rates. Click on
OK.
The Simulink block for LMS is to be found in the Signal Processing Toolbox.
Select View -> Library Browser -> Signal Processing Blockset ->Filtering-> Adaptive Filters.
Highlight Adaptive Filters. Drag-and-drop the LMS Filter block onto the model.
The most critical variable in an LMS lter is the Step size (mu).
If mu is too small, the lter has very ne resolution, but reacts too slowly to the audio signal.
If mu is too great, the lter reacts very quickly, but the error also remains large.
We will start with 0.005.
Because we are working with frames of 64 samples, it is convenient congure the delay using frames. Double-
click on the Delay block.
Change the Delay units to Frames.
Set the Delay (frames) to 1. This makes the delay 64 samples.
6 Since we are working with frames, the delay from Discrete Components library will not work!
So we can hear the dierence without LMS denoising and with LMS noise reduction, we will use a DIP
switch of the DSK6713.
Select View -> Library Browser -> Embedded Target for TI C6000 DSP. Highlight DSK6713 Board
Support.
Drag-and-drop the Switch block onto the model. Also drag-and-drop the LED block onto the model.
We now need to setup a way to switch between straight through without noise reduction and with LMS
noise reduction.
Select View -> Library Browser -> Simulink. Highlight Commonly Used Blocks.
Drag-and-drop a Constant onto the model.
Drag-and-drop a Switch block onto the model.
Drag-and-drop a Relational Operator block onto the model.
The switch values lie between 0 and 15. We will use switch values 0 and 1. Double-click on the Constant
block. Set the Constant value to 1 and the Sample time to inf .
Click on the Signal Data Types tab. Set the Output data type mode to int16. This is compatible with
the DAC on the DSK6713.
Double click on the Relational Operator block. Change the Relational operator to ==. Click on the
Signal Data Types tab.
Move the blocks and join them as shown in the Figure below.
From the Toolbar, select the Up Arrow icon. This returns you to the next higher level.
When built, the single lines are replaced by double lines. This shows frames.
From the folders on the left, select the source code for the project.
To check out the microphone and loudspeakers, set the DIP switches on the DSK6713 as follows:
The microphone is fed directly to the loudspeakers. There is no LMS noise reduction.
To run the LMS Noise Reduction subsystem, set the DIP switch to 1.
Change the value of Step size (mu) between 0.0001 and 0.5. This is the critical value.
Low values of mu give good resolution, but a slow reaction time.
High values of mu give less resolution, but faster reaction times.
Find the best value of mu for noise reduction on the TI DSK6713.
Try dierent value of Filter Length. What is the minimum value that will allow the lter to work correctly?
Inside the Adaptive Filters are dierent LMS types. Which are suitable for LMS denoising and which are
not?
Figure 40
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names
may be trademarks or registered trademarks of their respective holders.
1. The AM algorithm
2. The transmission and reception parameters (modulation index and carrier frequency).
2.2.2 Simulation
2.2.2.1 The Environment
Figure 1 shows the data ow for the AM modulation simulation. The AM modulation model receives an
input signal from an external signal generator, modulates it and displays the modulation on the scope.
Table 2.1
• Congure the Sine Wave Generator Block (Double click on the DSP sine object). Set the sine frequency
to 1000 Hz, sample time to 1/96000, samples per frame to 64 and close the box, and change its label
to information.
• Use the same block to create the carrier signal. You may copy the block already created or select
it form the Simulink library. Set the carrier frequency to 15,000 Hz. The remaining parameters are
identical to the ones of the information signal. Change its label to carrier
• Add new DSP-constant to your model:
• Double-click on the constant object and set its constant value to 1.5:
• Add a new multiplexer from the same directory as the adder (choose product).
• Add a new scope object:
• Set the number of frames parameter to 5. This parameter determines the horizontal scaling of the
presented signal.
• Run the model, pause the simulation and activate the scope window. The modulated signal should be
displayed as follows:
In this section you will create the model for an AM receiver based on Square Root (SQRT) demodulation.
The principle of operation is shown Figure 1.
• Add the new math function block to your model. This block can be congured to implement various
mathematical functions.
• Use the math function block to create the Square root function. You may retrieve it from the library
or copy the square block.
• Add a digital lter design block. This block enables you to design lters using the MATLAB ®
FDATool.
• Congure the lter to be Low-Pass Filter. Since the carrier frequency (fc) is 15 KHz and the maximal
frequency of the information is 1 KHz, the lter will be designed to pass frequencies below 5 KHz, and
rejects frequencies higher than 10 KHz (please refer to Figure 16).
16
• Add a "Multiplier" and a "Subtract" block.
• Add two "DSP Constant" blocks.
• Add the matrices concatenation object. This object will enable the modulated and the de-modulated
signals to be displayed simultaneously in the scope:
16 The subtraction is created by reconguring the adder block, and choosing +- instead of: ++
• Run the simulation (push the play button). Double click on the scope. Scale the display to t the
scope window (Choose from the menus: Axes=>Autoscale). Choose a dierent color for each signal
(Please refer to Figure 19).
• You may change the simulation parameters, and check their inuence.
The real-time implementation model will be created upon the simulation model, after the following changes:
• The signal generator block will be replaced by the CODEC of the DSK6713
• The virtual scope will be replaced also by the CODEC
• A target denition block (DSK6713) will be added.
• DSK6713
• Dual Channel Oscilloscope
• Signal Generator
• Remove the scope and the information signal (the 1,000 Hz).
• Open the Simulink library browser and add the "C6713DSK".
• Add the Analog to Digital and Digital to Analog converters (ADC and DAC) to your model:
• After placing the selector, double-click to open the dialog box and choose columns in the select
label and {1,2} in the indices to output label.
1. Congure the ADC and DAC blocks to a sampling rate to 96 KHZ and 16-bit samples.
• You should congure the DSP constants as shown in Figure 28. The frame period for all constants
should be -1
• Build the project and load the program to the DSK memory using ctrl+B.
• Make sure that the signals generator amplitude is set to 1 Volt and frequency of [0.1,5] kHz.
• Display the modulated and demodulated signals in the scope.
• A variable frequency carrier generator (Please refer to secion "A Congurable Carrier Wave Generator"
in the Appendix)
• An additional model for AM detection (Please refer to secion "The Coherent Detector (in brief )" in
the Appendix).
• Build GUI that we will enable:
The modulation index and carrier frequency will be changed through RTDX.
• Replace the constant modulation index by an RTDX input (Please refer to Figure 30), and name it
InputModulation.
• Replace the sine wave block used for the carrier by the congurable carrier blocks (you may nd them
17 18
in the Congurable_Carrier.mdl le) , and create a subsystem for the carrier generator as shown
in Figure 32.
• Enter the Conguration Parameters menu (ctrl+E). Choose Real-Time Workshop=>TIC6000 Code-
19
Generator, In The Run-Time box change the Build Action to Build :
20
• Open the AM_Coherent.mdl le, and repeat step for this le.
You now have two load les each one corresponding to a dierent AM scheme.
• Now, double click on the list-box and change the string eld:
• When the GUI is launched the DSK should be loaded with a default model (SQRT)
• When the user selects a new model> Its correspondent *.out le should be loaded to the DSP.
• When the modulation index is changed, its new value should be written to the DSP through the
correspondent RTDX channel.
• When the carrier frequency modulation index is changed, its new value should be written to the DSP
through the correspondent RTDX channel.
You may change the modulation index and frequency for both models, and observe its inuence on the
modulated and demodulated signals.
2.2.5 Appendix
2.2.5.1 A Congurable Carrier Wave Generator
The Simulink sine wave block cannot be congured during run-time; its frequency is a parameter that should
be set in advance. We will introduce the implementation of a block where the frequency is a variable that
can be set in real-time (In this case using RTDX). The block is based on the following relationship:
= Re ejωc t
cosωc t (2.1)
fc h fc
i
cosωc nTs = cos2π n = Re ej2π fs n (2.2)
fs
The following model implements the last equation. Please note that a feedback path was included for phase
continuity
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names
may be trademarks or registered trademarks of their respective holders.
2.3.1.1.1
23
• Powerpoint Presentation - Multichannel.ppt
24
• CCS Example Project - C67.rar
25
• Simulink Model for Audio Conference Bridge and Legacy Driver Files - C67_Simulink_conference.rar
TLV320AIC24 can be gluelessly cascaded to any SMARTDM-based device to form a multichannel CODEC,
27
and up to eight TLV320AIC2x CODECs can be cascaded .
The SMARTDM port is connected to the Multichannel Buered Serial Port (McBSP) in the DSP as
shown in Figure 3.
The TLV320AIC24 supports various types of analog interfaces, and can operate with sampling rates to
104 KSPS, with 16 bit samples. The block diagram is shown in Figure 4. The TLV320AIC24 features are
summarized in Figure 5.
The driver operates in a double-buering scheme as shown in Figure 6. There are two buers in each direction
(Receive/Transmit). For each frame to processes occur simultaneously:
1. The CPU processes samples from one of the receive buers, and stores the results in the correspondent
transmit buer.
2. The EDMA reads and writes samples that belong to the next frame.
(a) Frame #n
The driver uses two EDMA channels. The rst will read from a xed location in the memory, which is the
received data register (DRR) of the MCBSP port, to a buer in the memory that will hold those samples.
The second will write from a buer in the memory to a xed location that is the transmit register (DXR) of
the MCBSP port.
Samples are send/received to/from the CODEC in an interleaved mode. The EDMA receive channel
sorts the samples and place the samples of each channel placed in consecutive addresses in the data memory.
A symmetric process occurs in the opposite direction. Figure 7 describes the process of receiving samples
and Figure 8 describes the process of transmitting samples. Once a buer is received/transmitted a Callback
(please refer to section ) function is called, activating the signal processing procedures.
2.3.3.2
1. aic24_defs.h This le contains the denitions of the various registers of the TLV320AIC24.
2. aic24.h Needed for the DSP conguration.
3. aic24.c Contains the various initialization routines.
4. AIC24-C6713.cdb - DSP-BIOS conguration le.
Those les should be integrated with a user le, explained in the next section.
The driver interface is implemented in the user dened le. This le consists of the main program and the
callback processing function.
The driver allocates a handle to the chain of CODECs, initializes it and afterwards activates the components.
This le:
1. Initializes the AIC24 handle. This is a structure that contains handles to the EDMA and to the
MCBSP port. It also contains their conguration structures, pointers to user buers (the data is read
and written through them) and some more variables like the AIC24 register values, the current buer
etc. handle and the data is exchanged through a callback function. The function AIC24_Init Defaults
initializes the handle with the values provided by user and some default values.
28
2. Congures the TLV320AIC24 mode .
3. n addition, the user needs to map the analog input/output ports to the channels in the
SMARTDM/McBSP (Please refer to ).
4. Run the AIC24_Start, the main function that:
The user is required to create a callback function were the processing is implemented. This function receives
pointers to two buers as arguments; one buer contains the latest information read from the CODECs,
while the second will contain the data to be written to the CODECs. The callback function template is
shown:
The Callback Function Template
In this section we will describe the way the driver is used in the CCS environment.
• aic24.c
• aic24.h
• aic24_defs.h
• AIC24-C6713.cdb
• Add aic24.c and AIC24-C6713.cdb les to your project.
• Add the user le with the callback function.
28 The CODEC can operate in DATAMODE or PROGRAMMING mode. We'll use DATAMODE only. For a detailed
explanation, please refer to the TLV320AIC24 datasheet.
29 This is not mandatory. You may add the les from any directory.
2.3.3.5 An example
The rst part of the program denes the buers for reading and writing samples.
Buer Allocation
+
#if DATAMODE == 1 ,
#define BUFS_PER_CHANNEL 1
#else
#define BUFS_PER_CHANNEL 2
#endif
The callback function follows the template introduced in the previous section, and calls the subroutine
copyData.
The Callback Function
+
void copyData Int16 *inbuf, Int16 *outbuf, Int16 length ,
{
Int16 i = 0;
// The callback function that is called when the EDMA buffers are full
// The function copies the data from channel 0 to channel 2
void process(Int16 *r_data, Int16 *w_data)
{
if (hAIC24.DataMode)
{
int i;
for (i=0; i<DATANUM; i++)
r_data[0*DATANUM+i] [U+2A53]= 0xfffe;
}
copyData(r_data+0*DATANUM, w_data+2*DATANUM, DATANUM);
}
The main program:
After this step, the program will enter in an endless loop. Samples will be processed each time an EDMA
interrupt occurs.
The main program
30 The driver sets a default conguration. Those commands are needed if changes in the default conguration are required.
int main()
{
// setting up the AIC24 handle
AIC24_InitDefaults([U+2A53]hAIC24, NUM_CODECS, DATANUM, r_data1, r_data2, w_data1, w_data2, process);
hAIC24.Regs[1].creg6.reg6a.control_bit.mici = 0;
hAIC24.Regs[1].creg6.reg6a.control_bit.inp1 = 0;
hAIC24.Regs[1].creg6.reg6a.control_bit.inp2 = 0;
hAIC24.Regs[1].creg6.reg6a.control_bit.inp3 = 0;
hAIC24.Regs[1].creg6.reg6a.control_bit.inp4 = 0;
hAIC24.Regs[1].creg6.reg6b.control_bit.outp1 = 0;
hAIC24.Regs[1].creg6.reg6b.control_bit.outp2 = 0;
hAIC24.Regs[1].creg6.reg6b.control_bit.outp3 = 0;
hAIC24.Regs[2].creg6.reg6a.control_bit.mici = 0;
hAIC24.Regs[2].creg6.reg6a.control_bit.inp1 = 0;
hAIC24.Regs[2].creg6.reg6a.control_bit.inp2 = 0;
hAIC24.Regs[2].creg6.reg6a.control_bit.inp3 = 1;
hAIC24.Regs[2].creg6.reg6a.control_bit.inp4 = 0;
hAIC24.Regs[2].creg6.reg6b.control_bit.outp1 = 1;
hAIC24.Regs[2].creg6.reg6b.control_bit.outp2 = 0;
hAIC24.Regs[2].creg6.reg6b.control_bit.outp3 = 0;
hAIC24.Regs[3].creg6.reg6a.control_bit.mici = 0;
hAIC24.Regs[3].creg6.reg6a.control_bit.inp1 = 0;
hAIC24.Regs[3].creg6.reg6a.control_bit.inp2 = 0;
hAIC24.Regs[3].creg6.reg6a.control_bit.inp3 = 0;
hAIC24.Regs[3].creg6.reg6a.control_bit.inp4 = 0;
hAIC24.Regs[3].creg6.reg6b.control_bit.outp1 = 0;
hAIC24.Regs[3].creg6.reg6b.control_bit.outp2 = 0;
hAIC24.Regs[3].creg6.reg6b.control_bit.outp3 = 0;
Connect an audio source to J14, a speaker / headphone to J4 and check Path #1.
Connect an audio source to J13, a speaker / headphone to J5 and check Path #2.
The main idea is to create a Simulink environment that reads samples form 4 channels, process them and
send them to 4 output channels. The example model is shown in Figure 14.
The Simulink driver block is based on the driver described in the previous chapters. Both drivers read and
write samples using a double-buering mechanism, but they dier in the way they activate the processing
algorithm.
The algorithm code, in the Simulink environment, runs as a separate free-running task. At the start of
the function it checks the semaphore to see if data is ready to read from the buer if not then it stays
in a wait state until the semaphore is posted by the callback routine (Please refer to section ). Once this
has been posted, it reads the data elements from the addresses supplied by the appropriate pointers. Once
the algorithm has then processed the data, it writes the data elements from the addresses supplied by the
appropriate pointers. After process is concluded, it will wait for the next frame of samples. This process
then repeats until halted.
The callback function, in the Simulink environment, needs to set the appropriate pointers each time an
EDMA interrupt occur, and post a semaphore for the Algorithm task afterwards.
1. aic24_defs.h This le contains the denitions of the various registers of the TLV320AIC24.
2. aic24.h Needed for the DSP conguration.
3. aic24.c Contains the various initialization routines.
4. aic24link.c
The rst three les are the same les used for the CCS driver. The ai24link.c le is similar to the user
dened le (test.c for example) described in ,
This le contains the following functions and denitions:
Buers Denitions:
Int16 *InSig1;
Int16 *InSig2;
Int16 *InSig3;
Int16 *InSig4;
Int16 *OutSig1;
Int16 *OutSig2;
Int16 *OutSig3;
Int16 *OutSig4;
An AIC24 handle and a Semaphore handle
As explained the semaphore will be used to wait for the data to arrive.
AIC24_Handle hAIC24;
SEM_Obj AIC24_ready_sem;
void AIC24LINK_init()
{
// setting up the AIC24 handle
AIC24_InitDefaults([U+2A53]hAIC24, NUM_CODECS, DATANUM, r_data1, r_data2, w_data1, w_data2, AIC24LINK_pr
SEM_new([U+2A53]AIC24_ready_sem,0);
}
The callback function.
The callback function AIC24LINK_process simply sets the channel buer pointers (the pointers the model
uses) to the correct places and posts on the semaphore.
SEM_post([U+2A53]AIC24_ready_sem);
}
void AIC24LINK_wait()
{
SEM_pend([U+2A53]AIC24_ready_sem, SYS_FOREVER);
}
AIC24LINK_wait
This function pends on the semaphore.
AIC24LINK_start
This function calls AIC24_start.
2.3.4.3
The Simulink block will be created from the AIC23 driver used in the Custom Device Driver/Legacy Code
Integration Simulink demo.
Figure 2.91: The Simulink demo for Device Driver/Legacy Code Integration
31 The EDMA and interrupts congurations are handled as in the original CCS driver.
The next steps will guide you through the Algorithm block conguration
• Add 6 terminators (inputs and outputs) both inside and outside the "Algorithm" box and of course
32
wiring them appropriately. Double click on each terminator and set its dimension to 64 (except for
32 The terminator dimension should match the value of the DATANUM constant in the aic24link.c le
the internal terminators). Set the data type to int16.The 8 input and output ports should be linked
to the buers (i.e. the pointers) in the aic24link.c le.
• Right-click the wires connecting the terminators to the algorithm and select "Signal Properties". A
new window will be opened window, Select "RealTime Workshop" tab and "ImportedExternPointer".
Enter the signal name. It should have the same name of the correspondent pointers in the driver (As
dened in the aic24link.c le).
• Double-click the "Algorithm" box again and then open the "System Outputs" block. Delete the code
and add a call to AIC24LINK_wait. This way the loop of the task stops each time and waits for the
data.
The model is now ready to generate real-time code for processing of 4 audio channels. AN example is shown
in the next chapter.
33 The TLV320AIC24 contains three analog interfaces for headsets. The use of an additional channel requires minor hardware
changes in the board.
The algorithm processes 64 samples (each channel). It calculates the absolute power of each channel (sum
of absolute values). Three counters are used, each one corresponding to a distinct channel.
For each frame the counter correspondent to the loudest channel is incremented. When a channel counter
34
equals a threshold , the correspondent channel is selected.
For Each 64 samples frame the following algorithm is implemented:
This section will describe the process of generating a real-time application using Simulink blocks for the
algorithm itself and the driver introduced in the previous chapter. The Simulink model is shown in Figure
35
21 .
34 The requirement for a threshold amount of wining rounds was set in order to prevent random noise or occasional spikes
from interfering with the algorithms function. This threshold is congurable. In this example it was set to 10.
35 The algorithm is implemented for 4 channels, however we will use only three of them.
The block diagram shown in Figure 20 is translated to the model shown in the following gures.
• The 4 level values compose a 4 element vector. This vector is fed to the Max abs value block:
• The index of the Maximum level enters the index selection block. The correspondent channel is
incremented and compared to the threshold.
• If the counter value equals the threshold, the index is selected as input to the conference block
36
The real-time model can be found in the le C67_Simulink_conference.rar.
2.3.6 References
1. "TLV320AIC20K/24KEVM User's Guide ", TI Document SLAU088A, April 2005
37
(http://focus.ti.com/lit/ug/slau088a/slau088a.pdf )
2. "DSP−CODEC Development Platform User's Guide", TI Document SLAU090, September 2002
38
(http://focus.ti.com/lit/ug/slau090/slau090.pdf )
3. "Low Power Highly-Integrated Programmable 16-Bit 26-KSPS Dual Channel
CODEC (Rev. D)" TI Document SLAS363D, March 2002 Revised April 2005
39
(http://focus.ti.com/lit/ds/slas363d/slas363d.pdf )
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names
may be trademarks or registered trademarks of their respective holders.
The following table is based on the one the Codec's EVM Datasheet.
It matches the board connectors with the inputs and outputs.
(Notice, this table includes corrections and elaborations in compare to the one in the Datasheet).
Figure 2.102
The Inputs and Outputs of a certain channel are set by its 6a and 6b registers.
Those registers can be set, like before, between the initialization of the Handle and its activation.
40
If, for example, the input samples of channel 0 in the CODEC should be received from INP3 . The
conguration should be as follows:
int main()
{
// setting up the AIC24 handle
AIC24_InitDefaults([U+2A53]hAIC24, 4, 64, r_data1, r_data2, w_data1, w_data2, process);
hAIC24.Regs[0].creg6.reg6a.control_bit.mici = 0;
hAIC24.Regs[0].creg6.reg6a.control_bit.inp1 = 0;
hAIC24.Regs[0].creg6.reg6a.control_bit.inp2 = 0;
40 According to the table the connection is to J10, since we are working with 24K EVM and channel 0 is located at the master
side.)
hAIC24.Regs[0].creg6.reg6a.control_bit.inp3 = 1;
hAIC24.Regs[0].creg6.reg6a.control_bit.inp4 = 0;
hAIC24.Regs[0].creg6.reg6b.control_bit.outp1 = 0;
hAIC24.Regs[0].creg6.reg6b.control_bit.outp2 = 1;
hAIC24.Regs[0].creg6.reg6b.control_bit.outp3 = 0;
In the case above, output of channel 0 is connected to OUTP2 (i.e. J1).
A single channel can be connected to a number of outputs. It is not recommended to connect two CODEC
channels to a single output.
The default channel conguration is:
Even Channels (i.e. 0,2,. . .) Input: MICI
Even Channels (i.e. 0,2,. . .) Output: OUTP1
Odd Channels (i.e. 1,3,. . .) Input: INP1
Odd Channels (i.e. 1,3,. . .) Output: OUTP2
Jumper State
W1: Closed
W2: 2-3
W3: 1-2
W4: 1-2
W5: Closed
P1.13-P1.14: Closed
P1.9-P1.10: Closed
P1.11-P1.12: Closed
Table 2.2
Jumper State
W1: 1-2
W2: 2-3
Table 2.3
41 Other entries were reset ('0'), as they should not be connected to the channel's input.
2.3.7.2 DSP
RegisterValue Remarks
cnt EDMA_CNT_FRMCNT_OF(ChannelBuerSize
The number of frames is the size of the buer
1)
EDMA_CNT_ELECNT_OF(TotalNumChannels)
Each frame has NumChannel elements
rld EDMA_RLD_ELERLD_OF(TotalNumChannels)
Should be the same as Element Count
Table 2.4
RegisterValue Remarks
cnt EDMA_CNT_FRMCNT_OF(ChannelBuerSize
Each frame has NumChannel elements
1)
EDMA_CNT_ELECNT_OF(TotalNumChannels)
Each frame has NumChannel elements
rld EDMA_RLD_ELERLD_OF(TotalNumChannels)
Should be the same as Element Count
Table 2.5
RegisterValue Remarks
Transmit
MCBSP_XCR_XPHASE_SINGLE Transmit one phase only
Con-
trol
Reg-
ister
(XCR)
Pin MCBSP_PCR_XIOEN_SP All pins are dedicated for MCBSP (Not GPIO)
Con-
trol
Reg-
ister
(PCR)
MCR 0 Unused
RCER 0 Unused
XCER 0 Unused
Table 2.6
697 Hz 1 2 3
770 Hz 4 5 6
852 Hz 7 8 9
941 Hz * 0 #
2.4.2 Simulation
2.4.2.1 The Simulation Model
Figure 1 shows the model used to simulate DTMF detection and generation.
The DTMF generator is composed by 7 sine wave generators, corresponding to the 7 DTMF frequencies.
The oscillators are grouped as described in Table 1. The oscillators outputs are multiplexed and summed
(Please refer to Figure 2). Upon selection of a digit to be transmitted, the correspondent oscillators are
activated.
The DTMF detection comprises two processes, the frequency detection algorithm itself, and a leading
edge detection subsystem.
The frequency detection subsystem measures the energy present at the seven frequencies, and calculates
the digit by taking the component of maximum energy in the lower and upper frequency groups. The process
is shown in Figure 3. This process runs continuously; however the calculated digit is reported only if its
energy is above a threshold as determined by the leading edge detection subsystem. The DTMF detection
process is shown in Figure 4.
The DTMF receiver will be based on the DTMF receiver from the simulation model, with the following
changes:
51
• Samples will be read from the Analog to Digital Converter, and ltered by a DC removal block
• Digits will be reported through RTDX.
• Addition of the DSK6713 target preference
• Open the simulation model DTMF.mdl, remove all the blocks besides the DTMF receiver block.
• Open the Simulink ® library browser and add the "C6713DSK".
51 This block is necessary to convert the unipolar format of the samples to a 2's complement format for processing by the
DSP.
• The TO RTDX will be used to report the detected digits to the PC. Add it to your model:
2.4.3.3 Functionality
• Initialization: Initialize the RTDX interface and loading the DTMF Receiver program we have built
in the last section to the DSK.
52
• Generate the DTMF signal samples: The GUI will enable the user to select a sequence of 11 digits
to be transmitted. It will create the samples of the DTMF signal based on this selection, and send
them to the sound card.
• Display the detected digits reported by the DSK
2.4.3.4 Description
52 If the user selects less than 11 digits, the sequence is padded with DTMF digit '1'.
• Dial the digits: every digit dialed is added to a specic buer, and displayed under the Dialed Digits
label.
• Delete the last digit
• Clear all the digits
53
• Send: Create the DTMF signal from the digits selected . A dual-tone signal will be created for each
digit. Silence will be inserted between consecutive digits. This signal is sent to the sound blaster using
the sound command in MATLAB.
• Display: Digits reported by the DSK will be displayed under the Detected Digits label.
• Activate the GUIDE (Graphic User Interface Integrated Development Environment in MATLAB.
53 The DSK operates with a buer of 11 digits so if the user dialed less then 11 digits we are padding them to 11 in the
MATLAB.
• Add 12 Push buttons for the keypad and set their String property to the proper values (0-9,*,#) using
the property inspector.
• Add the Send, Clear and Delete buttons
• Add 2 Edit Texts objects for display
• You may now add the labels (static texts):
· Dialed Digits
· Detected Estimation
· DTMF Transmitter
• Press the play button to open the MATLAB script. Name the script DTMF.m.
• Enter the Initialization (DTMF_OpeningFcn ) as shown:
function res=generateTable()
t=(1:256*6)/8192;
res(1,:)=sin(2*pi*697*t)+sin(2*pi*1209*t);
res(2,:)=sin(2*pi*697*t)+sin(2*pi*1336*t);
res(3,:)=sin(2*pi*697*t)+sin(2*pi*1477*t);
res(4,:)=sin(2*pi*770*t)+sin(2*pi*1209*t);
res(5,:)=sin(2*pi*770*t)+sin(2*pi*1336*t);
res(6,:)=sin(2*pi*770*t)+sin(2*pi*1477*t);
res(7,:)=sin(2*pi*852*t)+sin(2*pi*1209*t);
res(8,:)=sin(2*pi*852*t)+sin(2*pi*1336*t);
res(9,:)=sin(2*pi*852*t)+sin(2*pi*1477*t);
res(10,:)=sin(2*pi*941*t)+sin(2*pi*1209*t);
res(11,:)=sin(2*pi*941*t)+sin(2*pi*1336*t);
res(12,:)=sin(2*pi*941*t)+sin(2*pi*1477*t);
function handleButton(hObject,handles,k)
%get the digits buffer
A=handles.A;
%if we have to erase so we are doing it here:
if handles.initFlag==1
handles.initFlag=0;
A=[];
end
%check if the string is too long with the new digit:
if length(A)==handles.maxSize
fprintf('Error: too many digits\n');
return;
end
%concatenate the new digit to the existing buffer
A=[A k];
handles.A=A;
set(handles.text1, 'String', strrep(strrep(strrep(int2str(A),'10','*'),'11','0'),'12','#'));
guidata(hObject,handles);
%Update the upper label with the digits read from dsk estimation
set(handles.text4, 'String', strrep(strrep(strrep(int2str(y),'10','*'),'11','#'),'20','*'));
handles.initFlag=1;
guidata(hObject, handles);
It will generate the DTMF samples Buer, based on the User Dialed information. The samples will be
sent to the sound-card. The program will then monitor the RTDX channel to receive the digits reported by
the DSK.
• Enter the functions activated by the Clear and delete push buttons:
return
end
A=A(1:end-1);
set(handles.text1, 'String', strrep(strrep(strrep(int2str(A),'10','*'),'11','0'),'12','#'));
handles.A=A;
guidata(hObject, handles);
2.5.1.1 Objectives
• Design models of Echo and Reverberation for the Texas Instruments C6000 family of DSP devices
using MATLAB ® and Simulink®.
• Modify an existing Simulink model.
• Run the model in real-time on the Texas Instruments C6713 DSK.
2.5.1.2 Level
Beginner - Assumes only very basic knowledge of MATLAB and Simulink. It is suitable for students with
limited knowledge of Texas Instruments DSPs.
This laboratory was originally developed using the following hardware and software:
2.5.2 Simulation
We shall start by running the Echo and Reverberation Simulink models. These use .wav les as the inputs.
Double-click on the Delay block and change the Delay (samples) to a dierent value.
Run the model and hear how the eect has changed. Try a few dierent settings between 100 and 20000
Delay (samples).
Double-click on the Delay block. Change the Delay (samples) to a dierent value then run the model
and listen to the eect.
Double-click on the Gain block. Change the Gain to 0.95 then run the model. Listen to the eect.
2.5.2.2.4 Questions
The stages required to implement Echo and Reverberation are now described.
Start Code Composer Studio for C6713 DSK and use Debug -> Connect
You are now going to implement the Echo Subsystem shown below.
Double click on the Eect 1 subsystem block. An empty model will appear.
You will now drag-and-drop some library components onto the model.
From Commonly Used Blocks, drag-and-drop a Gain block, a Sum block and two Data Type
Conversion blocks onto the model.
From the Simulink Library Browser, select Discrete. Highlight Integer Delay and drag-and-drop this
block onto the model.
The delay time will be 0.5 seconds. Using a sampling rate of 8000 Hz, this requires 8000 x 0.5 = 4000
samples. In the equation given in the lecture, this would make N = 4000.
Double click on the Integer Delay block. Change the Number of delays eld to 4000, then click on
OK.
We want to set the gain to 0.9. If you multiply an integer value by 0.9, then the value 0.9 will be rounded-
down to zero. Instead, you need to convert the integer value to a oating-point value such as single, and
then convert it back later. Click on OK.
We required that 0.9 of the delayed input is added to the normal input. Therefore, set the Gain to 0.9
then click on OK.
Double click on the second Data Type Conversion block. Set the Output data type mode to int16. This
is compatible with the DAC on the C6713 DSK.
From the Toolbar, select the Up Arrow icon. This returns you to the next higher level.
Note that the reverberation subsystem is very similar to that of echo. We will cut-and-paste from the
Echo Subsystem
From the C6713 Audio Template top level, double-click on the Eect 2 subsystem.
Double click on the Eect 1 subsystem. Cut-and-paste a copy of the echo block as follows: while left-
clicking the mouse, mark the area to be copied.
Return to the Eect 2 subsystem and Edit -> Paste (Ctrl + V) into the model.
The blocks are facing the wrong way. Turn them round using Format -> Flip Block.
Because the sound goes round several times with reverberation, a shorter delay time can be used. Here the
delay time is 0.1 seconds.
Connect the blocks as shown below. Change the title to Reverberation Subsystem.
From the Toolbar, select the Up Arrow icon. This returns you to the next higher level.
The nal subsystem to be implemented will be Improved Echo. This is based on the Echo subsystem,
but with several delay paths.
Double click on the Eect 3 subsystem box. The required components are shown below.
You should now have enough knowledge to implement this subsystem block without further assistance. This
time you are on your own!
To check out the microphone and loudspeakers, set the DIP switches on the C6713 DSK as follows:
The microphone is fed directly to the loudspeakers without any digital signal processing.
Change the value of the Integer Delay block for echo. Listen to the eect of using short and long delays.
Set the delay time to a large value and sing a round such as Frere Jacques or Row, Row, Row your Boat.
In the Reverberation Subsystem block, change the Gain from 0.8 to higher and lower values. Notice how
the system can become unstable if the gain is too large.
In the Improved Echo Subsystem, you may wish to experiment with the number of delay elements, the
delay times and the amounts of gain. Try to make the echo as realistic as possible.
Add your own subsystem block and add your own signal processing. You might want to design a subsystem
with both echo and reverberation.
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names
may be trademarks or registered trademarks of their respective holders.
2.6.1.1 Objectives
• Run the Simulink model of signal-to-noise ratio measurement on a PC, to determine the optimum
parameter settings.
• Modify the Simulink model for real-time measurement of signal-to-noise ratio using the Texas Instru-
ments C6713 DSK.
• Run the project on the Texas Instruments C6713 DSK with a microphone and computer loudspeakers
/ headphones.
2.6.1.2 Level
Intermediate - Assumes prior knowledge of MATLAB ® and Simulink. It also requires some understanding
of statistics and some knowledge of Texas Instruments DSPs.
This laboratory was originally developed using the following hardware and software:
2.6.2 Simulation
2.6.2.1 Procedure
It will be seen that the output of the algorithm (Unltered S/N) varies from frame to frame. The next
step is to ne-tune the algorithm parameters.
The model is run several times to determine the best values of the parameters:
Change the sine wave frequency from 500 Hz (default) to 1000 Hz then run the model several times. Make
a note of the four dierent meter outputs (S/N Ratio from RMS Signals, Unltered S/N, Filtered S/N and
Buered).
band.
Change the Sine Wave Frequency to 300Hz then run the model.
Increase the Samples per frame to 1024 in both the Sine Wave and the Random Source Blocks.
Figure 2.162: Adjusting the Frame Size for the Random Source
Click on the Delay Block. Change the number of Delay (samples) to 50.
Run the model again and make a note of the accuracy of the measurement.
64
Change Delay (samples) to 12 and run the model again.
Question: How does the value of delay (samples) aect the accuracy of the model?
64 The Delay (samples) should be smaller than the frame size, otherwise the frames do not overlap.
Run the model and make a note of the accuracy of the measurements. Repeat, but this time, use a gain
of 0.01 (1% noise).
Question: Does the algorithm work better for high signal-to-noise ratios or for low signal-to-noise ratios?
Make a note of the answer.
Change the sample time in both the Sine Wave and the Random Noise blocks to 48000 Hz.
You should now know what are the optimum parameters for the simulation.
Set these parameters and run the model.
You have now run the signal-to-noise ratio model and should be aware of the best settings for consistency
of measurements, delay and sampling frequency.
You are now ready to go to the C6713 DSK Model.
There are several stages required in order to implement the Signal-to-Noise measurement. These are now
described.
Start Code Composer Studio for C6713 DSK and use Debug -> Connect
You will now use the knowledge you have gained during the PC Simulation to produce an optimized version
of this algorithm for use with the Texas Instruments C6713 DSK.
Double-click on the Delay block. Set the Delay (samples) to the best value found during simulation. The
value will not be 999!
From the Toolbar, select the Up Arrow icon. This returns you to the next higher level.
From the folders on the left, select the source code for the project.
To check out the microphone and loudspeakers, set the DIP switches on the C6713 DSK as follows:
Note that when you are not speaking, there is no audio output at all just silence.
Double-click on the Lowpass block. Change the Order to a value other than 10.
Run the updated model and listen to the eect on the audio noise gate.
While running the Simulation, you will have noticed that the Signal-to-Noise Algorithm works better on
some frequencies than others.
Add the appropriate lter to select only the frequencies where the algorithm works well.
When stage 3.2 has been completed, modify the model so that the output is the better of the two stereo
inputs.
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names
may be trademarks or registered trademarks of their respective holders.
1. Periodogram
2. Burg
3. M-Cov
Periodogram
Figure 2.180
The Periodogram block computes a nonparametric estimate of the spectrum. The block averages the
squared magnitude of the FFT computed over windowed sections of the input and normalizes the spectral
average by the square of the sum of the window samples.
The Modied Covariance Method
Figure 2.181
The Modied Covariance Method block estimates the power spectral density (PSD) of the input using
the modied covariance method. This method ts an autoregressive (AR) model to the signal by minimizing
the forward and backward prediction errors in the least squares sense. The order of the all-pole model is the
value specied by the Estimation order parameter. To guarantee a valid output, you must set the Estimation
order parameter to be less than or equal to two thirds the input vector length. The spectrum is computed
from the FFT of the estimated AR model parameters.
Burg Method
Figure 2.182
The Burg Method block estimates the power spectral density (PSD) of the input frame using the Burg
method. This method ts an autoregressive (AR) model to the signal by minimizing (least squares) the
forward and backward prediction errors while constraining the AR parameters to satisfy the Levinson-Durbin
recursion.
2.7.2 Simulation
2.7.2.1 The Environment
Figure 4 shows the data ow for the Estimation simulation. The input signal for the estimator is an AR
process generated by feeding an all-poles lter with white noise. The AR coecients generate the reference
spectrum to be compared against the estimated one.
3. Double click on the random source object, and congure its parameters to t the white noise charac-
teristics we want to achieve:
74
5. Double-click on the lter and ll in the following parameters
74 The Auto-Regressive process is represented by an all-pole IIR lter. The AR coecients are the ones in the Denominator
coecients label.
75
7. Congure the FFT length of the three models to 128 :
10. Add a magnitude FFT block in order to get the spectrum from the AR coecients:
13. The Math Function block should be congured to calculate the reciprocal:
14. Add a new gain to your model (to represent the white noise variance in the reference spectrum gener-
ation) and set its value to 0.1:
15. In order to display the Real and Estimated spectra simultaneously, you need to add a new concatenate
object:
76
20. When running the model , you should see the get the following display:
Figure 21 shows the block-diagram for the real time implementation. The DSP will deliver two outputs.
The rst is the reference spectrum; the second is an estimated spectrum of the output of the all-pole lter.
Three real-time models will be created, each one corresponding to an estimator. The user will be able to
select the desired estimator through a Graphic User Interface (GUI).
The real-time implementation model will be created from the simulation model, after the following
changes:
• The noise generator block will be replaced by the CODEC of the DSK6713
• The virtual scope will be replaced also by the CODEC
• A target denition block (DSK6713) will be added.
Equipment Used:
• DSK6713
• Dual Channel Oscilloscope
• Signal Generator
5. Congure the DAC block to a sampling rate to 8 KHZ and 16-bit samples.
6. Double- click on the concatenation object and change the number of inputs from 4 to 2.
7. Replace the white noise generator by the Analog to Digital converter (ADC).
8. Congure the ADC blocks to a sampling rate to 8 KHZ and 16-bit samples.
The GUI shown in Figure 32 will be used to select the model. Upon selecting a model, its correspondent
load le will be loaded to the DSP.
Periodogram
Burg
M-Cov
4. A script le spectrum.m will open, when you press the play button. Name the script spectrum.m
5. The GUI will perform the following tasks:
• Upon activating the GUI, the default model is loaded to the DSP.
• When the user selects a new model, it is loaded to the DSP.
handles.output = hObject;
%remember the current model:
handles.last_model=1;
CCS_Obj.run;
% Update handles structure
guidata(hObject, handles);
7. Selecting a new model:
end
8. When the user changes the model, the list-box handler function is invoked:
2.8.1.1 Objectives
• Design a model of Wavelet Noise Reduction for the Texas Instruments C6000 family of DSP devices
using MATLAB ® and Simulink®.
• Modify an existing Simulink demonstration model.
• Run the project on the Texas Instruments C6713 DSK with a microphone and computer loudspeakers
/ headphones.
2.8.1.2 Level
Intermediate. Assumes prior knowledge of MATLAB and Simulink. It also requires a theoretical under-
standing of wavelets and some knowledge of Texas Instruments DSPs.
This laboratory was originally developed using the following hardware and software:
2.8.2 Simulation
2.8.2.1 Simulink Model
Open WaveletDenoising.mdl
Run the model. The colors change to show the dierent lter channels. Green = high frequency.
The scope output shows how the random noise has been separated out (Residual).
Add an extra scope as shown in Figure 4 to display the Diadic Filter Outputs.
It can be seen that the noise is on Out1, Out2 and Out3. The clean input signal is on Out4.
Double-click on the Soft Threshold block. This is the actual noise reduction stage. The elds are in order
Out1, Out2, Out3 and Out4.
Here Out1 has been given a threshold of 3. This means that only values > 3 are let through.
Out2, Out3 and Out4 have been given the value of 0. This means the whole signal is let through.
The output is shown in Figure 6. Note that the noise associated with Out2 and Out3 have not been
reduced.
Double-click on the Delay Alignment block. Temporarily remove the delays on Out1 and Out2.
From practical experimentation using the Simulink model, you should now understand how wavelet denoising
works.
Start Code Composer Studio for C6713 DSK and use Debug -> Connect.
Highlight Embedded Target for TI C6000 DSP then Audio. Click on Wavelet Denoising.
The Wavelet Denoising model is now displayed. Double-click on the function() box.
For convenience, copy the model to the MATLAB Work directory where most models are stored.
In order to run the model on the C6713 DSK and be able to compare the performance with and without
noise reduction, we will make some small modications to the demo model.
You will now update the existing model by dragging-and-dropping some library components onto the
model.
Double-click on the blue box to the left marked C6713 DSK ADC. The following options will appear.
Change the ADC source to Mic In and tick the Stereo box. If you have a quiet microphone, tick
the +20dB Mic gain boost box. When done, click on OK.
The DAC settings need to match those of the ADC. Check that they are the same.
To change between no wavelet denoising and with wavelet noise reduction, we will use a DIP switch of the
C6713 DSK.
Select View -> Library Browser -> Embedded Target for TI C6000 DSP. Highlight C6713 DSK Board
Support.
Drag-and-drop the Switch block onto the model. Also drag-and-drop the LED block onto the model.
We now need to setup a way to switch between straight through without noise reduction and with wavelet
noise reduction.
Select View -> Library Browser -> Simulink. Highlight Commonly Used Blocks.
The switch values lie between 0 and 15. We will use switch values 0 and 1. Double-click on the Constant
block. Set the Constant value to 1 and the Sample time to inf .
Click on the Signal Data Types tab. Set the Output data type mode to int16. This is compatible with
the DAC on the C6713 DSK. Click on OK.
Double click on the Relational Operator block. Change the Relational operator to ==. Click on the
Signal Data Types tab.
Move the blocks and join them as shown in the Figure below.
Double click on the Dyadic Analysis Filter Bank block. The values of the Dyadic Analysis Filter Bank are
shown below. You do not need to change them yet. Click on OK.
The delay alignment is shown below, with dierent delay times for the dierent frequencies.
The Soft Threshold sets the threshold below which noise is ignored for each of the four channels. Zero
means no noise reduction.
Double-click on the Dyadic Synthesis Filter Bank. There is no need to change the values at this time. Click
on OK when done.
From the Toolbar, select the Up Arrow icon. This returns you to the next higher level.
From the folders on the left, select the source code for the project.
Figure 2.247: The Completed Model Running under Code Composer Studio
To check out the microphone and loudspeakers, set the DIP switches on the C6713 DSK as follows:
To run the Wavelet Noise Reduction subsystem, set the DIP switch to 1.
The next stage is to modify the model. We will change the wavelet type to Symlets.
Double-click on the Dyadic Analysis Filter Bank block. Change the Filter eld to Symlets. Click on
OK.
The wavelet type should be the same as that used in the Dyadic Analysis Filter Bank. Double-click on the
Dyadic Synthesis Filter Bank block. Change the Filter eld to Symlets. Click on OK.
Run the updated model and listen to the eect of using dierent lter types.
Inside the Dyadic Analysis Filter Bank are dierent wavelet types. Which are suitable for wavelet denoising
and which are not? Note: you will also have to alter the values used in the Dyadic Synthesis Filter Bank.
Experiment with the delay alignment times. Try higher and lower values.
What is the eect of completely removing the Delay Alignment block?
In the Soft Threshold block, change the values. The existing vector of [3, 2, 1, 0] reduces high frequency
noise, but does not aect low frequencies.
Add your own subsystem block controlled by the DIP switches and add your own wavelet denoising algorithm.
Choose your own wavelet, number of channels, sampling frequency and thresholds.
375
376 CHAPTER 3. VIDEO AND IMAGING
3. Set the model to Generate a CCS Project in the Simulation->Conguration Parameters -> Build
Action, as shown in the following picture:
We now need to create Simulink dedicated blocks to execute CCS commands. The rst is the Build.
We can do this in many ways: clicking Build icon, pressing Ctrl-B or in MATLAB ® typing make_rtw.
Given this command is available in MATLAB, we will create a custom block with this command.
•
•
• · Give it a name. In our example we use Generate Code & Create Project
· Choose the shadow, colour etc. . .
· Right click on the Subsystem, choose Block Properties. Go to the Callbacks tab, and under
OpenFcn enter: make_rtw;, as shown in the following picture:
Figure 3.3: Creating the Generate Code & Create Project Simulink block
Table 3.1
Figure 5 shows the data ow for the edge detection simulation. The Edge detection model reads the source
picture from a le in the PC, and displays both the original and the processed images.
6
3. Double Click and select the TMW2.jpg image (Please refer to Figure 7).
4. In order to display the picture the "Video Viewer" from the "Sinks" group of the Video and Image
Processing Blockset (Please refer to Figure 8). This block displays an input RGB or intensity video
stream or image. The edge detection block operates on intensity images.
6. The conversion from RGB to intensity will be executed in the Color Space Conversion: from the
"Conversions" group of the Video and Image Processing Blockset (Please refer to Figure 10).
7. Double Click and select the "R'G'B' to intensity" conversion scheme as shown in Figure 11.
9. Run the model, you should get the image shown in Figure 13
3.1.3.2 Real-Time
shows the data ow for the real time implementation of the image processing algorithms. The algorithms
will be implemented using the DSK6416. A MATLAB will run simultaneously in the PC. This script will
read the source picture from a le in the PC, convert it to grayscale and send it to the DSK6416 through
an RTDX channel. The processed picture will be sent from the DSK6416 through a second RTDX channel.
The script will display three images:
1. Add the "From RTDX" from the "RTDX Instrumentation" group of the "Embedded Target for the TI
TMS320C6000 DSP" Blockset (Please refer to Figure 15). This block will be used receive data from
the PC using a specied RTDX.
7
2. Congure the block to receive data from a channel named "inputimage" as shown in Figure 16 . For
8
the test we will send in an image over RTDX . The selection of `Blocking Mode' will cause the code
running on the DSP to wait until the RTDX transfer is complete before executing. This will give the
MATLAB script full control over the execution.
7 If you are using the XDS560 or the Blackhawk USB560, you will need to enable High Speed RTDX in the "C61416DSK"
block.
8 The "Output Dimensions" should contain the Frame size
3. Add the "To RTDX" from the "RTDX Instrumentation" group of the "Embedded Target for the TI
TMS320C6000 DSP" Blockset (Please refer to Figure 15). This block will be used to send the processed
image to the PC using a specied RTDX.
Congure the block to send data through a channel named "outputimage" as shown in Figure 9.
4. The RTDX channel transfers data in the uint8 format. Therefore the output of the Edge Detection
Block should be converted to this format. Add the "Convert Image" block from from the "Conversions"
group of the Video and Image Processing Blockset, (Please refer to Figure 19). The block should be
congured as shown in Figure 20.
5. Save your model (We used the name stills_R_W.mdl). Your model should look as shown in Figure
21.
9
6. Now you can generate the code to your DSK by using Ctrl-B . When the model builds, it creates an
object in the MATLAB workspace which represents CCS, by default called CCS_Obj. This object
will be used to interact with the application on the DSP from MATLAB.
7. Build the project. Double-click the Build Project block.
8. Load the project. Double-click the Load Project block.
9. Run the target. Double-click the Run block. It should now be running, as displayed in CCS:
9 If you do so, the build will fail at compilation in CCS due to an ISRAM space issue. In this case, we can x this by
redening the location for .far as SDRAM rather than ISRAM (the default) in the board properties box. Rebuild, and it should
compile ne.
The purpose of the MATLAB code we want is to dene an interface with the RTDX channels, to control the
execution of the application on the processor, to send/retrieve data from the processor and to display it. An
example script, picture_script.m will do this. The steps are also detailed below:
1. With the application running, we can congure the RTDX channels in CCS.
%% Enable RTDX
r.enable('all');
%% Import an image from file to send to the DSP
Y = imread('TMW2.jpg');
I = rgb2gray(Y);
3. We then send this to the DSP:
This laboratory was originally developed using the following hardware and software:
• MATLAB ® R2008a
• Code Composer Studio (CCS) v3.3
• Texas Instruments DM6437 Digital Video Development Platform (DVDP) .
• Video camera and screen.
3.2.2 Simulation
Start by creating a new model in Simulink ®.
1. Open the Simulink library browser and add the "From Multimedia File" from the "Sources" group of
the Video and Image Processing Blockset (Please refer to Figure 1).
17
2. Double Click and select the vipmem_Y.avi input le(Please refer to Figure 2).
3. In order to display the picture the "Video Viewer" from the "Sinks" group of the Video and Image
Processing Blockset will be used.
5. Run the model, you should see the video clip. A single frame is shown mage shown in Figure 6.
18
6. Save your model (We used the name Video_sim.mdl", that you may nd it here ).
The procedure for capture/display video using the DM6437 is shown in Figure 7.
This procedure is similar to the one developed for stills pictures. Video will be capture/display using a
camera and a monitor. Image acquisition and Processing will run in a DSP/BIOS task.
5. Rename Function- Call Subsystem to Video Processing and connect it to the Task block.
19
6. Save the model as Video_R_W.mdl. Your model should look as follows :
19 You may add a title to the model, as done here ( Video Processing Template)
7. Double-click the Task block and make the same changes as shown in Figure 34.
10. Double-click the Video Capture block and change the Sample Time (and the Video capture mode
only if you are using the components in the PAL mode) as shown in Figure 12.
11. Double-click the Video Display block and change the Video capture mode only if you are using the
20
components in the PAL mode as shown in Figure 13.
20 If the camera video capture mode is NTSC you should choose this option
13. Generate code & create project. Double-click the " Generate code &.." block.
14. Build the project. Double-click the Build Project block.
15. Load the project. Double-click the Load Project block.
21
16. Run the target. Double-click the Run block. This model can be found here .
This section will describe a Simulink model used to generate code for capturing and displaying video frames
22
from/to the PC target using the TCP/IP protocol .
Figure 3.38: Capturing and Displaying Video Using the TCP/IP port
Figure 3.40: Creating the Bulid / Reload & Run Simulink block
7. Add the "Task" block from the "DSP/BIOS library" group of the "Target Support Package TC6"
Blockset.
8. Add the Function- Call Subsystem from the Ports & Subsystems" group of the "Simulink" Blockset
(Please refer to Figure 18).
9. Rename Function- Call Subsystem to R_W Algorithm and connect it to the Task block.
10. Add the "IP Cong" block from "Target Support Package TC6->DM6437 EVM Board Support"
11. Save the model as RW_dm6437_tcpip.mdl. Your model should look as follows:
12. Double-click the Task block and make the same changes as shown in Figure 20.
13. Double-click the IP Cong block and make the same changes as shown in Figure 21.
14. Double-click the R_W Algorithm block. A new window will be opened.
15. In the new window, add the "TCP/IP Recive", "TCP/IP Send", "Byte Unpack" and "Byte Pack"
from the "C6000 DSP Communication Libary" group of the ""Target Support Package TC6" Blockset
as shown in Figure 22.
17. Double-click the TCP/IP Receive block and make the same changes as shown in Figure 24.
(a)
(b)
Figure 3.47: "TCP/IP Receive" Conguration (a) Main Screen (b) Data Types
.
18. Double-click the TCP/IP Send block and congure it as shown in Figure 25:
19. Double-click the Byte Unpack block and congure it as shown in Figure 26.
20. Double-click the Byte pack block and congure it as shown in Figure 27.
21. Open a new m-le, copy the following code and save it as "RW_tcpip_script.m" at the same directory
as the model.
22. Create another new Simulink model. Add the "Byte Pack" from the "C6000 DSP Communication
Libary" group of the ""Target Support Package TC6" Blockset as shown before and the "TCP/IP
Receive", "TCP/IP Send" from the "Instrument Control Toolbox" blockset.
23. Congure the " TCP/IP Receive " and " TCP/IP Send " blocks :
(a)
(b)
Figure 3.51: "TCP/IP Receive" "TCP/IP Send" Blocks Conguration (a) "TCP/IP Receive" (b)
TCP/IP Send
24. Add the "To Video Display" from the "DM6437 EVM Board Support" group of the ""Target Support
Package TC6" Blockset , also add the "From Multimedia File" from " Signal Processing Sources" group
of the "Signal Processing blockset".
25. Congure the " From Multimedia File " block
(a)
(b)
Figure 3.52: "From Multimedia File" Conguration (a) "TCP/IP Receive" (b) TCP/IP Send
26. Add the Subsystem from the Ports & Subsystems" group of the "Simulink" Blockset as shown before.
27. Rename Function- Call Subsystem to Display.Double-click the Display block. A new window will
be opened. In the new window, add the "Byte Unpack" and " To Video Display " as shown before,
add the "Reshape" from the "Math Operations" grope of the "Simulink" blockset. (Congurations are
the same as before).
28. Connect the blocks as follows:
(a)
(b)
Figure 3.54: Capturing and Displaying Video Using TCP/IP (a) The Captured Video (b) The Displayed
Video
23
33. This model can be found here .
This laboratory was originally developed using the following hardware and software:
• MATLAB ® R2008a
• Code Composer Studio (CCS) v3.3
• Texas Instruments DM6437 hardware.
3.3.2.1 Simulation
36
Open the stills_R_W.mdl Simulink model (generated in the "A Framework for Image Processing with
37
the DSK6416 " module).
Add to it the blocks shown in the following table:
36 http://cnx.org/Members/jfaing/m23996/stills_sim.mdl
37 http://cnx.org/content/m23996/latest/
Edge Detection Video and Image Processing Blockset / Analysis & Enhancement 1
Draw Shapes Video and Image Processing Blockset / Text & Graphics 1
Table 3.2
Use the Edge Detection block to nd the edges in the intensity image. This process improves the eciency
of the Hough Lines block as it reduces the image area over which the block searches for lines. The block also
converts the image to a binary image, which is the required input for the Hough Transform block. Use the
default parameters.
Use the Video Viewer block to display the edges found by the Edge Detection block. Set the Input image
type parameter to Intensity.
Use the Hough Transform block to compute the Hough matrix by transforming the input image into
the rho-theta parameter space. The block also outputs the rho and theta values associated with the Hough
matrix. Set the block parameters as follows:
Figure 3.56
Use the Find Local Maxima block to nd the location of the maximum value in the Hough matrix. Set the
block parameters as follows:
Figure 3.57
Use the Selector blocks to separate the indices of the rho and theta values, which are output at the Idx port,
that are associated with the maximum value in the Hough matrix. Set the Selector block parameters as
follows:
Use the Variable Selector blocks to index into the rho and theta vectors and determine the rho and theta
values that correspond to the longest line in the original image. Set the parameters of the Variable Selector
blocks as follows:
• Select = Columns
• Index mode = Zero-based
Use the Hough Lines block to determine where the longest line intersects the edges of the original image.
You use these coordinates to superimpose a white line on the original image. Use the default parameters.
Use the Draw Shapes block to draw a white line over the longest line on the original image. Set the block
parameters as follows:
Use the Video Viewer block to display the original image with a white line superimposed over the longest
line in the image. Set the Input image type parameter to Intensity.
38
Connect the blocks as shown in the gure below. Use the le circuit.tif as input.
Figure 3.58
Create a Subsystem for the Hough algorithm. Select the blocks as shown in the following picture:
Figure 3.59
In the main menu, click on Edit/Create Subsystem (you may also enter Ctrl+G), as follows:
Figure 3.60
Figure 3.61
Figure 3.62
Create a Subsystem for the Line Drawing and Image Construction. Select the blocks as shown in the
following picture:
Figure 3.63
In the main menu, click on Edit/Create Subsystem (you may also enter Ctrl+G),
Your model should resemble the following gure:
Figure 3.64
Double-click the " Line Drawing and Image Construction ", and you should see:
Figure 3.65
Create a Subsystem for the Line Detection. Select the blocks as shown in the following picture:
Figure 3.66
Figure 3.67
The Video Viewer1 window displays the original image with a white line drawn over the longest line in
the image.
You may repeat the simulation here to experiment the various algorithms with dierent thresholds.
39 http://cnx.org/Members/jfaing/m23996/stills_sim.mdl
40 http://cnx.org/content/m23996/latest/
Figure 3.69: The Edge Detection Real Time Implementation Model for Stills Images
3.3.3.1 Simulation
41
Open the video_sim.mdl Simulink model (generated in the "A Framework for Video Processing with
42
the DM6437 DVDP " module). Copy the line Detection block in this model into the video_sim.mdl,
and connect it to the I/O blocks as follows:
41 http://cnx.org/Members/jfaing/m23999/video_sim.mdl
42 http://cnx.org/content/m23999/latest/
Figure 3.72
Double-Click the Line Detection block. In the open window, add the Submatrix block from the Signal
Processing Toolbox (EIhter from the Math Functions / Matrices and Linear Algebra / Matrix Operations
group or from the Signal Management / Indexing group. Connect it between the input node and the Edge
Detection Block as follows:
Figure 3.73
Figure 3.74
This will dene the Region of Interest (ROI). Rename the block to Dene ROI
Select the Edge Detection Block, and create a Subsystem for the Enhanced Detection, as shown in
the following picture:
Figure 3.75
Figure 3.76
Double Click the Enhanced Edge Detection block. Rename the Input port to ROI, and the output
port to Binary Image
Figure 3.77
Table 3.3
Place the blocks so that your model resembles the following gure. Create the Calculated threshold
based on histogram with the selected blocks.
Figure 3.78
The model should look as shown in the following picture. Create the Histogram based binary thresh-
olding with the selected blocks.
Figure 3.79
Double-click the Hough Algorithm block in the model. You should change it to select the two longest
lines.
Figure 3.80
Figure 3.81
Add an Embedded MATLAB function block (from the Simulink/User-Dened Functions group).
Double-Click the block and enter the following MATLAB function:
if isempty(lastThetas)
lastThetas = thetas;
end
if count == 4
%after the 4th frame, engage the test logic
for I = 1:length(rhos)
if (abs(rhos(I) - lastRhos(I)) > 30) || (abs(thetas(I) - lastThetas(I)) > 10*(pi/180))
%too much change - just use the old values
% outR(I) = lastRhos(I);
% outT(I) = lastThetas(I);
Rhos(I) = lastRhos(I);
Thetas(I) = lastThetas(I);
end
end
else
%otherwise just output the computed values
count = count+1;
end
%assign outputs
%Rhos = outR;
%Thetas = outT;
Figure 3.82
In the main model, double-click the Line Drawing and Image Construction block.
Change the conguration of the Draw Lines block as follows:
Figure 3.83
Now, it will draw the polygon based on the two longest lines.
Add the following blocks to the subsystem:
Table 3.4
Figure 3.84
• Selector5:
Figure 3.85
• Selector4:
Figure 3.86
• Selector3:
•
• Vertices Matrix:
Figure 3.87
Draw Lane
Figure 3.88
Figure 3.89
• Extraction
Figure 3.90
Rename the Line Detection to Lane Detection. Save the model as LaneDetection.mdl The model should
look as follows:
Figure 3.91
Double Click the Lane Detection block. You may rename the blocks' names. It will look as follows:
Figure 3.92
3.3.3.2.1 Procedure
43
Open the RW_dm6437_tcpip.mdl Simulink model (generated in the "A Framework for Video Processing
44
with the DM6437 DVDP " module).
Save the model as "lane_dm6437_tcpip.mdl".
Change the name of the R_W Algorithm block to Lane Algorithm.
Figure 3.94: The Real Time Implementation Model for Lane Detection
Right click on the "Build/Reload & Run" subsystem, choose Block Properties. Go to the Callbacks
tab, and under OpenFcn* enter: lane_tcpip_script('lane_pcl_tcpip');, as shown in the following picture:
43 http://cnx.org/Members/jfaing/m23999/RW_dm6437_tcpip.mdl
44 http://cnx.org/content/m23999/latest/
Figure 3.95
Double-click the Task block and make the same changes as shown:
Figure 3.96
Figure 3.97
Figure 3.98
Figure 3.99
Figure 3.100
Figure 3.101
Figure 3.102
Figure 3.103
Double-click the Video Source block and make the same changes as shown:
Figure 3.104
Figure 3.105
Double-click the Display block, Double-click the Data Unpack block and Congure the "Byte Unpack"
block as shown:
Figure 3.106
function lane_tcpip_script(hostModelName)
% controls host-side TCP/IP processing for
% Video Surveillance demo:
%********** Initialization ********************
% Get model name
modelName = gcs;
% Connect to CCS
CCS_Obj = connectToCCS(modelName);
saved_visibility = CCS_Obj.isvisible;
CCS_Obj.visible(1);
% Load application
loadApp(modelName, CCS_Obj);
% Run application
fprintf('Running application: %s\n', modelName);
CCS_Obj.run;
%[EOF] tcpip_surveil_script.m
Open a new m-le, copy the following code and save it as "lane_tcpip_script.m" at the same directory as
the model.
Build load and run the project from the "lane_dm6437l_tcpip.mdl" model. Double-click the "Build / Reload
& Run" block.
Running the script, you will see:
This block will enable you to simulate the edge detection procedure in the input image using the Sobel,
Prewitt, Roberts, or Canny methods.
If the selected method is Sobel, Prewitt, or Roberts, the Edge Detection block nds the edges in an input
image by approximating the gradient magnitude of the image. The block convolves the input matrix with
the Sobel, Prewitt, or Roberts kernel. The block output can be either the result of this convolution operation
(two gradient components of the image) or a binary image, obtained by comparing the convolution result
against a threshold. If a pixel value is `1', in this binary image it is an edge. Please refer to Figure 2
Figure 3.109: The Edge Detection Block Conguration Window for Sobel, Prewitt and Roberts Meth-
ods
If the selected method is Canny, the Edge Detection block nds edges by looking for the local maxima of
the gradient of the input image. It calculates the gradient using the derivative of the Gaussian lter. The
Canny method uses two thresholds to detect strong and weak edges. Please refer to Figure 3.
Figure 3.110: The Edge Detection Block Conguration Window for the Canny Method
56 http://cnx.org/Members/jfaing/m23996/stills_sim.mdl
57 http://cnx.org/content/m23996/latest/
You may repeat the simulation here to experiment the various algorithms with dierent thresholds.
3.4.3.2 Real-Time
58
1. Open the stills_R_W.mdl Simulink model (generated in the "A Framework for Image Processing
59
with the DSK6416 " module).
2. Add the "Edge Detection" block from from the "Analysis & Enhancement" group of the Video and
Image Processing Blockset, as it was done for the simulation.
3. Connect the various blocks as shown in Figure 6. Save the model (EdgeDetectionPic-
tureDSK6416.mdl).
58 http://cnx.org/Members/jfaing/m23996/stills_sim.mdl
59 http://cnx.org/content/m23996/latest/
4. Generate code & create project. Double-click the " Generate code &.." block.
5. Build the project. Double-click the Build Project block.
6. Load the project. Double-click the Load Project block.
7. Run the target. Double-click the Run block.
60
8. Run the le EdgeDetectionPicturescript.m , this should give you the images in gure 7.
60 http://cnx.org/Members/jfaing/module.2008-08-11.5404829390/EdgeDetectionPicturescript.m
4. Run the model. A single frame of the input and output video is shown in Figure 9.
You may repeat the simulation here to experiment the various algorithms with dierent thresholds.
3.4.4.2 Real-Time
61
1. Connect the camera and the display to the board and open the Video_R_W.mdl (placed in the
62
A Framework for Video Processing with the DM6437 DVDP module.).
61 http://cnx.org/content/m23999/latest/Video_R_W.mdl
62 http://cnx.org/content/m23999
2. Change the name of the Video Processing block to Edge Detection (Please refer to Figure 10). A
new window will be opened
3. Add the "Edge Detection" block from the "Analysis & Enhancement" group of the Video and Image
Processing Blockset, as it was done for the simulation.
4. Add the "Image Data Type Conversion" block from the " Conversion" group of the Video and Image
Processing Blockset.
5. Set the model in the Simulation->Conguration Parameters, as shown in Figure 11.
6. Generate code & create project. Double-click the " Generate code &.." block
7. Build the project. Double-click the Build Project block.
8. Load the project. Double-click the Load Project block.
9. Run the target. Double-click the Run block. The results will be diaplyed in the screen as shown in
Figure 12.
1. Functional Requirements
2. System modeling and simulation
3. Code generation and implementation
This laboratory was originally developed using the following hardware and software:
• MATLAB ® R2008a
• Code Composer Studio (CCS) v3.3
• Texas Instruments DM6437 hardware.
Figure 3.120
The Motion Energy estimation is based on the calculation of the Sum of Absolute Dierences (SAD)
according to the following equation:
P P
SAD = i j | Ik (i, j) − Ik−1 (i, j) |
where:
Table 3.5
The Video Surveillance system block diagram is shown in Figure 2. The source video is displayed and played
back through the system. This incoming video stream is processed by a subsystem that estimates the motion
within the scene and captures the interesting video frames. The system can display either the recorded video
frame or the Absolute Dierences (AD) image.
The user can congure the motion energy threshold value and select which image will be displayed
(Display Control). The system outputs include, besides the displayed image, the following features:
• A graph of the motion energy as a function of time. This graph displays the threshold value as well.
While the generated code is running on the target, a host side Simulink ® model simultaneously sends video
frames to the target via TCP/IP protocol using TCP/IP Blocks from Instrument Control Toolbox . The
target receives video frames sent by the host side Simulink model, computes the sum of the absolute value
of dierences (SAD) between successive video frames, and returns an estimate of motion. When the motion
estimate value exceeds a threshold, the target increments a counter and sends the corresponding frame back
to the host.
3.5.3 Simulation
1. Open a new Simulink model
2. Add the blocks shown in the following table (Please refer also to Figure 3):
Generate data for motion en- Matrix Concatenate Simulink / Math Opera- 2
ergy and threshold display tions
Table 3.6
1. Congure one of the Add block for subtraction, you may also change its icon shape to a circular form
70
as follows :
Figure 3.123
2. Congure its xed point mode of operation Congure one of the Matrix Sum blocks for adding rows:
70 The symbol | is used to place the + and - perpendicular to each other
Figure 3.124
Figure 3.125
4. Congure the xed point mode of operation for the second Matrix Column Add block:
Figure 3.126
1. Congure on of the Video Source "From Multimedia File" block for reading frames from the "vip-
men.avi" le.
Table 3.7
Figure 3.127
Figure 3.128
Figure 3.129
Figure 3.130
Figure 3.131
71
6. The Floating Scope will be used to display the motion energy and the threshold as a function of
71 The threshold is changed upon a user command. The simultaneous display of the threshold and motion energy will enable
time. Double-Click the block. A cope screen will appear, you should then click the icon as shown in
the following picture:
Figure 3.132
Figure 3.133
Figure 3.134
Figure 3.135
Figure 3.136
Table 3.8
Figure 3.138
In this scope display, yellow represents the motion estimate from each video frame, and magenta is the
threshold level. In the Motion Threshold scope here, we see that we identied ve frames with motion
above the threshold that were captured and recorded.
72 http://cnx.org/Members/jfaing/m23999/video_sim.mdl
73 http://cnx.org/content/m23999/latest/
5. In this block, add a Add the Function- Call Subsystem from the Ports & Subsystems" group of the
"Simulink" Blockset.
6. Rename Function- Call Subsystem to Video Frame Capture Motion Threshold and Double-click it.
7. Open the model "surveillance_sim.mdl", created in section and copy it into Video Frame Capture
Motion Threshold .
8. Add three input ports "In1" from the "Sources" group of the "Simulink" blockset and three output
ports "Out1" from the "Sinks" group of the "Simulink" blockset.
9. Add a "Switch" from the "Signal Routing" group of the "Simulink" blockset and a "Gain" from the
"Math Operation" group of the "Simulink" blockset.
10. Double-click the Motion Energy block and add him another output port as shown:
Figure 3.139
Figure 3.140
Figure 3.141
Figure 3.142
Figure 3.143
Figure 3.144
Figure 3.145
Figure 3.146
Figure 3.147
19. Connect the Video Frame Capture Motion Threshold block as shown:
Figure 3.148
20. Open the RW_pcl_tcpip.mdl model, created in the "Video R_W" le
21. Rename the model "my_pc_surveil_tcpip.mdl".
22. Add the "Manual Switch" from the "Signal Routing" group of the "Simulink" blockset and three
"Constant" blocks from the "Signal Processing" group of the "Signal Processing" blockset.
23. Congure the " Constant " blocks:
Table 3.9
Figure 3.149
Figure 3.150
Figure 3.151
Figure 3.152
Figure 3.153
31. Add to the "Display" subsystem the "Insert Text" from the " Text & gure__" group of the " Video
and Image Processing " blockset, " Floating Scope" from the "Sinks" group of the "Simulink" blockset.
32. Congure the " Insert Text " block :
Figure 3.154
33. Add the Subsystem from the Ports & Subsystems" group of the "Simulink" Blockset
34. Rename it "Combine Count"
35. Add a "Frame Counter" subsystem as we did in paragraph 14 at the rst section.
Figure 3.155
36. Add a "Matrix Concatenate" from the "Math Operations" group of the "Simulink" blockset.
37. Connect the block as shown:
Figure 3.156
Figure 3.157
Figure 3.158
40. Open a new m-le, copy the following code and save it as "my_tcpip_surveil_script.m" at the same
directory as the model.
function my_tcpip_surveil_script(hostModelName)
%my_tcpip_surveil_script controls host-side TCP/IP processing for
% Video Surveillance demo:
% 1) Builds and runs the target application
%********** Initialization ********************
% Get model name
modelName = gcs;
% Connect to CCS
CCS_Obj = connectToCCS(modelName);
saved_visibility = CCS_Obj.isvisible;
CCS_Obj.visible(1);
% Load application
loadApp(modelName, CCS_Obj);
% Run application
fprintf('Running application: %s\n', modelName);
CCS_Obj.run;
%[EOF] tcpip_surveil_script.m
41. Open a new m-le, copy the following code and save it as "my_tcpip_surveil_script.m" at the same
directory as the model.
42. now we have two models ("my_pc_surveil_tcpip.mdl" and "my_dm6437evmsurveil_tcpip.mdl") and
1. Build load and run the project from the "my_dm6437evmsurveil_tcpip.mdl" model. Double-click the
" Build / Reload & Run" block.
2. Running the script, you will see:
Figure 3.159
Figure 3.160
If you want to display the Absolute Dierences Image, change the state of the switch from 0 to 1. You
will then see:
Figure 3.161
4.1 Overview
This course focuses on work-ow and application-based teaching rather than individual DSP algorithms
implementation. Each module starts from an algorithm that is prototyped step-by-step, and then deployed
on the hardware. The course contains a suite of example applications in various elds such as Audio,
Video, Imaging, Communications and Control. The basic examples enable students to experiment with
real-time DSP applications, showing how to create prototypes using the Mathworks and Texas Instruments
development tools (hardware and software). Advanced level examples are also included, where the basic
tools are integrated with external dedicated hardware and/or software modules.
Platforms used: TMS320F2808 eZdsp Starter Kit (DSK), TMS320F2812 eZdsp Start Kit (DSK),
TMS320C6713 DSP Starter Kit (DSK), TMS320C6416 DSP Starter Kit (DSK), DM6437 Digital Video
Development Platform (DVDP).
This material and more is available as a complete CD-ROM, that can be obtained from Texas Instru-
2 3
ments and Mathworks
521
522 INDEX
C Covariance, 2.7(300)
N Noise Reduction, 2.8(332)
Attributions
Collection: From MATLAB and Simulink to Real-Time with TI DSP's
Edited by: Jacob Fainguelernt
URL: http://cnx.org/content/col10713/1.1/
License: http://creativecommons.org/licenses/by/2.0/
Module: "A Framework for Video Processing with the DM6437 DVDP"
By: Jacob Fainguelernt
URL: http://cnx.org/content/m23999/1.1/
Pages: 397-424
Copyright: Cathy Wicks
License: http://creativecommons.org/licenses/by/2.0/
About Connexions
Since 1999, Connexions has been pioneering a global system where anyone can create course materials and
make them fully accessible and easily reusable free of charge. We are a Web-based authoring, teaching and
learning environment open to anyone interested in education, including students, teachers, professors and
lifelong learners. We connect ideas and facilitate educational communities.
Connexions's modular, interactive courses are in use worldwide by universities, community colleges, K-12
schools, distance learners, and lifelong learners. Connexions materials are in many languages, including
English, Spanish, Chinese, Japanese, Italian, Vietnamese, French, Portuguese, and Thai. Connexions is part
of an exciting new information distribution system that allows for Print on Demand Books. Connexions
has partnered with innovative on-demand publisher QOOP to accelerate the delivery of printed course
materials and textbooks into classrooms worldwide at lower prices than traditional academic publishers.