The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathW orks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern
theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand
Documentation by the federal government (or other entity acquiring for or through the federal government)
and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the
government’s needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Docu mentation, unused, to The MathWorks, Inc.
Trademarks
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.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
March 2007Online onlyNew for Version 3.2 (Release 2007a)
September 2007 Online onlyUpdated for Version 3.3 (Release 2007b)
March 2008Online onlyUpdated for Version 3.4 (Release 2008a)
October 2008Online onlyUpdated for Version 4.0 (Release 2008b)
March 2009Online onlyUpdated for Version 4.1 (Release 2009a)
September 2009 Online onlyUpdated for Version 4.2 (Release 2009b)
March 2010Online onlyUpdated for Version 4.3 (Release 2010a)
xPC Ta rget Drivers
When to Write Your Own Drivers
Restrictions on Customizing xPC Target Drivers
Expected Background
Resources f or Customizing xP C Target Drivers
What Makes Up an xPC Targ et Driver?
................................1-2
....................1-3
........1-3
..............................1-3
.........1-4
...............1-6
Contents
Before You Start
Introduction
Driver Types
Bus Types and Register Access
Register Acces s
Inlining xPC Target Drivers
Creating a Custom Driver
Debugging Notes
...................................1-8
......................................1-8
.....................................1-9
......................1-9
...................................1-10
......................... 1-10
.......................... 1-11
..................................1-16
PCI Drivers
2
PCI Bus Considerations ............................2-2
Introduction
PCI Configuration Space API
Memory-Mapped Accesses
I/O Port Accesses
......................................2-2
........................2-3
..........................2-6
..................................2-6
Sample PCI Device Driver
..........................2-8
v
ISA and PC/104 Drivers
3
ISA and PC/104 Bus Considerations .................3-2
Using the xPC Target Driver Authoring Tool
Setting Up Driver Variables
Saving the Configuration
Reloading the Configuration
Creating the C File Template
Creating a C MEX File for the Driver
Customizing the Device Driver Mask
.........................7-4
...........................7-7
........................7-8
........................7-8
...............7-4
...........7-4
.................7-8
.................7-9
vii
8
9
10
I/O Structures — By Category
I/O Structures — Alphabetical List
I/O Functions — By Category
Port I/O ........................................... 10-2
“Restrictions on Customizing xPC Target Drivers” on page 1-3
“Expected Background” on page 1-3
“Resources for Customizing xPC Target Drivers” on page 1-4
“What Makes Up an xPC Target Driver?” on page 1-6
xPC Target Drivers
The xPC Target™ software provides device drivers for a variety of third-party
boards. xPC Target users access these drivers as Simulink
the xPC Target library (
Target so ftw are does not supply a driver, you can write your own. This guide
provides guidelines for writing custom xPC Target device d rivers.
®
blocks from
xpclib). If you have a board for which the xPC
1-2
The xPC Target driver library contains drivers that support third-party
boards with many I/O capabilities and applications. This includes drivers for
different types of I/O boards, including
g-to-digital
Analo
Digital-to-analog
Audio
ters
Coun
Shared memory
There are also drivers that support particular protocols, including
232, RS-422, RS-485
RSGPIB
CAN
P
UD
ARINC 429
MIL-1553
Introduction
When to Write You
Consider writin
• No xPC Target dr
• You are unable
• You need to ext
• The MathWorks
board.
Restrictio
The xPC Targ
drivers aim
from a driv
Target ker
layers tha
The xPC Ta
runs to th
own driv
• You cann
er:
the manu
depend
able will not be able to load the DLL.
execut
g your own device drivers for the xPC Target block library if:
iver exists for your I/O needs.
to use a bo ard that t he xPC Target software supports.
end t h e functionality of an existing xPC Target driver.
xPC Target te am will not write a device driver fo r your
ns on Customizing xPC Target Drivers
et software has its own kernel, and you will be writing device
ed at that kernel. An xPC Target driver is therefore different
er for another en vironment, such as Microsoft W indows. The xPC
nel is optimized and small, and does not have the operating system
t traditional kernels do.
rget software installs its own kernel on the target PC. This kernel
e exclusion of any other operating system. When writing your
ot use a driver DLL that accompanies the I/O board from
facturer. A manufacturer-supplied DLL will have external
encies that the xPC Target kernel cannot resolve. The xPC Target
rOwnDrivers
• Do not c
• If you
you no
acces
able
Expe
s guide assumes that you are already knowle dgeable about w riting device
Thi
vers. It describes the steps specific to writing device drivers for the xPC
dri
get environment. To write your own device drivers for the xPC Target
Tar
tem, you need the following background:
sys
reate your own driver DLL.
do not have access to the register programming information, neither
r The MathWorks can write a device driver for the board. If you have
s to the source code of an existing driver for the board, you m ig ht be
to port it to the xPC Target kernel.
cted Background
1-3
1 Customizing xPC Target™ Drivers
• Good C programming skills
• Knowledge of how Simulink simulation works, for example, the type and
order of calls
• Knowledge of writing S-functions and compiling those functions a s C-MEX
functions. This includes a comprehensive knowledge of Simulink callback
methods and the Simulink
• Basic knowledge of Real-Time Workshop
• Understanding of I/O hardware. Because of the real-time nature of the
xPC Target software, you must develop drivers with minimal latency.
Most drivers access the I/O hardware at the lowest possible level (register
programming). Therefore, you must understand how to control the board
with register information.
• Knowledge of port and memory I/O access over various buses. You need
this information to access I/O hardware at the register level.
• Knowledge of PC hardware fundamentals and internals
SimStruct functions.
Resources for Customizing xPC Target Drivers
This section lists the resources that a re available to you from The MathWorks.
References
The following MathWorks documentation provides information that you can
refer to when customizing xPC Target drivers:
See...
Simulink User’s GuideOverall description of the Simulink environment and how the
MATLAB®External
Interfaces
1-4
For...
Simulink software performs simulations.
How to write MATLAB MEX-files.
Introduction
See...
For...
Developing S-FunctionsHow to write MATLAB C-MEX S-functions (noninlined S-functions).
Note the following references in this guide:
• “S-Function Callback Methods — Alphabetical List” the Simulink
software invokes these methods when simulating a model with
S-functions. Real-Time Workshop uses the same methods in
generated real-time applications.
descriptions of the functions that access the fields of an S-function’s
simulation data structure (
SimStruct). S-function callback
methods use these functions to store and retrieve information
about an S-function.
Real-Time Workshop
Target Language
Compiler
Real-Ti
User’s G
me Workshop
uide
®
How to write target language compiler (TLC) files to inline S-function
drivers. This is an optional reference and depends on whether or not
youchoosetoinlineyourdriver.
Overall description of Real-Time Workshop fundamentals, and
guidelines on understanding I/O boards and low-level programming
for drivers for those boards.
MathWorks Consulting
You can
about
alternatively contact the MathWorks Consulting Services Group
the fee-based creation of a driver for your board.
Source Code
an examine the source code for existing xPC Target device drivers as a
You c
rence for your custom drivers. Refer to the following directory:
Note In this directory, you might notice that some drivers use outdated xPC
Target driver functions. F or the current functions to use, see “xPC Target
Exported Functions” on page 1-6.
1-5
1 Customizing xPC Target™ Drivers
xPC Target Exported Functions
The xPC Target software provides kernel functions that you can use when
writing your device drivers. These functions enable you to input and output
data, configure PCI devices, and specify time-out intervals. Use only the
functions documented in this guide. The guidelines in this document are
not applicable if you are using an xPC Target software version prior to xPC
Target software version 3.2 (R2007a). See Chapter 11, “I/O Functions —
Alphabetical List”, for a descriptio n of these functions.
Third-Party Directory
The xPC Target software provides the following directory to help you integrate
your custom driver.
This directory provides template files that you copy and customize for your
drivers. Place all files that support your drivers in this directory.
1-6
What Makes Up an xPC Target Driver?
An xPC Target device driver is an S-function with functions that access an
I/O board.
Like any device driver, an xPC Target driver interfaces between the user and
an I/O device. Unlike typical device drivers, xPC Target device drivers:
• Can have the following parts
- Driver code, that is C code written as an S-function using exported xPC
Target kernel functions (see “xPC Target Exported Functions” on page
1-6)
- Optional Simulink block interface (Simulink mask) that users use to
configure the device and access output
- Optional MATLAB code that you can w rite to perform o perations such as
cross-block checking or parameter value range checking. You reference
this file through the Simulink mask.
• Can be included in a Simulink library
• Are configured like any other Simulink block
Block mask
Introduction
Underlying driver code (C-file)
Mask editor
Anatomy of an xPC Target™ Driver
Mask initialization (M-file)
1-7
1 Customizing xPC Target™ Drivers
Before You Start
In this section...
“Introduction” on page 1-8
“Driver Types” on page 1-9
“Bus Types and Register Access” on page 1-9
“Register Access” on page 1-10
“Inlining xPC Target Drivers” on page 1-10
Introduction
This topic assumes that you satisfy the requirements outlined earlier in
“Expected Background” on page 1-3 and that you have reviewed the following
sections to prepare:
• “References” on page 1-4
1-8
• “Source Code” on page 1-5
• “xPC Target Exported Functions” on page 1-6
• “Third-Party Directory” on page 1-6
It also assumes that you already have a board for which you want to write
a driver. Before you start, use the following checklist to specify the driver
you want to write:
• Determine the functions of your board that you want to access with your
driver.
• Determinethebustypefortheboard.
- PCI
- ISA
• Select the I/O access mapping type.
- I/O port mapped
- Memory address mapped
Before You Start
• Select polling versus interrupt.
• Specify the blocks for the drivers. Identify
- Input and output ports
- Mask parameters
- Work variables to be shared between driver start, output, and terminate
routines
• Determine your timing considerations.
• Decide whether you use Inlined functions.
If yes, see the Target Language Compiler documentation of the Real-Time
Workshop.
Driver Types
• Standard I/O
• Communication
• DMA
• Interrupt-driven
Bus Types and Register Access
The xPC Target software supports the two standard PC bus types, ISA and
PCI. The ISA bus is a 16-bit bus with an 8 MHz clock. Another form of ISA
bus is the PC/104. The PCI bus is a 32-bit or 64-bit bus with a 33 MHz or 66
MHz clock. Another form of PCI bus is the PC/104+ (PC/104-Plus).
A driver performs I/O accesses through either I/O ports or memory addresses
(memory mapped).
The xPC Target software accesses I/O port addresses for ISA and PCI buses
as follows:
1-9
1 Customizing xPC Target™ Drivers
BusAccess
ISABoard switches or jumpers usually select I/O port address and any
PCIThe BIOS determines the I/O port address during PCI PNP (Plug
The m e mory space for I/O boards is different for ISA and PCI boards.
memory-mapped region.
and Play) configurations.
Bus
ISAThe xPC Target software only permits use of the memory address
PCIUpper memory address space, typically greater than 2 GB
Memory Space
between 0xA0000 and 0xFFFFF
Register Access
A device board supports either I/O port or memory-mapped access to onboard
registers. See the board manufacturer’s register programming documentation.
Inlining xPC Target Drivers
You can choose to inline or not inline xPC Target drivers. Note the distinction
between Simulinkand Real-Time Workshop conditional compilation. Writing
a device driver as an inlined S-function ensures that the driver can coexist
with xPC Target device drivers.
Inlining drivers allows you to customize code generated from Real-Time
Workshop. If you choose to create inlined drivers, yo u must use the Real-Time
Workshop Target Language Compiler.
Note For convenience, you can create a noninlined version of the driver
first, and create an inlined driver for the Target Language Compiler from
the first driver.
1-10
Creating a Custom Driver
The following is a generic procedure for how to create a custom device driver.
For additional notes on writing custom xPC Target drivers, see Chapter 6,
“Custom xPC Target Driver Notes”. For a description of a tool that helps you
create simple custom drivers, see Chapter 7, “Creating Custom Drivers Using
the xPC Target Driver Authoring Tool”. A simple custom device driver is one
which performs no DMA or interrupt handling.
Note You might need administrative or write privileges to add a custom
device driver to the xPC Target system. Otherwise, see “Creating Custom
Blocks” in the Simulink User’s Guide.Thistopicdescribeshowtoaddcustom
blocks to a library.
1 Write your driver in C, using the approved I/O functions as appropriate
(see Chapter 9, “I/O Structures — Alphabetical List” and Chapter 11, “I/O
Functions — Alphabetical List”). An example device driver for the analog
inputs of the Diamond MM-32 board is available at
4 Open the Simulink Library Browser a nd create a new library, for example,
your_company_namelib.mdl (see “Creating Block Libraries” in the
“Working with Block Libraries” in the chapter of Simulink User’s Guide).
Use a unique library name to prevent conflicts with other libraries.
5 In the new library, create an S-function block. From the Simulink Library
Browser, drag an S-Function block to the new library.
6 Configure the S-Function block.
a In the new library, right-click the S-Function block and select
S-Function Parameters.
b In S-function nam e, enter the name, without extension, of the driver.
For example,
step 1).
c In S-function param eters, enter the parameters you defined for the
driver. The parameter names you enter here must match the names you
will later enter for the driver block mask (through the Parameters
and Initialization panes of the Mask Editor dialog box). For example,
addiamondmm32. (This is the driver C-file you created in
1-12
d Leave the S-function modules parameter with the default value,
unless you need to separate your driv er C-file into multiple files. If that
is the case, see “Specifying Additional Source Files for an S-Function”
in the “Integrating External Code W ith Generated C and C++ Code”
chapter of the Real-Time Workshop User’s Guide.
Creating a Custom Driver
7 Double-click the S-Function block and create a block mask (see Chapter 4,
“Masking Drivers”).
8 Save and close the S-Function block.
9 At the bottom of the S-Function block, enter a block name. For example,
MM-32.
10 Save and close the library.
11 To make your new library visible in the Simulink Library Browser, move
Ensure that these files have unique names to prevent conflicts.
15 To update the directories that you added, at the MATLAB Command
Window, type
rehash toolbox
When you are done, your library will appear in the Simulink Library Browser
with
xPC Target: added to the beginning of the library name.
xPC Target: your_company_namelib Blockset
1-15
1 Customizing xPC Target™ Drivers
Debugging Notes
While developing your custom driver, you can use printf statements in your
code. This displays output on the left-hand side of the target PC monitor. If
your
printf statements scroll off the monitor, consider disabling the target
PC scope area to provide more display area for these statements:
1 At the MATLAB Command Window, type xpcexplr to start xPC Target
Explorer.
2 In xPC Target Explorer, navigate to target_P C_node >
Configuration > Appearance.
3 Clear the En
4 Recreate the target boot disk and reboot the target PC.
The scope area on the target PC monitor no longer appears.
5 Continue
able target scope check box.
with the device driver development.
1-16
PCI Drivers
• “PCI Bus Considerations” on page 2-2
• “Sample PCI Device Driver” on page 2-8
2
2 PCI Drivers
PCI Bus Considerations
In this section...
“Introduction” on page 2-2
“PCI Configuration Space API” on page 2-3
“Memory-Mapped Accesses” on page 2-6
“I/O Port Accesses” on page 2-6
Introduction
When writing xPC Target drivers for PCI devices, consider the memory access
method. A PCI device can be either I/O port mapped or memory mapped.
• I/O port m apped — The BIOS assigns a port range.
• Memory mapped — The BIOS assigns a memory region, if your device
is memory mapped.
2-2
The PC BIOS automatically assigns a conflict-free set of resources to any PCI
device found in the system at boot-up. You typically do not know where the
board resides (base address) before driver initialization. However, you can
obtain this information by que ryi ng the PCI configuration space at run time.
The xPC Target software provides functions to accomplish this (see the “PCI
Configuration Information” on page 10-2 functions).
To locate a PCI device, you need the following:
• Vendor and device ID
• Optionally, subsystem vendor and subsystem device ID
Note You need the subsystem vendor and subsystem device ID if the
vendor and device ID do not uniquely identify the board.
• Slot number or bus and slot number
PCI Bus Considerations
You can have the drivers locate PCI devices in one of the following ways:
• If the system has one board of any one type, you can use the driver
slot
option to search for the first board that matches a vendor and device ID. To
initiate this search, set this option to
• If the system contains multiple boards of the same type, setting the
-1.
slot
option to -1 does not find the additional boards. In that case, specify the
bus and slot numbers with the vendor and device IDs.
PCI Configuration Space API
Before you can access a PCI device, you need to access the configuration space
to locate the board in the target PC memory. This section describes the
proceduretodothis.
For PCI devices, the driver will need to access the PCI configuration space
for the board. This space contains relevant board information such as the
base address and acces s type (I/O port or memory mapped). The xPC Target
software prov ides functions that allow the driver to access this space.
• Vendor and device ID — The driver searches all boards for the specified
vendor (manufacturer) and device ID. The PCI Steering Committee, an
independent standards body, assigns a unique vendor ID (
PCI board vendor. Each vendor then assigns a unique ID to each PCI board
type it supports.
uint16)toeach
Note Vendor and device IDs do not always uniquely identify a board. For
example, all boards that use the PLX-9080 bus interface chip have a vendor
ID of 10B5 (the vendor ID assigned to PLX Technology, Inc.). The device
ID for the chip is 9080. In cases like this, to select a particular board that
contains this chip, you must use a subvendor and subdevice ID in addition
to the vendor and device IDs.
• Slot number or bus and slot number — The driver looks only for the board
that matches the specified vendor and device ID and slot number.
2-3
2 PCI Drivers
PCI Device Information
Use the xpcGetPCIDeviceInfo function to get information for a PCI device in
your system. The syntax for this function is:
This function returns the xpcPCIDevice structure filled according to the
following:
If You Supply...
This Function....
All the parametersLooks for a device that matches all the parameters
and returns the
xpcPCIDevice structure for that
device. Use this form if you know that your system has
multiple boards from the same vendor with the same
ID and you want your user to specify the exact device.
XPC_NO_SUB for
the
subVendorId
or subDeviceId
parameter
Does not consider the subvendor or subdevice ID when
looking for a match for the specified device. It returns
the
xpcPCIDevice structure for a device that matches
the other parameters. You can use this form if you
do not plan to use the
subVendorId or subDeviceId
values.
XPC_NO_BUS_SLOT
for the slot for the
device
Returns the first PCI device it finds that matches
the remaining parameters. You can use this form if
you know that your system has only one board with
aparticularIDset.
Passing Slot Information from the Block Mask to Its Driver
xPC Target drivers use the following convention to fill in slot parameters and
retrieve slot information. Choose the convention that will work best for you.
2-4
PCI Bus Considerations
Set...
To...
Set slot = -1Assume bus = 0 and call the xpcGetPCIDeviceInfo
function to find the first instance of the board.
Set slot = SAssume bus = 0 and call the xpcGetPCIDeviceInfo
function to find the specified board. If the board
matches the IDs, return the PCI information to the
driver. Otherwise, return an error.
Set slot = [B, S]CheckbusB and slot S f o r the specified board . If the
board match es the IDs, return the PCI information to
the driver. Otherwise, return an error.
Setting
slot = [0, S]isidenticaltosl ot = S.
The following example illustrates how to use the xpcGetPCID eviceInfo
function to program the driver to accept slot number input or slot and bus
number input from the driver block.
1 Call this function from the mdlStart callback function.
2 Pass the slot number or slot and bus number into the xpcG etPC IDeviceInfo
function using code like the following:
uint16_TvendorId, deviceId;
int32_Tbus, slot, subvendor, subdevice;
xpcPCIDevicepciInfo;
/* S_PCI_SLOT_ARG is passed in fr om the mask */
/* Typically the slot arg is a scalar containing -1 if there is only one board of
this type in the target */
/* If there are multiple boards of this type the slot arg is a vector containing bus
and slot info */
/* This code snipped parses the slot arg into bus and slot */
if ( (int_T)(mxGetN(ssGetSFcnParam(S, S_PCI_SLOT_ARG))) == 1 ) {
/* Set subvendor and subdevice to XPC_NO_SUB, XPC_NO_SUB if they are not necessary */
/* xpcGetPCIDeviceInfo() populates the pciInfo struct */
if ( xpcGetPCIDeviceInfo(vendorId, deviceId,
subvendor, subdevice,
bus, slot,
&pciInfo) ) {
sprintf(msg, "Board 0x%x not found at bus %d slot %d", deviceId, bus, slot);
ssSetErrorStatus(S, msg);
return;
}
For detailed information on the xpcPCIDevice structure, see xpcPCIDevice.
2-6
Memory-Mapped Accesses
A memory-mapped PCI board uses up to six memory regions to access board
regions and memory. Each region might also have a different length. You
must call the
xpcReserveMemoryRegion function for each PCI memory region
you want to access; use the returned virtual address to access the region.
Failure to do this will result in a segmentation fault.
To access a memory mapped location, do the following:
This driver illustrates digital input driver code for the Keithley 1800 series
PCI devices.
Note Remember to enter the C-file name (without the extension) as the
S-function name for the S-Function block.
2-8
ISA and PC/104 Drivers
3
3 ISA and PC/104 Drivers
ISA and PC/104 Bus Considerations
In this section...
“Introduction” on page 3-2
“I/O Mapped” on page 3-2
“Memory Mapped” on page 3-3
Introduction
When writingxPC Target drivers for ISA and PC/104 devices, consider the
memory access method. A PCI device can be either port mapped or memory
mapped. Most ISA and PC/104 boards are port mapped. Those that are
memory mapped typically need large register banks or are interfaced via
dual-port memory.
Note ThexPC Target kernel does not support ISA and PC/104 PNP boards.
This means that you can write xPC Target device drivers only for ISA and
PC/104 boards for which you can set the base address manually. To manually
set the base address, insert jumpers or move DIP switches on the board.
3-2
• Port mapped
The base port address on the board is set via jumpers or switches. You
might need to reset the s e addresses if there are conflicts.
• Memory mapped
The I/O and memory on the board are set via jumpers or switches. You
might need to reset the s e addresses if there are conflicts.
I/O Mapped
The base port address on the board is set via jumpers or switches. D riv ers
cannot discover these addresses on their own; you must specify these
addresses to the driver.
Memory Mapped
The I/O and memor
cannot discover
addresses to th
Reserved Space on the Target PC
The xPC Target
memory-mapp
addresses in
this range.
y on the board is set via jumpers or switches. D rivers
these addresses on their own; you must specify these
e driver.
kernel reserves space in the region (C0000 to DC000) for
ed I/O cards. You must set up ISA and PC/104 cards to use
ISA and PC/104 Bus Considerations
3-3
3 ISA and PC/104 Drivers
3-4
Masking Drivers
• “Creating Driver S ubsystem Masks” on page 4-2
• “Driver Mask Guidelines” on page 4-3
• “Cross-Block Checking” on page 4-5
• “When You Are Done” on page 4-6
• “Sample Driver Mask” on page 4-7
4
4 Masking Drivers
Creating Driver Subsystem M asks
This chapter describes guidelines for creating a Simulink block user interface
(mask) for the S-Function block associated your driver. A mask defines
the menu items that will be passed to the S-function. The mask can call a
MATLABfiletodoparameterorrangevaluechecking. Youcanalsomodify
the labels of a block to show port numbers or other information. After you
create the C code for an xPC Target device driver:
1 Create an optional MATLAB file.
2 Create an S-Function block for the driver.
3 Create a mas
This is the basic Simulink mask, with parameters and descriptions as
necessary. Whenyouaredone,youcanmakethedevicedriverandits
mask available for users to add to their models.
k for the S-Function block.
4-2
Driver Mask Guidelines
This topic lists guidelines you should follow when creating a mask for your
xPC Target driver. You should already know how to create masked blocks.
See the “Working with Block Masks” chapter in Simulink User’s Guide for
further information.
Users access the masked block to interact with the driver, w h ich in turn
interacts with the device.
• Create an S-Function block for the driver.
• Decide on the set of parameters the user will need to provide to the driver.
You should have already programmed this into the driver C code itself.
• Select appropriate descriptive names for these parameters.
• For each parameter, decide if the parameter can accept a finite number of
possible input values. If ye s, consider using one of the following widgets:
- Check box — For yes/no or 1/0 inputs
Driver Mask Guidelines
- Drop-down list — For a finite list of choices
Yourmaskcanalsobedynamic,wherethe dialog changes according to
user selections.
• Choose readable and appropriate variable names.
• As necessary and appropriate, configure the library block so that the block
mask modifies its label according to user input. For example, a check box
might cause the dialog to change.
• Ensure that the title beneath the driver block terminates with a blank
space. This is because if a model contains more than one block of any given
type, Simulink appends a num ber to the title under the block. Adding a
blank space to the end of the label ensures readability.
• Name the block appropriately so that it indicates the purpose of the driver.
• If you w ant to link help information to the mask Help button, see “Defining
Mask Documentation” in the “Working with Block Masks” chapter of
Simulink User’s Guide for details.
• From within the mask, you can call a custom file to perform a number of
operations, including the following:
4-3
4 Masking Drivers
- Range checking for all parameters. For example, if you expect input
values from
values greater than 10.
1 to 10, do not allow users to enter negative values, or
- Cross-block checking (see “Cross-Block Checking” on page 4-5).
4-4
Cross-Block Checking
Cross-block checking determines if multiple blocks are trying to access the
same hardware. You should include cross-block checking in your driver
to prevent such conflicts. You can perform cross -block checking by calling
find_system from the block mask in a number of ways. Use the following
guidelines when performing cross-block checking:
Cross-Block Checking
• Therecommendedwayistocallthe
InitFcn callback function. There are two phases of MATLAB file execution
during an update system operation. If you call the
from a block
InitFcn callback function, defined in the Block Parameters
find_system function from the block
find_system function
dialog of the block, no additional updates are triggered.
• Decide on the level of cross-block checking for your hardware. For example,
boards that use the 8255 chip for digital I/O need to check if two different
blocks are requesting opposing directions (for example, input and output)
for the same group of 8 bits. On this chip, there are three groups of 8 bits.
You can configure each group for input or output. The associated xPC
Target driver generates an error in
InitFcn if find_system detects that
two blocks are trying to use the same group of 8 bits for input and output.
See
which is called as mpci8255(1) for the Measurement Computing PCI-DAS
1200 digital input and output blocks. During an update diagram sequence,
Simulink calls the
InitFcn callback function once for each block. Simulink
might call the initialization commands in the mask multiple times.
4-5
4 Masking Drivers
When You Are Done
After you write the driver S-function and create the S-Function block, optional
block mask, and MATLAB file for it, be sure to:
• Check the text of each error message for spelling and appropriateness.
• (Optional) Use a coding standard indentation such as four or eight spaces
with no tabs.
• Copy your new blocks into a custom directory with a unique name.
To enable your new blocks to be viewable in the Simulink Library Browser,
see “Creating a Custom D river” on page 1-11.
• Test the driver f or the following:
- Run the mex commandonthedrivertobuildthedriverforsimulation
- Verify the hardware I/O under as many conditions as possible.
and code generation.
4-6
Sample Driver Mask
The f ol lowing is the b lock mask for t he Diamond MM-32 Analog Input block.
Sample Driver Mask
If you were to create this mask as a new mask, you would:
1 Open the Mask Edito r for the block.
2 Select the Parameters tab and click the Add button on t he left three tim es.
Three blank lines appear in the Dialog parameters section. Fill them in as
follows, starting with the first line:
• In the Prompt column, enter
Channel configuration
First channel number:
4-7
4 Masking Drivers
Number of channels:
Range
Sample time:
Base address (for examp le 0x300):
• In the Variable co lumn, enter the parameter names. Be sure that these
names match the S-function parameters field of the S-Function block.
configuration
firstChan
numChans
range
sampleTime
base
• In the Type column, select:
4-8
popup
edit
edit
popup
edit
edit
• In the Evaluate and Tunable columns, ensure that the first five check
boxes of Evaluate and all the check boxes for Tunable are selected.
Sample Driver Mask
3 Select the Initialization tab. The tab displays the dialog variables you
where maddiamondmm32 references the maddiamondmm32.m file for the
driver.
In this file, you should check the range values of the parameters. Checking
the mask here will catch illegal values early in the build process.
4-9
4 Masking Drivers
This example returns a string to display on the block with the variable
port_label commands with which to label the input and output ports. The
number and content of the
vector
5 Select the Documentation tab. This tab contains three fields, Mask type,
that the user enters in the mask.
port_label commands depend on the channel
Mask description,andMask help.
In the Mask type field, enter the type of driv er. For example:
addiamondmm32
In the Mask description field, enter a description for the d river. For
example:
MM-32
Diamond
Analog Input
In the Mask help field, if you are providing any online documentation to
associate with the Help button, you can call that online documentation
from this field. See “Defining Mask Documentation” in the “Working with
Block Masks” chapter of Simulink User’s G uide for details.
4-10
6 Click OK to save the mask.
After you create the block mask, you can define an
InitFcn callback for the
block. A model calls this callback at the start of model simulation.
1 Right-clicktheblockandselectBlock Properties from the drop-down list.
2 Select the Callback tab from the dialog. From the list, select InitFcn.
Enter MATLAB code in the edit box.
Oneconventionistousethesamefunctionthatisusedatmask
initialization time (for example,
argument that indicates that this is being called at
maddiamondmm32(1)
maddiamondmm32.m), but with a single
InitFcn time.
Sample Driver Mask
At InitFcn time, no variables in the mask exist yet. You cannot pass them
into the
using the
InitFcn. However, in the function, you can get the string values
get_param function. For example:
function [baseDec, maskDisplay, maskDescription] = ...
'Only one Diamond Systems MM-32 A /D block per ...
physical board allowed in a model - each block of ...
this type must have a distinct ISA address.');
end
return
end
4-11
4 Masking Drivers
4-12
Interrupt Support
• “xPC Target Interrupts” on page 5-2
• “Adding Interrupt Support” on page 5-7
• “Hook Function Prototypes — Alphabetical List” on page 5-15
5
5 Interrupt Support
xPC Target Interrupts
In this section...
“Introduction” on page 5-2
“Interrupt Process ing in the xPC Target Environment” on page 5-2
Introduction
If your device supports interrupts, you can use the procedures in this chapter
to add your custom interrupt functions to the xPC Target framework.
Your users can use interrupts in xPC Target applications in one of the
following ways:
• Use the interrupt with the xPC Target Async IRQ Source block to execute a
function-call subsystem when an interrupt occurs.
• Use the interrupt to run the model in place of the timer interrupt, available
through the model Configuration Parameters dialog box in the Real-Time
Workshop > xPC Target options pane.
5-2
Note Although users can use interrupts inoneoftwoways,youprogramfor
these interrupts using the same procedure, as described in “Adding Interrupt
Support” on page 5-7. However, before you start programming the interrupts,
see “Interrupt Processing in the xPC Target Environment” on page 5-2 for a
description of the flow of xPC Target interrupt processing.
Interrupt Processing in the xPC Target Environment
When a model executes, it executes in the following order:
1 Call all mdlStart routines in block execution order.
2 Call the Start function, if one exists.
ow background graphics and network tasks to run until an interrupt
3 All
curs.
oc
xPC Target™ Interrupts
The following illustrates the flow of processing once a hardware interrupt
occurs. This is background information to help you understand the context in
which the interrupt functions run.
5-3
5 Interrupt Support
Interrupt occurs
Call PreHookFunction
(if one exists)
For each device
on this IRQ
No
Did PreHookFunction
return a value of
XPC_RUN_ISR?
Yes
Function
call on
interrupt?
Yes
Async IRQ source block only
(Call interrupt service
function call subsystem;
interrupt preemption
disallowed)
Yes
Call PostHookFunction
(if one exists)
Another
device?
No
Send wakeup to
model thread
5-4
No
Return from interrupt
Model thread executes after return
from interrupt; new interrupts might
preempt
xPC Target™ Interrupts
When a hardware interrupt occurs, the generated code uses the following steps
for each device on this IRQ to determine which device generated the interrupt:
1 Call the PreHook function, if one exists. The return value determines the
action.
2 The generated code determines whether this device generated the interrupt.
• If the
PreHook function returns XPC_RUN_ISR, execution continues to
step 3.
• If the
PreHook function returns XPC_DROP_ISR, the generated code goes
to step 5.
3 The generated code determines whether the Async IRQ Source block has a
function-call subsystem connected.
• If so, the generated code calls the interrupt service function-call
subsystem. When the interrupt service function subsystem returns, the
generatedcodegoestostep4onpage5-5.
• If this board is configured to run the model, and this board did interrupt,
send a wakeup call to the model thread. The model thread does not
immediately execute. It waits until after all the boards that use this IRQ
have been checked and the return from the interrupt has been executed.
4 Call the PostHook function, if one exists. If one does not e xist, the
generated code g oes to step 5.
5 The generated code checks whether a nother device using the same IRQ
exists in the system.
If so, execution returns to the beginning of step 1.
If no other device exists, generated code goes to step 6.
6 Returns from the interrupt.
The xPC Target kernel now runs the highest priority thread. The highest
priority ready thread is the model if a wakeup call was sent to it.
5-5
5 Interrupt Support
Note The Allow preemption of function call subsystem check box has
no effect. Interrupts are never enabled when the function-call subsystem
is executed.
5-6
Adding Interrupt Support
In this section...
“Introduction” on page 5-7
“Guidelines for Creating Interrupt Functions” on page 5-9
“Filling in the Driver board Structure” on page 5-10
Introduction
To add interrupt handling for a custom driver, you must create
• A descriptor file to connect a board type to the functions needed to start,
handle, and stop interrupts
• A C file to implement these functions
Include the following functions. See “Hook Function Prototypes —
Alphabetical List” on page 5-15 for the prototype details.
Adding Interrupt Support
Functio
PreHook
PostHook
n
Descrip
Runs just before either a function-call subsystem
or entire model is called. Program this function to
acknowledge the interrupt and cause the board to
stop issuing the interrupt signal.
Runs after return from function call on interrupt,
and before model execution. It is typically not used.
tion
5-7
5 Interrupt Support
FunctionDescription
Start
Runs as the last item when starting a model, just
before the model runs. It is typically used to turn
on interrupt generation. Program this function to
enable interrupts on the board and start any action.
Stop
Runs at the beginning of a stop request, before any
mdlTerminate entries for any block in the model
runs. It is typically used to turn off interrupt
generation. Program this function to disable
interrupts from the board and stop any action. This
is the first action called, when a target application
stops executing.
Note You mu
them on in t
should ca
To add int
1 Create a
matlabroot\toolbox\rtw\targets\xpc\target\build\
xpcblocks\thirdpartydrivers
st use the
he
Start function. In this way, the stop and start functions
ncel each other.
errupts for your custom driver, use the following general steps:
hook file in the following directory:
Stop function to turn off interrupts if you have turned
5-8
Hook fi
matla
xpc68
2 Name the hook file something like:
3 As necessary, create the interrupt functions the PreHook, PostHook, Start,
Stop functions and add them to the hook file. See “Guidelines for
.
.c). For example, look at files in
,suchas
Creating Interrupt Functions” on page 5-9 for information on how to create
these functions.
Adding Interrupt Support
4 Copy the file sample_int.m toauniquefilenameinthefollowingdirectory:
matlabroot\toolbox\rtw\targets\xpc\target\build\
xpcblocks\thirdpartydrivers
For example:
your_company_name_int.m
The x PC Target software searches in this directory for file names that end
with
_int.m and looks for board interrupt descriptions.
5 Open and edit the following file:
matlabroot\toolbox\rtw\targets\xpc\target\build\
xpcblocks\thirdpartydrivers\
your_company_name_int.m
Addtothisfileaboard structure for each xPC Target supported board for
which interrupt functions have been written. See “Filling in the Driver
board Structure” on page 5-10 for a description of how to fill in a board
structure.
6 Save and close the file.
7 At the MATLAB Command Window, type:
rehash toolbox
8 Restart the MATLAB interface to update the Async IRQ Source block and
Configuration Parameters dialogs.
Guidelines for Creating Interrupt Functions
xPC Target interrupt functions have predefined purposes and typically follow
a particular order. This section describes the guidelines on creating interrupt
functions. See “Hook Function Prototypes — Alphabetical List” on page 5-15
for the prototypes for these functions.
To prepare for the creation of the hook file, examine the existing xPC Target
hook files (
copy and modify one that is the same board type, PCI or ISA, as the board for
which you are creating a custom driver. For example,
an ISA board. Place your new file in
matlabroot\toolbox\rtw\targets\xpc\target\build\src) and
xpc6804hooks.c is for
5-9
5 Interrupt Support
matlabroot\toolbox\rtw\targets\xpc\target\build\
xpcblocks\thirdpartydrivers\
When modifying an existing hook f ile:
• Change the nam es of all of the functions to match those you have selected
for your board.
• Do not change the function signatures.
• Do not remove the
• The
PreHook and PostHook functions run with interrupts disabled. Do not
__cdecl string.
change the interrupt status in these functions.
When writing the interrupt functions, note the following:
• When an interrupt occurs, the kernel calls the
PreHook function.
Note This function is run with interrupts disabled. If this function cannot
turn off the interrupt, an infinite loop will occur because the interrupt
service routine (ISR) will continuously call the
PreHook function.
• Because the PostHook function has limited use, you most likely do not need
to define this function. Set this function to
• The generated code calls the
Start function during the startup phase of
model execution as the last action, after the model has called all
'NULL' if you do not need it.
mdlStart
routines.
This function is typically used to enable interrupts from the board. The
target application is ready to accept interrupts a few microseconds after
this function is called. Do not try to enable interrupts from the board
mdlStart function.
5-10
• When a target application stops executing, the generated code calls the
Stop function first. Disable interrupts from the board in this function.
Filling in the Driver board Structure
This section describes how to fill in a driver board structure, element by
element.
Adding Interrupt Support
• Depending on the bus type of your board, select a board structure of an
existing board that has the same bus type. The information passed to the
functions is slightly different for an ISA board or a PCI board. You will use
this structure as a template for your own board entry. The following is a
structure for an ISA or PC/104 device:
• name — Enter an appropriate board name string. The xPC Target
software uses this string to populate the drop-down list for the I/O boardgenerating the interrupt parameter in the following:
- Async IRQ Source block
- PCI slot (-1: autosearch) or ISA base address parameter in the
xPC Target Options section of the model Co n figuration Parameters
dialog box
•
VendorId, DeviceId, SubVendorId, SubDeviceId — Enter the appropriate
ID strings. If you have a PCI board, the board manufacturer identifies
5-11
5 Interrupt Support
that board with either two or four ID values, depending on the specific
hardware. When calling the hook functions, the xPC Target kernel obtains
thePCIinformationfortheboardandpassesittothehookfunctions. Use
these parameters to help identify the interrupting board.
- For VendorId and DeviceId, enter the IDs you get from the board
manufacturer.
- Many boards do not have SubVendorId and SubDeviceId values. In
these cases, i nsert the value
from checking for them.
If you have an ISA bo ard, it does not have a vendor or device ID; instead,
the generated code will insert the ISA base address in the first base address
entry of the PCI structure. To indicate to the kernel that this is an ISA
board, set
If you do not need hook functions:
VendorId to -1 and DeviceId to 1.
-1 to prevent The xPC Target software
- Set VendorId to -1 and DeviceId to -1.
- Set Fnc and PostHookFcn to 'NULL'.
5-12
- Set StartFunction and StopFunction to 'NULL'.
The Async IRQ Source b lo ck will s ti ll call the subsystem when an interrupt
occurs.
The following table summarizes your options for this element:
VendorId DeviceId
+ID+ID
-1+1
-1-1
• Enter the names of the interrupt functions. See “Hook Function Prototypes
— Alphabetical List” on page 5-15 for the prototype details.
Usage
PCI board
ISA board
Special case: If the driver does not need hook
functions. The driver can still use the Async IRQ
Source block. As an example, see the source code
for the serial communication driver.
- PreHookFunct ion
Prototype:
int __cdecl your_ company_name_boardPreHook(xpcPCIDevice *pciInfo);
If any of these four functions does not need to exist, set the corresponding
board structure entry to ' NULL' to prevent calls to that function in that
context.
Note The differences between hook functions for PCI and ISA devices are:
- PCI devices — A hook function for a PCI device has all fields of the
xpcPCIDevice structure filled in except the VirtAddress field. To get
the virtual address for a physical memory, in the
the
xpcReserveMemoryRegion function and save the resulting virtual
address in the
pointer to the same instance of this structure is passed to all four
functions. This action makes data, such as virtual addresses, available
to all functions.
VirtAddress field of the xpcPCIDevice structure. A
Start function, call
- ISA devices — A hook function for an ISA device has the base I/O
address entered in the first physical address. No other fields in the
xpcPCIDevice structure are filled in.
5-13
5 Interrupt Support
• HookIncludeFile — Interrupt handling file that contains the
Descriptionyour_company_name_boardStop runs before the mdlTerminate function
of the blocks i n the model. It is typically used to turn off interrupt
generation.
See AlsoxpcPCIDevice
5-19
your_company_name_boardStop
5-20
6
Custom xPC Target Driver
Notes
• “S-Function Guidelines” on page 6-2
• “mdlStart and mdlTerminate Considerations” on page 6-4
• “DMA Considerations” on page 6-5
• “Passing Parameters” on page 6-6
• “Accessing Registers” on page 6-7
6 Custom xPC Target™ Driver Notes
S-Function Guidelines
You implement xPC Target device driver blocks using Simulink S-functions.
An S-function is a set of subroutines that implements a function. On the host,
youcanwriteanS-functioninMATLABcode,C,orFortran. ForxPCTarget
device drivers, you must write an S-function in C.
Simulink S-functions have a number of callback methods. For xPC Target
drivers, you typically need to write C code for the following callback methods:
Method
mdlInitializeSizes
mdlInitializeSampleTimes
mdlStart
mdlOutputs
mdlTerminate
After you create the S-function, createamaskforit.SeeChapter4,“Masking
Drivers”. Also, refer to the Simulink documentation (in particular, DevelopingS-Functions).
Of particular note when writing S-functions:
• Keep track of the input parameters the driver will require. When you
create a mask for the driver, you will need to know this.
• Work vectors are not shared between runs. All S-function work variables
are cleared after calling
S-function calls
• Declare all memory-mapped registers as
Description
Initializes the S-function with the number of inputs, outputs,
states, parameters, and other characteristics.
Initializes the sample rates of the S-function.
Initializes the state vectors of this S-function. It also initializes
hardware as necessary.
Computes the signals that this block emits.
Performs any actions required at termination of the simulation.
mdlTerminate. This implies that each time the
mdlStart, you must reinitialize all work variables.
volatile.
6-2
• An S-function is compiled into a M EX-file to run as part of the simulated
model on the host PC. During code generation, the S-function calls the
mdlInitializeSizes and mdlInitializeSampleTimes functions to
determine the data structures that are used on the target. The same C-file
S-Function Guidelines
is also compiled with your application to run on the target PC. Because of
the following reasons, you must conditionally compile code for the host
PC and the target PC.
- The host PC runs Windows and the target PC runs the xPC Target
kernel.
- The host PC does not have the same I/O hardware as the target PC.
The preprocessor symbol
for simulation (via
Target environment. Use this s ymbol to conditionally compile host PC or
target PC specific code. For example:
#ifdef MATLAB_MEX_FILE /* host/simulation */
/* simulation code, typic ally nothing */
#else /* target */
/* code to access I/O board */
# endif
IfyouwantthecodetorunonboththehostandtargetPCs,donot
conditionalize the code.
• Include the
This provides definitions for the functions exported by the xPC Target
kernel. The xPC Target kernel exports a number of functions for use in
device drivers.
See “mdlStart and mdlTerminate Consi de rations” on page 6-4 for notes on
specific applications of the callback methods.
xpctarget.h file in your S-function.
MATLAB_MEX_FILE is defin e d when you compile
mex). Undefine this symbol when compiling for the xPC
6-3
6 Custom xPC Target™ Driver Notes
mdlStart and mdlTerminate Considerations
When you load a target application onto a target PC, the driver executes the
mdlStart callback m ethod. If the execution is successful, the driver then
executes
If
mdlStart does not successfully complete, the application does not execute
mdlTerminate.(Typically,mdlStart might not successfully complete if
the application cannot find a referenced I/O board or if the board does not
successfully initialize.)
mdlTerminate.
When the target application does start, it executes
repeatedly executes
the application calls the
With the above considerations, write
they cancel each other out. Ensure that
resources that you allocated in
to high in
mdlStart, reset it to the default level in mdlTerminate.(Failure
mdlOutputs. At the end of target application execution,
mdlTerminate function.
mdlStart and mdlTerminate so that
mdlTerminate deallocates any
mdlStart. For example, if you set an output
mdlStart again, then
to reset the output causes a high output before the application starts.) As
another example, if, in the mdlStart function, you allocate memory, have
mdlTerminate free the memory.
Although this description distinguishes between the driver initia l iza tio n and
application start phases, you do not nee d to actually differentiate betw een
them. If you do need to do so, use the
returns
1 while the model is initializing, and 0 otherwise.
xpcIsModelInit function. This function
6-4
DMA Considerations
If your board directly accesses system RAM, such as a DMA controller, you
must allocate that memory using the
This function allocates the buffer such that the buffer v irtual address is the
same as its physical address.
DMA Considerations
xpcAllocPhysicalMemory function.
6-5
6 Custom xPC Target™ Driver Notes
Passing Parameters
See “Passing Parameters to S-Functions” in Developing S-Functions.
6-6
Accessing Registers
In this section...
“I/O Space” on page 6-7
“Memory-Mapped Space” on page 6-7
I/O Space
For registers in I/O space, use the xPC Target I/O read and write functions:
• Read functions
uint32_T xpcInpDW(uint16_T port );// read a 32 bit word
uint16_T xpcInpW(uint16_T port );// read a 16 bit word
uint8_TxpcInpB(uint16_T port );// read an 8 bit byte
Accessing Registers
• Write fun
void xpc
void xpc
void xpc
ctions
OutpDW(uint16_T port, uint32_T value ); // write 32 bits
OutpW(uint16_T port, uint16_T value ); // write 16 bits
OutpB(uint8_T port, uint8_T value ); // write a byte
For registers in memory-mapped space, access them by dereferencing
through a pointer that contains the virtual address returned by the
xpcReserveMemoryRegion function. Because modern compilers have
aggressive optimizers, you must declare the pointer to be volatile. Doing
so ensures that the compiler does not optimize out reads and writes using
that pointer. The following pseudocode illustrates this using two methods:
structure and array.
6-7
6 Custom xPC Target™ Driver Notes
• Structure
struct bdregs {
};
If your hardware uses registers with different lengths, it might be easier to
use the structure method.
• Array
#define REG10
#define REG21
etc.
volatile int reg1;
volatile int reg2;
etc.
struct bdregs *regs = pciInfo.Virtua lAddress[1];
regs->reg1 = 0x1234;// Sets reg1 to that value
regs->reg2 = 0x56789abc;
etc.
• “Generating Custom Driver Templates” on page 7-4
7
7 Creating Custom Drivers Using the xPC Target™ Drive r Authoring Tool
xPC Target Driver Authoring Tool
xPC Target Driver Authoring Tool helps you create templates for simple
custom device drivers. A simple custom device driver is one that does not
perform DMA or interrupt processing. The xPC Target Driver Authoring Tool
is not useful for these more complicated applications.
Based on the inputs you provide to xPC Target Driver Authoring Tool, it can
create a number of files, including the following. Of these files, you need to edit
only the source C code file. You can also optionally edit the block mask file.
File
driver_name.c
driver_name.h
sfcn_driver_name.c
sfcn_dr
driv
sfcn_driver_name.mexw32
iver_name.tlc
er_block_name.mdl
Description
Template for the source C code for driver. You
need to enter your C code.
Header file for driver.
S-function file for driver. This file contains
S-function callback methods and options for
the driver.
Optiona
generat
only if
See “In
1-10 for f
Drive
wheth
Optio
Afte
crea
bloc
Simu
fil
box
Optional. If you requested the creation of a C
MEX file, the tool generates one for you.
l. Real-Time Workshop TLC code
ion file. You typically need a
youwanttoinlineyourcustomdriver.
lining xPC Target Drivers” on page
urther information. The xPC Target
r Authoring Tool creates this file for you
er or not you want to inline the driver.
nal. Blockmaskmodelfilefordriver.
r the xPC Target D river Authoring Tool
tes the supporting files, it creates the
kmaskforthedriveranddisplaysitinthe
link model window. The tool creates this
eonlyifyouselecttheMEX C file check
.
.tlc file
7-2
xPC Target™ Driver Authoring Tool
Note The xPC Target Driver Autho ring Tool creates custom driver templates
using the Legacy Code Tool (LCT). You do not need any prior knowledge of the
Legacy Code Tool to use the xPC T arget Driver Authoring Tool. If you want to
read about the Legacy Code Tool, see “Integrating Existing C Functions into
Simulink Models with the Legacy Code Tool” in Developing S-Functions.
7-3
7 Creating Custom Drivers Using the xPC Target™ Drive r Authoring Tool
Generating Custom Driver Templates
In this section...
“Using the xPC Target Driver Authoring Tool” on page 7-4
“Setting Up Driver Variables” on page 7-4
“Saving the Configuration” on page 7-7
“Reloading the Configuration” on page 7-8
“Creating the C File Template” on page 7-8
“Creating a C MEX File for the Driver” on page 7-8
“Customizing the Device Driver Mask” on page 7-9
Using the xPC Target Driver Authoring Tool
The prerequisites for creating a custom xPC Target device driver using the
xPC Target Driver Authoring Tool are the same as those for creating a device
driver manually. See “Expected Background” on page 1-3 and “Before You
Start” on page 1-8 for further information.
7-4
The following sections assume that you have identified the following
component specifications for the driver. See “Before You Start” on page 1-8
for guidelines for the following driver components, including their data type
and size:
Input ports
Output ports
Parameters
Work variables
Setting Up Driver Variables
1 In the MATLAB Command Window, change directory to the one in which
you want to save the driver code.
2 Start xPC Target Driver Authoring Tool. Type
xpcdrivertool
The xPC Target Driver A uthoring Tool is displayed.
Generating Custom Driver Templates
3 In the Main tab, enter:
• Driver name — The name for your driver. The tool will cre ate supporting
files using this string as the prefix. For example, type
testdriver.
• Sample time — Select one of the following:
Mask parameter — If you want the block sample time to be settable
–
as a block dialog box parameter (Sample Time).
–
Inherited — If you want the block to inh erit its sample time from
a connected block. No Sample Time parameter is displayed in the
block dialog box.
4 If you have input ports for the block, click the Input Ports tab.
The Inport Ports tab is displayed.
5 Click the Add button. Enter your input port information in the following
fields. Repeat as necessary for your defined input ports.
• Variable —Enterthenameoftheinput. Forexample,
speed.
7-5
7 Creating Custom Drivers Using the xPC Target™ Drive r Authoring Tool
• Size — Enter the maximum size number of storage locations to b e
allocated for the parameter. If you want this number to b e a variable one,
enter a value of 0. This setting means that you can pass an additional
function argument that contains the size into the start, output, and/or
terminate functions along with the port/parameter variable.
• Type — From the list, select the data type for the input port.
• Output — This check box is always selected. It ensures that the input
portvaluewillbepassedintotheS-function
method.
6 If you have o utput ports for the block, click the Output Ports tab.
The Output Ports tab is displayed.
7 Click the Add button. Enter your output port information in the following
fields. Repeat as necessary for your defined output ports.
mdlOutputs callback
• Variable — Enter the name of the output. For example,
speed.
• Size — Enter the maximum size number of storage locations to b e
allocated for the size.
• Type — From the list, select the data type for the output port.
• Output — This check box is always selected. It ensures that the output
portvaluewillbepassedintotheS-function
mdlOutputs callback
method.
8 If you have parameters for the block, click the Parameters tab.
The Parameters tab is displayed.
9 Click the Add button. Enter your parameter info rm ation in the following
fields. Repeat as necessary for your defined parameters.
• Type — From the list, select the data type for the parameter.
• Size — Enter the maximum size number of storage locations to b e
allocated for the parameter. If you want this number to be a variable
one, enter a value of 0. This means that you can pass an additional
7-6
Generating Custom Driver Templates
function argument that contains the size into the start, output and/or
terminate functions along with the port/parameter variable.
• Start — Select the check b ox if you want the parameter value to be
passed into the S-function
mdlStart callback method.
• Output — Se lect the check box if yo u want the parameter value to be
passed into the S-function
mdlOutputs callback method.
• Terminate — Select the check box if you want the parameter value to
be passed into the S-function
10 If you h ave work varia bles to be shared between the start, output, and
mdlTerminate callback method.
terminate routines for the block, click the Work Variables tab.
The Work Variables tab is displayed.
11 Click the Add button. Enter your work variables information in the
following fields. Repeat as necessary for your defined parameters.
• Variable — Enter the name of the work variable. For ex ample,
speed.
• Type — From the list, select the data type for the work variable.
• Size — Enter the maximum size of the work variable.
• Start — Select the check box if you want the work variable value to be
passed into the S-function
mdlStart callback method.
• Output — Select the check box if you want the work variable value to be
passed into the S-function
mdlOutputs callback method.
• Terminate — Select the check box if you want the work variable value
to be passed into the S-function
mdlTerminate callback method.
Saving the Configuration
The xPC Target Driver Authoring Tool allows you to save your configuration
session as a MAT-file.
1 In the xPC Target Driver Authoring T ool, click the Main tab.
2 Click Save settings.
The tool saves the
testdriver.mat file in the current working directory.
7-7
7 Creating Custom Drivers Using the xPC Target™ Drive r Authoring Tool
You can iteratively change the configuration and resave the MAT-file as often
as you like.
Reloading the Configuration
The xPC Target Driver Authoring Tool allows you to reload your configuration
session as a MAT-file.
1 In the xPC Target Driver Authoring T ool, click the Main tab.
2 Click Load settings.
The tool loads the
testdriver.mat file into the tool.
Creating the C File Template
To generate a template for the d river C source code file:
1 In the xPC Target Driver Authoring T ool, click the Main tab.
2 Select Generate C file template.
3 Click the Build button.
The tool creates the following files:
•
testdriver.c
• testdriver.h
• sfcn_testdriver.c
• sfcn_testdriver.tlc
4 With your favorite editor, open the testdriver .c file and edit i t. This is the
source C code for your driver. The S-function code in
will reference this C file.
sfcn_testdriver.c
Creating a C MEX File for the Driver
To create a C MEX file for the driver, you can use either the xPC Target
Driver Authoring Tool or the
mex function.
7-8
Generating Custom Driver Templates
Note Use the xPC Target Driver Authoring Tool to build the C Mex file if
you have not edited the C source code file (
testdriver.c). If you h a ve edited
thisfileandwanttokeepthosechanges, do not use the xPC Target Driver
Authoring Tool to build the driver. Doing so overwrites your changes to the
C source code. Instead, use the
mex function (see “Creating a C MEX File
UsingthemexFunction”onpage7-9).
Creating a C MEX File Using the xPC Target Authoring Tool
1 In the xPC Target Driver Authoring T ool, click the Main tab.
2 Select Generate block and mask.
3 Click the Build button.
Thetoolcreatesthefile
sfcn_testdriver.mexw32.
Creating a C MEX File Using the mex Function
1 In the MATLAB Command Window, change directory to the one that
contains the driver files.
2 Compile and link the MEX-file. For example:
mex sfcn_testdriver.c testdriver.c
This function creates the sfcn_testdriver.win32mex file.
Customizing the Device Driver Mask
The xPC Target Driver Authoring Tool creates a mask for the device driver.
You can customize this block mask as described in Chapter 4, “Masking
Drivers”. If you customize the mask, do not use the xPC Target Driv er
Authoring Tool again to build your files . Doing so overwrites the driver files
and you will lose your mask customizations.
7-9
7 Creating Custom Drivers Using the xPC Target™ Drive r Authoring Tool
7-10
I/OStructures—B y
Category
8
xpcPCIDevice
xpcTime
Type definition for PCI configuration
space structure
Type definition of time structure
8 I/O Structures — By Category
8-2
I/OStructures—
Alphabetical List
9
xpcPCIDevice
PurposeType definition for PCI configuration space structure
Physical base addresses that are assigned
by the PCI BIOS.
Virtual address of device. As
necessary, enter the return value
from
xpcReserveMemoryRegion.See
“Description” on page 9-3 for details.
Length of each region. This value contains
the number of b ytes that the board segment
responds to during the configuration space
read. This value might be larger than the
space required by the registers as specified
in the hardware manufacturer manua l.
9-2
xpcPCIDevice
AddressSpaceIndicator
MemoryType
Prefetchable
InterruptLine
VendorId
DeviceId
SubDeviceId
SubVendorId
Indicates whether the b oard is I/O port
mapped or memory-mapped. Values are
one of t h e following. Verify this value in
the hardware manufacturer manual for
accuracy.
0
1
Memory-mapped
I/O port mapped
Type of memory. This field is relevant only
AddressSpaceIndicator has a value of 0.
if
0
Located anywhere in the 32-bit
address space
1
2
Located below 1 MB
Located anywhere in the 64-bit
address space
Indicates whether or not the memory is
prefetchable. Typically, this field is not
required.
Contains the assigned interrupt line,
values between 0 and 15. The BIOS assigns
this value. You need this value only if you
are writing an interrupt driver.
Contains vendor ID.
Contains device ID.
Contains subdevice ID.
Contains subvendor ID.
DescriptionThe xpcPCIDevice structure defines the PCI configuration space
structure. The following are additional notes on the
• The PCI specification allows the definition of up to six different base
addresses (addressable regions). Most boards respond to one or two
BaseAddress field:
9-3
xpcPCIDevice
of these addresses. Base addresses are filled in during the BIOS
plug and play initialization, before the xPC Target kernel starts to
execute. The hardware designer of the board decides how many
address spaces are defined and what they are used for. Many boards
use one address space to contain all of the registers for the board,
other boards separate functions into different address spaces. See
the board hardware manufacturer manual for this information.
• For memory-mapped segments, call the
function to convert the physical address in BaseAddress to a virtual
address that is suitable for the CPU to read and w rite the segment.
You can then optionally save this address in the
You might want to save the address if you have several segments and
you want to pass them all to a board access library.
xpcReserveMemoryRegion
See AlsoxpcGetPCIDeviceInfo, xpcShowPCIDeviceInfo
VirtAddress field.
9-4
PurposeType definition of time structure
Prototypetypedef struct xpcTime64Struct{
uint32_T NanoSecondsLo;
uint32_T NanoSecondsHi;
} xpcTime64;
typedef union xpcTimeStruct{
xpcTime64 U64;
//uint64_T NanoSeconds;
} xpcTime;
xpcTime
Header
xpctarget.h
File
Members
U64.NanoSecondsLo
U64.NanoSecondsHi
Bottom 32 bits of 64-bit value.
Top 32 bits of 64-bit value.
DescriptionThe xPCTime structure holds the time value in nanoseconds, as a 64-bit
integer.
32 bits, respectively. The
functions use this structure to return time values.
NanoSecondsLo and NanoSecondsHi hold the lower and upper
xpcGetElapsedTime and xpcSubtractTime
See AlsoxpcGetElapsedTime, xpcSubtractTime
9-5
xpcTime
9-6
I/OFunctions—By
Category
Port I/O (p. 10-2)I/O port input and output functions