Introduction to Embedded Systems Using Windows Embedded CE

A Tutorial Approach with Laboratory Exercises for Windows Embedded CE 6.0 and the eBox 2300 SoC Embedded Computer
© 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?
• Any electronic device that incorporates a computer in its implementation. • The user of the device is often not even aware that a computer is present. • The computer is used primarily to provide flexibility and to simplify the system design.

Some Interesting Examples of Embedded Systems:

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

Product: NASA's Twin Mars Rovers. Microprocessor: Radiation Hardened 20Mhz PowerPC Commercial Real-time OS Software and OS was developed during multi-year flight to Mars and downloaded using a radio link

Photograph courtesy of NASA/JPL CALTECH

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 Look for one next time you order fast food!

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 Downloads News using extra bandwidth on FM radio stations in major cities

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 Also plays MP3s and Videos

10

Product: HP iPAQ Pocket PC Microprocessor: Marvel XSCALE (ARM) OS: Windows CE

Product: Motorola Q Pocket PC Phone Microprocessor: TI OMAP (ARM+DSP) OS: Windows Mobile 5.0 (Windows CE OS)

11

Product: HP iPAQ Pocket PC Phone Microprocessor: TI OMAP (ARM+DSP) OS: Windows CE

Product: Atronic Slot Machine Microprocessor: X86 OS: Windows CE Slots are networked to a casino’s back office computer system. State Gaming agencies audit code and payoff odds.

12

Product: Dresser Wayne Ovation iX Gas Pump Microprocessor: Marvel Xscale (ARM) OS: Windows CE Displays video ads & is networked to a gas station’s back office computer system. Also has remote maintenance features.

Product: Bernina Artista 200 Sewing Machine Microprocessor: Marvel StrongARM OS: Windows CE Can download new images from the internet and sew them

13

Product: LG VoIP Phone Microprocessor: Freescale i.MX21 ARM OS: Windows CE

Product: Gumstix Connex Embedded Computer Board (size of a stick of gum) Microprocessor: Marvel 400Mhz Xscale OS: DrumStix community project developing a BSP for Windows CE Great low-power CE target board for student projects.

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

More Examples of Embedded Systems
Aircraft & Aircraft autopilots, avionics and navigation Military Systems systems, automatic landing systems, guidance systems, engine controls. Biomedical Cars XRAY, MRI, and Ultrasound imaging systems, patient monitors, heart pacers.

Engine control, anti-lock braking systems, traction control systems, air bag controls, heating and air conditioning controls, GPS mapping, Satellite Radio, On-board Diagnostics. Communications Communication Satellites, network routers, switches, hubs.

15

Examples of Embedded Systems - Continued
Computer I/O devices Electronic Instrumentation Home Electronics Keyboards, mice, printers, scanners, displays, modems, hard disk drives, DVD drives, graphics cards, USB devices. Data acquisition systems, oscilloscopes, voltmeters, signal generators, logic analyzers. Microwave ovens, dishwashers, DVD players, televisions, stereos, security systems, lawn sprinkler controls, thermostats, cameras, TVs, clock radios, answering machines, satellite or cable box, appliances. Elevator controls, surveillance systems, robots, CNC machines, Programmable Logic Controllers, industrial automation and control systems.

Industrial Equipment

Examples of Embedded Systems - Continued
Office Machines Personal Devices FAX machines, copiers, telephones, calculators, cash registers. Cell phones, portable MP3 players, Video players, Personal Digital Assistants (PDAs), electronic wrist watches, handheld video games, digital cameras, GPS systems. Industrial robots, autonomous vehicles, space exploration robots (i.e. Mars robots) Video Game systems, “Aibo”, "Furby“, and “Elmo” type robot toys.

Robots Toys

16

Importance of Embedded Systems
• Ratio of Embedded Devices / Desktop PCs is greater than 100 • The typical house may contain over 50 embedded processors • A high-end car can have over 50 embedded processors • Embedded systems account for the most of the world’s production of microprocessors!

Challenging System Design Goals
• Reliability
– Can’t Crash, may not be able to reboot – Can’t update many embedded devices

• Performance & Power
– Real-time issues in many applications – May need to run on battery power – Limited memory and processing power

• Cost
– Fast time to market on new products – Consumer Products are very cost competitive

17

Real-Time System
• A real-time system responds to events.
External Input Event Process New Data External Output Event

Example: An Automobile airbag system. When the airbag’s motion sensors detect a collision, the system needs to respond by deploying the airbag within 10ms or less. – or the system fails!

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

Multi-Tasking and Scheduling
• Many embedded systems are real-time systems with several inputs and outputs. Multiple events are occurring independently. • Programming is simplified by separating the tasks, but this requires the CPU to switch back and forth among the different tasks • An operating system that supports multitasking has features to time slice the CPU among multiple tasks. • OS provides Synchronization Primitives

19

Product: TMIO ConnectIO Oven OS: Windows CE Also refrigerates food before cooking and is controlled over the internet or via phone

Internet Oven: Example Tasks
•Control Oven Temperature (when cooking) •Control Refrigeration Temperature (when cooling) •Check for Keypad input and handle input •Check cooking time to turn oven on/off (for timed cooking) •Update time and temperature display on front panel •Check for Internet communications and handle messages •Check for Phone communications and handle messages
How would all of these tasks be scheduled? Is synchronization needed anywhere? What networking and communications support is needed? Would an OS help?

20

Why have an OS in an embedded device?
• Support for multitasking, scheduling, and synchronization • Support for a wide range of I/O devices • Support for file systems • Scheduling and buffering of I/O operations • Support for networking • Memory management • Support for graphics displays • Security and Power Management

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

Typical Software Development Tools Used for Embedded Applications
•Compiler - compile C/C++ and in-line assembly language •Linker – links compiled application code, OS, and runtime libraries •Memory Image tools – tools to place code in non-volatile memory at a given physical memory address •Debugger – tool to debug OS and applications programs •Loader – load OS at power on and applications. Also a tool to download new code from the development system is typically provided.

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

Processor Bit Size Used in New Embedded Designs
64-bit 32-bit 16-bit 8-bit 4-bit 0.00% 10.00% 20.00% 30.00% 40.00% 50.00% 60.00%

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

32-64 bit Annual Processor Sales
Processor Sales Volume
ARM X86 MIPS SuperH PowerPC 0.00% 5.00% 10.00% 15.00% 20.00% 25.00% 30.00% 35.00% 40.00%

Based on 2002 sales data

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

Number of Processors Used in New Embedded Designs
1 Processor

2 Processors

3-5 Processors

More Than 5 0.00% 10.00% 20.00% 30.00% 40.00% 50.00% 60.00%

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

Open Source OS?
• “Free” OS can cost more for product development • More time to develop kernel, device drivers & product can increase labor cost more than the commercial OS license fees saved • Some other licenses still required for many devices in addition to free OS (real-time kernel, browser, encoders & decoders, encryption, media player) • Open source license model may require that you publish your device’s source code • Some Studies even show a recent decline in Open Source OS use:
– http://www.embedded-forecast.com/EMFTCD2003v3.pdf – http://www.embedded.com/showArticle.jhtml?articleID=187203732

27

Commercial Operating Systems used in New Embedded Designs
Microsoft Emb. Wind River Symbian Green Hills Palm Others 0.00% 5.00% 10.00% 15.00% 20.00% 25.00% 30.00%

Data was derived from EETimes and Embedded Systems Design Magazine 2006 Embedded Market Survey

Programming Languages Used in New Embedded Designs
C C++ C# Java Assembly Others 0.00% 10.00% 20.00% 30.00% 40.00% 50.00% 60.00% 70.00%

Data was derived from EETimes and Embedded Systems Design Magazine 2006 Embedded Market Survey

28

Conclusions
• Embedded devices can be found everywhere in large numbers! • Most new devices are using 32-bit processors • Most new devices with an OS use a commercial off-the-shelf OS • The C family (C, C++, C#) is the most widely used language for embedded systems

Product Life Cycle
Design Phase
• • Design Concept Product Planning • • •

Development Phase
Design Review Build Prototype Product Testing • • •

Production Phase
Pilot Production Mass Production Technical Support

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

Processor

Main Memory
(SDRAM or SRAM)

Flash Memory
(non-volatile 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

A single bus architecture was used on early computers.

Processor

Memory

I/O Hardware

System Bus

But Modern systems are more complex and actually contain a hierarchy of different busses!

31

A First Generation Bus Example: ISA
• ISA bus used in early PCs for Plug-in Cards • Address Bus (SAx)
– Originally 16 bits then expanded to 24

• Data Bus (SDx)
– 8 bits then 16 bits – EISA expanded it to 32 bits

• Bus Status Signals
– MEMR, MEMW, IOR, IOW

• 5V TTL signals

Digital Logic Review: A simple address decoder circuit for 4-bit address (A3..A0) = 0xA
A3 A2 A1 A0

Address Decoder Output

Would need to decode more address bits in an actual system

32

Tri-state logic gate outputs are used to drive most bus signals
control 0 0 1 1 input 0 1 0 1 output High Z High Z 0 1 tri-state control input

input

output

Hardware allows only one tri-state gate at a time to drive a bus signal! Works just like a large multiplexer: One of several inputs connects to the output

Legacy PC I/O address assignments
I/0 address range I/O device 000h – 200h Reserved for Internal Devices: Interrupt & DMA controllers, timers 278h - 27Fh Parallel Printer (LPTx:) 2E8h - 2EFh Serial Port 4 (COM4:) 2F8h - 2FFh Serial Port 2 (COM2:) 378h - 37Fh Parallel Printer (LPT1:) 3B0h - 3BBh MDA Adapter 3BCh - 3BFh Parallel Printer (LPTx:) 3C0h - 3CFh VGA/EGA Adapter 3D0h - 3DFh CGA Adapter 3E8h - 3EFh Serial Port 3 (COM3:) 3F0h - 3F7h Floppy Controller 3F8h - 3FFh Serial Port 1 (COM1:)

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

Address

Valid Address

I/O Write

Data

Valid Data

Clock data into a register on this edge!

An Example ISA Bus I/O Read Operation

Bus Clock

Address

Valid Address

I/O Read

Data

Valid Data

34

Typical I/O Input Port Hardware Operation
Bus I/O Read Command Device’s I/O Address Decoded Address Bus Address Decoder Circuit Data Bus bit x One tri-state gate is needed for each bit on the data bus Tri-state Control Data bit x in from I/O Device

Typical I/O Output Port Hardware Operation

Address Bus

Address Decoder Circuit

Data Bus

R e g i s t e r

Data out to I/O Device

Device’s I/O Address Decoded Bus I/O Write Command

Clock

35

Options for Building Custom I/O ICs
• Full custom VLSI devices and Application Specific Integrated Circuits (ASICs) have very high setup costs – a very large volume is required to recover development cost. Typically made only by the major chip vendors. • Field Programmable Gate Arrays (FPGAs) are programmed by the end user. Low development costs, but higher unit costs, slower clock rates, and higher power levels. – only a moderate volume needed to recover development costs

Using an HDL to design I/O hardware
-- VHDL-based Address Decoder for 0x3E0 PORT_IO_DECODE <= '1' WHEN ADDRESS = X"3E0" AND AEN='0' ELSE '0';
-- VHDL-based I/O Input Port - use tri state buffers DATA <= PORT_DATA_IN WHEN PORT_IO_DECODE = '1' AND IOR = '0' ELSE "ZZZZZZZZ";

-- VHDL-based I/O Output Port – use a register (with DFFs) PROCESS BEGIN -- clock on positive edge of ISA IOW WAIT UNTIL IOW'EVENT AND IOW='1'; -- use address decoder output for the DFF clock enable IF PORT_IO_DECODE = '1' THEN -- save data on ISA data bus in register PORT_DATA_OUT <= DATA; END IF; END PROCESS;

36

Software for I/O port transfers
• Can use in-line assembly language in C/C++ • Most C/C++ compilers have built-in function calls for I/O port input and output • C# can call C/C++ functions in a DLL

In-line Assembly Example for X86
// I/O Input Routine __asm{ mov dx, IO_address in al, dx mov IO_data,al } // I/O Output Routine __asm{ mov dx,IO_address mov al,IO_data out dx, al }

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

A Second Generation Bus - PCI
• • • • • • • 32-bit Multiplexed Address and Data Bus (AD) Address sent on first clock cycle Bus command sent on first clock cycle (C/BE) Data on subsequent clock cycles Bus Clock rates 33 to 512Mhz One Data transfer per clock is possible Supports Data Bursts (example to follow)

38

PCI Bus Commands (C/BE)
PCI Bus Command Interrupt Acknowledge Special Cycle I/O Read I/O Write Reserved Reserved Memory Read Memory Write Reserved Reserved Configuration Read Configuration Write Memory Read Multiple Dual Address Cycle Memory Read Line C/BE 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110

Memory Write and Invalidate 1111

PCI Read Burst Cycle
0 Bus Clock 1 2 3 4 5 6 7 8 F rame #

AD

Address

Data1

Data2

Data3

C/BE#

Bus-Cmd

BE#’s

IRDY#

TRDY#

DEVSEL#

Address Phase

Data Phase Bus Transaction

Data Phase

Data Phase

39

PCI Read Burst Cycle
Clock Cycle 0 1 2 Description of PCI operation Bus is idle 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). 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) 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. The target sets TRDY high to indicate it need an additional clock cycle for the next data transfer. The second data transfer occurs when both TRDY and IRDY are low. The initiator saves the target data. The target drives the data value, but the initiator requests an additional clock cycle by set IRDY high. 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. All bus signals are tri-stated or driven to the inactive state.

3 4 5 6 7 8

PCI Write Burst Cycle
0 Bus Clock 1 2 3 4 5 6 7 8 F rame #

AD

Address

Data1

Data2

Data3

C/BE#

Bus-Cmd

BE-1

BE-2

BE-3

IRDY#

TRDY#

DEVSEL#

Address Phase

Data Phase

Data Phase Bus Transaction

Data Phase

40

PCI Write Burst Cycle
Clock Cycle 0 1 2 Description of PCI operation Bus is idle 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). 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) 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. The initiator sets IRDY high and the target sets TRDY requesting an additional clock cycle. The initiator drives new data and byte enables and sets IRDY low. The initiator sets FRAME high indicating the final data transfer. The target drives the data value, but the initiator requests an additional clock cycle by set IRDY high. The initiator sets IRDY low to complete the third data transfer. The target saves the data value. All bus signals are tri-stated or driven to the inactive state.

3 4 5 6 7 8

Accelerated Graphics Port (AGP)
• Newer Graphics cards were consuming most of the PCI bus bandwidth • Solution: Move graphics card to its own PCI bus • A connection with only 1 device is technically a port and not a bus. • Extra clock phase signals were added to increase clock rate 2X, 4X, and 8X

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)

Third Generation Bus – PCI Express
• High-Speed Serial line(s) are used to transfer PCI signals • Fewer signal lines are used, but with much higher bandwidth on each signal line
– More stringent design restrictions on drivers, length, loading, crosstalk, and terminations

• Clock rates from 2.5 Gbps to 10 Gbps • Can combine serial lines into groups called lanes to provide more bandwidth to a device • No changes needed in software – works the same as PCI

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.

I/O Transfer Methods
• Programmed I/O (Software Polling) • Interrupt Driven I/O • Direct Memory Access (DMA)

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

Programmed I/O Pseudo Code
// loop until output ready=1 do { // read status and mask off ready bit status = read_port(status_port_address); output_ready = status & 0x01; } while (output_ready == 0); // output new data value write_port(data_port_address, data_value);

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 ……. Mov… Add… …… ….. ……. …… ……. …… ……… ….. ……. ….. ….. …. ……. 2. ISR Code executes …… Mov.. Out.. ……. Reti 4. ISR Returns 3. IST Launched (Optional) ………. ………… ….. …….. …….. ……. …….. .

Interrupts – Other Issues
• Interrupt latency time – set by longest instruction or longest block of code that disables interrupts. Determines the max time to respond to an interrupt. ISR may launch an interrupt service thread (IST) to complete operations so that it can return in less time. • Some critical code (non reentrant) might require that interrupts be disabled. Most machines have an enable and disable interrupt instruction. But doing this impacts interrupt latency time.

47

Interrupts
• Interrupt controller hardware is needed to set priority and enable/disable each interrupt signal • Additional bus signals needed
– ISA – IRQx lines – PCI – INTx lines

• For security, the OS must control all interrupt hardware, the vector table, and the ISRs.

Direct Memory Access
• A DMA controller transfers blocks of data directly to/from memory and the I/O device. • DMA controller is a state machine with an address pointer and a counter. Counts down number of memory locations for transfer and drives bus address and control lines (is a Bus Master) • Processor not involved in transfer once it starts

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

DMA Bus Cycle
Processor With Cache Memory I/O Hardware using DMA

System Bus

• Processor does not drive the bus during a DMA bus cycle • Bus Arbitration hardware is needed to support multiple bus masters

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.

OS File I/O Operations
• Open (or Create): For a read operation on an existing file, the open operation searches for the file, for a write operation it searches for available space on the storage device and typically allocates buffer space to handle file transfers. • Read: The next block of data is read from the open file. A file identifier or handle and a pointer to a buffer area in which to return the data read are arguments. • Write: The next block of data to write to the open file. A file identifier or handle and a pointer to a buffer area from which to copy the data to write are arguments. • Seek: Move to a specific location within a file. The argument is normally the record number to seek to. Seek is much faster than reading multiple times to move to a specific record in a file. • Close: Close the open file. For a write operation, close flushes all write buffers and updates the directory entries for the new file.

51

Windows Embedded CE File I/O API Calls
• • • • Open with CreateFile Read with ReadFile Write with WriteFile Seek with SetFilePointer

• Close with CloseHandle

Unicode and ASCII Character Encoding
• For international market will need to support different languages
– www.unicode.org/charts/

• Unicode is a 16-bit character code that supports scripts for different languages • ASCII is an 8-bit character code for English (Basic Latin Script) • Have to work with both and convert!

52

ASCII Character to Hexadecimal Conversion Table
0 1 2 3 4 5 6 7 0 NUL DLE SP 0 @ P ` p 1 SOH DC1 ! 1 A Q a q 2 STX DC2 " 2 B R b r 3 ETX DC3 # 3 C S c s 4 EOT DC4 $ 4 D T d t 5 ENQ NAK % 5 E U e u 6 ACK SYN & 6 F V f v 7 BEL ETB ' 7 G W g w 8 BS CAN ( 8 H X h x 9 HT EM ) 9 I Y i y A LF SUB * : J Z j z B VT ESC + ; K [ k { C FF FS , < L \ l | D CR GS = M ] m } E SO RS . > N ^ n ~ F SI US / ? O _ o DEL

•Example: Find “A” in the table above. It is in row 4 and column 1, so it’s ASCII value is 0x41. •In Unicode, the first 128 characters are the same as the 8-bit ASCII character with a high byte of all zeros to pad it to 16-bits.

Important ASCII Control Characters (<0x20)
• ASCII characters below 0x20 are control codes, they do not print a character - they perform control operations • LF (line feed) - Moves the cursor down to a new line, but not to the left. “\n” in C/C++/. Some systems automatically add CR to a LF. • CR (carriage return) - Moves the cursor all the way to the left, but does not advance to the next line. “\r” in C/C++/. For a new line, both CR and LF are needed. • SP (space) prints a blank space and cursor moves to the next character position. • FF (form feed) - Advances paper to the top of the next page on printers or clears the display window in terminals. “\f” in C/C++/.

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.

Chapter 3: I/O Interfacing Standards for External Devices

55

Common Digital I/O Interfacing Standards for External Devices
•Parallel Port •Serial Port •PS/2 •SPI & I2C •Analog I/O •USB •Audio AC97

Parallel Port transfer of an 8-bit data value to a printer
Data Lines Busy Data Valid

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)

RS-232 Serial Interface
• Transmit and Receive data lines • No clock signal exchanged – Sender and receiver need to have same baud rate • Baud rate is the clock rate of the bits • Normal Bits: Start, 8 Data, Stop • Voltage levels: a 1 is >3V and a 0 is <-3V • Special RS232 voltage level converter chips are typically used

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

RS-232C Serial interface transmission of an 8-bit data value
0x50 = ASCII “P” 0 Mark (1) Space (0) Start Bit 0 LSB 1 2 3 4 5 Data Bit number 6 7 MSB Stop Bit 0 0 0 1 0 1 0

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 Keyboard Transmission of a Keyboard Scan Code

PS/2 Clock PS/2 Data Start Bit 0 1 1 0 1 0 0 Data Bits (low to high) 0 Parity Stop Bit Bit

Scan code 16H for “1” key

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

The two SPI slave device configuration options.
Slave 0

Master CS0 CS1 CS2 SCLK SDO SDI

Slave SDI SDO

Master CS0 CS1 CS2 SCLK SDO SDI

SDI

SDO

SDI Slave SDO

Slave 1 SDI SDO

Slave

SDI

Slave 2 SDI 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

I2C interface serial transmission of an 8-bit data value

SDA MSB ACK Signal from Slave Byte Complete SCL 1 2 3-6 7 8 9 R/W ACK Clock Line Held Low while serviced 1 2 3-7 8 9 ACK ACK Signal from Receiver

S

P STOP

ST RT A

Address

Data

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

A low-cost USB Microcontroller is typically used in USB Devices
+5V bytes D+ DSerial Interface Engine (SIE) USB Transceiver bytes USB Interface Program & Data (R AM & ROM) I/O Ports

GND USB Connector

General Purpose Microprocessor

63

USB Data Rates
• • • • USB 2.0 – Up to 480 Mbps USB 1.0 – 12 Mbps and 1.5 Mbps USB 2.0 supports USB 1.0 devices Needed higher USB 2.0 data rates for external drives and video

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
O U T A D D R E N D P C R C 5 D A T A 1 Payload Data Data Packet C R C 1 6 A C K H/S Pkt O U T A D D R E N D P C R C 5 D A T A 0 Payload Data Data Packet C R C 1 6 A C K H/S Pkt

Token Packet

Token Packet

Payload D ata D+ Serial Interface Engine D(SIE) A C K Payload D ata

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

Figure 3.9 Realtek ALC202 AC97 Device Block Diagram

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

Car Body Network with CAN & LIN
Mirror Lock Lock Window Lift Universal Light Light

CAN Seat Instruments Power Train ITS x6 Central Body Ctrl Climate Light St-Wheel Panel Seat CAN Htng Roof Htng Interior Light Htng Seat

Htng Wiper WHtg Trunk

1 backbone, 13 nodes 8 subnets, 1-8 local nodes 52 nodes total

Lock Sub-Bus Mirror

Universal Motor Lock Universal Panel

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

SOF 11 Bit Identifier RTR r1 r0

D LC Data (0-8 Bytes) 15 Bits

Slot

D elimiter

Figure 3.10 A CAN 2.0A Message Frame

71

Local Interconnect Network (LIN)
• Can be implemented with a UART and microcontroller firmware • Data rates up to 20K Baud • Only one bus master • Lower cost, lower data rates, and 1 less wire than CAN

Message Frame Header Response CheckSum Field Interfram Space or Break

Sync Break

Sync Field

Ident Field

Data Field

Data Field

Data Field

Data Field

Interbyte Space In_Frame Response Space

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) Preamble 7 bytes SFD 1 byte Destination Address 6 bytes Source Address 6 bytes Length PDU 2 bytes Data and Padding 46 to 1500 bytes CRC 4 bytes

• • • • • • •

Preamble - 56-bit start region, denotes the beginning of a Ethernet frame SFD - Start Frame Delimiter, 8-bit value marking the end of the preamble Destination MAC Address – 48-bit address denoting were data is headed Source MAC Address – 48-bit address denoting were data came from Length/Type (PDU) - 16-bit sub-protocol label field with length or type Data Payload – The data being sent CRC (or Frame Check Sequence), a CRC value computed on the entire frame. Used to detect bit errors occurring during transmission.

75

A Small Ethernet Network
P ri nter Computer

C

A

Ethernet Medium

Compu ter

Computer

B

D

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
Bridge Segment 1 Segment 2

D

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
Data TCP Header IP Header Frame Header TCP Data Application Protocols

Transport Protocols

IP Data Frame Trailer

Internet Protocols

Frame Data

Network Topology

Network Software Support
• Ethernet controller hardware filters, buffers, sends, and receives Ethernet packets • Software is still needed to implement protocols • OS typically provides software to implement the network protocols (TCP/IP, HTTP, FTP, etc.) • OS may also support networked file systems • Common network applications (i.e. browser, telnet, ftp) may be provided with OS or available from third parties

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.

Wireless Networking Standards • WiFi - IEEE Standard 802.11 • Bluetooth - IEEE Standard 802.15.1 • ZigBee - IEEE Standard 802.15.4 • Features of each on the next slide

79

Feature Application Area Target Cost Memory Requirement Battery Life Network Size Peak Data Rate

802.11b/WiFi Web, Email, Video $25 1MB+ .5-5 Days 11,000+ 1, 2, 5.5, 11, (54-802.11g) Mbps

802.15.1/Bluetooth Cable Replacement $15 250KB 1-7 Days 7 1Mbps

802.15.4/ZigBee Control & Monitoring $5 4KB - 32KB+ 100-1000 Days 20-250 250 Kbps @ 2.4 GHz 40 Kbps @ 915 MHz 20 Kbps @ 868 MHz 60 mW active @ 0 dBm 5–2000 mW sleep (mode dependent) 0 dB –85 dBm –92 dBm @ 868/915 MHz ~50 m @ 0 dBm ~10 m @ 0 dBm 16 @ 2.4 GHz 10 @ 915 MHz 1 @ 868 MHz O-QPSK @ 2.4 GHz BPSK @ 868/915 MHz 30 dBm

Power Consumption (targeted) Adjacent Channel Rejection Receiver Sensitivity Range Line of Sight Range— Indoor (approx.) Number of Channels Modulation Technique Maximum Transmit Power

1.5 W active @ 20 dBm 45 mW sleep >35 dB –80 dBm ~200 m @ 11 Mbps ~500 m @ 1 Mbps ~40 m @ 11 Mbps ~100 m @ 1 Mbps 11 - DSSS 79 - FHSS GFSK—FHSS BPSK/QPSK—DSSS 20 dBm—FHSS 30 dBm—DSSS

80 mV active @ 0 dBm 100 mW sleep 0 dB –70 dBm ~30 m ~100 m, Class 1 ~10 m ~30 m, Class 1 79 GFSK

20 dBm

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

CE Target Hardware: eBox 2300
Hardware Features:
• Vortex86 200Mhz SoC • 128MB SDRAM • 256MB Flash • VGA • 10/100Mbps Network • AC97 Audio • PS/2 Keyboard & Mouse • CF Slot • 3 - USB V1.1 Ports • 2 - RS-232 Serial Ports • Int. Wireless LAN (Optional) • Fanless Design • Low Power: 7-15 watts @5V • Small: 4.5 x 4.5 x 1.5 inches

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

Inside the eBox 2300
Audio CODEC 128MB SDRAM 256MB FLASH Ethernet Controller

BIOS ROM

Vortex86 SoC PS/2, USB, VGA, serial, & Network connectors

Bottom of PCB: Mini PCI & CF slot

82

Vortex86 System on a Chip (SoC) is used to build the eBox
Ethernet LAN RTL8100B Mini-PC1 SDRAM 128M 64-Bit Vortex 86 North Bridge Ultra IDE Flash CF Slot VGA +5V Input +5V SB+5V +3.3V SB+3.3V +2.5V +1.8V SB+1.8V Vortex 86 South Bridge Control Logic AMI BIOS 256 Doc/Flash LAN2 10/100M RJ45

CPU-Vortex 86 Vortex 86-SoC

PC1

LPC

Super I/O W83697HF

Com1 Com2

PS/2 Keyboard 32.768KHz RTC Battery PS/2 Mouse USB 1.1 x 3 AC97 AC97 CodeC Line In Line Out Mic In

Vortex86 SoC Chip
• Includes an X86 200Mhz Processor core • Includes traditional Northbridge and Southbridge PC motherboard features • A few additional parts are needed to provide the I/O features typically found on a PC • External SDRAM and FLASH devices are required • Using SoC approach reduces size, cost, and power • Runs Windows Embedded CE using standard PC hardware reference platform (CEPC)

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 Video (SiS-550) Audio (SiS-7019) Ethernet (RealTek-8100) Serial Ports (16550 UART) USB Ports (USB 1.1 Host) USB Flash Drive CF storage card IDE Disk MiniPCI (internal slot) Internal 802.11 Wireless Card (optional) (VIA VT6655 - US only) CE 6.0 Drivers Vortex86_Display (Driver included with ICOP eBox BSP) Vortex86_Audio (Driver included with ICOP eBox BSP) RTL8139 (Driver provided with CE 6.0) Com16550 (Driver provided with CE 6.0) OHCI (Driver provided with CE 6.0) USB Storage Class (Driver provided with CE 6.0) ATAPI & Compact Flash / PC Card Storage (ATADISK) (Driver provided with CE 6.0) ATAPI (Driver provided with CE 6.0) PCI Bus (Driver provided with CE 6.0) VIA VT6655 (Driver provided by VIA & ICOP)

Adding Peripherals to eBox 2300
• • • • • • Can attach any PS/2 keyboard and mouse Use any standard VGA monitor PC style audio speakers and microphone USB Flash drives Other USB devices that have CE drivers available Serial device (one port normally used for CE Debug) • CF cards that have CE drivers available • Standard 10/100Mbs Network connection • Can add internal Mini PC Wireless card with antenna

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

Other USB I/O options
• Various USB devices built using FTDI USB chipsets ( www.DLPdesign.com/usb/ DLP-D245PB-G) • Lower board cost than Phidgets ($40), but more hardware effort is required. • The DLP-245PB-G has both digital and analog I/Os. • Some have free CE drivers (6.0 status?) • DIP modules plug into a standard .1” protoboard

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.10 Low-cost sensors from left to right: Line following, IR proximity, shaft encoder, GPS, Sonar, IR distance, Electronic Compass, CMOS Camera

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.

Internal Wireless Kit

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.

Low-cost Robot Base for the eBox

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

Windows Embedded CE 6.0
• • • • Initial version developed in mid 1990s Supports ARM, MIPS, SHx, and X86 processors Hard real-time OS Not a port of Desktop Windows - Designed from scratch for embedded devices • Core technology used in Windows Mobile SmartPhone and PocketPC devices • Default setup has a look and feel similar to the Desktop Windows OS

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

Virtual Memory Address Space
• Designed primarily for 32-bit processors with Virtual memory mapping (232 - 4G) • Virtual memory used for memory protection of kernel • 2G of Virtual memory address space setup for Kernel Space • 2G of Virtual memory address space setup for User Space

97

CE Kernel
2 GB Kernel Space

File system GWES Drivers

User VM Memory Mapped files 2 GB per Process User DLLs Process Code User VM

. ..

..

.
Up to 32 K Processes

Figure 6.1 The Windows Embedded CE 6.0 Virtual Memory Space Model.

Applications
User Space SHELL
Services Services Services Services User Mode Services Drivers Services Services

SERVICES . EXE

UDEVICE . EXE

COREDLL /

WINSOCK /

COMMCTRL /

WININET / COMMDLG

DEVICE .DLL KERNEL . DLL Kernel Space OAL . DLL Boot Loader FILESYS GWES NETWORK Drivers KCOREDLL Hardware DLL

Figure 6.2 Windows Embedded CE 6.0 Architecture.

98

CE User Processes
• Shell – Standard or custom interface for device • Services.exe hosts n number of services • UDevice.exe hosts n number of user mode drivers

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

Figure 6.3 CE 6.0 System Calls

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

Figure 6.4 CE 6.0 Kernel Architecture.

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
NOTE: Remember that Physical memory size is independent of the Virtual Memory Address Space!

0x80000000

Shared System Heap 255 MB RAM Backed Mapfiles 256 MB Shared User DLLs 512 MB User Space 2 Gigabytes Each process has its own mapping

R/W for OS components Read only for user process
RAM Backed Map files Mapped at fixed location for better backwards compatibility All DLLs – code and data Same mapping across all processes Data pages are unique physical pages Code pages are shared
0x40000000

Process space 1 GB per process

0x00000000

Figure 6.5 User Space Virtual Memory Mapping

102

CPU Specific VM

0xFFFFFFFF

System Trap Area Kernel Virtual Memory Shared by all kernel Servers and drivers

Kernel VM (if supported by CPU) 256 MB Kernel VM 256 MB

Kernel Space 2 Gigabytes Fixed mapping independent of user space

Object Store (128MB) Kernel XIP DLLs (128 MB)

All XIP DLLs in kernel Uncached access to physical memory

Static Mapped Uncached 512 MB Static Mapped Cached 512 MB

0x80000000

Figure 6.6 Kernel Space Virtual Memory Mapping.

Table 6.1 CE 6.0 Virtual Memory Map. Mode Kernel Kernel Kernel Kernel Kernel Kernel Kernel User User Range 0xF0000000 0xFFFFFFFF 0xE0000000 0xEFFFFFFF 0xD0000000 0xDFFFFFFF 0xC8000000 0xCFFFFFFF 0xC0000000 0xC7FFFFFF 0xA0000000 0xBFFFFFFF 0x80000000 0x9FFFFFFF 0x7FF00000 0x7FFFFFFF 0x70000000 0x7FEFFFFF Size 256 MB 256 MB 256 MB 128 MB 128 MB 512 MB 512 MB 1 MB 255 MB Description CPU specific VM Kernel VM, CPU dependent Kernel VM Object store Kernel XIP DLLs Statically mapped Uncached Statically mapped Cached Unmapped for protection Shared system heap Comments System call trap area. Kernel data page. Kernel space virtual memory, unless disallowed by the CPU, such as SHx. Kernel space virtual memory, shared by all servers and drivers loaded in kernel. RAM based storage for RAM file system, CEDB databases, and RAMbased registry. Legacy data store. XIP DLLs for the kernel and all servers and drivers loaded in the kernel. Direct access to physical memory bypassing the CPU cache. Direct access to physical memory accessed through the CPU cache. Buffer between user and kernel spaces. Shared heap between the kernel and the process. Kernel and kernel servers can allocate memory in it and write to it. Read only for user processes It is a system optimization that allows a process to get data from a server without having to make a kernel call.

103

User

0x60000000 0x6FFFFFFF

256 MB

RAM backed map files

User

0x40000000 0x5FFFFFFF

512 MB

User mode DLLs Code and data

User

0x00010000 0x3FFFFFFF 0x00000000 0x00010000

1 GB 64 KB

User

Process User allocatable VM CPU dependent user kernel data

RAM backed mapfiles are mapped at fixed location for backward 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. DLLs loaded at bottom and grow up: • Based starting at 0x40000000. • Code and data are intermixed. • 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. Executable code and data User VM (heap) virtual allocations: 1 VM allocations start above the exe and grow up. User kernel data is always r/o for user. Depending on CPU, it can be kernel r/w (ARM), or kernel r/o (all others).

Figure 6.7 Example of Virtual to Physical memory mapping on a device.

104

What is in Memory?
• OS Kernel • Application Code & Data • Object Store – File System, Registry, Builtin 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 item name Compression Database Support Bit-based Description An application programming interface (API) that compresses the data in the RAM and ROM file systems, as well as the database volumes. An API that provides built-in CEDB database support. 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. A file system driver capable of reading data from the ROM file system and the RAM file system in the object store. A file system driver capable of reading data from the ROM file system. A registry system that stores data inside files, or hives, which can be kept on any file system. A system that stores all registry data within the object store. The Storage Manager is responsible for all external storage items, such as file systems, file system filters, and partitioning. A Catalog item that is used to load a portion of an OS image from persistent media into RAM for execution. This Catalog item uses demand paging to load additional modules as needed.. A file system driver that supports both Compact Disc File System (CDFS) and Universal Disc File System (UDFS) and reads compact discs (CDs), digital video discs (DVDs), and CD-ROMs. An API that provides enhanced database functionality, including support for transactions, access by multiple users, multiple sort orders, key properties and databases. A file system driver that supports the file allocation table (FAT) file system.

RAM and ROM File System ROM-only File System Hive-based Registry RAM-based Registry Storage Manager Binary Rom Image File System CD/UDFS File System EDB Database Engine FAT File System

Extended FAT File System Partition Driver Storage Manager Control Panel Applet Transaction-safe FAT File System (TFAT) System Password Release Directory File System Silent FATFS UI

A file system driver that supports the Extended FAT file system. A driver that interprets the partitions on a storage device for the Partition Manager. A control panel application that allows a user to manipulate storage devices. A transaction-safe FAT file system that ensures the file allocation table is not corrupted during power cycles. An API that provides support for authentication on a device to prevent unauthorized access. A functionality that provides support for the Release Directory File System 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)

Processes and Threads
• Preemptive scheduling with 256 priority levels • Round-robin scheduling of threads with same priority • Highest Priority 0 threads run to completion • Time slice 1-100ms (100 ms is Default)

107

Priority Levels
Table 6.3 Priority Levels Description Reserved for real-time above drivers. Used by the default CE-based device drivers. Reserved for real-time below drivers. Maps to non-real-time priorities.

Range 0 through 96 97 through 152 153 through 247 248 through 255

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 lowerpriority thread delays the execution of a higherpriority 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

Figure 6.10 Priority Inversion Example.

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

Table 6.4 Windows CE 5.0 Real-Time Test Results Interrupt ISR IST Response Times starts starts Minimum 1.2 µs 31.7 µs Average 3.3 µs 67.2 µs Maximum 13.3 µs 103.0 µs

110

Real-Time Performance of CE 6.0
100 ms

Response Cycle Time

Soft Real-Time
20 ms 10 ms 5 ms

Hard Real-Time
Windows CE

Hard Real-Time Linux?

Windows XP

1 ms 500 us 0

100 µs

1,000 µs

5,000 µs

10,000 µs

Cycle Variation or Jitter (µs) (µ
Figure 6.10 CE Real-Time Performance Measurements showing Response Cycle Time. Soft and Hard RealTime. Real-Time categories are based on OMAC study and OS times are without any third party real-time Realrealextensions to the OS.

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

User Mode Driver Host Process User Application

4
User Mode Driver udevice.exe

User Mode 1 Kernel Mode Device Manager

6

3 2

5
Reflector Service

1
Parent Bus Driver
Figure 6.12 User Mode Driver Architecture

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!

Table 6.5 Registry Root Constants Root key constant Description HKEY_CLASSES_ROOT Stores file type matching and OLE configuration data. HKEY_CURRENT_USER Stores user-specific data for the user who is currently logged in. This root points to the relevant key of HKEY_USERS. Changes made are automatically made in the user's key under HKEY_USERS. HKEY_LOCAL_MACHINE Stores machine-specific data and configuration information for device drivers and applications. HKEY_USERS Stores data for all users including a default user.

115

Device Manager
• • • • Manages Devices and their Interfaces Decides which drivers to load Uses Registry to find drivers Runs continuously

Table 6.6 Device Manager Components Component Description devcore Provides the core Device Manager functionality. iorm Provides the I/O Resource Manager functionality. Iorm is a required component and cannot be removed. pmif Pmif provides the interface to Power Manager DLL entry points. nopmif Nopmif provides the stubbed version of the Power Manager entry points.

116

Process File System (FileSys.dll) Device Manager (Device.exe) Graphics, Windowing, and Events Subsystem (GWES.dll)

Table 6.6 Processes that Load Drivers. Drivers FileSys.dll loads file system drivers. For more information, see the section on File Systems. Device.exe loads audio drivers, battery drivers, keyboard drivers, mouse drivers, NDIS drivers, notification LED drivers, serial 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. GWES.dll loads a device driver if GWES is the only client of a driver. Device drivers loaded by GWES present a standard set of functionality for all similar devices. Drivers that GWES loads might expose the stream interface or they might expose other interfaces. Having alternatives make accessing the drivers much faster. GWES loads display drivers, printer drivers, and touch screen drivers.

Security Best Practices
• Use Mutual Authentication • Avoid storing user credentials on the device • Use smart cards to store credentials • Use pass-through authentication • Use a strong authentication protocol • Avoid using plain text passwords

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 Clear file system Yes Clean boot signaled? Yes Persistent storage file system? Warm boot No Clear RAM No Yes

No

Clean boot signaled? Yes Persistent storage file system? Power-on reset

Battery backup level reaches zero

Power-on reset Critical battery-low event Critcal off

On

Scheduler idle Any interrupt Activity timer time-out Wake-up events

Idle

Suspend

Figure 6.13 CE 6.0 Power States and Transitions.

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-toTransition to a stopped microprocessor, as a result of certain events. A Suspend device driver's XXX_PowerDown (Device Manager) function is called. SuspendTransition 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-toTransition when critically low battery power is detected. You must Critical off implement the function for transitioning to the Critical Off state for your device.

Figure 6.14 CE 6.0 Power Manager Architecture.

119

Security
• Control access to the device • Protect against unauthorized applications • Secure data storage and file systems • Secure network and internet connections

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

Service Dynamic Host Configuration Protocol (DHCP) client Windows Internet Name Service (WINS) Domain Name System (DNS) client Extended DNS Querying and Update

Dial-up (PPP/SLIP) support. TCP/IP network printing

Simple Network Management Protocol (SNMP) extension agent Wide area network (WAN) support

Table 6.8 TCP/IP Services Description DHCP clients are dynamically assigned with various configuration parameters, such as an IP address, subnet mask, default gateway, and other critical network configuration information. WINS is a NetBIOS name client that manages the name resolution process by maintaining an up-to-date list of NetBIOS computer names and their respective IP addresses.. CE does not support hosting a DNS server. However, CE queries a DNS server for name resolution if such a server exists on the network. This service provides the Dynamic DNS protocol that allows you 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. CE implements dial-up networking with Remote Access Service (RAS) and Point-to-Point Protocol (PPP). In CE, TCP/IP supports network printing through the Server 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. The SNMP extension agent provides an MIB-2 subagent that allows the state of TCP/IP to be monitored and controlled. This service provides users with access to the Internet.

TCP/IP connectivity utilities Network Utilities Internet Protocol Helper (IP Helper) Remote Procedure Call (RPC) Windows HTTP Services (WinHTTP) Windows Internet (WinInet) Windows Sockets (Winsock)

Basic TCP/IP connectivity utilities, including File Transfer Protocol (FTP) and telnet servers. The telnet server allows remote administration through a standard telnet client. A sample FTP server is used for copying files to and from remote computer systems over a network using TCP/IP. Many network troubleshooting tools are available for CE, for example, ipconfig, iPv6, ipv6tun, netstat, ping route, and tracert. IP Helper provides application programming interfaces (APIs) that assist in the network administration of the local computer. Microsoft Remote Procedure Call (RPC) is used to creating distributed client/server programs. The RPC run-time stubs and libraries manage most of the processes relating to network protocols and communication. This enables you to focus on the details of an application rather than the details of the network. WinHTTP provides developers with a server-supported, high-level interface to the HTTP/1.1 Internet protocol.. WinInet handles all communication between an application and Winsock. Applications access the TCP/IP stack through the Winsock interface.

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.

Figure 6.18 Steps in Developing a new OS Run-time image.

124

Figure 6.19 The CE Build system.

Build System Files
• • • • • Used to control the OS build operation More complex than just make files! Controls which code is in kernel Controls where code is loaded in memory Also sets up initial registry, file system, and data base on device

125

File type Dirs File Makefile File ModuleDefinition File Sources File

Table 6.9 Source Code Configuration File Types. Description Identifies additional subdirectories that contain more source code. Contains the variables needed to compile and link the source code. Contains the statements defining an executable or dynamic-link library. Contains the macro variables needed to build the source code. It lists the include and library files needed to build the module. (one of the build files an application developer will often need to modify)

File type Binary Image Builder File (*.bib) Registry File (*.reg) File System File (.dat) Database File (.db) String File (.str)

Table 6.10 Run-time Image Configuration Files. Description Defines the modules and files to be included in the run-time image. Defines the registry keys and values for a run-time image created during a cold boot. Defines the RAM file system directories, files, and links for a runtime image created during a cold boot. Defines the databases to be included in the object store of a runtime image created during a cold boot. Defines locale-specific string replacements for text that is visible to a user in .reg, .dat, and .db files. Each line in the .str file must end with a <CR> to enable correct processing.

126

Table 6.11 Scope of Run-time Image Configuration Files. File name Scope These files apply to the Common project, which Common.bib, Common.reg, contains the core CE-based modules and components. Common.dat, Common.db, 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. These files apply to the Wceapps project, which Wceappsfe.bib, contains the components that support WordPad word Wceappsfe.reg, processing software and Inbox electronic messaging Wceappsfe.dat, Wceappsfe.db, Wceappsfe.str software.

Wceshellfe.bib, Wceshellfe.reg, Wceshellfe.dat, Wceshellfe.db, Wceshellfe.str Msmq.bib, Msmq.reg, Msmq.data, Msmq.db, Msmq.str Platform.bib, Platform.reg, Platform.dat, Platform.db, Platform.str Project.bib, Project.reg, Project.dat, Project.db, Project.str Config.bib

These files apply to the Wceshellfe project, which contains the components that support the CE-based shell modules. These files apply to the MSMQ project, which contains Message Queuing Server modules. These files apply to the hardware platform. These files apply to the workspace that contains your CE-based run-time image. This file applies to your run-time image. It contains MEMORY and CONFIG sections for the run-time image.

127

*.Bib entry to add mydll.dll to kernel

Name MYDLL.DLL

Path

Memory block Section override Type NK SHC

%_WINCEROOT%\RELEASE\MYDLL.DLL

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

Note: Turn off on-access virus scanning!

129

Figure 7.1 The Visual Studio 2005 IDE

Figure 7.2 Creating a new OS Design Project.

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.

Figure 7.6 Selecting a Design Template Variant 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.

Figure 7.14 OS Build succeeded with no errors.

136

Tutorial II: Downloading a new OS kernel to the eBox 2300

Downloading the new OS
• • • • • • • Setup network connection to target device Set Target Device Connectivity Options Attach Target Device Target device sends Bootme request New OS downloads to device Device boots OS Debug messages display on PC

Note: Watch out for firewall settings!

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.

Figure 7.18 The target device is downloading the new OS image.

139

Figure 7.19 The target device display is seen running the new OS image.

Tutorial III: Creating, compiling, and debugging a C/C++ Subproject

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.

Figure 7.22 Setting up a breakpoint in the “Hello World” C/C++ application.

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.

Tutorial IV: Generating a new SDK for use by application developers

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.

Figure 7.27 Setting the install file name to MySDK.

146

Figure 7.28 Including managed code (C#) support in the new SDK.

Tutorial V: Creating and Building a C# Project

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

Figure 7.29 Creating a C# Project.

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.

Tutorial VI: Deploying new application code to the target device

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.

Figure 7.37 Select the MySDK Device to connect.

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

// FileIO.cpp : Defines the entry point for the console application. // // FileIO demo program // Shows how to create, write, and read a file using CE file APIs // // Remember CE uses 16-bit Unicode for character strings! // _T("....") generates a Unicode string // TCHAR is a Unicode string type // #include "stdafx.h" int _tmain(int argc, TCHAR *argv[], TCHAR *envp[]){ HANDLE hFile; DWORD cBytes; char cBuffer[] = "Hello File World\n"; printf("\nCreating CE_Demo.txt file\n"); // Open File for Write hFile = CreateFile(_T("\\Temp\\CE_Demo.TXT"), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // Check for file open errors if (hFile == INVALID_HANDLE_VALUE){ printf("file write open errors\n"); Sleep(1000); return 0;

157

} if (!WriteFile(hFile, cBuffer, strlen(cBuffer), &cBytes, NULL)){ printf("file write errors\n"); Sleep(1000); return 0; } // Close File CloseHandle(hFile); // Open File again for read hFile = CreateFile(TEXT(""), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // Check for file open errors if (hFile == INVALID_HANDLE_VALUE){ printf("file read open errors\n"); Sleep(1000); return 0; } // Read back data just written to new file if (!ReadFile(hFile, cBuffer, 79, &cBytes, NULL)){ printf("file read errors\n"); Sleep(1000); return 0; } // Display Data read back and delay 4 seconds before exiting printf("%s\n",cBuffer,cBytes); printf("the file data was written and read back OK\n"); Sleep(4000); // Close File CloseHandle(hFile); return 1; }

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; int _tmain(int argc, TCHAR *argv[], TCHAR *envp[]) { DWORD cBytes_out, cBytes_in; DWORD dwMask; char cBuffer_out[] = "\f\n Hello Serial World! \n\r Type something and watch it echo back \n\r Ctrl C to exit \n\r"; TCHAR cBuffer_in[80]; // Display message on console printf("\nOpening COM2: Serial Port - Type ctrl C on other device to exit\n\r"); // Open Serial Port COM2: for Read and Write // Note: COM1: is normally setup to send out Debug info // In this case COM2: becomes COM1: in the OS hSerial = CreateFile(_T("COM1:"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); // Check for file open errors if (hSerial == INVALID_HANDLE_VALUE){ printf("file open errors\n"); Sleep(4000); return 0; } // Modify Com Port settings (i.e. Baud Rate, #bits, parity etc) if(!ModifyCommSettings (hSerial)){ printf("com port settings errors\n"); Sleep(4000); return 0; }

// 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; } // Set Communication event mask for WaitCommEvent for rxchar (recieve character) in buffer SetCommMask(hSerial, EV_RXCHAR | EV_ERR); 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

// Configure the port settings according to the new specifications // of the DCB structure. if (!SetCommState (hSerial, &PortDCB)){ printf("Unable to configure the serial port"); Sleep(4000); return false; } // Set read time outs ctos.ReadIntervalTimeout = MAXDWORD; ctos.ReadTotalTimeoutMultiplier = MAXDWORD; ctos.ReadTotalTimeoutConstant = 1; ctos.WriteTotalTimeoutMultiplier = 0; ctos.WriteTotalTimeoutConstant = 0; if(!SetCommTimeouts(hSerial, &ctos)){ printf("Unable to configure the serial port"); Sleep(4000); return false; } return true; }

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!)

Table 8.1 16550 UART I/O Ports Register Function Data (DLB=1, Baud rate divisor LSB) Interrupt Enable (DLB=1, Baud rate divisor MSB) Interrupt ID Data Format Modem control Line Status Modem status Scratch-Pad

I/O Port Address Base + 0 Base + 1 Base + 2 Base + 3 Base + 4 Base + 5 Base + 6 Base + 7

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" // For WRITE_PORT_UCHAR & READ_PORT_UCHAR functions #include "..\WINCE600\CEPC_x86\cesysgen\ddk\inc\ceddk.h" // Also need to include CEDDK.lib in link (see sources file) // add $(_SYSGENOAKROOT)\lib\$(_CPUINDPATH)\ceddk.lib // to TARGETLIBS entries void Setup_UART (PUCHAR Data_Port_Address); void Write_Serial_Character (PUCHAR Data_Port_Address, UCHAR Serial_Data); UCHAR Read_Serial_Character (PUCHAR Data_Port_Address); int _tmain(int argc, TCHAR *argv[], TCHAR *envp[]) { PUCHAR Data_Port_Address; UCHAR Serial_Input_Data = 0; char Title[]= "\f\n Hello Serial World!\n\rType something and watch it echo back\n\rCtrl C to exit\n\r"; int i; // Force Console to Display printf("I/O Port READ/WRITE Demo Program - Echos data on COM2:\n\r Type Ctrl C on other device to exit\n\r"); // Data Port Address for COM2: Data_Port_Address = (PUCHAR)0x2F8;

// Sets up UART for 9600 Baud & No Interrupts with 8D NP 1S Setup_UART(Data_Port_Address); // Print title out on serial port for (i=0; i<strlen(Title); i++) Write_Serial_Character(Data_Port_Address, (UCHAR)Title[i]); // Start Echo Loop - Loop until Ctrl C is hit while (Serial_Input_Data != 0x03){ // Read in Data Serial_Input_Data = Read_Serial_Character (Data_Port_Address); // Copy Data to Console printf("%c", Serial_Input_Data); // Write Data Back out (Echo) Write_Serial_Character(Data_Port_Address, Serial_Input_Data); } return 0; } void Write_Serial_Character (PUCHAR Data_Port_Address, UCHAR Serial_Data) // Write out a character to the serial port { UCHAR Status; // Wait for TX output ready bit=1 // Status I/O Port Address is Data I/O Port Address + 5 do{ Status = READ_PORT_UCHAR(Data_Port_Address + 5); } while ((Status & 0x40) == 0); // Write (Echo) new data back out on COM2: WRITE_PORT_UCHAR(Data_Port_Address, Serial_Data); return; }

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.

PBWORKSPACEROOT Defines the location of the current Platform Builder workspace. The default is %_WINCEROOT%\PBWorkspaces \%_TGTPROJ%. However; if you have placed your root directory in a location other than the default; that location is used as the definition for %PBWORKSPACEROOT%. _PLATFORMROOT Defines the location of the Platform directory. The default is %_WINCEROOT%\Platform.. _PRIVATEROOT Defines the location of an alternate root directory, such as a directory to contain a different Set Environment Variable tool, Setenv.bat. You can set this variable to point to a directory of your choice. The default is %_WINCEROOT%\Private. 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. Defines the location of the project you are building; for example, %_PBWORKSPACEROOT%\WINCE500 \%PBCONFIG%. Defines the location of public projects. The default is %_WINCEROOT%\Public. 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. Defines the name of the current active workspace.

_PROJECTOAKROOT

_PROJECTROOT

_PUBLICROOT _SDKROOT

_TGTPROJ

ILASMIO Example Program
• Operates the same as the previous serial port examples • X86 in-line assembly language is used for I/O port read and write operations (instead of CEDDK functions) • Will only work on X86 Processors • Example of how low-level code can use assembly language to talk to hardware • Should only use assembly language when absolutely necessary – in just a few of the lowest level OS routines

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; }

Thread and Synchronization Example Program
• • • • • Uses CreateThread API to create a thread Sleep used for time delays CreateEvent sets up an event SetEvent signals an event WaitForSingleObject waits until the event is signaled

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; int _tmain(int argc, TCHAR *argv[], TCHAR *envp[]) { HANDLE hThread1; DWORD dwThread1ID = 0; INT nParameter = 1; int count1 = 0; printf(" \n"); _tprintf(_T(" Hello Thread World!\n")); g_hMainEvent = CreateEvent(NULL, FALSE, FALSE, NULL); Sleep(1000); hThread1 = CreateThread (NULL, 0, WorkerThread, (LPVOID)nParameter, 0, &dwThread1ID); while (count1 < 100){ printf(" main thread computes value: %d\n",count1); count1++; SetEvent(g_hMainEvent); Sleep(370); } CloseHandle(hThread1); CloseHandle(g_hMainEvent); return 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.

Other Remote Tools
• Zoom – used for remote screen capture • Remote Registry Editor – Edit and view the target device registry • Remote File Viewer – see files on target device, download (export) a file • Heap Walker - displays information about the heap. • Call Profiler - provides a graphical interface for profiling and analysis. • Spy – display a list of windows open on the target and messages

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)

// 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 critical sections // #include "stdafx.h" //Thread Function DWORD WINAPI ConsumerThread (LPVOID lpArg); // Critical Section CRITICAL_SECTION CriticalSection; // Shared Circular Buffer and pointers int count = 0; int in = 0; int out = 0; DWORD Buffer[3]; int _tmain(int argc, TCHAR *argv[], TCHAR *envp[]) { HANDLE hThread1; DWORD dwThread1ID = 0; INT nParameter = 1; int i; 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; }

DWORD WINAPI ConsumerThread (LPVOID lpArg) { INT threadnumber = (INT) lpArg; // Consumer while (1){ // Check for Buffer Empty while (count == 0) { printf("Buffer Empty - Consumer Waiting\n"); Sleep(0); }; // Remove item from Buffer // Shared Global Variables - use Critical Sections EnterCriticalSection (&CriticalSection); --count; printf(" consumer thread consumes item from Buffer[%d] with time stamp %d\n",out,Buffer[out]); out = (out + 1) % 4; LeaveCriticalSection (&CriticalSection); // Random delay to simulate process consuming Buffer item Sleep(Random()>>21); } return 0; }

172

Figure 8.7 The Producer Consumer Problem.

Producer Consumer Problem
• While loops consume CPU time and power • Count violates mutual exclusion rule • Use three semaphores
– One for mutual exclusion lock – One to detect buffer full and block – One to detect buffer empty and block

• Different initial values used for semaphores

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); int _tmain(int argc, TCHAR *argv[], TCHAR *envp[]) { HANDLE hThread1; DWORD dwThread1ID = 0; INT nParameter = 1; int i; printf(" \n"); // setup semaphores and their initial and max values mutex_semaphore = CreateSemaphore(NULL, 1, 1, TEXT("mutex")); // 1 for mutex lock full_semaphore = CreateSemaphore(NULL, 0, 4, TEXT("full")); // 0 items in buffer empty_semaphore = CreateSemaphore(NULL, 4, 4, TEXT("empty")); // 4 max items in buffer _tprintf(_T(" Producer Consumer example\n")); for (i=0; i<4; i++) Buffer[i] = 0; hThread1 = CreateThread (NULL, 0, ConsumerThread, (LPVOID)nParameter, 0, &dwThread1ID);

// 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; }

// Producer while (1){

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

// Playsound.cpp : Defines the entry point for the console application. // #include "stdafx.h" int _tmain(int argc, TCHAR *argv[], TCHAR *envp[]) { int i; _tprintf(_T("Hello Audio World!\n")); Sleep(1000); // Play WAV file seven times on audio device for (i=0; i<7; i++) { // Uses registry wave file entry for EXCLAM // Can replace with path to your wav file // if you add | SND_FILENAME to third arg PlaySound (TEXT("EXCLAM"), NULL, SND_SYNC); Sleep(500); } Sleep(1500); return 0; }

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

Windows Callback Function
• The function that handles the applications messages • Called by OS when a message is generated for the Window • A case (switch) statement is used to decode the message • The action for each message is coded into each case • After the message is processed, the callback function returns

178

Table 8.3 Common Hungarian Notation Prefixes Used for Variables in Windows Programs Variable Type Integer Word (16-bit) Double Word (32-bit) Long (32-bit signed) Char String (zero terminated) Pointer Long Pointer Handle Window Handle Structure Size Hungarian Prefix i or n w or s dw l c sz p lp h hwnd cb

// WinAPP.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "resource.h" #define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; TCHAR szTitle[MAX_LOADSTRING]; TCHAR szWindowClass[MAX_LOADSTRING]; // current instance // The title bar text // The title bar text

// Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_WinAPP, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_WinAPP);

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; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC) WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = 0; wc.hCursor = 0; wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); wc.lpszMenuName = 0; wc.lpszClassName = szWindowClass; } 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; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); 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"); } } }

C# Serial Port Hello World
using System; using System.Collections.Generic; using System.Text; using System.IO.Ports; namespace Hello_CS_Serial_World { class Program { static void Main(string[] args) { SerialPort _serialPort; // Create a new SerialPort object with desired settings. _serialPort = new SerialPort(); //Defaults to ("COM1", 9600, Parity.None, 8, StopBits.One) _serialPort.Open(); _serialPort.WriteLine("Hello CS Serial World"); _serialPort.Close(); } } }

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

Phidgets Driver Subproject
• Phidgets are USB-based modules that can be added to the eBox for additional I/O such as digital and analog I/O and sensors • A PhidgetsDrivers subproject is provided to easily add the Phidgets drivers files to the CE kernel • Adds registry entry for Phidgets • Needed in any application that uses Phidgets

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
// Example using LoadLibrary to load Phidgets driver hModule = ::LoadLibrary(_T("phidget21.dll")); if (hModule == NULL) return 0; // Example showing the use of GetProcAddress for each entry point typedef int (__stdcall *Phidget_open)(CPhidgetHandle phid, int serialNumber); Phidget_open open = (Phidget_open)::GetProcAddress(hModule, _T("CPhidget_open"));

See the PhidgetLCD Subproject for a complete example

C# Phidget API calls
• See source code for applications seen in previous screen capture • All of these sample C# Phidget applications are in the WindowsCE.Net Examples project

186

Calling C/C++ functions from C#
• C# can call C/C++ Functions • Must expose C/C++ Functions in a DLL • Special Interface is called “P/Invoke”

[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

Table 9.1 CE Device Driver Libraries Library Description Microprocessor- Device drivers for high integration microprocessor-native native libraries peripherals. For example, the ARM microprocessor, and its companion chip integrates many peripherals on the microprocessor, such as LCD, serial, USB Host, USB function, and so on. An SDB or hardware platform that uses a specific microprocessor will use the same set of microprocessor-native drivers. In Windows Embedded CE, most microprocessors are high-integration microprocessors that contain many native peripherals. These are referred to as SOC (system-on-chip) drivers and these are in ..\WINCE600 \Platform\Common\Src\SOC. Microprocessor- OAL functions for devices such as a real-time clock, timer, and a specific OAL debug Ethernet controller that are common to a microprocessor. support libraries This library minimizes the OAL code written. These are also referred to as SOC (system-on-chip) drivers and are in ..\WINCE600 \Platform\Common\Src\SOC.

188

BSP or hardware platformspecific drivers Other common peripheral drivers

Device drivers for peripherals that are specific to a given SDB or hardware platform. These drivers have hardware platform-specific code and can only be used on that hardware platform. These drivers are in ..\WINCE600\Platform\<Hardware Platform Name> \Src\Drivers. Drivers for strategic peripheral chipsets that are commonly found or included on many SDB or hardware platform designs. These include 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.

Stream Interface Driver
• Best choice for a simple driver for a device that produces and/or consumes streams of data • Driver is a DLL & has 12 Standard Entry Points • Applications use standard file system APIs • Device Manager checks registry for device name on Open to locate driver library • Probably will want to use CEDDK functions in driver code to communicate with hardware

189

Device Manager
Stream Interface Stream Interface

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)

OAL

Window CE Kernel

Device Manager
Interrupt Events

Software Hardware

Hardware Platform

Built-in Device

Figure 9.2 Stream Interface Architecture

190

Table 9.2 Stream Interface Driver Functions. Programming element XXX_Close (Device Manager) XXX_Deinit (Device Manager) XXX_Init (Device Manager) XXX_IOControl (Device Manager) XXX_Open (Device Manager) Description This function closes the device context identified by hOpenContext.. This function is required to access the device with CreateFile. If you implement XXX_Close, you must implement XXX_Open. This function de-initializes a device. It is called by Device Manager.This function is required by drivers loaded by ActivateDeviceEx, ActivateDevice, or RegisterDevice. This function initializes a device. It is called by Device Manager.This function is required by drivers loaded by ActivateDeviceEx, ActivateDevice, or RegisterDevice. This function sends a command to a device.This function might 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. This function opens a device for reading, writing, or both. An 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.

XXX_PowerDown (Device Manager) XXX_PowerUp (Device Manager) XXX_PreClose (Device Manager) XXX_PreDeinit (Device Manager) XXX_Read (Device Manager)

Optional. This function ends power to the device. It is useful only with devices that can be shut off under software control. Optional. This function restores power to a device. Optional. This function marks the closing handle as invalid and wakes any sleeping threads. This function marks the device instance as invalid and wakes sleeping threads. This function is required if the XXX_PreClose function is implemented. This function reads data from the device identified by the open context. This function might 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. This function moves the data pointer in the device. This function might 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. This function writes data to the device. This function might 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_Seek (Device Manager) XXX_Write (Device Manager)

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.

Table 9.4 CEDDK vs. Kernel Functions for DMA. Using CEDDK.dll functions Using kernel functions CEDDK.dll provides these The kernel provides these functions for functions for obtaining a buffer obtaining a buffer for DMA transfers: for DMA transfers: AllocPhysMem HalAllocateCommonBuffer FreePhysMem HalFreeCommonBuffer HalTranslateSystemAddress CEDDK.dll functions can handle bus and hardware platformspecific address translations. CEDDK.dll functions are useful for common buffer DMA. CEDDK.dll functions use a default memory alignment of 64 KB. You must handle hardware platform-specific address translations. You can call HalTranslateSystemAddress to translate the address. The kernel functions may be useful for scatter/gather DMA. The kernel functions allow you to change the default memory alignment.

192

// Allocate an adapter object on the stack DMA_ADAPTER_OBJECT AdapterObject; AdapterObject.ObjectSize = sizeof(AdapterObject); AdapterObject.InterfaceType = PCIBus; AdapterObject.BusNumber = 0; // Allocate a single paged 4 KB output buffer dma_out_page[0] = (PUCHAR) HalAllocateCommonBuffer(&AdapterObject, 4096, &dma_out_logical_address, FALSE); if (!dma_out_page[0]) { ERRMSG("PDD_AudioInitialize: DMA Buffer Page Allocation Failed"); return FALSE; }

KOM Driver Example
• Educational example of a simple stream interface device driver – not a production quality driver! • Used instead of standard COM port driver provided with CE • Based on earlier serial port IO example • Uses CEDDK functions to communicate with 16550 UART compatible hardware on eBox serial port • Must be setup as a DLL

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> // For WRITE_PORT_UCHAR & READ_PORT_UCHAR functions // need to add to sources file include section: // ..\Wince600\ICOP_Vortex86_60A_x86\cesysgen\ddk\inc; \ // ..\Wince600\ICOP_Vortex86_60A_x86\cesysgen\oak\inc; \ #include "ceddk.h" // Also need to include CEDDK.lib in link (see sources file) // add $(_SYSGENOAKROOT)\lib\$(_CPUINDPATH)\ceddk.lib // to TARGETLIBS entries // Declare the Standard External Stream Driver Functions __declspec(dllexport) extern DWORD KOM_Init(LPCTSTR pContext, LPCVOID lpvBusContext); __declspec(dllexport) extern BOOL KOM_Deinit( DWORD hDeviceContext ); __declspec(dllexport) extern DWORD KOM_Open( DWORD hDeviceContext, DWORD AccessCode, DWORD ShareMode ); __declspec(dllexport) extern BOOL KOM_Close( DWORD hOpenContext ); __declspec(dllexport) extern BOOL KOM_IOControl( DWORD hOpenContext, DWORD dwCode, PBYTE pBufIn, DWORD dwLenIn, PBYTE pBufOut, DWORD dwLenOut, PDWORD pdwActualOut ); __declspec(dllexport) extern void KOM_PowerUp( DWORD hDeviceContext ); __declspec(dllexport) extern void KOM_PowerDown( DWORD hDeviceContext ); __declspec(dllexport) extern DWORD KOM_Read( DWORD hOpenContext, PUCHAR pBuffer, ULONG Count ); __declspec(dllexport) extern DWORD KOM_Write( DWORD hOpenContext, PUCHAR pBuffer, ULONG Count ); __declspec(dllexport) extern DWORD KOM_Seek( DWORD hOpenContext, long Amount, WORD Type ); void DBGOut(DWORD dwValue); void Setup_UART (PUCHAR Data_Port_Address); void Write Serial Character (PUCHAR Data Port Address, UCHAR

UCHAR Read_Serial_Character (PUCHAR Data_Port_Address); PUCHAR Data_Port_Address; UCHAR Serial_Input_Data = 0; // ---------------------------------------------------BOOL APIENTRY DllMain( HANDLE hModule, DWORD LPVOID lpReserved ) { switch(ul_reason_for_call) { case DLL_PROCESS_ATTACH: OutputDebugString(L"KOM_DRIVER break; case DLL_PROCESS_DETACH: OutputDebugString(L"KOM_DRIVER break; case DLL_THREAD_ATTACH: OutputDebugString(L"KOM_DRIVER break; case DLL_THREAD_DETACH: OutputDebugString(L"KOM_DRIVER break; default: break; } return TRUE; } ul_reason_for_call,

DLL_PROCESS_ATTACH\n"); DLL_PROCESS_DETACH\n"); DLL_THREAD_ATTACH\n"); DLL_THREAD_DETACH\n");

// Stream Driver Init... DWORD KOM_Init( LPCTSTR pContext, LPCVOID lpvBusContext) { OutputDebugString(L"KOM_DRIVER - KOM_Init - Context: "); OutputDebugString(pContext); OutputDebugString(L"\n"); OutputDebugString(L"DemoDriver - Exit KOM_Init\n"); return 0x1234; } BOOL KOM_Deinit( DWORD hDeviceContext ) { OutputDebugString(L"KOM_DRIVER - KOM_Deinit\n"); OutputDebugString(L"KOM_DRIVER - Exit KOM_Deinit\n"); return TRUE; }

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"); // Data Port Address for COM2: Data_Port_Address = (PUCHAR)0x2F8; // Sets up UART for 9600 Baud & No Interrupts with 8D NP 1S Setup_UART(Data_Port_Address); OutputDebugString(L"DemoDriver - Exit KOM_Open\n"); return 0x5678; } // Stream Driver Close BOOL KOM_Close( DWORD hOpenContext ) { OutputDebugString(L"KOM_DRIVER - KOM_Close\n"); OutputDebugString(L"hOpenContext - "); DBGOut(hOpenContext); OutputDebugString(L"\n"); // Add Close Function Code Here OutputDebugString(L"KOM_DRIVER - Exit KOM_Close\n"); return TRUE; }

// Stream Driver IOCTL BOOL KOM_IOControl( DWORD hOpenContext, DWORD dwCode, PBYTE pBufIn, DWORD dwLenIn, PBYTE pBufOut, DWORD dwLenOut, PDWORD pdwActualOut ) { OutputDebugString(L"KOM_DRIVER - KOM_IOControl\n"); OutputDebugString(L"hOpenContext - "); DBGOut(hOpenContext); OutputDebugString(L"\n"); // Add IOCTL Functon Code Here OutputDebugString(L"KOM_DRIVER - Exit KOM_IOControl\n"); return TRUE; } // Stream Driver PowerUP void KOM_PowerUp( DWORD hDeviceContext ) { OutputDebugString(L"KOM_DRIVER - KOM_PowerUp\n"); OutputDebugString(L"hDeviceContext - "); DBGOut(hDeviceContext); OutputDebugString(L"\n"); // Add PowerUP Function Code Here OutputDebugString(L"KOM_DRIVER - Exit KOM_PowerUp\n"); } // Stream Driver PowerDown void KOM_PowerDown( DWORD hDeviceContext ) { OutputDebugString(L"KOM_DRIVER - KOM_PowerDown\n"); OutputDebugString(L"hDeviceContext - "); DBGOut(hDeviceContext); OutputDebugString(L"\n"); // Add PowerDown Function Code Here OutputDebugString(L"KOM_DRIVER - Exit KOM_PowerDown\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"); // Data Port Address for COM2: Data_Port_Address = (PUCHAR)0x2F8; // Read in Serial Data for (i=0; i<Count; i++) pBuffer[i] = Read_Serial_Character(Data_Port_Address); OutputDebugString(L"KOM_DRIVER - Exit KOM_Read\n"); return Count; }

// Stream Driver Write DWORD KOM_Write( DWORD hOpenContext, PUCHAR pBuffer, ULONG Count ) { ULONG i; OutputDebugString(L"KOM_DRIVER - KOM_Write\n"); OutputDebugString(L"hOpenContext - "); DBGOut(hOpenContext); OutputDebugString(L"\n"); // Data Port Address for COM2: Data_Port_Address = (PUCHAR)0x2F8; // Write out Serial Data for (i=0; i<Count; i++) { Write_Serial_Character(Data_Port_Address, pBuffer[i]); DBGOut((DWORD)pBuffer[i]); }

//

OutputDebugString(L"KOM_DRIVER - Exit KOM_Write\n"); 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; } void DBGOut(DWORD dwValue) { TCHAR tcTemp[10]; wsprintf(tcTemp,L"%ld",dwValue); OutputDebugString(tcTemp); } void Write_Serial_Character (PUCHAR Data_Port_Address, UCHAR Serial_Data) // Write out a character to the serial port { UCHAR Status; // Wait for TX output 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 UART transmit buffer full release remainder of time slice if ((Status & 0x40) == 0) Sleep(0); } while ((Status & 0x40) == 0); // Write data out on COM2: WRITE_PORT_UCHAR(Data_Port_Address, Serial_Data); return; }

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 UART recieve buffer empty 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; // Setup UART to 9600 Baud 8D,NP,1S no interrupts // 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;

}

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

Registry Entry for KOM driver

[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

*.def file for external defs
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

// KOM_Tester.cpp : Defines the entry point for the console application. // // Serial Port File I/O Test Program for KOM_Port Driver // // 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" HANDLE hSerial; int _tmain(int argc, TCHAR *argv[], TCHAR *envp[]) { DWORD cBytes_out, cBytes_in; char cBuffer_out[] = "\f\n Hello KOM Serial World!\n\rType something and watch it echo back\n\rCtrl C to exit\n\r"; TCHAR cBuffer_in[80]; // Display message on console printf("\nOpening KOM2: Serial Port to test new KOM Driver - Type ctrl C on other device to exit\n\r"); // Open Serial Port COM2: for Read and Write // Note: COM1: is setup to send out Debug info // so COM2 becomes COM1 hSerial = CreateFile(_T("KOM1:"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); // Check for file open errors if (hSerial == INVALID_HANDLE_VALUE){ printf("file open errors\n","%X", hSerial); Sleep(4000); return 0; }

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; // Read in characters, copy to console display and Echo (write) back // Loop until ctrl C (0x03) is typed while (cBuffer_in[0] != 0x03){ // Read back data any serial data and display if (ReadFile(hSerial, cBuffer_in, 1, &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; } }

Running KOM Driver Test Program
Run Programs s KOM_Tester PB Debugger Loaded symbols for 'C:\WINCE600\OSDESIGNS\OSDESIGN7\OSDESIGN7\ RELDIR\ ICOP_VORTEX86_60A_X86_RELEASE\KOM_TESTER.EXE' s KOM_Tester 22:33:23 11/25/2006 Eastern Standard Time End s KOM_Tester 22:33:23 11/25/2006 Eastern Standard Time PB Debugger Loaded symbols for 'C:\WINCE600\OSDESIGNS\OSDESIGN7\OSDESIGN7\ RELDIR\ ICOP_VORTEX86_60A_X86_RELEASE\CONSOLE.DLL' 61200 PID:400002 TID:4880012 DemoDriver - KOM_Open 61200 PID:400002 TID:4880012 hDeviceContext 61200 PID:400002 TID:4880012 4660 61201 PID:400002 TID:4880012 61202 PID:400002 TID:4880012 DemoDriver - Exit KOM_Open 61203 PID:400002 TID:4880012 KOM_DRIVER - KOM_Write 61203 PID:400002 TID:4880012 hOpenContext 61204 PID:400002 TID:4880012 22136 61204 PID:400002 TID:4880012 61317 PID:400002 TID:4880012 KOM_DRIVER - Exit KOM_Write 61318 PID:400002 TID:4880012 KOM_DRIVER - KOM_Read 61318 PID:400002 TID:4880012 hOpenContext 61319 PID:400002 TID:4880012 22136 61319 PID:400002 TID:4880012 69052 PID:400002 TID:4880012 KOM_DRIVER - Exit KOM_Read 69066 PID:400002 TID:4880012 KOM_DRIVER - KOM_Write 69067 PID:400002 TID:4880012 hOpenContext -

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

KOM Driver Works!
• Can see characters echoed on serial port • Debug messages show that the driver is being called correctly by the test program • But, this is not a production quality driver and it would need a lot of improvements!

202

Chapter 10: Advanced OS Topics

Porting the OS to a new design
• Need to develop a Board Support Package (BSP) • BSP includes the following:
– Boot Loader – OEM Adaptation Layer (OAL) – Device Drivers for Board

• Will be easier if you have some of these items from a similar board

203

Windows CE Platform Development Process
Device Bring-Up Platform Development
Develop Custom Drivers Testing and Integration Load ROM Monitor Custom Windows CE Catalog Items

Application Development

Hardware Design

Boot Minimum Kernel on Hardware Create Boot Loader Testing and Integration Applications and Middleware Develop and Integrate Catalog Items Testing and Integration

Testing and Integration

OAL Development

BSP Development

Figure 10.1 The Process of porting CE to a new target device.

Table 10.1 Elements of a Board Support Package (BSP). Element Description Boot loader During development, downloads the OS images. OEM adaptation Links to the kernel image and supports hardware initialization layer (OAL) and management. Device drivers Supports peripherals on-board or are attached at run time. Run-time image When created, a BSP can be reconfigured through configuration files environment variables and .bib and .reg file modifications.

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/ startup

kernel.dll
NKGLOBAL

oal.exe

OEMInit Globals() Globals()

OEMGLOBAL

Figure 10.2 The Initial Startup Sequence for CE

Startup library

KITL IOCTL

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
IOCTL IOCTL library library

OS Timer library library
Timers

Interrupt Interrupt library library

Startup library library

Cache Cache library library

RTC library library
RTC

Caches

Hardware

USB port

Ethernet port

Serial port

Figure 10.3 Porting CE to a new target device requires changes to the OAL routines.

206

Figure 10.4 BSP Structure

Hardware Debug Tools
• Use special debug/trace pins on processor • Can follow instruction execution and set hardware breakpoints • Useful when initially testing a new board – software debug tools will not work until OS is running • May require a special connector or processor socket on the PCB

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 CETEST.EXE

CE 6.0 Device ActiveSync, KITL, Winsock Clientside.EXE

CETK Test DLLs Log

TUX.EXE

Kato.DLL

TUX Test DLLs

Figure 10.5 The CE Test Kit (CETK) Architecture

209

Figure 10.6 The CE Test Kit (CETK) UI running on the development PC.

Figure 10.7 The CE Application Verifier tool.

210

Figure 10.8 The CE Stress Testing tool.

Safety Critical Coding
• Applications that can endanger people or cause catastrophic failure are “safety critical” • Extra precautions must be taken • Special safety-critical coding rules typically used in such cases • Examples: Biomedical, Aircraft, Vehicles, & Industrial Equipment

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.

6. Declare all data objects at the smallest possible level of scope. 7. Each calling function must check the error codes returned and each called function must check for valid parameters. 8. The preprocessor must only be used for header files and simple macros. 9. The use of pointers must be limited. No more than one level of dereferencing. 10. All code must compile with all compiler warnings enabled. Code analysis tools should also be used.

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

License and IP Issues
• Any legal issues will take longer to resolve than you expect • May need legal agreements approved on OS, the development of custom device drivers, and applications developed by third parties • Need to determine any such costs or license fees early on and include in product cost estimates

213

Figure 10.9 The CE Run-time License Assessment tool lists features present in an NK.BIN file.

Software Project Management
A discussion of software engineering coding practices and project management can be found in: Code Complete, Second Edition by Steve McConnell and Software Estimation: Demystifying the Black Art by Steve McConnell.

214

Sign up to vote on this title
UsefulNot useful