Emb Sys Design
Emb Sys Design
and Programming
Course Code: EECE216P
Microprocessor:
8-bit
Microcontroller
Inside view of a Microsoft Mouse
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
Product:Vendo Vue
40 vending
machine.
Microprocessor:
Two 16-bit Hitachi
H8/300H
Processors
A robot hand
dispenses items
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
Microprocessor:
64-bit MIPS R7000.
OS: Aperios -
Sony’s Real Time
OS
Used in Robocup
Soccer Teams
Video: http://www.pleoworld.com/
Product: Pleo
robotic toy
dinosaur
Processors:
two 32-bit
(main is ARM)
and four 8-bit
microcontrollers
Pleo Autopsy Photos
From: http://www.ifixit.com/Guide/First-Look/Pleo
Pleo Processor Boards
From: http://www.ifixit.com/Guide/First-Look/Pleo
Product: Amazon’s Kindle DX eBook reader
Processor: Freescale
532 MHz, ARM-11
90 nm processor,
32MB main memory,
4 GB moviNAND
flash storage, 3G
modem, and a 3.7 V
1530 mAh lithium
polymer battery
OS: Linux
Product: Radiant
Systems Point-of-Sale
(POS) Terminal
Microprocessor:
Intel X86 Celeron
OS: Windows XP
Embedded
Microprocessor:
X86
OS: Windows XP
Product: Tektronix
Logic Analyzer
Microprocessor:
X86
OS: Windows XP
Product: Kuka
Industrial Robot
Arm
Microprocessor:
X86
OS: Windows CE
(CE is now called IoT)
Microprocessor: X86
OS: Windows
Product: LagoTek
Home Automation
Controller
Microprocessor:
ARM + DSP
Microprocessor: X86
Microprocessor:
Marvel Xscale (ARM)
Microprocessor:
Marvel StrongARM
Microprocessor:
Marvel Xscale
(ARM)
Microprocessor:
ARM
OS: Windows
Mobile now QNX
Product: MediaCart
It measures urine
sugar, blood
pressure, body fat
and weight on a daily
basis. This data can
be transferred over
the network.
Product: S class
Mercedes
Microprocessors:
around 100
embedded
processors and over
a hundred million
lines of code!
Product: Zoll
Automated
External
Defibrillator
(AED)
Commercial OS
Coca-Cola’s new
Freestyle is the
Most Advanced
Soda Fountain
Ever
http://www.youtube.com/watch?v=9V-yphI7JPk
iRobot AVG Telepresence Robot
More Examples of Embedded Systems
Aircraft & Aircraft autopilots, avionics and navigation
Military Systems systems, automatic landing systems,
guidance systems, engine controls.
Biomedical XRAY, MRI, and Ultrasound imaging
systems, patient monitors, heart pacers.
Cars 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.
Examples of Embedded Systems - Continued
Soft Real-Time
Response Cycle Time
20 ms
10 ms Windows?
Hard Hard Real-Time
Linux?
5 ms
Real-Time
Windows IoT
1 ms Mbed RTOS
Real-Time Performance OS Measurements showing Response Cycle Time . Soft and Hard Real-Time
categories are based on OMAC study and OS times are without any third party real-time extensions to
the OS.
Using Additional Microcontrollers
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 free or only a
few dollars per device – less than a desktop OS
• Some very simple low-end devices might not need an
RTOS or OS – but new devices are getting more
complex
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.
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
Data was derived from EETimes and Embedded Systems Design Magazine 2006 Embedded Market Survey
Processor Architectures Widely
Used in New Embedded Designs
Data was derived from EETimes and Embedded Systems Design Magazine 2006 Embedded Market Survey
Use of RTOS/OS Kernels
in New Embedded Designs
69% of new designs use an RTOS/OS, 31% do not
Open Source OS?
• “Free” OS might 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 in some cases
• 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
• Internal ongoing support needed for device’s version of OS
can be significant. Linux has around 2K patches a year!
Who writes Linux?
Red Hat 12.4%
Novell 7.0%
IBM 6.9%
Unknown 6.4%
Intel 5.8%
Consultants 2.6%
Oracle 2.3%
Renesas Technology 1.4%
The Linux Foundation 1.3%
Academics 1.3%
Programming Languages Used in
New Embedded Designs
Data was derived from EETimes and Embedded Systems Design Magazine 2006 Embedded Market Survey
Conclusions
• Embedded devices can be found everywhere
in large numbers!
• Most new devices are using 32-bit processors
• New devices split almost evenly between, no
OS, commercial OS, or Open Source OS
• The C family (C, C++, C#,Java) is the most
widely used language for embedded systems
Additional Information
• See
– Embedded Software: Facts, Figures, and Futu
re
, IEEE Computer April 2009
– EE Times Embedded Markey Surveys
Product Life Cycle
Figure 1.10 The Embedded device product life cycle phases, Design, Development, and Production.
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
• Mass Production often moves to another
location or country
33%
Gross Margin
Average Discount
10%
15%
Most Embedded systems use two types of memory. RAM for main memory and Flash
memory instead of a hard disk to store the OS and application programs. Flash may be on
processor chip and/or a uSD card in small devices. RAM may be on the processor chip.
Memory in an embedded device
• Need both volatile and non-volatile memory
• Flash memory typically used instead of Hard
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 RAM to execute?
– Add a special Cache for Flash?
• Need software development tools that support
code storage and execution in ROM
Reliability in Embedded Devices
• Moving parts tend to wear out faster than
electronics!
• Would also like to avoid any cooling fans
whenever possible for both reliability and
power concerns
• Hard disk drives have a higher failure rate
than flash since they have moving parts
Flash and Solid State Drives (SSD)
• Up to 5x more reliability
• Up to 10x faster than hard disk
• Up to 90x less power and heat
• Smaller and less weight
• But 4x cost of hard disk per bit
Power Management
• To minimize power consumption and
prolong battery life
– Slow down clock
– Turn off processor clock, wake on timer or I/O
interrupt – called sleep
– Power off unused hardware units – but will lose
values in registers so reinit is needed
– Read wiki example for mbed at:
https://developer.mbed.org/cookbook/Power-Ma
nagement
Brown Out Detection
• Circuit Detects Power Loss on Processor
– Generates interrupt on low supply voltage
– Could be Loss of AC or low battery
– A few ms. of power is left in capacitors
– Put I/O devices in fail safe mode
– Perhaps time to save a few critical values
– Stop processor before crash
– Read wiki example for mbed at:
https://developer.mbed.org/cookbook/WatchDog-T
imer#brown-out-detection
Introduction to Common
Embedded System User
I/O Devices
User Input Devices
• Study the examples on the Wiki page at:
https://developer.mbed.org/users/4180_1/no
tebook/user-input-devices/
Busy
nStrobe
nAck
1 2 3 4
I/O Device Handshake Lines
• I/O Devices are a lot slower than the processor!
• In addition to data lines, need digital lines from
an I/O device that it is ready for another data
transfer (both for input and output data transfer)
• Computer must wait for these lines to be in the
correct state before another data transfer can
start!
• If this is not done – data values will be lost!
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)
Legacy Parallel Ports
• Similar Parallel port/register style
interfaces with ready signals are still used
inside chips for I/O transfers and a few
logic bits (GPIO ports)
• Between chips and devices, it is now
cheaper to use high speed serial interfaces
– Pins can cost as much as 50,000+ gates!
– Cables and connectors with more wires cost a
lot more!
Hardware PWM
• PWM – Pulse Width Modulation
• Special hardware output pin(s) with a digital signal that
automatically turns on and off at a rapid rate
• On time (i.e., duty cycle of square wave) can be changed
in software by writing to an I/O register
• Clock time can also be changed in software – typically
only done once during initialization
• PWM hardware automatically pulses the output pin
• Software only needs to set the new duty cycle whenever
a change is needed
Pulse Width Modulation (PWM)
With fast PWM (ON/OFF square wave outputs) LEDs, motors, and speakers will
respond to the average DC voltage level. With transistors, PWM is significantly
more energy efficient than using analog outputs.
PWM Applications
• Most new microcontrollers have hardware PWM controller(s). A
driver circuit may be needed for high current and/or higher voltage
devices.
• More energy efficient than analog outputs
• Relays are too slow for PWM – must use transistor drivers
• Used for dimming LEDs, motor speed control and audio output
(Class D)
• Similar PWM idea used in higher efficiency switching power
supplies – a big power saver vs. linear supplies
• Can implement software PWM using a timer with interrupts when
PWM hardware is not available
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
RS-232 Signals Used on Cables
RS-232 Serial Cable
Tx Rx
U U
8-bit 8-bit
A Rx Tx A
Parallel Parallel
Data R R Data
T Ground T
0 0 0 0 1 0 1 0
Mark (1)
Space (0)
Start 0 1 2 3 4 5 6 7 Stop
Bit Data Bit number Bit
LSB MSB
SDA
MSB ACK Signal ACK Signal
from Slave from Receiver
Byte Complete Clock Line Held
Low while serviced
The FFC cable has the CSI pins and power for the camera module
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. Carefully examine noise levels and the
non-linear response of sensors, amplifiers, low pass
filters, and A/D or D/A devices
Analog I/O
• Analog sensors will pick up noise from power
supplies along with other circuits used in the
analog portion of a design
• Many power supplies have enough noise to impact
the accuracy of analog sensor readings.
• Add a filter or decoupling capacitor near the
analog devices and/or consider a separate analog
power supply running to analog devices only.
Digital devices will add noise to a DC power
supply.
The MCP3008 10-bit 200Ksps A/D chip is used in USB modules and has an SPI interface.
Signal Conditioning
on Analog Inputs
Analog Signal Microprocessor
Sensor Conditioning A/D input pin
Voltage Circuit
+5V
bytes
D+ bytes USB Program & Data
Serial I/O Ports
D- Interface (R AM & ROM)
Interface
Engine
(SIE)
General
GND Purpose
Microprocessor
USB USB
Connector Transceiver
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 3.0 is around 10x USB 2.0
• New USB C – 20X faster and cables cannot
be plugged in upside down – but the 24-pin
cables cost more
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
The USB Serial Interface Engine
(SIE) handles USB packets
D C D C
A E C A E C
O A Payload R A O A Payload R A
D N R D N R
U T Data C C U T Data C C
D D C D D C
T A 1 K T A 1 K
R P 5 R P 5
1 6 0 6
Token Packet Data Packet H/S Pkt Token Packet Data Packet H/S Pkt
Payload
D ata
D+ Serial Payload
Interface D ata
Engine
D- (SIE) A
C
K
USB
Transceiver
USB Packets
• Contain a packet type
• USB Address and Endpoint fields
• Each device can have several endpoints
• Endpoint is a hardware buffer between the
SIE and the firmware running on the
microcontroller (typically 8-64 bytes)
• CRC error code checked and Ack sent
back
New 24-pin USB C connector
The colors above indicate the different possible pin I/O functions.
Light blue indicates basic DigitalIn/Out pin use is also possible
mbed wait API
• wait(x); waits for time period x (in seconds).
• Used to add small time delays to code
• Some I/O applications will require small time
delays to work correctly
• Note: When using the RTOS in thread code later,
will need to use Thread::wait(mS); instead of wait
DigitalOut Applications
• For digital devices that need a few control bits
• Also called GPIO (General Purpose IO)
• Used to turn on/off LEDs
• Driver circuit will be needed for higher current or
higher voltage devices (>15-40mA, and/or >5V)
including motors, solenoids, relays, and high
power LEDs
DigitalOut Applications
LEDs used for basic ON/OFF indicators
Most small LEDs need a 80-220 ohm series resistor!
– should have only 2-3V across LED terminals
Longer LED wire lead is +, shorter one – or ground
DigitalOut Applications
• Chip select, enable, or reset lines on some I/O
ICs
• Some older and/or high speed devices use a
parallel data interface (several DigitalOut bits) –
BusOut or PortOut are faster for this use).
• Most new I/O devices use a serial interface (i.e.,
Serial, SPI, I2C, USB) to save IC pins, PCB area,
and cost. A pin on an IC package can cost as
much as 50,000 transistors inside the chip.
DigitalOut Applications
• Turn a transistor driver circuit on/off which
then turns on/off a higher current and/or
voltage I/O device
• Relays will even need a transistor driver
circuit for the required coil current!
DigitalOut Applications
• Basic on/off control of a motor or solenoid
• Requires a transistor driver circuit to boost current and
also perhaps voltage (12-24VDC at a few amps is not
uncommon)
• Higher current/voltage devices might also use a relay or
a high power MOSFET
DigitalOut Applications
• Control a driver circuit for a stepper motor with 4-bits
• Stepper motors provide low cost position control
DigitalOut Applications
• For on/off control of AC devices such as small home
appliances, a relay, solid state relay, or TRIAC is
typically used that is controlled by the digital out logic bit
• Circuit is available in low-cost small plug-in AC modules that are
a bit safer for students to use – just add 2 wires for digital signal
and gnd – Keeps high AC voltages off of breadboard!
mbed DigitalOut API
#include "mbed.h"
DigitalOut myled(LED1);
int main() {
while(1) {
myled = 1;
wait(0.2);
myled = 0;
wait(0.2);
}
}
mbed DigitalOut API
DigitalIn enable(p5);
DigitalOut led(LED1);
int main() {
while(1) {
if(enable) {
led = !led; //Blinks if enable input high
}
wait(0.25);
}
}
mbed DigitalIn API
• .mode() controls internal pullups use PullUp, PullDown,
PullNone as arguments. Default is PullDown. SPST
switches need a Pullup or PullDown!
void flip() {
led = !led;
}
int main() {
button.rise(&flip); //jump to flip function on the rising edge
while(1) { // wait around, interrupts will interrupt this!
flash = !flash;
wait(0.25);
}
}
mbed InterruptIn API
PwmOut led(LED1);
int main() {
while(1) {
for(float p = 0.0f; p < 1.0f; p += 0.1f) {
led = p; //dim led using PWM
wait(0.1);
}
}
}
mbed PwmOut API Hello World
• “RS232” serial ports (like PC COM Port) will need a voltage level
conversion circuit. If not “RS232” , normal (TTL) logic levels are
used for serial interfaces.
• Special RS232 voltage level conversion ICs (i.e., MAX232) are
available just for RS232 signals
Serial Applications
Mbed and other USB Virtual Com Ports such as USB to RS232 cables
simulate and/or convert to serial signals in software using a USB
microcontroller and a USB cable. Normal serial APIs can be used at
both ends.
Serial Applications
Many mbed boards have a second small ARM USB microcontroller used
to download code to the main processor just like a flash drive. This
processor on the back of the LPC1768 board, has firmware that also
provides a USB virtual com port. In software, it works just like a serial
port on both mbed and the PC (but signal is on USB cable!).
Serial Applications
#include "mbed.h"
Serial pc(USBTX, USBRX); // USB tx, rx
int main()
{
pc.printf("Hello World!\n");
while(1) {
pc.putc(pc.getc() + 1);
}
}
mbed Serial API
#include "mbed.h"
//Visual volt meter using LEDs
AnalogIn my_pot(A0);
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);
int main() {
while (1){
led1 = (my_pot > 0.2f) ? 1 : 0;
led2 = (my_pot > 0.4f) ? 1 : 0;
led3 = (my_pot > 0.6f) ? 1 : 0;
led4 = (my_pot > 0.8f) ? 1 : 0;
}
}
mbed AnalogIn API
int main()
{
const double pi = 3.141592653589793238462;
const double amplitude = 0.5f;
double rads = 0.0;
float sample = 0;
while(1) {
// sinewave output
for (int i = 0; i < 360; i++) {
rads = (pi * i) / 180.0f;
sample = amplitude * (cos(rads + pi) + 1.0) ;
aout = sample;
}
}
}
mbed AnalogOut API – Int Arg
#include "mbed.h"
// The sinewave is created on this pin
AnalogOut aout(p18);
int main()
{
const double pi = 3.141592653589793238462;
const double amplitude = 0.5f;
const double offset = 65535/2; //scaled for 16-bits unsigned
double rads = 0.0;
uint16_t sample = 0;
while(1) {
// sinewave output
for (int i = 0; i < 360; i++) {
rads = (pi * i) / 180.0f;
sample = (uint16_t)(amplitude * (offset * (cos(rads + pi))) +
offset);
aout.write_u16(sample);
}
}
}
SPI Applications
• Works like a big shift register with a clock line and data
• Can hook up multiple SPI devices in a chain to form one
long shift register
• More bandwidth than serial or I2C (driver circuit supports
a faster clock & fewer address bits are needed than I2C)
• Used for SD cards
• Used for high speed A/D and D/A chips
• Newer sensors often support both SPI and I2C
• Hardware SPI controllers on most new microcontrollers,
but can be done in software
SPI Applications
int main() {
cs = 1;
// Setup spi for 8 bit data, high steady state clock,
// second edge capture, with a 1MHz clock rate
spi.format(8,3);
spi.frequency(1000000);
// Select the device by seting chip select low
cs = 0;
// Send 0x8f, the command to read the WHOAMI register
spi.write(0x8F);
// Must write to read it – send dummy byte
int whoami = spi.write(0x00);
printf("WHOAMI register = 0x%X\n", whoami);
}
mbed SPI API
int PCF8574::read() {
char foo[1];
_i2c.read(_address, foo, 1);
return foo[0];
}
#include "mbed.h"
#include "PCF8574.h"
• PWM
– Dimming LEDs
– Using RBG LEDs
– Audio Output with a Speaker
– DC Motor Speed Control
– RC Servos
– Electronic Speed Control modules (ESC)
I/O Device Interfacing Case Studies
• Analog Input
– Potentiometer
– Temperature Sensor
– Light Sensor
– MEMs Microphone
– Analog Joystick
I/O Device Interfacing Case Studies
• Analog Output
– Audio output using a speaker
I/O Device Interfacing Case Studies
• I2C
– I/O Expander
– Touch keypad
– LIDAR distance sensor
– 9 DOF IMU
I/O Device Interfacing Case Studies
• SPI
– I/O Expander
– Using a uSD card for file I/O
I/O Device Interfacing Case Studies
• Serial
– Using a TTL serial LCD module
– Using an RS232 serial device
– Using a GPS module
– Interfacing to other microprocessors
• Wi Fi module
• Bluetooth module
• iRobot Roomba or Create Robot
Driving Motors and Relays
• High current devices like motors, relays,
solenoids, buzzers, speakers, and high output
LEDs 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
• In some cases, driver circuits will also need to
boost voltage levels in addition to current
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 to amplify current levels
• 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.
Driving a high current Load
Vcc
Discrete Power
Digital Transistor
Logic LOAD
Control
Signal Optional Voltage
Suppression Diode
Use Decoupling Capacitors
on Power Supply lines!
10-1000uf .01-.1uf
Electrolytic Ceramic
GND
•Two capacitors (made of different dielectric materials) are
typically connected in parallel from Vcc to GND.
• A larger electrolytic capacitor (i.e., 100+ uf) and a smaller one
(i.e., .01 to .1 uf) in parallel are needed to filter noise
This Phidgets relay board contains two electromechanical
relays that can switch loads up to 5 A at 240 VAC or 10 A
at 100 VDC. The maximum operation speed is 20 times
per minute and lifetime is 105 to 107 cycles. The control
input is a digital logic signal. The control input feeds into a
discrete power transistor that provides the higher current
levels needed to drive the relay’s coil (5V at 75 mA).
Limitations of Mechanical Relays
Easy way to switch high current and/or high
voltage loads and provides electrical
isolation, but…
• Number of lifetime ON/OFF cycles is limited by
mechanical wear (typically 106 to 107 cycles)
• Slow ON/OFF times – around 20 per minute
• Contacts can wear out due to arcing on inductive loads
(perhaps as few as 105 cycles) even on rated loads
• Oxidation on relay contacts can be a problem on low
voltage analog signals (around 2V needed to initially
punch through oxidation layer between metal contacts)
• Worn out relays will sometimes stick
H-Bridge - DC Motor Driver Circuit
H-Bridge Control Functions
Input Function Operation
10 Forward DC Motor runs in the
forward direction
01 Reverse DC Motor runs in the
reverse direction
00 Stop Motor is not connected
– Coasts
11 Brake* or Motor Terminals
Shorted or
Short Power Supply Power Supply
(not allowed!) Shorted!
*The Brake function requires a more complex decoder circuit to control the power
transistors. Check the H-Bridge data sheet to make sure it is supported before using
it. In some old very simple H-Bridge circuits using only one type of power transistor
(i.e., N or P), the fourth state must be avoided (i.e., illegal state) and it will short out
the power supply! Most new H-bridge ICs now support the brake feature, but in
some cases it might still overheat the IC when used too frequently.
H-Bridge Example - Forward
HIGH LOW
H-Bridge Example - Reverse
LOW HIGH
Figure 3.10 Fairchild FAN8100N Low Voltage Dual H-Bridge DC Motor Driver IC.
Images courtesy of Fairchild Semiconductor.
Higher current H-Bridge modules often use discrete power
transistors assembled on a board. This dual H-Bridge module
switches up to 10 amps at 24V DC. The eight power
transistors can be see arranged on the right side of the board.
Photograph courtesy of RoboticsConnection.
This ST VNH2SP30 30Amp DC MOSFET motor driver IC
contains an H-bridge circuit. It supports 5V PWM speed
control up to 20Khz. Image courtesy of www.pololu.com.
Electromechanical Relays
•They have slow ON/OFF times – around 20 per minute. Too slow for motor
speed control or dimming lights.
•Relay contacts can wear out due to arcing on inductive loads (perhaps as few
as 105 cycles) even on rated loads.
•Worn out relays will sometimes stick due to mechanical wear and an audible
click is typically heard during switching.
Solid State Relays
• Optical isolation between input and output load
• Unlike electromechanical relays, No moving parts
• May be fast enough for motor speed control and dimming lights
• Resistant to shock and vibration
• 150X more reliable than mechanical relays
System Bus
A3
Address
A2 Decoder
A1 Output
A0
Hardware allows only one tri-state gate at a time to drive a bus signal!
Original PC design only decoded low 10 I/O address bits to save hardware.
Each I/O device must have a unique address on a bus!
An Example ISA Bus I/O Write Operation
Bus Clock
I/O Write
Bus Clock
Valid Address
Address
I/O Read
One tri-state
gate is needed
for each bit on
the data bus
Typical I/O Output Port Hardware
Operation
R
Address e
Address Bus Decoder g
Circuit Data Bus i Data out to
s I/O Device
t
e
r
Problems: Does not port to other processors and many people do not
understand assembly language!
ARM Assembly Language
• See mbed wiki page on ARM assembly
language:
– https://developer.mbed.org/cookbook/
Assembly-Language
• I/O registers (ports) are memory mapped
on RISC processors, so Load and Store
instructions can be used directly for I/O
(unlike “in” and “out” special case on X86)
Example X86 I/O Port R/W Functions
• READ_PORT_UCHAR(I/O_Address)
– Returns 8-bit input value from input port
• WRITE_PORT_UCHAR(I/O_Address,I/O_Data)
– Sends 8-bit data value to output port
• Used in some versions of Windows
• Typically used in code for low-level device
drivers
ARM I/O Registers
• On RISC processors, I/O registers are memory
mapped, but not on X86 processors.
• C pointers set to the correct address are the
fastest way to access these I/O registers (faster
than function calls). Pointers are used in mbed’s
I/O API library code.
• Wiki page with details and examples at:
– https://developer.mbed.org/users/4180_1/notebook/
cc-io-register-names/
A Second Generation Bus - PCI
Bus Clock
F rame #
IRDY#
TRDY#
DEVSEL#
Bus Transaction
PCI Read Burst Cycle
Clock Cycle Description of PCI operation
0 Bus is idle
1 The initiator sets FRAME low, places the address on the Address/Data (ADx) lines,
and the bus command (read) on the Command/Byte Enable (C/BE) lines (address
phase).
2 The initiator tri-states the address and waits for the target to return a data value by
turning on its tri-state drivers. Device Select (DEVSEL) low indicates a target
device has decoded its address range and it is responding to the command. The
target drives TRDY high to indicate the target needs another clock cycle to respond
with the data.(data phase)
3 The target drives the data value and sets target ready (TRDY) low to indicate that
data is valid. When both IRDY and TRDY are low a data transfer occurs.
4 The target sets TRDY high to indicate it need an additional clock cycle for the next
data transfer.
5 The second data transfer occurs when both TRDY and IRDY are low. The initiator
saves the target data.
6 The target drives the data value, but the initiator requests an additional clock cycle
by set IRDY high.
7 The initiator sets IRDY low to complete the third data transfer. The initiator saves
the target data value, The initiator drives FRAME high to end the data phase.
8 All bus signals are tri-stated or driven to the inactive state.
PCI Write Burst Cycle
0 1 2 3 4 5 6 7 8
Bus Clock
F rame #
IRDY#
TRDY#
DEVSEL#
Bus Transaction
PCI Write Burst Cycle
Clock Cycle Description of PCI operation
0 Bus is idle
1 The initiator sets FRAME low, places the address on the Address/Data (ADx) lines, and
the bus command (write) on the Command/Byte Enable (C/BE) lines (address phase).
2 The initiator places the data on the ADx lines and byte enables on C/BE lines, Device
Select (DEVSEL) low indicates a target device has decoded it’s address range and it is
responding to the command. When both IRDY and TRDY are low the target saves the
data. (data phase)
3 The initiator drives new data and byte enables. When both initiator ready IRDY and
TRDY are low a data transfer occurs and the target saves the data.
4 The initiator sets IRDY high and the target sets TRDY requesting an additional clock
cycle.
5 The initiator drives new data and byte enables and sets IRDY low. The initiator sets
FRAME high indicating the final data transfer.
6 The target drives the data value, but the initiator requests an additional clock cycle by
set IRDY high.
7 The initiator sets IRDY low to complete the third data transfer. The target saves the data
value.
8 All bus signals are tri-stated or driven to the inactive state.
PCI IP Cores
Intel 82541 Ethernet Controller IC
System Bus
Programmed I/O
Interrupt
DMA
Mbed I/O Transfer Examples
• Most mbed APIs use software polling
• Basic GPIO with DigitalIn and DigitalOut
do not have or use any ready bits
• Serial API uses interrupts with a character
buffer – getc and putc check buffer status
• RawSerial does not use a character buffer
Mbed I/O Transfer Examples
• Most mbed user I/O pins and devices can
be setup to generate an interrupt
– Pindetect switch debounce code uses
interrupts
• Mbed has DMA controllers, but they are
currently not used in standard APIs. Some
DMA examples are available but are not
easy to use
General Purpose OS Transfers
• Most use interrupt driven I/O with buffering
• DMA typically used for disk I/O transfers
• Hardware protection forces user programs
to use OS APIs for I/O operations
• May need to write a custom I/O device
driver for new hardware
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.
WindowsFile I/O API Calls
Lock
Lock
Window Lift
Universal Light
CAN Light
Seat
Htng
Instruments
Htng Wiper
Power Train Central WHtg
Body Ctrl Roof Interior
ITS Light
Trunk
Htng
Climate
x6
Seat
Light Seat
Htng
St-Wheel Panel CAN
Universal Motor
Lock Lock
1 backbone, 13 nodes
8 subnets, 1-8 local nodes Sub-Bus
Universal Panel
52 nodes total
Mirror
Controller Area Network (CAN)
• Messages contain a message number and
not an address
• Lower number messages have priority
• Each devices checks the message
number to see if it needs to handle the
message
• Data rates up to 1M Baud
• Special CAN chips are available
Message Frame
Bus Idle Arbitration Field Control Data Field CRC Field ACK EOF Int Bus Idle
RTR r0
r1 D elimiter
Header Response
Figure 3.16 A Typical LIN Frame Consisting of Synch Break, Synch Field, Identifier, Data Field and
Checksum.
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 I 2C bus signals. Images courtesy of Prodigy Test Solutions.
Network Interface
Standards
Networking
• Ethernet Frames
• Ethernet LAN
• The TCP/IP Protocol Suite
• Software APIs for networking
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)
P ri nter
C
Computer
A
Ethernet Medium
Statio n S tati on
A D
Bridge
Segment 1 Segment 2
S tati on S tati on
B C
TCP/IP Protocol
• Application Protocols – HTTP, SMTP,
SSH, etc.
• Transport Protocols – TCP, UDP
• Network Communication Protocols – IP
• Network Topology – Ethernet, Wi-Fi,
Token Ring, etc.
Network Protocol Layers
TCP TCP
Header Data Transport Protocols
IP
Header IP Data Internet Protocols
Frame Frame
Frame Data Network Topology
Header Trailer
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
OS Networking Software
https://developer.mbed.org/handbook/RTOS
• Each thread and the RTOS needs its own stack area in
RAM. Around 8 threads max or so on LPC1768 mbed
(limited by 32K RAM)
mbed RTOS
See https://en.wikipedia.org/wiki/Real-
time_operating_system#Algorithms
Other Synchronization Issues
• https://developer.mbed.org/cookbook/RPC-Interface-
Library has examples on adding new RPC procedures
and variables using the library code
• RPCFunction - A class which can be used to call user
defined functions over RPC (in mbed RPC code)
• RPCVariable - A class which allows you to read and write
the value of a variable on mbed using RPC (in mbed RPC
code)
• SerialRPCInterface- A class which will set up RPC for
serial by registering all the base classes and setting up
the serial port on an interrupt
mbed RPC
• RPC Commands are in the format: "/<Object
name>/<Method name> <Arguments separated by
spaces>
• If you send just CRLF mbed will return a list of objects
that can be used
• If you send "/<object name>/" then mbed will return the
methods which can be used on this object.
• Command is not echoed back. Must send both ASCII
CR and LF at end of line!
Mbed RPC Demo using USB Serial
• https://developer.mbed.org/users/kennyainny/notebook/
mbed-net-rpc-library---revised/ uses new version of RPC
library
• Demo sets up a C# GUI on PC and controls mbed using
RPC over USB virtual com port.
PC C# GUI controlling mbed via RPC
Serial RPC using Interrupts
The USB serial port displays status and debug messages on the PC. The mbed IP address is
displayed along with connection messages. The GET request is coming from the PCs web browser
using mbed’s IP address for RPC. The debug messages can use a lot of code space, slow things
down, and probably should not be used in a final product. Often times a “Debug” switch feature is
available in code or a compiler to not include debug messages.
RPC HTTP Demo
A web browser connects to mbed’s IP and the RPC arguments are added at the end of the
URL (“http://<mbed IP>/rpc/”). The image above shows the PC’s RPC request to list RPC
objects and mbed returns the object names as an ASCII string that appear as the text for the
web page in the browser. Since this is a local IP address for mbed, the PC needs to be on the
same subnet. Application programs running on the PC can do HTTP GET requests for RPC
(without running a web browser).
IoT Devices
275 Billion IoT devices by 2035
Early Consumer IoT Devices
•https://developer.mbed.org/users/hbindra3/notebook/
alexa-dot/
•https://developer.mbed.org/users/omabogunje3/
notebook/dot-bot-two-way-communication-between-aws-
and-mbed/
•https://developer.mbed.org/users/RohanIyengar/
notebook/amazon-dot-alexa-controlled-game-playing/
Other mbed IoT Examples
http://www.postscapes.com/internet-of-things-award/
winners/
Next Step Up in Performance
#include "stdafx.h"
BOOL ModifyCommSettings (HANDLE hComPort);
HANDLE hSerial;
cBuffer_in[0] = 0;
// Read in characters, copy to console display and Echo
// Loop until ctrl C is typed
while (cBuffer_in[0] != 0x03){
// Wait for character in input buffer - events are more efficient than
looping
WaitCommEvent(hSerial, &dwMask, 0);
cBytes_in = 1;
// Loop just in case more than one character is in UARTs input buffer
while (cBytes_in != 0){
// Read back data any serial data and display
if (ReadFile(hSerial, cBuffer_in, 64, &cBytes_in, NULL)){
if (cBytes_in == 0) break;
// Display Data read back
printf("%s",cBuffer_in, cBytes_in);
// Echo characters back to sender
if (!WriteFile(hSerial, cBuffer_in, cBytes_in,
&cBytes_out, NULL)){
printf("\rfile write errors\n");
Sleep(4000);
return 0;
}
}
}
}
// Close File
CloseHandle(hSerial);
return 1;
}
// 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;
}
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 I/O Port Address
Data (DLB=1, Baud rate divisor LSB) Base + 0
Interrupt Enable (DLB=1, Baud rate divisor MSB) Base + 1
Interrupt ID Base + 2
Data Format Base + 3
Modem control Base + 4
Line Status Base + 5
Modem status Base + 6
Scratch-Pad Base + 7
// 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"
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);
// 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;
}
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
// 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);
#include "stdafx.h"
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // The title bar text
return msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASS wc;
return RegisterClass(&wc);
}
//
// FUNCTION: InitInstance(HANDLE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global
// variable and create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// 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)
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
C# Hello World Console Application
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Threading;
namespace Hello_CS_World
{
class Program
{
static void Main(string[] args)
{
bool _continue = true ;
string message;
StringComparer stringComparer=StringComparer.OrdinalIgnoreCase
// Display title and prompt line on console
Console.WriteLine("Hello C# World");
Console.WriteLine ("Type QUIT to Exit");
WSAStartup Initiates use of WS2_32.DLL by a process. Required once before other WinSock API
calls can be used.
connect Establishes a connection to a specified socket.
socket Creates a socket that is bound to a specific service provider.
bind Associates a local address with a socket.
listen Places a socket in a state where it is listening for an incoming connection.
accept Permits an incoming connection attempt on a socket.
sendto Sends data to a specific destination using a socket.
recvfrom Receives a datagram using a socket and stores the source address.
getaddrinfo Provides protocol-independent translation from an ANSI host name to an address.
freeaddrinfo Frees address information that the getaddrinfo function dynamically allocates in
addrinfo structures.
getnameinfo Provides name resolution from an IPv4 or IPv6 address to an ANSI host name and from
a port number to the ANSI service name.
shutdown Disables sends or receives on a socket.
closesocket Closes an existing socket
Figure 8.10 The Winsock_echo network loopback test program running on the eBox.
Web Services
Client Web
Application Service
HTTP
on Device Object
Web Service Code Example
• C# Server Code on remote system:
[WebMethod (namespace="http://myserver/xmlwebservices/")]
public int Add(int a, int b)
{
return a + b;
}
namespace CreateRemote
{
namespace CreateRemote
{
#region Enumerations
// Definitions of iRobot Create OpenInterface Command Numbers
// See the Create OpenInterface manual for a complete list
public enum Commands
{
// Create Command // Arguments
Start = 128,
SafeMode = 131,
FullMode = 132,
Drive = 137, // 4: [Vel. Hi][Vel Low][Rad. Hi][Rad. Low]
DriveDirect = 145, // 4: [Right Hi][Right Low][Left Hi][Left Low]
Sensors = 142, // 1: Sensor Packet ID
CoverandDock = 143,// 1: Return to Charger
Demo = 136, // 2: Run Demo x
Song = 140, // Download Song Notes - up to 16 notes
PlaySong = 141, // 2: Play Song number x
LED = 139, // 3: LED output control
Stream = 148, // x+1: [# of packets]IDs of packets to stream
QueryList = 149, // x+1: [# of packets] IDs of requested packets
StreamPause = 150, // 1: 0 = stop stream, 1 = start stream
}
/* iRobot Create Sensor Packet IDs */
public enum Sensors
{
BumpsandDrops = 7,
Distance = 19,
Angle = 20,
}
#endregion Enumerations
public partial class Form1 : Form
{
public SerialPort port;
public Int16 left = 50;
public Int16 right = 50;
public byte Color = 0;
private bool ProcessingSensorDataPacket = false;
public bool raw_sensor_debug = false;
public volatile short bumpandrop_data = 0;
public Form1()
{
InitializeComponent();
// Serial Port Open Code - used to communicate with iRobot Create robot
port = new SerialPort("COM1",57600,Parity.None,8,StopBits.One);
port.Handshake = Handshake.None;
port.ReadTimeout = 60000;
port.WriteTimeout = 60000;
try // Just in case .NET CF not updated
{
port.Open();
}
catch (Exception com_open_except) { }
}
// Start Button - send start and safe mode, start streaming sensor data
private void button5_Click(object sender, EventArgs e)
{
port.Write(new byte[] { (byte)Commands.Start,
(byte)Commands.SafeMode }, 0, 2);
Thread.Sleep(100);
port.Write(new byte[] { (byte)Commands.Stream, 1,
(byte)Sensors.BumpsandDrops}, 0, 3);
Thread.Sleep(200);
port.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
}
// Stop Button - turn off drive motors
private void button6_Click(object sender, EventArgs e)
{
port.Write(new byte[] { (byte)Commands.DriveDirect,
(byte)0, (byte)0,
(byte)0, (byte)0 }, 0, 5);
}
// Forward Button - turn on drive motors
private void button1_Click(object sender, EventArgs e)
{
port.Write(new byte[] { (byte)Commands.DriveDirect,
(byte)(right >> 8), (byte)right,
(byte)(left >> 8), (byte)left }, 0, 5);
// Reverse Button - reverse drive motors
private void button4_Click(object sender, EventArgs e)
{
port.Write(new byte[] { (byte)Commands.DriveDirect,
(byte)(-right >> 8), (byte)-right,
(byte)(-left >> 8), (byte)-left }, 0, 5);
}
// Left Button - drive motors set to rotate to left
private void button3_Click(object sender, EventArgs e)
{
port.Write(new byte[] { (byte)Commands.DriveDirect,
(byte)(right >> 8), (byte)right,
(byte)(-left >> 8), (byte)-left }, 0, 5);
}
// Right Button - drive motors set to rotate to right
private void button2_Click(object sender, EventArgs e)
{
port.Write(new byte[] { (byte)Commands.DriveDirect,
(byte)(-right >> 8), (byte)-right,
(byte)(left >> 8), (byte)left }, 0, 5);
}
// Charger Button - return to charger using IR beacons
private void button7_Click(object sender, EventArgs e)
{
port.Write(new byte[] { (byte)Commands.Demo, (byte) 1}, 0, 2);
}
// Play Song Button - define and play a song on robot
private void button8_Click(object sender, EventArgs e)
{ // Send out notes & duration to define song and play song
port.Write(new byte[] { (byte)Commands.Song, 0, 16,
91, 24, 89, 12, 87, 36, 87, 24, 89, 12,
91, 24, 91, 12, 91, 12, 89, 12, 87, 12, 89, 12,
91, 12, 89, 12, 87, 24, 86, 12, 87, 48 }, 0, 35);
Thread.Sleep(100);
port.Write(new byte[]{(byte)Commands.PlaySong,
(byte)0 },0,2);
}
// Slider trackbar to set motor speed
private void Speed(object sender, EventArgs e)
{
left = (Int16) trackBar1.Value;
right = (Int16) trackBar1.Value;
}
// Checks for Proper Checksum at end of Sensor Data Packet
bool validData(byte[] buf, byte chksum)
{
foreach (byte b in buf) chksum += b;
if (chksum != 0)
{
return false;
}
else return true;
}
// Event activated whenever new serial data is recieved
// packets are sent every 15 MS
void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
if (ProcessingSensorDataPacket) return;
{
ProcessingSensorDataPacket = true;
try
{
// align with sensor packet header value and read in data
while (port.ReadByte() != 19) { }
byte[] buf = new byte[port.ReadByte()];
port.Read(buf, 0, buf.Length);
// grab final checksum, validate checksum, and update sensor data
if (validData(buf, (byte)(port.ReadByte()+
(buf.Length + 19))))
{ // Display raw sensor data on console for debug?
if (raw_sensor_debug) {
foreach (byte b in buf) Console.Write(b + " ");
Console.WriteLine();
};
// Checksum OK - so save new sensor data in packet
bumpandrop_data = buf[1];
}
}
catch (TimeoutException)
{
Console.WriteLine("Serial port Read timed out?");
}
catch
{
}
ProcessingSensorDataPacket = false;
}
}
// Update Sensor Display - timer executes this every 300 MS
private void timer1_Tick(object sender, EventArgs e)
{
// Flash through different colors on LED to indicate program is running
Color += 64;
port.Write(new byte[] { (byte)Commands.LED, 0, Color,
200 }, 0, 4);
// mask off sensor bits & Update Sensor Check Boxes on GUI
checkBox1.Checked = (bumpandrop_data & 1) == 1;
checkBox1.Update();
checkBox3.Checked = (bumpandrop_data & 2) == 2;
checkBox3.Update();
checkBox4.Checked = (bumpandrop_data & 4) == 4;
checkBox4.Update();
checkBox5.Checked = (bumpandrop_data & 8) == 8;
checkBox5.Update();
checkBox6.Checked = (bumpandrop_data & 16) == 16;
checkBox6.Update();
}
// Checkbox to display raw sensor data on console for debug
// delays response a bit - data backs up in buffers when on
private void checkBox2_CheckStateChanged(object sender,
EventArgs e)
{
raw_sensor_debug = checkBox2.Checked;
}
}
}
For debug purposes, checking “Display Raw Sensor Packets” in the CreateRemote GUI will display
incoming robot sensor data packets on the PC’s console window.
PC with mbed custom I/O
• Use mbed to add custom I/O hardware to a PC
• Use the USB virtual com port interface for
communication between mbed and the PC.
• C++/C# Code from earlier serial port examples
will work
• RPC can be used for complex applications
• PC can use a GUI for user interface
Serial IO Example
• https://developer.mbed.org/users/kennyainny/notebook/
mbed-net-rpc-library---revised/ uses new version of RPC
library
• Demo sets up a C# GUI on PC and controls mbed using
RPC over USB virtual com port.
PC C# GUI controlling mbed via RPC
Introduction to OS I/O
Device Drivers
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
developer write a new device driver.
Device Drivers
• Depending on OS, a device driver that is part of
the kernel code may be required to communicate
with any I/O hardware
• RISC I/O registers may be in a protected memory
region that user code cannot access directly (but
OS Kernel drivers can)
• On X86 processors, I/O instructions are privileged
and protected by the mode bit, so I/O instructions
need to be executed in kernel mode (not in a user
mode program – so need driver)
• Some Linux examples run I/O code as superuser
to avoid this issue – but it is not as secure.
Stream Interface Driver
• Best choice for a simple driver for a device that
produces and/or consumes streams of data
• Applications use standard file system APIs to
call the driver
• Driver must have several required Standard
Entry Points for OS
• These entry points are used by the OS file
system API calls from user application code
– (i.e., open, read, write, seek, close…)
Windows Stream Interface Driver Functions.
Programming Description
element
XXX_Close (Device This function closes the device context identified by
Manager) hOpenContext.. This function is required to access the device
with CreateFile. If you implement XXX_Close, you must
implement XXX_Open.
XXX_Deinit (Device This function de-initializes a device. It is called by Device
Manager) Manager.This function is required by drivers loaded by
ActivateDeviceEx, ActivateDevice, or RegisterDevice.
XXX_Init (Device This function initializes a device. It is called by Device
Manager) Manager.This function is required by drivers loaded by
ActivateDeviceEx, ActivateDevice, or RegisterDevice.
XXX_IOControl This function sends a command to a device.This function might
(Device Manager) or might not be required, depending on the device capabilities
that the driver exposes. This function requires an
implementation of XXX_Open and XXX_Close.
XXX_Open (Device This function opens a device for reading, writing, or both. An
Manager) application indirectly invokes this function when it calls
CreateFile to obtain a handle to a device. This function is
required to access the device with CreateFile.
XXX_PowerDown Optional. This function ends power to the device. It is useful
(Device Manager) only with devices that can be shut off under software control.
XXX_PowerUp Optional. This function restores power to a device.
(Device Manager)
XXX_PreClose Optional. This function marks the closing handle as invalid and
(Device Manager) wakes any sleeping threads.
XXX_PreDeinit This function marks the device instance as invalid and wakes
(Device Manager) sleeping threads. This function is required if the XXX_PreClose
function is implemented.
XXX_Read (Device This function reads data from the device identified by the open
Manager) 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.
XXX_Seek (Device This function moves the data pointer in the device. This function
Manager) 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_Write (Device This function writes data to the device. This function might or
Manager) might not be required, depending on the device capabilities that
the driver exposes.This function requires an implementation of
XXX_Open and XXX_Close.
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 Windows CE (now called Windows
IoT)
• Based on earlier serial port IO example
• Uses CEDDK functions to communicate with
16550 UART compatible hardware on PC serial
port
• Must be setup as a DLL in Visual Studio
// This is a Sample Stream Interface Device Driver
// Educational example intended to illustrate how stream drivers work
// using the serial I/O port hardware on the target system
// and show the use of READ_PORT_UCHAR and WRITE_PORT_UCHAR
// from the CE Device Driver Kit (CEDDK)
//
// Setup for X86 PC (CEPC)
// using 16550 UART compatiable serial port hardware
//
// Not intended to replace a good serial port device driver!
// Does not use interrupts, have any timeouts, or provide
// support for all of the serial port's features
// Would normally use OS API calls for this operation!
//
// FOR DEMO: Connect Ebox COM2: to PC with null modem cable
// Run HyperTerminal with 9600 Baud 8 data bits 1 stop bit
// no parity and no flow control
#include "stdafx.h"
#include <windows.h>
#include "ceddk.h"
PUCHAR Data_Port_Address;
UCHAR Serial_Input_Data = 0;
// ----------------------------------------------------
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");
return Count;
}
// Stream Driver Seek
DWORD KOM_Seek( DWORD hOpenContext, long Amount, WORD Type )
{
OutputDebugString(L"KOM_DRIVER - KOM_Seek\n");
OutputDebugString(L"hOpenContext - ");
DBGOut(hOpenContext);
OutputDebugString(L"\n");
// Add Seek Function Code Here
OutputDebugString(L"KOM_DRIVER - Exit KOM_Seek\n");
return 0;
}
return;
}
Windows 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
• Can use Regedit program to add
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
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;
}
// 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