Lecture 8 - I/O, Sensors and Interrupts

I/O, Sensors, and Interrupts

EEN 417

Fall 2013

Plan for today’s class period

1.

I/O

2.

Sensors

3.

Interrupts

4.

Wrap-up

I/O

Connecting the Analog and

Cyber:

• Digital

• Discrete in time

• Sequential

Digital Worlds

Physical:

• Continuum

• Continuous in time

• Concurrent

What is going on here?

• Physical Connection

• Handshake

• Multiple connections

• Timing Characteristics

?

?

Interfaces

A Typical Microcomputer Board

•This board has analog and digital inputs and outputs.

What are they?

How do they work?

Parallel vs. Serial Digital

Interfaces

 Parallel

– Multiple data lines transmitting data

– Speed

– Ex: PCI, ATA, CF cards, Bus

 Serial

– Single data line transmitting data

– Low Power, length

– Ex: USB, SATA, SD cards,

PCI-Express

Simple Digital Output: GPIO

•Open collector circuits are often used on GPIO (generalpurpose I/O) pins of a microcontroller.

•The same pin can be used for input and output. And multiple users can connect to the same bus.

•Why is the current limited?

Serial Interfaces

•The old but persistent RS-232 standard supports asynchronous serial connections (no common clock).

•How does it work?

Many but not all uses of

RS-232 are being replaced by USB, which is electrical simpler but with a more complex protocol.

Uppercase ASCII "K" character (0x4b) with 1 start bit, 8 data bits, 1 stop bit.

Image license: Creative Commons

ShareAlike 1.0

License

UART: Universal Asynchronous

Receiver-Transmitter

• Convert serial data to parallel data, and vice versa.

• Uses shift registers to load store data

• Can raise interrupt when data is ready

• Commonly used with

RS-232 interface

Example Using a Serial

Interface

In an Atmel AVR 8-bit microcontroller, to send a byte over a serial port, the following C code will do: while(!(UCSR0A & 0x20));

UDR0 = x;

• x is a variable of type uint8.

• UCSR0A and UDR0 are variables defined in header.

• They refer to memory-mapped registers in the UART.

Send a Sequence of Bytes

for(i = 0; i < 8; i++) { while(!(UCSR0A & 0x20));

UDR0 = x[i];

}

How long will this take to execute? Assume:

• 57600 baud serial speed.

• 8/57600 =139 microseconds.

• Processor operates at 18 MHz.

Each while loop will consume 2500 cycles.

Receiving via UART

Again, on an Atmel AVR: while(!(UCSR0A & 0x80)); return UDR0;

• Wait until the UART has received an incoming byte.

• The programmer must ensure there will be one!

• If reading a sequence of bytes, how long will this take?

Under the same assumptions as before, it will take 2500 cycles to receive each byte.

Input Mechanisms in Software

 Polling

 Main loop checks each I/O device periodically.

 If input is ready, processor initiates communication.

 Interrupts

 External hardware alerts the processor that input is ready.

 Processor suspends what it is doing.

 Processor invokes an interrupt service routine (ISR).

 ISR interacts with the application concurrently.

Polling

Processor Setup Code

Processor checks I/O control register for status of peripheral 1

Ready

Not Ready

Processor checks I/O control register for status of peripheral 2

Ready

Not Ready

Processor services I/O 1

Processor services I/O

2

Processor checks I/O control register for status of peripheral 3

Not Ready

Ready Processor services I/O 3

Interrupts

 Interrupt Service Routine

Short subroutine that handles the interrupt

Processor Setup Code

Register the Interrupt Service Routine

Interrupt!

Processor executes task code

Context switch

Resume

Run Interrupt Service Routine

Timed Interrupt

Processor Setup

Timer

Register Interrupt Service Routine

Initialize Timer

When timer expires, interrupt processor

Reset timer

Execute Task Code

Processor jumps to ISR

Resumes

Update Tick / Sample

Issues to Watch For

•Interrupt service routine execution time

•Context switch time

•Nesting of higher priority interrupts

•Interactions between ISR and the application

•Interactions between ISRs

•…

Standards

 Serial:

– Synchronous:

• SPI, I2C, JTAG, USB

– Asynchronous:

• RS232

 Parallel:

– Bus protocols

• Advanced Technology Attachment (ATA)

• Peripheral Component Interface (PCI)

• …

An I/O View of a Microcontroller

Another I/O View of a Microcontroller

Simple MP3 Player

• Uses serial for control

• Parallel for data transfer

• Direct memory access

Application of a

Microcontroller

SENSORS

Sensors and Actuators

• Sensors:

 Cameras

 Accelerometers

 Rate gyros

 Strain gauges

 Microphones

 Magnetometers

 Radar/Lidar

 Chemical sensors

 Pressure sensors

Actuators:

 Motor controllers

 Solenoids

LEDs, lasers

LCD and plasma displays

Loudspeakers

Modeling Issues:

Physical dynamics

Noise

Bias

Sampling

Interactions

Magnetometers

•A very common type is the

Hall Effect magnetometer.

•Charge particles (electrons, 1) flow through a conductor (2) serving as a Hall sensor.

Magnets (3) induce a magnetic field (4) that causes the charged particles to accumulate on one side of the

Hall sensor, inducing a measurable voltage difference from top to bottom.

•The four drawings at the right illustrate electron paths under different current and magnetic field polarities.

Edwin Hall discovered this effect in 1879.

Image source: Wikipedia Commons

Accelerometers

• Uses:

 Navigation

 Orientation

 Drop detection

 Image stabilization

 Airbag systems

The most common design measures the distance between a plate fixed to the platform and one attached by a spring and damper. The measurement is typically done by measuring capacitance.

Spring-Mass-Damper

Accelerometer

•By Newton ’ s second law,

F=ma.

•For example, F could be the

Earth ’ s gravitational force.

•The force is balanced by the restoring force of the spring.

Spring-Mass-Damper System

x

Exercise: Convert to an integral equation with initial conditions.

Measuring tilt

q

Difficulties Using

Accelerometers

 Separating tilt from acceleration

 Integrating twice to get position: Drift

 Vibration

 Nonlinearities in the spring or damper

Feedback dramatically improves accuracy and dynamic range of microaccelerometers.

•The Berkeley Sensor and

Actuator Center (BSAC) created the first silicon microaccelerometers, MEMS devices now used in airbag systems, computer games, disk drives (drop sensors), etc.

Digital

T

V/F

+

-

M. A. Lemkin, “ Micro Accelerometer

Design with Digital Feedback Control ” ,

Ph.D. dissertation, EECS, University of

California, Berkeley, Fall 1997

Measuring Changes in

Orientation:

Gyroscopes

•Optical gyros: Leverage the Sagnac effect, where a laser light is sent around a loop in opposite directions and the interference is measured.

When the loop is rotating, the distance the light travels in one direction is smaller than the distance in the other. This shows up as a change in the interference.

Images from the Wikipedia Commons

Inertial Navigation Systems

• Combinations of:

 GPS (for initialization and periodic correction).

 Three axis gyroscope measures orientation.

 Three axis accelerometer, double integrated for position after correction for orientation.

• Typical drift for systems used in aircraft have to be:

 0.6 nautical miles per hour

 tenths of a degree per hour

• Good enough? It depends on the application!

Strain Gauges

Mechanical strain gauge used to measure the growth of a crack in a masonry foundation. This one is installed on the Hudson-Athens

Lighthouse. Photo by Roy Smith, used with permission.

Images from the Wikipedia Commons

Design Issues with Sensors

 Calibration

– Relating measurements to the physical phenomenon

– Can dramatically increase manufacturing costs

 Nonlinearity

– Measurements may not be proportional to physical phenomenon

– Correction may be required

– Feedback can be used to keep operating point in the linear region

 Sampling

– Aliasing

– Missed events

 Noise

– Analog signal conditioning

– Digital filtering

– Introduces latency

Aliasing

•Sampled data is vulnerable to aliasing , where high frequency components masquerade as low frequency components.

•Careful modeling of the signal sources and analog signal conditioning or digital oversampling are necessary to counter the effect.

A high frequency sinusoid sampled at a low rate looks just like a low frequency sinusoid.

Digitally sampled images are vulnerable to aliasing as well, where patterns and edges appear as a side effect of the sampling. Optical blurring of the image prior to sampling avoids aliasing, since blurring is spatial lowpass filtering.

Noise & Signal Conditioning

• Example:

|X d

( w

) | 2

|X n

( w

) | 2 w

Filter:

F ( w

) w

Filtered signal:

|X d

( w

) F ( w

) | 2

|X n

( w

) w

( w

) | 2

A full treatement of this requires random processes.

Motor Controllers

•bionicHand.jpg: Photo by Touch Bionics It ’ s got an embedded computer, a rechargeable battery, and five small dc motors. It costs US

$18 500. And it can do things most other prosthetic hands just can ’ t, like grabbing a paper cup without crushing it, turning a key in a lock, and pressing buttons on a cellphone. The fingers of Touch Bionics ’ iLIMB Hand are controlled by the nerve impulses of the user ’ s arm, and they operate independently, adapting to the shape of whatever they ’ re grasping. The hand can also do superhuman tricks, like holding a very hot plate or gripping an object tirelessly for days. A skin-tone covering gives the bionic hand a lifelike look, but some customers refer semitransparent models, to proudly flaunt their robotic hands. “ They like the

Terminator look, ” says Touch Bionics CEO

Stuart Mead. IEEE Spectrum, Oct. 2007.

Cameras

 Computer-controlled digital cameras

 Digital video cameras

 Specialized cameras

– infrared

– ultra fast/high resolution

– motion trackers

Pirates of the Caribbean: the Curse of the Black Pearl

(2003, Disney) pioneered the use of motion trackers coupled with computer-generated graphics.

At the right: the transformation of Geoffrey Rush

Photo Credit: Industrial Light & Magic.

© Disney Enterprises Inc. and Jerry Bruckheimer Inc.

All rights reserved.

Overview of PhaseSpace

Motion Tracker Technology

Impulse camera detecting peaks on two linear sensors with 3600 pixels each, arranged in a straight line, each with 60 degree field of view.

y

Calculation of marker position by correlating the peaks in the x and y directions.

x

Up to 72 infra-red markers, where each has a unique flashing frequency so that the detector can distinguish them.

Up to 24 cameras can surround the scene

Motion Suit

•Up to 38 IR markers on the suit

•Wireless control by the server

INTERRUPTS

Input Mechanisms in Software

 Polling

 Main loop checks each I/O device periodically.

 If input is ready, processor initiates communication.

 Interrupts

 External hardware alerts the processor that input is ready.

 Processor suspends what it is doing.

 Processor invokes an interrupt service routine (ISR).

 ISR interacts with the application concurrently.

Interrupts

 Interrupt Service Routine

Short subroutine that handles the interrupt

Processor Setup Code

Register the Interrupt Service Routine

Interrupt!

Processor executes task code

Context switch

Resume

Run Interrupt Service Routine

Interrupts:

Details

Program memory addresses, not data memory addresses.

• Triggers:

Source: ATmega168 Reference Manual

 Hardware interrupt: A level change on an interrupt request pin

 Software interrupt: Special instruction or write a memory-mapped register

• Responses:

 Disable interrupts.

 Push the current program counter onto the stack.

 Execute the instruction at a designated address in the flash memory.

• Design of interrupt service routine:

 Save and restore any registers it uses.

 Re-enable interrupts before returning from interrupt.

Timed Interrupt

Processor Setup

Timer

Register Interrupt Service Routine

Initialize Timer

When timer expires, interrupt processor

Execute Task Code

Processor jumps to ISR

Update Tick / Sample

Resumes

Reset timer

Example 1: Set up a timer on an ATmega168 to trigger an interrupt every 1ms.

 TCCR: Timer/Counter Control Register

 OCR: output compare register

 TIMSK: Timer Interrupt Mask

• The “ prescaler ” value divides the system clock to drive the timer.

• Setting a non-zero bit in the timer interrupt mask causes an interrupt to occur when the timer resets.

Source: iRobot Command Module Reference Manual v6

Setting up the timer interrupt hardware in C

#include <avr/io.h> int main (void) {

TCCR1A = 0x00;

TCCR1B = 0x0C;

OCR1A = 71;

TIMSK1 = 0x02;

...

} memorymapped register

This code sets the hardware up to trigger an interrupt every 1ms.

Source: ATmega168 Reference Manual

Example: Do something for 2 seconds then stop volatile uint timer_count = 0; void ISR(void) { if(timer_count != 0) { timer_count--;

}

} int main(void) {

// initialization code

SysTickIntRegister(&ISR);

... // other init timer_count = 2000; while(timer_count != 0) {

... code to run for 2 seconds

}

} static variable: declared outside main() puts them in statically allocated memory (not on the stack) volatile: C keyword to tell the compiler that this variable may change at any time, not (entirely) under the control of this program.

Interrupt service routine

Registering the ISR to be invoked on every SysTick interrupt

Concurrency

volatile uint timer_count = 0; void ISR(void) { if(timer_count != 0) { timer_count--;

}

} int main(void) {

// initialization code

SysTickIntRegister(&ISR);

... // other init timer_count = 2000; while(timer_count != 0) {

... code to run for 2 seconds

}

} concurrent code: logically runs at the same time. In this case, between any two machine instructions in main() an interrupt can occur and the upper code can execute.

Reasoning about concurrent code

volatile uint timer_count = 0; void ISR(void) { if(timer_count != 0) { timer_count--;

}

} int main(void) {

// initialization code

SysTickIntRegister(&ISR);

... // other init timer_count = 2000; while(timer_count != 0) {

... code to run for 2 seconds

}

} what if the interrupt occurs right here?

Reasoning about concurrent code

volatile uint timer_count = 0; void ISR(void) { if(timer_count != 0) { timer_count--;

}

} int main(void) {

// initialization code

SysTickIntRegister(&ISR);

... // other init timer_count = 2000; while(timer_count != 0) {

... code to run for 2 seconds

}

} what if the interrupt occurs right here?

Reasoning about concurrent code

volatile uint timer_count = 0; void ISR(void) { if(timer_count != 0) { timer_count--;

}

} int main(void) {

// initialization code

SysTickIntRegister(&ISR);

... // other init timer_count = 2000; while(timer_count != 0) {

... code to run for 2 seconds

}

} what if the interrupt occurs right here?

Reasoning about concurrent code

volatile uint timer_count = 0; void ISR(void) { if(timer_count != 0) { timer_count--;

}

} int main(void) {

// initialization code

SysTickIntRegister(&ISR);

... // other init timer_count = 2000; while(timer_count != 0) {

... code to run for 2 seconds

}

} what if the interrupt occurs twice during the execution of this code?

Reasoning about concurrent code

volatile uint timer_count = 0; void ISR(void) { if(timer_count != 0) { timer_count--;

}

} int main(void) {

// initialization code

SysTickIntRegister(&ISR);

... // other init timer_count = 2000; while(timer_count != 0) {

... code to run for 2 seconds

}

} can an interrupt occur here? If it can, what happens?

Reasoning about concurrent code

D

E

A

B

C volatile uint timerCount = 0; void ISR(void) {

… disable interrupts if(timerCount != 0) { timerCount--;

}

… enable interrupts

} int main(void) {

// initialization code

SysTickIntRegister(&ISR);

… // other init timerCount = 2000; while(timerCount != 0) {

}

… code to run for 2 seconds

… whatever comes next

}

A key question: Assuming interrupt occurs infinitely often, is position C always reached?

Reasoning about concurrent code

volatile uint timer_count = 0; void ISR(void) { if(timer_count != 0) { timer_count--;

}

} int main(void) {

// initialization code

SysTickIntRegister(&ISR);

... // other init timer_count = 2000; while(timer_count != 0) {

... code to run for 2 seconds

}

}

What is it about this code that makes it work?

A question:

• What ’ s the difference between

• Concurrency

• and

• Parallelism

Concurrency and Parallelism

• A program is said to be concurrent if different parts of the program conceptually execute simultaneously .

• A program is said to be parallel if different parts of the program physically execute simultaneously on distinct hardware.

A parallel program is concurrent, but a concurrent program need not be parallel.

Concurrency in Computing

 Interrupt Handling

– Reacting to external events (interrupts)

– Exception handling (software interrupts)

 Processes

– Creating the illusion of simultaneously running different programs (multitasking)

 Threads

– How is a thread different from a process?

 Multiple processors (multi-cores)

• . . .

Summary

•Interrupts introduce a great deal of nondeterminism into a computation. Very careful reasoning about the design is necessary.

INTERRUPTS

For next time

• Read Chapters 4 and 6

• Assignment 5 – Chapter, Problems 1, 2, 3, 5 and 8.

– Due 11/2

• Enjoy fall break next Friday!