Professional Documents
Culture Documents
© Copyright 2007 Georgia Institute of Technology and James O. Hamblen, Portions © Copyright 2006 Microsoft Corporation, reprinted with permission from Microsoft Corporation. ActiveSync, ActiveX, Developer
Studio, DirectX, Microsoft, MS-DOS, Visual Basic, Visual C++, Visual C#, Visual Studio, Wind32, Windows, Windows NT, Windows XP, and Windows Server are either registered trademarks or trademarks of
Microsoft Corporation in the United States and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners. Microsoft Windows Embedded CE source
code is reprinted with permission from Microsoft Corporation.
Chapter 1: Introduction to
Embedded Systems
1
What is an Embedded System?
2
Product: Sonicare Elite
toothbrush.
Microprocessor: 8-bit
Has a programmable
speed control, timer,
and charge gauge
Product: Any PC
Mouse, Keyboard,
or USB Device
Microprocessor:
8-bit
Microcontroller
Inside view of a Microsoft Mouse
3
Product: Any Disk
Drive
Microprocessor: Dual
32-bit Marvel ARM
SOC & mixed signal
DSP
Product: Any
Printer
Microprocessor:
Intel, Motorola, or
ARM 32-bit RISC
4
Product:Vendo Vue
40 vending
machine.
Microprocessor:
Two 16-bit Hitachi
H8/300H
Processors
A robot hand
dispenses items
Product: Creative
Labs Zen Vision:M
Video & MP3 Player.
Microprocessor: TI
TMS320 DSP
5
Product: Cannon EOS
30D Digital Camera
Microprocessor: DIGIC II
Image Processor
Microprocessor:
Radiation Hardened
20Mhz PowerPC
Commercial Real-time OS
6
Product: Sony Aibo
ERS-7 Robotic Dog.
Microprocessor:
64-bit MIPS R7000.
OS: Aperios -
Sony’s Real Time
OS
Used in Robocup
Soccer Teams
Product: Radiant
Systems Point-of-Sale
(POS) Terminal
Microprocessor:
Intel X86 Celeron
OS: Windows XP
Embedded
7
Product: High End
Systems DL2 Digital Media
Server
Microprocessor: X86
OS: Windows XP
Embedded
Used for lighting effects in
shows and rock concerts
Product: Microsoft’s
Smart Personal Object
Technology (SPOT)
watch
Microprocessor: 32-bit
ARM with FM Radio
Chip
8
Product: Agilent
Oscilloscope
Microprocessor:
X86
OS: Windows XP
Product: Tektronix
Logic Analyzer
Microprocessor:
X86
OS: Windows XP
9
Product: Kuka
Industrial Robot
Arm
Microprocessor:
X86
OS: Windows CE
OS & Others
Kuka robot arms welding a Mercedes
Product: Pavion
Portable GPS
Navigation &
Multimedia System
Microprocessor:
ARM , DSP
OS: Windows CE
10
Product: HP iPAQ
Pocket PC
Microprocessor:
Marvel XSCALE
(ARM)
OS: Windows CE
Product: Motorola Q
Pocket PC Phone
Microprocessor:
TI OMAP (ARM+DSP)
11
Product: HP iPAQ
Pocket PC Phone
Microprocessor:
TI OMAP (ARM+DSP)
OS: Windows CE
Microprocessor: X86
OS: Windows CE
12
Product: Dresser Wayne
Ovation iX Gas Pump
Microprocessor:
Marvel Xscale (ARM)
OS: Windows CE
Product: Bernina
Artista 200 Sewing
Machine
Microprocessor:
Marvel StrongARM
OS: Windows CE
13
Product: LG VoIP
Phone
Microprocessor:
Freescale i.MX21
ARM
OS: Windows CE
Microprocessor: Marvel
400Mhz Xscale
14
Product: ICOP eBox
2300 System on a Chip
(SoC) PC
4.5 x 4.5 x 1.5 inches
Microprocessor:
200Mhz Vortex86 (X86)
OS: Windows CE
Low-cost CE target
board for student
projects
15
Examples of Embedded Systems - Continued
16
Importance of Embedded Systems
17
Real-Time System
• A real-time system responds to events.
External Process External
Input Event New Data Output Event
Real-Time System
• A real-time system must respond to external
inputs and produce new outputs in a limited
amount of time.
• The response time needs to be bounded.
Response times that are too long cause real-time
systems to fail.
• General purpose desktop Operating Systems are
not designed for real-time use
• Real-time Operating Systems need to be initially
designed for real-time use in order to provide fast
bounded response times
18
Hard & Soft Real-Time Systems
• Soft Real-Time System
– Critical tasks get priority. Normally meets the real-time response
constraint.
– Example: A Multimedia Player could skip a video frame or audio
sample occasionally and a user might not notice.
• Hard Real-Time System
– A new output response must be computed by the specified time
bound or the system will fail.
– Examples: In an aircraft flight control system when the pilot moves
the control yoke, the flight control surfaces need to move quickly
in response or the aircraft could crash.
– Virtual memory page swapping and garbage collection routines
needed for object oriented languages can cause problems in Hard
Real-Time systems
19
Product: TMIO
ConnectIO Oven
OS: Windows CE
20
Why have an OS in an embedded device?
Example:
A recent cell phone design contained over
five million lines of code!
• Few, if any projects will have the time and funding
needed to develop all of this code on their own!
• Typical Embedded OS license fees are a few dollars
per device – less than a desktop OS
• Some very simple low-end devices might not need an
OS – but new devices are getting more complex
21
Memory in an embedded device
• Need both volatile and non-volatile memory
• Flash memory frequently used instead of Disks
– Less power, smaller, and more reliable
• Store OS and applications in Flash memory
• Boot from Flash Memory at power up
• Flash is very slow compared to RAM
– Copy code to SRAM or SDRAM to execute?
• Need development tools that support code
storage and execution in ROM
22
What is actually being used in
New Embedded Designs?
• What Types of Processors are used?
• What Operating Systems are used?
• What Programming Languages are used?
• Will examine data from a 2006 Market
Survey of design engineers by EETimes
and Embedded Systems Design Magazine
64-bit
32-bit
16-bit
8-bit
4-bit
Data was derived from EETimes and Embedded Systems Design Magazine 2006 Embedded Market Survey
23
Processor Architectures Widely
Used in New Embedded Designs
• ARM
• X86
• PowerPC
• MIPS
• Xscale (ARM)
• Renesas SuperH
ARM
X86
MIPS
SuperH
PowerPC
24
Processor Selection Issues
• Software Support
– OS, Compilers, Debug Tools, Applications
• Price
• Performance
• Power
– Battery Life (MIPS/Watt), Cooling (Fan?)
• Desktop PC 100 W vs. Battery power 200 mw
• Availability
– Long term availability, Multiple Vendors?
ARM Processors
• 32-bit RISC low-power design from an English IP
company, ARM ltd (Advanced RISC Machines)
http://www.arm.com/
• ARM’s processor designs are licensed to over 100 chip
manufacturers. ARM does not make chips.
• Used in many devices such as Cellphones, iPod Nano,
Cameras, Handheld Games, HDTVs, and Set-Top boxes.
80% of ARM processors are in phones
• Good performance/power makes it a very popular choice
in low power and battery operated devices.
• ARM’s thumb instruction subset is coded into 16-bits and
decompressed on-the-fly to full 32-bit instructions. Can
switch from 16-bit to 32-bit instructions on the sub-routine
level.
25
X86 (IA-32) Processors
• Based on the Intel X86 CISC instruction set used in
processors in PCs since the mid 1980s
• Low cost due to widespread use in PC technology
• Processors and support chips are available from multiple
vendors
• A wide processor performance range is available
• Most X86 processors for desktop PCs have been
optimized for performance and not low power
• The major desktop PC processor vendors (Intel, AMD)
are moving on to newer designs and 64-bit architectures –
but other manufacturers are making X86 processors for
embedded devices
1 Processor
2 Processors
3-5 Processors
More Than 5
Data was derived from EETimes and Embedded Systems Design Magazine 2006 Embedded Market Survey
26
Use of Real-Time OS Kernels
in New Embedded Designs
Commercial OS
None
Internally Developed
Open Source
0.00% 5.00% 10.00% 15.00% 20.00% 25.00% 30.00% 35.00% 40.00% 45.00%
Data was derived from EETimes and Embedded Systems Design Magazine 2006 Embedded Market Survey
27
Commercial Operating Systems
used in New Embedded Designs
Microsoft Emb.
Wind River
Symbian
Green Hills
Palm
Others
Data was derived from EETimes and Embedded Systems Design Magazine 2006 Embedded Market Survey
C++
C#
Java
Assembly
Others
28
Conclusions
Figure 1.10 The Embedded device product life cycle phases, Design, Development, and Production.
29
Embedded System Design Cycle
• Short Product Development Cycle – 6 to
12 months (and getting shorter!)
• Software and Hardware must be designed
in parallel
• Software run on emulator or similar board
until final hardware becomes available
• Production may be offshore
Main Flash
Processor Memory Memory
(SDRAM or (non-volatile
SRAM) storage)
Figure 1.11 Most Embedded systems use two types of memory. SDRAM for main memory and Flash
memory instead of a hard disk to store the OS and application programs.
30
Chapter 2: Introduction to
Embedded System I/O
Architectures
System Bus
31
A First Generation Bus Example: ISA
A3
Address
A2 Decoder
A1 Output
A0
32
Tri-state logic gate outputs
are used to drive most bus signals
tri-state
control input output control
0 0 High Z input
0 1 High Z
1 0 0
1 1 1 input output
Hardware allows only one tri-state gate at a time to drive a bus signal!
Original PC design only decoded low 10 I/O address bits to save hardware
33
An Example ISA Bus I/O Write Operation
Bus Clock
I/O Write
Bus Clock
Valid Address
Address
I/O Read
34
Typical I/O Input Port
Hardware Operation
One tri-state
gate is needed
for each bit on
the data bus
R
Address e
Address Bus Decoder g
Circuit Data Bus i Data out to
s I/O Device
t
e
r
35
Options for Building Custom I/O ICs
36
Software for I/O port transfers
Problems: Does not port to other processors and many people do not
understand assembly language!
37
Windows CE C/C++
I/O Port R/W Functions
• READ_PORT_UCHAR(I/O_Address)
– Returns 8-bit input value from port
• WRITE_PORT_UCHAR(I/O_Address,I/O_Data)
– Sends 8-bit data value to output port
• Found in CE Device Driver Kit (CEDDK)
• Need to link to CEDDK.lib library and include
CEDDK.h – modify sources file for this
• Typically used in low-level device drivers
38
PCI Bus Commands (C/BE)
PCI Bus Command C/BE
Interrupt Acknowledge 0000
Special Cycle 0001
I/O Read 0010
I/O Write 0011
Reserved 0100
Reserved 0101
Memory Read 0110
Memory Write 0111
Reserved 1000
Reserved 1001
Configuration Read 1010
Configuration Write 1011
Memory Read Multiple 1100
Dual Address Cycle 1101
Memory Read Line 1110
Memory Write and Invalidate 1111
Bus Clock
F rame #
IRDY#
TRDY#
DEVSEL#
Bus Transaction
39
PCI Read Burst Cycle
Clock Cycle Description of PCI operation
0 Bus is idle
1 The initiator sets FRAME low, places the address on the Address/Data (ADx) lines,
and the bus command (read) on the Command/Byte Enable (C/BE) lines (address
phase).
2 The initiator tri-states the address and waits for the target to return a data value by
turning on its tri-state drivers. Device Select (DEVSEL) low indicates a target
device has decoded its address range and it is responding to the command. The
target drives TRDY high to indicate the target needs another clock cycle to respond
with the data.(data phase)
3 The target drives the data value and sets target ready (TRDY) low to indicate that
data is valid. When both IRDY and TRDY are low a data transfer occurs.
4 The target sets TRDY high to indicate it need an additional clock cycle for the next
data transfer.
5 The second data transfer occurs when both TRDY and IRDY are low. The initiator
saves the target data.
6 The target drives the data value, but the initiator requests an additional clock cycle
by set IRDY high.
7 The initiator sets IRDY low to complete the third data transfer. The initiator saves
the target data value, The initiator drives FRAME high to end the data phase.
8 All bus signals are tri-stated or driven to the inactive state.
Bus Clock
F rame #
IRDY#
TRDY#
DEVSEL#
Bus Transaction
40
PCI Write Burst Cycle
Clock Cycle Description of PCI operation
0 Bus is idle
1 The initiator sets FRAME low, places the address on the Address/Data (ADx) lines, and
the bus command (write) on the Command/Byte Enable (C/BE) lines (address phase).
2 The initiator places the data on the ADx lines and byte enables on C/BE lines, Device
Select (DEVSEL) low indicates a target device has decoded it’s address range and it is
responding to the command. When both IRDY and TRDY are low the target saves the
data. (data phase)
3 The initiator drives new data and byte enables. When both initiator ready IRDY and
TRDY are low a data transfer occurs and the target saves the data.
4 The initiator sets IRDY high and the target sets TRDY requesting an additional clock
cycle.
5 The initiator drives new data and byte enables and sets IRDY low. The initiator sets
FRAME high indicating the final data transfer.
6 The target drives the data value, but the initiator requests an additional clock cycle by
set IRDY high.
7 The initiator sets IRDY low to complete the third data transfer. The target saves the data
value.
8 All bus signals are tri-stated or driven to the inactive state.
41
Software for PCI devices
• Each PCI device has a 256 byte
configuration area
• At power up each device can respond with
manufacturer and device type information
• Allows system to locate and load device
drivers at power up
• Memory and I/O base addresses are
configured with software (no jumpers)
42
Vortex86-based Embedded PC
Hardware Block Diagram
Vortex86 Architecture
• Contains Northbridge and Southbridge chips on
the processor chip
• Northbridge connects to processor, memory and
provides PCI bus
• Southbridge and Ethernet devices connect to
PCI bus
• Southbridge provides Low Pin Count (LPC) bus
• ISA bus bridge for PC 104
• Super IO chip provides legacy PC IO interfaces
43
I/O Transfers
• I/O devices are orders of magnitude slower than a
Processor. Handshake lines are used to synchronize each
transfer.
• I/O device sets a hardware handshake line when it is ready
to transfer data. (input ready, output ready)
• Before any data transfer, the Processor must check that the
I/O device is ready by reading the device’s handshake line.
• Handshake line bits are connected to another I/O port
(status port). Typically the next I/O address after the I/O
data port.
• When the Processor reads or writes the data port, the
handshake line is usually reset in hardware.
44
Programmed I/O
• Processor must read and check I/O ready
bits for proper value before a transfer.
Requires looping, reading status port, and
constantly waiting for correct value.
• Processor then inputs or outputs data
value to/from I/O device.
• This approach is limited to systems with
just a few I/O devices
– Processor overhead to loop and check in software
45
Interrupts
• I/O ready signals generate a hardware Interrupt
signal. Eliminates Processor I/O ready wait
loops.
• An interrupt signal stops the Processor at the
next instruction and the Processor calls the
Interrupt service routine (ISR)
• Interrupt service routine transfers the data
• Interrupt routines must save all registers on the
stack for the interrupt return to work (ISRs like
subroutines - but “called” by a hardware signal)
Interrupts
• Interrupt control hardware is needed to support
and enable/disable multiple interrupt signals
• Lower number interrupts typically have a higher
priority (can even interrupt a higher number
interrupt’s ISR) Gives fast I/O devices priority.
• Most modern processors have a vectored
interrupt system. Each interrupt jumps to a
different ISR address (X86 uses a table lookup
of addresses in low memory to jump to ISR)
46
Servicing an Interrupt
1. Currently Running
Process is Interrupted
2. ISR 3. IST
……. Code Launched
Mov… executes (Optional)
Add…
…… …… ……….
….. Mov.. …………
……. Out.. …..
…… ……. ……..
……. Reti ……..
……
…….
………
4. ISR ……..
…..
Returns .
…….
…..
…..
….
…….
47
Interrupts
• Interrupt controller hardware is needed to set
priority and enable/disable each interrupt signal
48
Direct Memory Access
• DMA controller and Processor must both share
the bus. Need bus arbitration hardware to control
bus access (DMAs or Processor).
• DMA controller interrupts Processor when it’s
block transfer is complete.
• Processor programs DMA controller’s address
register and counter to start a new transfer.
• Need hardware for each DMA controller and an
interrupt system
System Bus
49
Direct Memory Access
• Need new bus signals for DMA. DMA controller must
request a bus cycle and wait until it is granted by bus
arbitration hardware
– ISA – DRQx and DACKx
– PCI – REQx and GNTx
• For security, the OS must control all DMA hardware.
• DMA normally used for high-speed block transfer devices
like disk drives (disks transfer sectors)
• Processor and DMA controllers can work in parallel on
different tasks (overlap of computation and I/O)
Tradeoffs
Transfer Technique Hardware CPU Overhead
Programmed I/O
Interrupt
DMA
50
Device Independent I/O
• Operating systems provide support for the
underlying I/O hardware.
• Many of the I/O devices can be supported in
applications programs by using the basic file
system API calls. (i.e. Parallel and Serial Ports)
• One important feature of an operating system is
the support it provides for file system I/O.
• It provides a uniform logical view of information
storage.
51
Windows Embedded CE
File I/O API Calls
52
ASCII Character to Hexadecimal Conversion Table
0 1 2 3 4 5 6 7 8 9 A B C D E F
0 NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI
1 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US
2 SP ! " # $ % & ' ( ) * + , - . /
3 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
4 @ A B C D E F G H I J K L M N O
5 P Q R S T U V W X Y Z [ \ ] ^ _
6 ` a b c d e f g h i j k l m n o
7 p q r s t u v w x y z { | } ~ DEL
53
Windows Embedded CE
• Unicode by default (but sometimes ASCII)
• New C type TCHAR for Unicode strings
• _T(“hi”) makes a Unicode string
• Functions are provided to convert between
ASCII and Unicode
– WideCharToMultiByte and
MultiByteToWideChar
Figure 2.15 A Tektronix logic analyzer setup to capture and decode PCI bus signals. This logic analyzer is actually an embedded system that runs Windows XP. A special PCI
interposer adapter card is used to quickly connect probes along with special firmware for the logic analyzer. Images courtesy of Nexus Technology.
54
Figure 2.16 A Tektronix logic analyzer with optional software setup to capture and disassemble an
ARM processor’s instruction execution sequence. This logic analyzer is actually an embedded system
that runs Windows XP. Images courtesy of Nexus Technology.
55
Common Digital I/O Interfacing
Standards for External Devices
•Parallel Port
•Serial Port
•PS/2
•SPI & I2C
•Analog I/O
•USB
•Audio AC97
Busy
nStrobe
nAck
1 2 3 4
56
Parallel Printer I/O Operation
• 1. Computer waits for port’s output ready
bit (i.e. busy=0)
• 2. Computer outputs a new 8-bit data
value
• 3. Computer toggles strobe control line
• 4. Computer must wait for ack to pulse low
before any data or strobe line changes
• Printer can be busy for long time periods
(out of paper, offline, page feed…etc)
57
RS-232 Serial Interface
• UART is the name for the hardware used
for a RS-232 Serial Interface
• UART – Universal Asynchronous Receiver
Transmitter
• Early PCs had a UART chip, but this
functionality is now found inside a larger
chip that also contains other I/O features
0 0 0 0 1 0 1 0
Mark (1)
Space (0)
Start 0 1 2 3 4 5 6 7 Stop
Bit Data Bit number Bit
LSB MSB
58
Personal System 2 (PS/2) Interface
• IBM standard from an early PC
• Used in low-cost keyboards and mice
• Two signal lines: clock & data
• Keyboard sends key scan codes
• Mouse sends 3 byte data packets
• 11bits sent: Start, 8 Data, Parity, Stop
• Can also send commands to Mouse and
Keyboard
• Uses Open Collector TTL bus signals
– 1 Pull-up resistor
– Device can only force signal low
• Small microcontroller used in a PS/2 device
PS/2 Clock
PS/2 Data
59
Serial Peripheral Interface (SPI)
• Developed by Motorola in the 1980s
• Works like a shift register for input and output
• 4 signals: clock, shift-in, shift-out, and chip
enable
• Chip enable turns on a tri-state driver on each
slave devices shift-out pin
• Two setup modes: one large shift register with
chip enables all connected or independent shift
registers each with a chip enable
• Common in A/D and D/A chips
Slave 0
Slave
SDI SDO SDI SDO
Master Master
CS0 CS0
CS1 CS1
CS2 SDI CS2 Slave 1
Slave
SCLK SDO SCLK SDI SDO
SDO SDO
60
Inter IC (I2C) bus
• Developed by Philips in 1980s
• Low pin count serial interface used to connect
chips on a circuit board
• Also used by Intel in the PC motherboard
System Management Bus (SMB)
• 7 bit address
• 1 bit Read/Write
• 8 Data bits
• Probably have one in your TV
SDA
MSB ACK Signal ACK Signal
from Slave from Receiver
Byte Complete Clock Line Held
Low while serviced
61
Analog I/O
• Analog inputs – convert to digital using an Analog
to Digital converter (A/D or ADC)
• Analog output – convert digital output to analog
using a Digital to Analog converter (D/A or DAC)
• A/D outputs and D/A inputs can be attached to
digital I/O ports
• Design issues to consider – number of bits of
accuracy, conversion time delay, and sample rate
needed by application
Figure 3.6 The MCP3008 10-bit 200Ksps A/D chip used in Phidget modules has an SPI interface.
62
Universal Serial Bus (USB)
• 1-bit serial sent over twisted pair wire
• USB Packets contain address and data
• Up to 127 devices on bus
• Special purpose low-cost USB single chip
microcontrollers are used.
• Length is limited to a few feet – a bus and
not a network
+5V
bytes
D+ bytes USB Program & Data
Serial I/O Ports
D- Interface (R AM & ROM)
Interface
Engine
(SIE)
General
GND Purpose
Microprocessor
USB USB
Connector Transceiver
63
USB Data Rates
USB Enumeration
• Hot pluggable – longer power and ground
(outer) pins on USB connector
• At power up, software (OS) can read
product and vendor ID codes (PID/VID)
• Codes are used to locate device driver
• The required Device Driver is loaded
• The new device is assigned its USB
address (0..127) with a command
64
The USB Serial Interface Engine
(SIE) handles USB packets
D C D C
A E C A E C
O A Payload R A O A Payload R A
D N R D N R
U T Data C C U T Data C C
D D C D D C
T A 1 K T A 1 K
R P 5 R P 5
1 6 0 6
Token Packet Data Packet H/S Pkt Token Packet Data Packet H/S Pkt
Payload
D ata
D+ Serial Payload
Interface D ata
Engine
D- (SIE) A
C
K
USB
Transceiver
USB Packets
• Contain a packet type
• USB Address and Endpoint fields
• Each device can have several endpoints
• Endpoint is a hardware buffer between the
SIE and the firmware running on the
microcontroller (typically 8-64 bytes)
• CRC error code checked and Ack sent
back
65
Serial Interface Engine (SIE)
• Special hardware unit that handles
sending and receiving high speed serial
USB packets
• Serial data rates needed are too high to
handle using only software running on the
microcontroller
• Microcontroller only transfers bytes to/from
endpoints in the SIE
USB Software
• OS typically has a USB driver that handles
enumeration and loads driver for device
• Some common USB device drivers may
be provided with OS (storage, serial,
keyboard, mouse)
• Most other devices need a device driver
from the manufacturer
66
CE USB Software Support
• OS handles USB enumeration
• Includes USB storage and serial driver
• Example USB driver shared source code
projects for Phidgets sensor boards and
Logitech QuickCam Pro Web camera
• Some common USB drivers included
(Flash, WiFi, Mouse, Keyboard)
Figure 3.9 A USB protocol analyzer captures and displays the USB packets exchanged with a USB
Flash Drive (www.usbdeveloper.com) .
67
Audio
• For PCs, AC 97 is a common audio
standard
• Needs analog signals so A/D and D/A
hardware is used inside the Audio IC
• Analog mixers can add analog signals
from different sources
• Audio driver typically provided with OS
68
Driving Motors and Relays
• High current devices like motors, relays,
solenoids, buzzers, and light bulbs can require
more than 500MA of current
• Even though voltage levels may be the same,
digital outputs from a GPIO (parallel) port typically
drive only 5-20MA of current
• They cannot drive high current devices directly
and trying to do so will likely blow out the output
circuit
Driver Circuits
• A higher current driver circuit must be added
after the digital output pin and before the device
• A driver circuit typically uses a discrete power
transistor
• For DC motors, consider using an H-bridge
circuit module. It contains four power transistors
than can also reverse the motor.
• Diodes are often used for additional protection
across the load on motors and relays. When you
turn off the current in an inductive load it
generates a reverse voltage spike that might
damage the transistor (back EMF). The diode
shorts it out.
69
CAN and LIN Bus
• Serial Buses Developed for Automotive Industry
in mid 1980s – More advanced than RS232
Serial
• CAN is used to connect car subsystem
processors together, has multiple bus masters,
& uses 2 wires
• LIN is used to connect a processor with it’s
smart sensors, a single master, & uses only 1
wire
• LIN used at lower levels along with CAN at
higher levels in the system
• Both are now found in other embedded devices
Lock Lock
Window Lift
Universal Light
CAN Light
Seat
Htng
Instruments
Htng Wiper
Power Train Central WHtg
ITS Body Ctrl Roof Interior
Light
Htng Trunk
Climate
x6
Seat
Light Seat
Htng
St-Wheel Panel CAN
Universal Motor
Lock Lock
1 backbone, 13 nodes
8 subnets, 1-8 local nodes Sub-Bus
Universal Panel
52 nodes total
Mirror
70
Controller Area Network (CAN)
• Messages contain a message number and
not an address
• Lower number messages have priority
• Each devices checks the message
number to see if it needs to handle the
message
• Data rates up to 1M Baud
• Special CAN chips are available
Message Frame
Bus Idle Arbitration Field Control Data Field CRC Field ACK EOF Int Bus Idle
RTR r0
r1 D elimiter
71
Local Interconnect Network (LIN)
Message Frame
Header Response
Figure 3.11 A Typical LIN Frame Consisting of Synch Break, Synch Field, Identifier, Data Field and
Checksum.
72
Figure 3.13 The Tektronix DPO7000 1-4 Channel Oscilloscope is an embedded device that runs
Windows XP. The display above is from an optional software package for the oscilloscope that
decodes and displays SPI bus signals. Images courtesy of Prodigy Test Solutions.
Figure 3.14 The Tektronix DPO7000 1-4 Channel Oscilloscope is an embedded device that runs
Windows XP. The display above is from an optional software package for the oscilloscope that
decodes and displays I2C bus signals. Images courtesy of Prodigy Test Solutions.
73
Chapter 4: Network
Interface Standards
Networking
• Ethernet Frames
• Ethernet LAN
• The TCP/IP Protocol Suite
• Software APIs for networking
74
Network Interfaces
• Ethernet is the most widely used network
interface
• Details found in IEEE Standard 802.3
• Data is transferred in Ethernet Packets (Frames)
• Data rates: 10Mbps, 100Mbps, and now 1Gbps
• Low-cost Ethernet controller chips are used
– Often attaches directly to a PCI bus
• Original Idea: each network device is assigned a
unique 48-bit address by the manufacturer
(MAC address)
An Ethernet Frame
Preamble 56 bits of alternating Is and Os.
SFD Start field delimiter, flag (10101011)
75
A Small Ethernet Network
P ri nter
C
Computer
A
Ethernet Medium
CSMA/CD
• Carrier sense multiple access with
collision detection (CSMA/CD)
• Device waits for medium to be idle
• Device starts transmitting data
• Device Listens to data to detect a collision
• When collision detected, stop and wait for
a random amount of time before starting
over
• Works a bit different in 1 Gbps Ethernet
76
An Ethernet Bridge Connecting
Two Segments
Statio n S tati on
A D
Bridge
Segment 1 Segment 2
S tati on S tati on
B C
TCP/IP Protocol
• Application Protocols – HTTP, SMTP,
SSH, etc.
• Transport Protocols – TCP, UDP
• Network Communication Protocols – IP
• Network Topology – Ethernet, Wi-Fi,
Token Ring, etc.
77
Network Protocol Layers
TCP TCP
Header Data Transport Protocols
IP
Header IP Data Internet Protocols
Frame Frame
Frame Data Network Topology
Header Trailer
78
Windows Embedded CE
Networking Software
• Includes a TCP/IP Protocol Suite
• Supports sockets model programming
interface in Windows Sockets (Winsock)
• Also has some higher level API interfaces
such as WinInet & WinHTTP
• Comes with browser & ping applications.
79
Feature 802.11b/WiFi 802.15.1/Bluetooth 802.15.4/ZigBee
Application Web, Email, Video Cable Replacement Control &
Area Monitoring
Target Cost $25 $15 $5
Memory 1MB+ 250KB 4KB - 32KB+
Requirement
Battery Life .5-5 Days 1-7 Days 100-1000 Days
Network Size 11,000+ 7 20-250
Peak Data 1, 2, 5.5, 11, 1Mbps 250 Kbps @ 2.4
Rate (54-802.11g) Mbps GHz
40 Kbps @ 915
MHz
20 Kbps @ 868
MHz
Power 1.5 W active 80 mV active @ 0 60 mW active @ 0
Consumption @ 20 dBm dBm dBm
(targeted) 45 mW sleep 5–2000 mW sleep
100 mW sleep (mode dependent)
Adjacent >35 dB 0 dB 0 dB
Channel
Rejection
Receiver –80 dBm –70 dBm –85 dBm
Sensitivity –92 dBm @
868/915 MHz
Range Line ~200 m @ 11 Mbps ~30 m ~50 m @ 0 dBm
of Sight ~500 m @ 1 Mbps ~100 m, Class 1
Range— ~40 m @ 11 Mbps ~10 m ~10 m @ 0 dBm
Indoor ~100 m @ 1 Mbps ~30 m, Class 1
(approx.)
Number of 11 - DSSS 79 16 @ 2.4 GHz
Channels 79 - FHSS 10 @ 915 MHz
1 @ 868 MHz
Modulation GFSK—FHSS GFSK O-QPSK @ 2.4
Technique BPSK/QPSK—DSSS GHz
BPSK @ 868/915
MHz
Maximum 20 dBm—FHSS 20 dBm 30 dBm
Transmit 30 dBm—DSSS
Power
Figure 4.5 The free Ethereal Network Protocol Analyzer capturing and decoding network
traffic on a desktop PC. The PC just loaded a short web page from a remote server (see
HTTP packets). (www.ethereal.com)
80
Chapter 5: The eBox 2300
Embedded Computer
System
81
Software for eBox 2300
• Windows Embedded CE Development Tools are free for
schools and students from the MSAA Program
– Need Visual Studio 2005 with CE 6.0 tools (C,C++,C#)
– Can download & debug on eBox using a network cable
– 180 Day free trial versions are also available
• Board Support Package (BSP) for CE 6.0
– An eBox 2300 BSP is being developed and will be free
– Includes all I/O drivers needed for board
• AMI ROM BIOS included on board
• Flash drive preloaded with Windows Embedded CE
– Runs LoadCEPC from DOS to boot CE OS
– Select CE boot sources from network, Flash, or USB
Audio CODEC
128MB SDRAM
256MB FLASH
Vortex86 SoC
PS/2, USB, VGA,
serial, & Network
Bottom of PCB: connectors
Mini PCI &
CF slot
82
Vortex86 System on a Chip (SoC)
is used to build the eBox
Ethernet LAN LAN2
RJ45
RTL8100B 10/100M
Mini-PC1
Com1
Vortex 86 Vortex 86 Super I/O
CPU-Vortex 86
North Bridge PC1 South Bridge LPC W83697HF
Com2
Vortex 86-SoC
Ultra IDE CF PS/2 Keyboard
Flash Slot 32.768KHz
PS/2 Mouse
RTC
VGA Battery USB 1.1 x 3
+5V Input +5V AC97
Line In
SB+5V AC97
Line Out
+3.3V CodeC
Mic In
SB+3.3V
+2.5V
+1.8V
SB+1.8V
83
eBox 2300 MSJK
• Special model for students and schools
• Includes CE preinstalled on Flash Drive
• All cables needed for CE development work
• Includes the two serial port option
• Available with Educational Discount (around $145
Qty 10)
• Internal Wireless Option (add around $40)
• For School Orders & Student Orders
www.embeddedpc.net/academic/ebox2300.html
Figure 5.5 The eBox VGA display output after successfully booting Windows Embedded CE 6.0.
84
Table 5.1 eBox 2300 Device Drivers for CE 6.0
eBox-2300 Peripherals CE 6.0 Drivers
Vortex86_Display
Video (SiS-550)
(Driver included with ICOP eBox BSP)
Vortex86_Audio
Audio (SiS-7019)
(Driver included with ICOP eBox BSP)
Ethernet (RealTek-8100) RTL8139 (Driver provided with CE 6.0)
Serial Ports (16550 UART) Com16550 (Driver provided with CE 6.0)
USB Ports (USB 1.1 Host) OHCI (Driver provided with CE 6.0)
USB Flash Drive USB Storage Class (Driver provided with CE 6.0)
ATAPI & Compact Flash / PC Card Storage
CF storage card
(ATADISK) (Driver provided with CE 6.0)
IDE Disk ATAPI (Driver provided with CE 6.0)
MiniPCI (internal slot) PCI Bus (Driver provided with CE 6.0)
Internal 802.11 Wireless
Card (optional) VIA VT6655 (Driver provided by VIA & ICOP)
(VIA VT6655 - US only)
85
Adding External I/O using USB
• Phidgets USB Devices ( www.phidgets.com )
• Supports Servos, Digital, & Analog I/O (50-125 Hz)
• Numerous plug-in sensor modules available
• Free Driver & source code shared projects for CE
86
Serial I/O options
• Cypress PSoC Evaluation Kit (CY3210)
• Mixed-Signal Microcontroller with digital and analog I/Os.
• Low Cost ($17 academic pricing) but need to develop
Firmware for serial commands (www.cypress.com/CUAP)
• For 16x2 LCD panel add $17
• Serial Interface and Small Protoboard on PCB
• Free graphical software tool, C compiler
USB WebCam
• USB webcam driver for Windows CE
• Supports Logitech QuickCam Pro 5000 ($65)
• Free Driver & source code shared project for CE
(http://msdn.microsoft.com/embedded/usewinemb/ce/sharedsrccode/)
• Also new CE 6.0 USB Camera driver at
www.microsoft.com/downloads
87
Low Cost Sensors
Figure 5.11 Special adapter boards make it easier to prototype with surface mount devices. A small
10-pin surface mount 16-bit SPI A/D chip is mounted on a special surface mount to DIP adapter
board that allows it to plug directly into a .1 inch student protoboard.
88
Low Cost R/C Servos
Figure 5.11 A low-cost radio control (R/C) servo motor. Inside the case are a DC
motor, reduction gears, PWM control, and driver circuitry. They can also be
modified and used as robot drive motors for small robots. A Phidgets servo
controller is available. A 1-bit digital Pulse Wide Modulation (PWM) signal is used
to control servos.
Figure 5.13 The internal 802.11 wireless kit for the eBox 2300 MSJK. Photograph courtesy of ICOP.
89
Cell Phone Modem
Figure 5.14 The Enfora SA-GL GSM/GPRS Stand Alone Cell Phone Modem can be used with CE
and the eBox. (www.enfora.com) Photograph courtesy of Enfora Inc.
Figure 5.15 The iRobot Create robot base can be used as a low-cost robot base for the eBox 2300.
An eBox, the Logitech web camera, and an extra battery pack are seen mounted to the Create robot
base above (www.irobot.com). Photograph courtesy of Microsoft.
90
Some Student Projects
using the eBox 2300
Figure 5.11 This project displays scrolling RSS web news feeds on the Phidgets LCD display.
91
Figure 5.12 VoIP Phone system using two eBoxes running CE 6.0.
Figure 5.13 A web-page based remote temperature control and monitoring system built using an
analog temperature sensor connected to a Phidgets 8/8/8 interface board attached to the eBox running
CE6.0. Phidget digital outputs seen in the red LEDs control relay signals for the heat, AC and fan.
92
Figure 5.14 This student robot project was controlled by an eBox running CE 6.0. The battery
powered eBox has the wireless option and can be seen on the top left of the robot.
Figure 5.15 Digital I/O from the Phidgets LCD interface board attached to the robot’s control
signals. The laser rangefinder is seen in the upper left.
93
Figure 5.16 This Student project developed a CE USB HID driver and GUI for a USB PSoC board.
Figure 5.19 This eBox Phidget project is a scanner built using an IR distance sensor with pan and tilt
servos. Note the clever use of the eBox mounting holes and a plastic sheet to attach the external
hardware. Photograph courtesy of Dan Slaeker.
94
Figure 5.23 Students mounted an eBox on this R/C plane along with a GPS receiver and
a small battery. They recorded flight data and displayed the data using Google earth.
Figure 5.23 Several Phidgets mounted on a plastic case for CE eBox student lab projects. Includes an
LCD, 8 LEDs, 8 switches, ADC with 8 different analog sensors, and 2 R/C servos on a pan & tilt
mount with an IR distance sensor. Wires are hidden inside the case.
95
Chapter 6: Architecture
of a Real-Time
Embedded OS – CE 6.0
96
Windows Embedded CE 6.0
• Kernel size 400K to 40M – Depends on
features included in OS build
• Tools provided include C/C++/C#
compiler, OS build tool (Platform Builder),
and debugger
• Hard drive not required – typically boots
from Flash memory device
• CE Development tools run as a Visual
Studio 2005 add on
97
CE Kernel
2 GB
File system
Kernel
Space GWES
Drivers
User VM
Memory Mapped files
2 GB .
per User DLLs
. ..
Process
..
Process Code Up to 32 K
User VM Processes
Figure 6.1 The Windows Embedded CE 6.0 Virtual Memory Space Model.
Applications
DEVICE .DLL
KERNEL . DLL
FILESYS GWES NETWORK
Kernel
Drivers
Space
OAL . DLL
Boot Loader KCOREDLL DLL
Hardware
98
CE User Processes
CE Kernel
• FilesSys.dll provides file system support and
communicates with file system drivers (FSD)
• GWES.dll is the Graphics, Windowing, and
Events Subsystems
• Networking DLLs Networking services
• Device.dll provides device driver services
• Kernel provide basic OS services
• API calls use KCOREDLL.dll to get to other
kernel services
99
Application Programs in CE
• CE Supports Threads
• Uses a critical subset of the Desktop
Windows APIs – around 2,000 vs. 20,000
• Means CE application source code can be
recompiled and run on the Desktop
Windows OS, but the reverse is not true
• Sample browser, Media player, WordPad
applications included with OS.
Application
Kernel Service
100
Kernel
• New Kernel (NK.bin) module
• Core of the operating system
• Base level functions in kernel: process,
thread, and memory management
• Includes some file management functions
• Kernel services allow applications to use
the core functions
101
Memory Setup In CE
• 4GB 32-bit Virtual Memory Address Space
• 2GB User Space in Virtual Memory
Address Space
• 2GB Kernel Space in Virtual Memory
Address Space
0x80000000
Shared System Heap R/W for OS components
255 MB Read only for user process
0x00000000
102
0xFFFFFFFF
CPU Specific VM
System Trap Area
Kernel VM
(if supported by CPU) Kernel Virtual Memory
256 MB
Shared by all kernel
Kernel VM
256 MB
Servers and drivers
Kernel Space Object Store (128MB)
2 Gigabytes
Kernel XIP DLLs (128 MB) All XIP DLLs in kernel
Fixed mapping
independent of Static Mapped
user space Uncached Uncached access to
512 MB physical memory
0x80000000
103
User 0x60000000 - 256 RAM RAM backed mapfiles are mapped at
0x6FFFFFFF MB backed map fixed location for backward
files compatibility. RAM backed map files are
memory mapped file objects that do not
have an actual file underneath them. They
are acquired by calling
CreateFileMapping with hFile equal to
INVALID_HANDLE_VALUE. This
region provides backward compatibility
for applications that used RAM-backed
map files for cross-process
communication, expecting all processes
to map views at the same virtual address.
User 0x40000000 - 512 User mode DLLs loaded at bottom and grow up:
0x5FFFFFFF MB DLLs • Based starting at 0x40000000.
Code and • Code and data are intermixed.
data • A DLL loaded in multiple
processes will load at the same
address in all processes.
• Code pages share same physical
pages.
• Data pages have unique physical
pages for each process.
User 0x00010000 - 1 Process Executable code and data
0x3FFFFFFF GB User User VM (heap) virtual allocations:
allocatable 1 VM allocations start above the exe
VM and grow up.
User 0x00000000 - 64 CPU User kernel data is always r/o for user.
0x00010000 KB dependent Depending on CPU, it can be kernel r/w
user kernel (ARM), or kernel r/o (all others).
data
104
What is in Memory?
• OS Kernel
• Application Code & Data
• Object Store – File System, Registry, Built-
in Compact Data Base
• Memory Mapped Files
File System
• FilesSys.dll provides file system support
and communicates with file system drivers
(FSD)
• CE supports two kinds of file systems, files
systems controlled by file system drivers &
registered file systems.
• File system drivers (FSDs) are provided
for a variety of file systems
105
Table 6.2 File Systems and Storage Management Catalog.
Catalog Description
item name
Compression An application programming interface (API) that compresses the data
in the RAM and ROM file systems, as well as the database volumes.
Database Support An API that provides built-in CEDB database support.
Bit-based A feature that helps identify what changes have occurred in a database
or RAM file system on the device and therefore must be replicated on
the desktop. This model relies on four bits per object to replicate the
data.
RAM and ROM A file system driver capable of reading data from the ROM file system
File System and the RAM file system in the object store.
ROM-only File A file system driver capable of reading data from the ROM file
System system.
Hive-based A registry system that stores data inside files, or hives, which can be
Registry kept on any file system.
RAM-based A system that stores all registry data within the object store.
Registry
Storage Manager The Storage Manager is responsible for all external storage items, such
as file systems, file system filters, and partitioning.
Binary Rom Image A Catalog item that is used to load a portion of an OS image from
File System persistent media into RAM for execution. This Catalog item uses
demand paging to load additional modules as needed..
CD/UDFS File A file system driver that supports both Compact Disc File System
System (CDFS) and Universal Disc File System (UDFS) and reads compact
discs (CDs), digital video discs (DVDs), and CD-ROMs.
EDB Database An API that provides enhanced database functionality, including
Engine support for transactions, access by multiple users, multiple sort orders,
key properties and databases.
FAT File System A file system driver that supports the file allocation table (FAT) file
system.
Extended FAT File A file system driver that supports the Extended FAT file system.
System
Partition Driver A driver that interprets the partitions on a storage device for the
Partition Manager.
Storage Manager A control panel application that allows a user to manipulate storage
Control Panel devices.
Applet
Transaction-safe A transaction-safe FAT file system that ensures the file allocation table
FAT File System is not corrupted during power cycles.
(TFAT)
System Password An API that provides support for authentication on a device to prevent
unauthorized access.
Release Directory A functionality that provides support for the Release Directory File
File System System
Silent FATFS UI Builds the Fatutil.dll file for a device with no graphical user interface
(GUI) components.
106
Processes and Threads
• 2GB of Virtual Memory per process
• Up to 32,000 Processes
• Each Process has one or more threads
• Thread – basic unit of execution managed
by scheduler
• Many threads per process – limited by
system resources (memory)
107
Priority Levels
Priority Scheduling
Figure 6.9 Example of Thread scheduling. Thread 1 has the highest priority and runs to
completion, Threads 2 & 3 have the same priority and execute in a round robin manner.
108
Priority Inversion
• A mutex or critical section held by a lower-
priority thread delays the execution of a higher-
priority thread when both are contending for the
same resource.
• CE enables the lower-priority thread to inherit
the more critical thread's priority and run at the
higher priority until it releases its use of the
resource.
• Changes Scheduling of threads around – so
would like to avoid inversion, if possible
109
Real Time Performance of CE
• Results based on hardware test setup
• Samsung SMDK2410 development board
• 200 MHz ARM with 16x16 cache
• Windows CE 5.0 with full UI
• Running a WMV video
110
Real-Time Performance of CE 6.0
100 ms
Soft Real-Time
Response Cycle Time
20 ms
10 ms Windows
XP
Hard Hard Real-Time
Linux?
5 ms
Real-Time
1 ms Windows
CE
500 us
Synchronization Primitives
• Critical Sections
• Mutexes
• Semaphores (counting)
• Events – used to indicate something
happened
111
Interprocess Communication
• Both the Shared Memory and Message
Passing Models are supported in CE
• Can share a heap in memory
• Memory mapped files and Pointers
• Point to Point Message Queue APIs
• Message Queuing (MSMQ) for
communications between different devices
Interrupt Processing
• Interrupt Service Handler (ISH) in Kernel
decides which ISR to call
• Uses an Interrupt Service Routine (ISR)
and an Interrupt Service Thread (IST)
• ISR handles basic interrupt tasks quickly,
starts IST and returns
• IST can complete remainder of task later
• Using both an ISR and IST reduces
Interrupt Latency
112
Figure 6.11 Processing an Interrupt in CE with an ISR and IST.
Device Drivers
• Abstracts device functions
• Manages operation of devices
• Drivers can be layered (MDD and PDD
layers) or monolithic
• Stream Interface for devices that produce
and consume streams of data
• Many standard drivers are provided with
the OS
113
User Mode Driver
• Allows an intermediate driver to load in
User mode
• Cannot directly access hardware
• Some drivers will be more stable in user
mode
• Reflector in kernel makes a user mode
driver work as if it was a kernel mode
driver
114
Registry
• Stores configuration information for
applications, drivers, and the OS
• OS uses registry to locate and load device
drivers
• Same basic setup as the desktop
Windows OS registry
• Space is limited, so keep any new entries
short!
115
Device Manager
• Manages Devices and their Interfaces
• Decides which drivers to load
• Uses Registry to find drivers
• Runs continuously
116
Table 6.6 Processes that Load Drivers.
Process Drivers
File System FileSys.dll loads file system drivers. For more information, see the
(FileSys.dll) section on File Systems.
Device Device.exe loads audio drivers, battery drivers, keyboard drivers,
Manager mouse drivers, NDIS drivers, notification LED drivers, serial
(Device.exe) drivers, PC Card drivers, USB drivers, and any other driver that
exposes the stream interface. Device.exe loads most of its drivers
with ActivateDeviceEx, and these drivers expose a stream interface.
Graphics, GWES.dll loads a device driver if GWES is the only client of a
Windowing, driver. Device drivers loaded by GWES present a standard set of
and Events functionality for all similar devices. Drivers that GWES loads
Subsystem might expose the stream interface or they might expose other
(GWES.dll) interfaces. Having alternatives make accessing the drivers much
faster. GWES loads display drivers, printer drivers, and touch
screen drivers.
117
Power Management
• Critical for Battery Operated Devices
(i.e. Cell Phones!)
• Support for Power Management is built
into CE at both the system level and at the
individual hardware device API level
No power
No No
Clear file
system
Yes Yes
Clean boot signaled? Clean boot signaled?
No No
Yes Yes
Clear RAM
Persistent storage file system? Persistent storage file system?
Warm boot
Power-on reset
Power-on reset
Battery backup
Critical battery-low event
level reaches Critcal off
zero
On Scheduler idle
Idle
Any interrupt
118
Table 6.7 Power State Transitions.
Transition Description
Power-on Target device clears working RAM and initializes the file system.
reset
Cold boot First application of power, for example, when a backup battery is
installed.
Warm Transition from the On power state. A warm boot clears the working
boot RAM.
On-to-Idle Transition from a fully running state to a state in which the
microprocessor is using little power.
Idle-to-On Transition of the microprocessor from low-power to full-power
operation.
On-to- Transition to a stopped microprocessor, as a result of certain events. A
Suspend device driver's XXX_PowerDown (Device Manager) function is called.
Suspend- Transition of a stopped microprocessor to full-power operation based
to-On on specific wake-up events. A device driver's XXX_PowerUp (Device
Manager) function is called.
On-to- Transition when critically low battery power is detected. You must
Critical off implement the function for transitioning to the Critical Off state for
your device.
119
Security
Security Tools
• Authentication
• Authorization
• Encryption
• Repudiation
120
Figure 6.15 CE Security System Architecture.
Networking
• Critical in most embedded devices
• Support for Networking is a major
component of a modern OS
• CE includes a TCP/IP protocol suite
• CE includes common Network Utility
Programs (ping, ipconfig, netstat…)
• CE supports WinSock, WinInet, and
WinHTTP APIs
121
Table 6.8 TCP/IP Services
Service Description
Dynamic Host DHCP clients are dynamically assigned with various
Configuration configuration parameters, such as an IP address, subnet mask,
Protocol (DHCP) default gateway, and other critical network configuration
client information.
Windows Internet WINS is a NetBIOS name client that manages the name
Name Service resolution process by maintaining an up-to-date list of NetBIOS
(WINS) computer names and their respective IP addresses..
Domain Name CE does not support hosting a DNS server. However, CE queries
System (DNS) client a DNS server for name resolution if such a server exists on the
network.
Extended DNS This service provides the Dynamic DNS protocol that allows you
Querying and Update to set the device name in a DNS server database. You can do this
programmatically or you can configure the device to register its
name in the database automatically when its name is changed or
when a network adapter becomes available. CE also supports
Secure DNS for more secure, dynamic updates. You can now
modify or remove multiple resource record sets that are
associated with a specific name. Dynamic Query and Modify
allows you to query arbitrary records in a DNS Server.
Dial-up (PPP/SLIP) CE implements dial-up networking with Remote Access Service
support. (RAS) and Point-to-Point Protocol (PPP).
TCP/IP network In CE, TCP/IP supports network printing through the Server
printing Message Block (SMB) protocol. It does not provide the Windows
Line Printer Remote (LPR) Spooler. However, independent
software vendors (ISVs) and original equipment manufacturers
(OEMs) can add this support.
Simple Network The SNMP extension agent provides an MIB-2 subagent that
Management allows the state of TCP/IP to be monitored and controlled.
Protocol (SNMP)
extension agent
Wide area network This service provides users with access to the Internet.
(WAN) support
122
Figure 6.16 CE Networking & TCP/IP Architecture.
OS Build System
• The Platform Builder Tool is used to build
a new OS Kernel
• Both a GUI-based interface and a batch
command mode build is supported
• New kernel can be downloaded to a target
system
• Several files are critical to understanding
the build system (Examples follow later)
123
Figure 6.17 Platform Builder is the tool used to build a new OS kernel image.
124
Figure 6.19 The CE Build system.
125
Table 6.9 Source Code Configuration File Types.
File type Description
Dirs File Identifies additional subdirectories that contain more source code.
Makefile Contains the variables needed to compile and link the source code.
File
Module- Contains the statements defining an executable or dynamic-link library.
Definition
File
Sources Contains the macro variables needed to build the source code. It lists the
File include and library files needed to build the module. (one of the build
files an application developer will often need to modify)
126
Table 6.11 Scope of Run-time Image Configuration Files.
File name Scope
Common.bib, Common.reg, These files apply to the Common project, which
Common.dat, Common.db, contains the core CE-based modules and components.
Common.str
IE.bib, IE.reg, IE.dat, IE.db, These files apply to the IE project, which contains the
IE.str components that support the Microsoft Internet
Explorer modules.
Wceappsfe.bib, These files apply to the Wceapps project, which
Wceappsfe.reg, contains the components that support WordPad word
Wceappsfe.dat, processing software and Inbox electronic messaging
Wceappsfe.db, Wceappsfe.str software.
127
*.Bib entry to add
mydll.dll to kernel
Chapter 7: Building a
customized CE Kernel
128
Tutorial I: Building a new OS
kernel using the eBox BSP
Building a Custom OS
• See 7.2 for software installation instructions
• Start Visual Studio 2005
• Create a new OS Design Project
• Select the correct BSP
• Choose an initial Design Template
• Select/Deselect Individual OS components
• Set OS build and environment variables
• Build OS
129
Figure 7.1 The Visual Studio 2005 IDE
130
Figure 7.3 The Windows Embedded CE 6.0 Design Wizard.
Figure 7.4 Selecting the eBox 2300 BSP in the Design Wizard.
131
Figure 7.5 Selecting a Design Template in the Design Wizard.
132
Figure 7.7 Selecting Applications and Media options in the Design Wizard.
Figure 7.8 Selecting Networking and Communications options in the Design Wizard.
133
Figure 7.9 A Security Warnings on a selected OS option.
Figure 7.10 The Catalog Items View (left column) is used to select individual items
for the OS.
134
Figure 7.11 The Configuration Manager can be used to select Debug or Release OS
Builds.
Figure 7.12 The Property Pages Window is used to set Build Options and Environment Variables.
135
Figure 7.13 Adding an Environment Variable using the Property Pages Window.
136
Tutorial II: Downloading a new
OS kernel to the eBox 2300
137
Figure 7.15 Setting up the target device connectivity options.
Figure 7.16 Detecting and Selecting the CEPCxxxxx target device to download.
138
Figure 7.17 Attaching the target device for downloading.
139
Figure 7.19 The target device display is seen running the new OS image.
140
Creating a new C/C++ Subproject
• Create a new Subproject in OSDesign Project
• Add C/C++ source code file(s)
• Specify include and library files (in sources file)
• Build Subproject without errors
• Rebuild OS
• New OS now includes new subproject code
• Can use Target -> Run Programs to execute
new subproject code after downloading and
booting new OS
Figure 7.20 Adding the C/C++ MyHelloWorld Subproject to the OS Design Project.
141
Figure 7.21 Select a typical “Hello World” C/C++ application and generate the code.
142
Figure 7.23 The eBox console display while running the “Hello World” C/C++ application.
Figure 7.24 Stopping at the breakpoint in the “Hello World” C/C++ application.
143
Figure 7.25 Switching the MyOS project to a Release build.
144
Software Development Kit (SDK)
• Needed by application developers
• Includes files and info needed on API’s
included in each OS design project
• Do not need an OS design project to
develop applications when an SDK is
available
• Required for C# project development
Creating a SDK
• Open OSDesign Project
• Use Project -> Add new SDK
• Setup the SDK properties windows
• Build All SDKs
• Output is an *.msi install file
• Install *.msi file to support applications
development
145
Figure 7.26 Setting the SDK property page names to MySDK.
146
Figure 7.28 Including managed code (C#) support in the new SDK.
147
C# Projects
• C# code is platform independent
• C# needs to be setup as a separate
project (not a subproject like C/C++ code)
• C# needs an SDK for each OS design
• C# uses a graphical design tool for GUI
design
• After designing the GUI, C# code is added
to respond to events
148
Figure 7.30 The new HelloCSWorld project is created and it opens a Forms design window.
Figure 7.31 A textbox and a button is added to the Form using the toolbox.
149
Figure 7.31 A textbox and a button is added to the Form using the toolbox.
150
C# Code Deployment
• C# is code is deployed after the OS boots so a
different network communications setup is
needed than is used for the initial OS boot
process (several setup steps are required)
• Need to setup and specify Target’s IP address
• Target must then run two communication
programs (ConmanClient2 and CMaccept)
• C# code can then be deployed to target and
debugged over network connection
• A second instance of Visual Studio is required to
debug C/C++ and C# code at the same time
Figure 7.33 First step in setting up the target device’s IP address for deploying code.
151
Figure 7.34 Second step in setting up the target devices IP address to deploy.
Figure 7.35 Final step, type in the target device’s actual IP address.
152
Figure 7.36 Start the Corecon components running on the target device.
153
Figure 7.38 The Corecon components are running on the target device and it is connected.
Figure 7.39 The new C# application has been deployed and is running on the eBox.
154
Figure 7.40 The new C# application’s textbox changes after the button is clicked.
Chapter 8: Applications
Programming in CE
155
Applications Programming in CE
• Subset of Desktop APIs
• C/C++ and C# supported
• May need to link to CE *.lib files for some
APIs (modify sources file)
• Console Applications require support for
console in kernel
• Source Code for Examples on CDROM
Console Applications in CE
• Simplest programming model in CE
• Outputs plain text to console window
• Console window appears after first printf
• No support to read input from keyboard
• Can read command line parameter
• Uses stdio.h and not fstream.h
• Will have Windows examples later
156
FileIO Example Program
• Demo of File system API calls
• File name is in Unicode
• Uses CreateFile to create a new file
• Writes to File with WriteFile
• Closes file with CloseHandle
• Opens file again for read with CreateFile
• Reads file with ReadFile
• Closes file with CloseHandle
• Uses Sleep(ms) for time delay
157
}
if (!WriteFile(hFile, cBuffer, strlen(cBuffer), &cBytes, NULL)){
printf("file write errors\n");
Sleep(1000);
return 0;
}
// Close File
CloseHandle(hFile);
Serial IO Example
• Uses same File System APIs to read and write
data from serial port.
• COM1 normally tied up with debug messages in
CE (COM2 becomes COM1)
• GetCommStatus and SetCommStatus APIs are
used to setup the baud rate, number of bits, and
handshake options
• SetCommEvent and WaitCommEvent APIs are
used to notify program that new serial data is
available
158
Serial IO Demo
• Serial port is setup for 9600 baud, 8 data
bits, no parity, 1 stop bit, and no
handshake
• To run demo attach eBox COM2 to an
unused COM port on the desktop PC
using the null modem cable provided with
the eBox
• Start HyperTerminal on the desktop PC
and set COM settings
Figure 8.1 HyperTerminal running on development system and communicating with eBox COM Port
159
// SerialIO.cpp : Defines the entry point for the console application.
//
// Serial Port File I/O Demo Program
//
// FOR DEMO: Connect Ebox COM2: to PC with null modem cable
// Run HyperTerminal with 9600 Baud 8 data bits 1 stop bit
// no parity and no flow control
#include "stdafx.h"
BOOL ModifyCommSettings (HANDLE hComPort);
HANDLE hSerial;
cBuffer_in[0] = 0;
// Read in characters, copy to console display and Echo
// Loop until ctrl C is typed
while (cBuffer_in[0] != 0x03){
// Wait for character in input buffer - events are more efficient than
looping
WaitCommEvent(hSerial, &dwMask, 0);
cBytes_in = 1;
// Loop just in case more than one character is in UARTs input buffer
while (cBytes_in != 0){
// Read back data any serial data and display
if (ReadFile(hSerial, cBuffer_in, 64, &cBytes_in, NULL)){
if (cBytes_in == 0) break;
// Display Data read back
printf("%s",cBuffer_in, cBytes_in);
// Echo characters back to sender
if (!WriteFile(hSerial, cBuffer_in, cBytes_in,
&cBytes_out, NULL)){
printf("\rfile write errors\n");
Sleep(4000);
return 0;
}
}
}
}
// Close File
CloseHandle(hSerial);
return 1;
}
160
// Function to set COM port options
BOOL ModifyCommSettings (HANDLE hComPort)
{
COMMTIMEOUTS ctos;
DCB PortDCB;
// Initialize the DCBlength member.
PortDCB.DCBlength = sizeof (DCB);
// Get the default serial port settings DCB information.
GetCommState (hSerial, &PortDCB);
// Change the common DCB structure settings to modify serial port
settings.
PortDCB.BaudRate = 9600; // Current baud
PortDCB.fBinary = TRUE; // Binary mode; no EOF check
PortDCB.fParity = TRUE; // Enable parity checking
PortDCB.fOutxCtsFlow = FALSE; // No CTS output flow control
PortDCB.fOutxDsrFlow = FALSE; // No DSR output flow control
PortDCB.fDtrControl = DTR_CONTROL_ENABLE; // DTR flow control type
PortDCB.fDsrSensitivity = FALSE; // DSR sensitivity
PortDCB.fTXContinueOnXoff = TRUE; // XOFF continues Tx
PortDCB.fOutX = FALSE; // No XON/XOFF out flow control
PortDCB.fInX = FALSE; // No XON/XOFF in flow control
PortDCB.fErrorChar = FALSE; // Disable error replacement
PortDCB.fNull = FALSE; // Disable null stripping
PortDCB.fRtsControl = RTS_CONTROL_ENABLE; // RTS flow control
PortDCB.fAbortOnError = FALSE; // Do not abort reads/writes on
error
PortDCB.ByteSize = 8; // Number of bits/byte, 4-8
PortDCB.Parity = NOPARITY; // 0-4=no,odd,even,mark,space
PortDCB.StopBits = ONESTOPBIT; // 0,1,2 = 1, 1.5, 2
161
Port IO Example
• Operates the same as the previous serial port
example
• Instead of File Systems APIs this code talks
directly to the serial port I/O hardware (A 16550
UART)
• Uses the CEDDK library functions
WRITE_PORT_UCHAR & READ_PORT_UCHAR
to read and write I/O ports
• Intended to demo the use of CEDDK functions
(not replace device driver!)
162
// PortIO.cpp : Defines the entry point for the console application.
// Educational example intended to illustrate how programmed I/O works
// using the serial I/O port hardware on the target system
// and show the use of READ_PORT_UCHAR and WRITE_PORT_UCHAR
// from the CE Device Driver Kit (CEDDK)
//
// Setup for X86 PC (CEPC)
// using 16550 UART compatiable serial port hardware
//
// Not intended to replace a good serial port device driver!
// Does not use interrupts, have any timeouts, or provide
// support for all of the serial port's features
// Would normally use OS API calls for this operation!
//
// FOR DEMO: Connect Ebox COM2: to PC with null modem cable
// Run HyperTerminal with 9600 Baud 8 data bits 1 stop bit
// no parity and no flow control
#include "stdafx.h"
163
UCHAR Read_Serial_Character (PUCHAR Data_Port_Address)
{
// Read in a character from the serial port
UCHAR Serial_Data, Status;
// Wait for RX input ready bit=1
// Status I/O Port Address is Data I/O Port Address + 5
do{
Status = READ_PORT_UCHAR(Data_Port_Address + 5);
// If not ready release remainder of time slice
if ((Status & 0x01) == 0) Sleep(0);
} while ((Status & 0x01) == 0);
// Read in new serial data
Serial_Data = READ_PORT_UCHAR(Data_Port_Address);
return Serial_Data;
}
void Setup_UART (PUCHAR Data_Port_Address)
{
UCHAR Temp;
// Will need a good PC Hardware Reference Text and/or
// the 16550 UART data sheet to fully understand this!
// Disable COMx: Interrupts (use Programmed I/O)
WRITE_PORT_UCHAR(Data_Port_Address + 1, 0);
// Set Baud Rate to 9600 with clock Divisor settings
// Put in set divisor mode
Temp = READ_PORT_UCHAR(Data_Port_Address + 3);
WRITE_PORT_UCHAR(Data_Port_Address + 3, Temp | 0x83);
// Set Divisor LSB (note: 12 = 115200/9600)
WRITE_PORT_UCHAR(Data_Port_Address , 12);
// Set Divisor MSB
WRITE_PORT_UCHAR(Data_Port_Address + 1, 0);
// Back to normal operation mode (and set for 8D NP 1S)
Temp = READ_PORT_UCHAR(Data_Port_Address + 3);
WRITE_PORT_UCHAR(Data_Port_Address + 3, Temp & 0x03);
return;
}
Sources File
• Need to include CEDDK.h header file
• Need to link to CEDDK.lib
• Requires new lines in subproject’s sources file
(controls the subproject’s build operation)
• Includes go in INCLUDES section
• Libraries go in TARGETLIBS section
• “/” is the continuation character
• Blank lines matter!
• Path variables typically used
164
Table 8.2 Environment Variables used for Paths
Environment variable Description
_WINCEROOT Defines the root directory. If you have enough space on a single
partition, create a root directory on that partition, such as
C:\WINCE600, and install the OS under it. To do this, set
%_WINCEROOT% to the full root directory path.
_FLATRELEASEDIR Defines the directory where the released source code and binary
files will be placed. The default is %_WINCEROOT%\
PBWorkspaces\%_TGTPROJ%\RelDir\%_TGTPLAT%\%_TG
TCPUFAMILY%_Release.
_PROJECTOAKROOT Defines the location of the Oak directory for your project.
During the build process; Build.exe places the files it builds in
this directory. The default is %_PROJECTROOT%\Oak.
_PROJECTROOT Defines the location of the project you are building; for
example, %_PBWORKSPACEROOT%\WINCE500
\%PBCONFIG%.
_SDKROOT Defines the location of the tools you use to build projects, such
as the command-line compiler, linker, debugger, and run-time
libraries. The default is %_WINCEROOT%\SDK.
165
void Write_Port (short int Data_Port_Address, UCHAR Data)
{
// X86 in-line assembly language
// use only when you have to!
_asm {
mov dx,Data_Port_Address
mov al,Data
out dx,al
}
return;
}
UCHAR Read_Port (short int Data_Port_Address)
{
UCHAR Data;
// X86 in-line assembly language
// use only when you have to!
_asm {
mov dx,Data_Port_Address
in al,dx
mov Data,al
}
return Data;
}
166
Figure 8.2 A thread running without synchronization can run several times before the main program
Figure 8.3 Thread running using WaitForSingleObject to wait for a synchronization event
167
// Thread_Demo.cpp : Defines the entry point for the console
application.
//
// Demo that shows how to create and synchronize a thread using an
event
//
#include "stdafx.h"
//Thread Function
DWORD WINAPI WorkerThread (LPVOID lpArg);
HANDLE g_hMainEvent = 0;
}
DWORD WINAPI WorkerThread (LPVOID lpArg) {
INT threadnumber = (INT) lpArg;
INT count = 0;
INT RunCode;
while (1){
// RunCode = WaitForSingleObject(g_hMainEvent, INFINITE);
// if (RunCode == WAIT_OBJECT_0){
printf(" worker thread %d computes value %d\n",
threadnumber, count);
count++;
Sleep(50);
// }
}
return 0;
}
168
Figure 8.4 The process viewer can be used to check the status of processes and threads.
Figure 8.5 The kernel tracker shows which process is running and displays synchronization events.
169
Figure 8.6 The kernel tracker displays all of these events.
170
Producer Consumer Problem
• Producer Thread put items in shared
buffer
• Consumer Thread takes items out of
shared buffer.
• A circular buffer is used (wraps around)
with an in and out pointer.
• Critical Sections used on access to global
data in first try (need mutual exclusion)
printf(" \n");
_tprintf(_T(" Producer Consumer example\n"));
for (i=0; i<4; i++) Buffer[i] = 0;
InitializeCriticalSection(&CriticalSection);
hThread1 = CreateThread (NULL, 0, ConsumerThread,
(LPVOID)nParameter, 0, &dwThread1ID);
171
// Producer
while (1){
// Check for Buffer Full
while (count == 4)
{
printf("Buffer Full - Producer Waiting\n");
Sleep(0);
};
// Insert new item into Buffer
// Shared Global Variables - use Critical Sections
EnterCriticalSection (&CriticalSection);
printf(" producer thread produces new item at
Buffer[%d] \n",in);
++count;
Buffer[in] = GetTickCount();
in = (in + 1) % 4;
LeaveCriticalSection (&CriticalSection);
// Random delay to simulate process producing new item for Buffer
Sleep(Random()>>21);
}
CloseHandle(hThread1);
DeleteCriticalSection(&CriticalSection);
return 0;
}
172
Figure 8.7 The Producer Consumer Problem.
173
// ProCom.cpp : Defines the entry point for the console application.
// Producer Consumer problem with a shared circular buffer
//
// Demo that shows how to create and use semaphores
//
#include "stdafx.h"
// Semaphores
static HANDLE mutex_semaphore; // mutual exclusion lock
static HANDLE full_semaphore; // something is in buffer
static HANDLE empty_semaphore; // buffer has an empty space
// Shared Circular Buffer and pointers
static int in = 0;
static int out = 0;
static int count = 0;
// Shared Buffer Area
DWORD Buffer[4];
//Thread Function
DWORD WINAPI ConsumerThread (LPVOID lpArg);
// Producer
while (1){
// Wait for empty space in buffer
WaitForSingleObject(empty_semaphore, INFINITE);
// Shared Global Variables - use mutex
WaitForSingleObject(mutex_semaphore, INFINITE);
// Insert new item into Buffer
Buffer[in] = GetTickCount();
count++;
// Check for buffer full message
if (count >= 4)
printf("producer thread produces new item at
Buffer[%d] %d Buffer now Full \n",in, Buffer[in]);
else
printf("producer thread produces new item at
Buffer[%d] %d \n",in, Buffer[in]);
in = (in + 1) % 4;
ReleaseSemaphore(mutex_semaphore, 1, NULL);
ReleaseSemaphore(full_semaphore, 1, NULL);
// Random delay to simulate process producing new item for Buffer
Sleep(Random()>>21);
}
CloseHandle(hThread1);
CloseHandle(mutex_semaphore);
CloseHandle(full_semaphore);
CloseHandle(empty_semaphore);
return 0;
}
174
DWORD WINAPI ConsumerThread (LPVOID lpArg) {
INT threadnumber = (INT) lpArg;
// Consumer
while (1){
// Wait for item in buffer
WaitForSingleObject(full_semaphore, INFINITE);
// Shared Global Variables - use mutex
WaitForSingleObject(mutex_semaphore, INFINITE);
count--;
// Check for Buffer Empty message
if (count == 0)
printf("consumer thread consumes item from
Buffer[%d] %d Buffer now Empty\n",out,Buffer[out]);
else
printf("consumer thread consumes item from
Buffer[%d] %d\n",out,Buffer[out]);
// Remove item from Buffer
out = (out + 1) % 4;
ReleaseSemaphore(mutex_semaphore, 1, NULL);
ReleaseSemaphore(empty_semaphore, 1, NULL);
// Random delay to simulate process consuming Buffer item
Sleep(Random()>>21);
}
return 0;
}
Figure 8.8 Sample Output from the second Producer Consumer Problem using Semaphores.
175
Audio Example Program
• Uses PlaySound to play a *.wav file
• Uses eBox AC97 Audio Device
• Need a speaker or headphone connected
to audio output jack on front of eBox
• OS also has waveIn and waveOut API
calls for audio
#include "stdafx.h"
176
Windows Application
• Windows Applications do not directly
request I/O read operations from the
mouse or keyboard
• The OS sends messages (mouse and
keyboard events) to a Windows
Application and it then responds to them
• Push vs. Pull Technology
Windows Application
• All Windows Applications have the
program entry point WinMain
• WinMain registers the Window class
• WinMain then creates, displays, and
updates the new Window
• WinMain always ends with a Windows
Messaging (While) Loop
177
Windows Messaging Loop
• Translates and Dispatches messages to
the Window
• Stays in Windows Messaging While Loop
as long as application is running
• Blocks waiting for each new message
• Messages that are Dispatched cause the
OS to activate the Windows callback
function
178
Table 8.3 Common Hungarian Notation Prefixes
Used for Variables in Windows Programs
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // The title bar text
179
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASS wc;
return RegisterClass(&wc);
}
//
// FUNCTION: InitInstance(HANDLE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global
// variable and create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
180
//
// FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM
lParam)
{
PAINTSTRUCT ps;
HDC hdc;
TCHAR szHello[MAX_LOADSTRING];
LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);
switch (message)
{
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any additional drawing code here...
RECT rt;
GetClientRect(hWnd, &rt);
DrawText(hdc, szHello, _tcslen(szHello), &rt, DT_CENTER);
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
C# Applications
• C# has a syntax similar to Java
• Also called managed code
• Compiles to the Common Intermediate
Language (CIL) – (like Java Byte Codes)
• One version of code for all processors
• .NET Compact Framework executes CIL
code (like Java Virtual Machine)
181
C# Advantages
• Middleware provided to make
programming of GUI and networking
easier (programmers are more productive)
• Built in threads and synchronization
• More run-time checking on array bounds
and data types (safe code)
• No direct pointer manipulations (like Java)
C# Disadvantages
• .NET Compact Framework increases
kernel size by several MBs.
• C# runs a bit slower and uses more
memory than C/C++
• Periodic Garbage Collection routines have
a negative effect on real-time performance
• Items above are bigger issues on a small
embedded device than on a desktop PC
with lots of memory and a fast processor
182
C# Hello World Console Application
using System;
namespace HelloNET
{
public class Hello
{
public static void Main()
{
Console.WriteLine("Hello NETCF World");
}
}
}
183
C# Window Applications
• GUI designed using graphical tools (Visual
Studio Application Designer)
• Tool automatically generates C# code
• Can generate Windows Applications
quickly
• Most time is spent writing code manually
to handle events (hitting buttons etc.)
• Example earlier in C# Tutorial
184
Figure 8.9 This Phidget USB device contains a LCD with digital and analog I/O.
Figure 8.10 The Phidget C# demo programs running on an eBox with several Phidgets attached.
185
C/C++ Phidget API Calls
186
Calling C/C++ functions from C#
[DllImport("Users.dll")]
private static extern uint Userfunction( . . .);
Chapter 9: Introduction
to I/O Device Drivers
187
Device Drivers
• Device drivers help provide a layer of
abstraction between the hardware and the
user’s application programs
• A user developing an application does not need
to understand the low-level hardware details of
each interface.
• Applications programmers can be more
productive working at a higher level of
abstraction using device drivers
• Numerous Drivers come with the OS
• New or unique hardware may require that the
user write a new device driver
188
BSP or Device drivers for peripherals that are specific to a given SDB or
hardware hardware platform. These drivers have hardware platform-specific
platform- code and can only be used on that hardware platform. These drivers
specific drivers are in ..\WINCE600\Platform\<Hardware Platform Name>
\Src\Drivers.
Other common Drivers for strategic peripheral chipsets that are commonly found or
peripheral included on many SDB or hardware platform designs. These include
drivers devices like Realtek RTL8139, generic NE2000, DEC/Intel 2114x
Ethernet chipsets, MediaQ MQ200, and ATI Rage XL display
chipsets, and Ensoniq audio chipsets. The goal is to provide
production quality drivers for 50% of the strategic chipsets that
cover more than 75% of the hardware platforms available on the
market. These are referred to as common drivers and are in
..\WINCE600\Public\Common\Oak\Drivers. Source code is
provided for modules in the Public directory.
189
Device Manager
MDD
Monolithic Stream
Interface Driver
PDD
Device
Figure 9.1 Two alternative architectures for a Stream Interface Driver. A Monolithic Stream Interface
Driver or a Layered Stream Interface Driver. In the layered driver architecture in CE, the two layers
are named the MDD and PDD.
Application
CreateFile
File System
Stream Interface
Driver
(Loaded at Boot up)
Device
Window CE
Manager
Kernel
OAL
Interrupt Events
Software
Hardware
190
Table 9.2 Stream Interface Driver Functions.
Programming Description
element
XXX_Close (Device This function closes the device context identified by
Manager) hOpenContext.. This function is required to access the device
with CreateFile. If you implement XXX_Close, you must
implement XXX_Open.
XXX_Deinit (Device This function de-initializes a device. It is called by Device
Manager) Manager.This function is required by drivers loaded by
ActivateDeviceEx, ActivateDevice, or RegisterDevice.
XXX_Init (Device This function initializes a device. It is called by Device
Manager) Manager.This function is required by drivers loaded by
ActivateDeviceEx, ActivateDevice, or RegisterDevice.
XXX_IOControl This function sends a command to a device.This function might
(Device Manager) or might not be required, depending on the device capabilities
that the driver exposes. This function requires an
implementation of XXX_Open and XXX_Close.
XXX_Open (Device This function opens a device for reading, writing, or both. An
Manager) application indirectly invokes this function when it calls
CreateFile to obtain a handle to a device. This function is
required to access the device with CreateFile.
191
Table 9.3 Functions used by ISTs.
Function Description
InterruptInitialize Links the event with the interrupt identifier of the ISR.
WaitForSingleObject Returns when the specified object is in the signaled state or
when the time-out interval elapses.
InterruptDone Instructs the kernel to re-enable the hardware interrupt related
to this thread.
HalTranslateSystemAddress
CEDDK.dll functions can handle You must handle hardware platform-specific
bus and hardware platform- address translations. You can call
specific address translations. HalTranslateSystemAddress to translate the
address.
CEDDK.dll functions are useful The kernel functions may be useful for
for common buffer DMA. scatter/gather DMA.
CEDDK.dll functions use a The kernel functions allow you to change the
default memory alignment of 64 default memory alignment.
KB.
192
// Allocate an adapter object on the stack
DMA_ADAPTER_OBJECT AdapterObject;
AdapterObject.ObjectSize = sizeof(AdapterObject);
AdapterObject.InterfaceType = PCIBus;
AdapterObject.BusNumber = 0;
if (!dma_out_page[0]) {
ERRMSG("PDD_AudioInitialize: DMA Buffer Page Allocation Failed");
return FALSE;
}
193
// This is a Sample Stream Interface Device Driver
// Educational example intended to illustrate how stream drivers work
// using the serial I/O port hardware on the target system
// and show the use of READ_PORT_UCHAR and WRITE_PORT_UCHAR
// from the CE Device Driver Kit (CEDDK)
//
// Setup for X86 PC (CEPC)
// using 16550 UART compatiable serial port hardware
//
// Not intended to replace a good serial port device driver!
// Does not use interrupts, have any timeouts, or provide
// support for all of the serial port's features
// Would normally use OS API calls for this operation!
//
// FOR DEMO: Connect Ebox COM2: to PC with null modem cable
// Run HyperTerminal with 9600 Baud 8 data bits 1 stop bit
// no parity and no flow control
#include "stdafx.h"
#include <windows.h>
#include "ceddk.h"
PUCHAR Data_Port_Address;
UCHAR Serial_Input_Data = 0;
// ----------------------------------------------------
194
// Stream Driver Open
DWORD KOM_Open( DWORD hDeviceContext, DWORD AccessCode, DWORD ShareMode
)
{
OutputDebugString(L"DemoDriver - KOM_Open\n");
OutputDebugString(L"hDeviceContext - ");
DBGOut(hDeviceContext);
OutputDebugString(L"\n");
195
}
// Stream Driver Read
DWORD KOM_Read( DWORD hOpenContext, PUCHAR pBuffer, ULONG Count )
{
ULONG i;
OutputDebugString(L"KOM_DRIVER - KOM_Read\n");
OutputDebugString(L"hOpenContext - ");
DBGOut(hOpenContext);
OutputDebugString(L"\n");
return Count;
}
return Count;
}
196
// Stream Driver Seek
DWORD KOM_Seek( DWORD hOpenContext, long Amount, WORD Type )
{
OutputDebugString(L"KOM_DRIVER - KOM_Seek\n");
OutputDebugString(L"hOpenContext - ");
DBGOut(hOpenContext);
OutputDebugString(L"\n");
// Add Seek Function Code Here
OutputDebugString(L"KOM_DRIVER - Exit KOM_Seek\n");
return 0;
}
return;
}
197
Registry & Drivers
• On an CreateFile (Open) API call the
Device Manager searches the registry for
an entry for the device name (i.e. KOM)
• The registry entry tells the device manager
which driver to use for the device
• So a new registry entry is needed for the
KOM driver to function correctly
[HKEY_LOCAL_MACHINE\Drivers\BuiltIn\KOM_DRIVER]
"Dll" = "KOM_Port.Dll"
"Prefix" ="KOM"
"Index"= dword:1
"Order"= dword:0
"FriendlyName" = "KOM Port Demo Driver"
"Ioctl" = dword:0
198
*.bib entry to add driver to kernel
MODULES
KOM_Port.dll $(_FLATRELEASEDIR)\KOM_Port.dll NK SHK
LIBRARY DemoDriver
EXPORTS
KOM_Init
KOM_Deinit
KOM_Open
KOM_Close
KOM_IOControl
KOM_PowerUp
KOM_PowerDown
KOM_Read
KOM_Write
KOM_Seek
199
KOM Tester Example
• Need test program for new KOM driver
• Attach serial port to HyperTerminal on PC
Open KOM1: Device
• Read & Write characters from serial port
• Close Device when CTL C sent
• Driver code outputs debug messages that
will show what is happening
#include "stdafx.h"
HANDLE hSerial;
200
// Write to title out to serial port.
if (!WriteFile(hSerial, cBuffer_out, strlen(cBuffer_out),
&cBytes_out, NULL)) {
printf("file write errors\n");
Sleep(4000);
return 0;
}
cBuffer_in[0] = 0;
}
// Close File
CloseHandle(hSerial);
return 1;
}
201
69067 PID:400002 TID:4880012 22136
69067 PID:400002 TID:4880012
69067 PID:400002 TID:4880012 KOM_DRIVER - Exit KOM_Write
69068 PID:400002 TID:4880012 KOM_DRIVER - KOM_Read
69068 PID:400002 TID:4880012 hOpenContext -
69069 PID:400002 TID:4880012 22136
69069 PID:400002 TID:4880012
69221 PID:400002 TID:4e80012 KOM_DRIVER - DLL_THREAD_DETACH
.
.
.
185145 PID:400002 TID:4880012 KOM_DRIVER - Exit KOM_Read
185159 PID:400002 TID:4880012 KOM_DRIVER - KOM_Close
185160 PID:400002 TID:4880012 hOpenContext -
185160 PID:400002 TID:4880012 22136
185162 PID:400002 TID:4880012
185162 PID:400002 TID:4880012 KOM_DRIVER - Exit KOM_Close
PB Debugger Unloaded symbols for 'C:\WINCE600\OSDESIGNS\OSDESIGN7\
OSDESIGN7\RELDIR\ICOP_VORTEX86_60A_X86_RELEASE\CONSOLE.DLL'
PB Debugger Unloaded symbols for 'C:\WINCE600\OSDESIGNS\OSDESIGN7\
OSDESIGN7\ RELDIR\ICOP_VORTEX86_60A_X86_RELEASE\KOM_TESTER.EXE'
206855 PID:400002 TID:40b0002 KOM_DRIVER - DLL_THREAD_DETACH
202
Chapter 10: Advanced
OS Topics
203
Windows CE Platform Development Process
Applications and
Middleware
OAL Development
Develop and Integrate
Catalog Items
Testing and
BSP Development Integration
204
Bootloader
• Need a boot loader to bring up the OS on
a new device
• The boot loader places the run-time image
into memory for execution and then jumps
to the OS startup routine
• OS startup routine uses OAL routines
• Several example boot loaders are
provided with the OS
Bootloader/
Bootloader/ kernel.dll
startup NKGLOBAL
oal.exe
OEMGLOBAL
Startup
KITL IOCTL
library
OEMInit
Globals()
Globals()
kitl.dll
205
Modifying the OAL
• OEM Adaptation Layer (OAL) is the lowest
level of routines in the OS that
communicate directly with hardware
• Includes the basic hardware units needed
for the OS such as the real time clock,
timers, interrupts, and the cache
• Needs to be modified for each new
hardware design
kernel.dll
NKGLOBAL
oal.exe
OEMGLOBAL KITL IOCTL
kitl.dll
OS Timer
Interrupt
Startup
IOCTL
Cache
library
library
library
library
library
library
RTC
Figure 10.3 Porting CE to a new target device requires changes to the OAL routines.
206
Figure 10.4 BSP Structure
207
Figure 10.5 This hardware debug tool is tracing the instruction execution of an XScale (ARM
family) processor using a general purpose Tektronix logic analyzer. The logic analyzer is running
Windows XP. Special software disassembles code to provide the XScale assembly language
mnemonics. Image courtesy of Nexus Technology.
Figure 10.6 This hardware debug tool is tracing the instruction execution of a P4 (X86 family)
target processor using an in-target probe (ITP) adapter box with special software running on a
desktop PC running Windows XP. It disassembles code to provide the X86 assembly language
mnemonics and displays register contents. Image courtesy of American Arium.
208
CETK for Testing
• The CE Test Kit (CETK) is a tool used to
test device drivers for the new OS
• Development system works as server for
CETK
• Application Verifier Tool used for runtime
testing
• CE Stress Tool runs image for long
periods of time (memory leaks or crashes)
Development
Workstation CE 6.0 Device
CETK Test
DLLs
TUX.EXE
Log
Kato.DLL
TUX Test
DLLs
209
Figure 10.6 The CE Test Kit (CETK) UI running on the development PC.
210
Figure 10.8 The CE Stress Testing tool.
211
Rules for Safety Critical Coding
1. Restrict all code to very simple control
constructs – no goto statements, direct, or
indirect recursion.
2. Give all loop structures a fixed upper bound.
This does not include non-terminating loops.
3. Do not use dynamic memory allocation after
initialization. Memory allocators can sometimes
have unpredictable behavior.
4. Functions should only be 1 page long. When
humans cross a page boundary the error rate
increases.
5. The average function should have around two
assertions. Assertions must be used to check
for anomalous conditions.
212
Code Analysis Tool
• CE includes the PREFast static code
analysis tool.
• In subproject or project properties select
the C/C++ tab
• Change default setting for code analysis to
“yes” to run
• Log report will then be generated in build
• Detects buffer overruns and memory use
problems and more
213
Figure 10.9 The CE Run-time License Assessment tool lists features present in an NK.BIN file.
214