CHAPTER 15I/O and Interrupts

15
Bräunl 2021 1 CHAPTER 15 I/O and Interrupts This chapter covers: Embedded operating systems Device Drivers Interrupt handling Timers / Watchdogs Real-Time features Input / Output Parallel and Serial Transmission Bräunl 2021 2 1. Device Drivers A number of I/O routines for a particular device are grouped together as a device driver In the RoBIOS embedded operating system we use a Hardware Description Table for this task Each device driver should comprise commands for Initialization of device Decommissioning of device Operation of device (e.g. writing to actuator, reading from sensor) Device-specific testing routines Bräunl 2021 3 Device Drivers Think about good software design before writing routines for a device driver Design the interface first Which routines are required? What parameters are required? Use existing standards, if any exist Bräunl 2021 4 Device Input A data transfer can be 1. CPU-initiated (polling) 2. Device-initiated (interrupt) device CPU

Transcript of CHAPTER 15I/O and Interrupts

Page 1: CHAPTER 15I/O and Interrupts

Bräunl 2021 1

CHAPTER 15 I/O and Interrupts

This chapter covers:

• Embedded operating systems• Device Drivers• Interrupt handling• Timers / Watchdogs• Real-Time features• Input / Output• Parallel and Serial Transmission

Bräunl 2021 2

1. Device Drivers

A number of I/O routines for a particular device are grouped together as a device driver

• In the RoBIOS embedded operating system we use a Hardware Description Table for this task

• Each device driver should comprise commands for– Initialization of device– Decommissioning of device– Operation of device

(e.g. writing to actuator, reading from sensor)– Device-specific testing routines

Bräunl 2021 3

Device Drivers

• Think about good software designbefore writing routines for a device driver

• Design the interface first– Which routines are required?– What parameters are required?

• Use existing standards, if any exist

Bräunl 2021 4

Device Input

A data transfer can be1. CPU-initiated (“polling”)2. Device-initiated (“interrupt”)

deviceCPU

Page 2: CHAPTER 15I/O and Interrupts

Bräunl 2021 5

2. Polling

devicedigital input line

CPU

Task: Count pulses,e.g. controller: buttons

robot: bumper switchcamera: frame start signal

Handle device without interrupt

“You need to be quick …”Bräunl 2021 6

Polling

Example Program: Count pulses (active low, use dig. input)This technique is called “polling”

int main(){ int counter = 0;

while(1){ if (!(DIGITALRead(1))

counter++;}

}

Is this correct?

Read input line 1Check for value 0

Bräunl 2021 7

Polling

Program is not correct!because it may count single pulse twice or more!• Depending on controller speed• Controller may also miss a short pulse if too slow,

but we assume for now this is not the case

We want to count the falling edges 1à0

Bräunl 2021 8

Polling

Second Try: Count pulses (active low, use dig. input)

int main(){ int counter = 0, previous = 0, now = 1;

while(1){ now = DIGITALRead(1); // read input line 1

if (!now && previous) counter++;previous = now;

}}

Is this correct?

if ( now ==0 &&previous ==1 )

Page 3: CHAPTER 15I/O and Interrupts

Bräunl 2021 9

Polling

Program should work now!

We want to count the falling edges 1à 0

n=1p=1

n=0p=1

n=1p=0

n=1p=1

n=0p=1

n=0p=0

n=1p=0

n=0p=1

n=1p=0

n=0p=1

n=1p=0

if ( now ==0 &&previous ==1 )

Bräunl 2021 10

3. Interrupts

Bräunl 2021 11

Interrupts

deviceinterrupt line

CPU

Handle device with interrupt

IRQ1’

• Controller has several interrupt lines with different priorities• Interrupts can come from internal sources (e.g. timer interrupt)

or external sources (e.g. sensor via interrupt request line)

Bräunl 2021 12

Interrupts

• Execution of one program (user) is temporarily suspended for another program with higher priority

(somewhat like a unscheduled subroutine call)• Sometimes also called exception• Interrupts can be raised either by software (special

CPU command) or by hardware (external signals

linked to CPU interrupt lines)

• Many embedded systems have interrupts that occur

at regular time intervals (e.g. every 0.01s)

Þ timer interrupts

Page 4: CHAPTER 15I/O and Interrupts

Bräunl 2021 13

Interrupts

Input/Output can be• CPU-initiation à Polling

– CPU initiates read/write with IN/OUT instruction– Timing relies only on CPU– May have to do this in loop in case device is not ready

à “busy-wait loop”à loss of CPU time à inefficient

• Device-initiated à Interrupts– Device signals CPU that it is ready via special interrupt line– CPU interrupts whatever it was doing and calls special “interrupt

service routine” (ISR)– CPU returns to previous task after finishing ISR (like subroutine)

Bräunl 2021 14

Interrupts• Often programmed in Assembly (time critical)• Special return operation required to clear interrupt register

(acknowledging that interrupt has been handled), e.g. Atmel: RETI (return from interrupt) instead of

RET (return from subroutine)• Often CPU registers need to be saved to / restored from

stack (time consuming)• Each interrupt (e.g. interrupt line) has to be associated with

the address of an interrupt service routine.This is done during system setup

Bräunl 2021 15

InterruptsExample Program: Count pulses (use interrupt)int main(){ ???

return 0;} How would you do this?

Unfortunately, this is where standard C/C++ stops –it does not have language constructs to deal with this.

Therefore Þ Non-standard C commands orback to Assembly!

Bräunl 2021 16

Interrupts

Example Program: Count pulses (use interrupt)

Step 1: Write routine that is called when an interrupt arrivesStep 2: Associate interrupt with this routine (initialization)Step 3: Enable interrupt

Page 5: CHAPTER 15I/O and Interrupts

Bräunl 2021 17

Interrupt Example• Read ATMega328P documentation!• Use interrupts to react to button press on ATMega line• Easier and more efficient than reading (polling)• Interrupts are machine-specific – even C programs with

interrupts will not work on other processor!• E.g.: Pin-change interrupt for ATMega.

When enabled, the status change (rising or falling edge) on the specified pin will raise an interrupt.

Bräunl 2021 18

Interrupt ExampleExample:Create an interrupt when input button is pressed• Pin change interrupts: Select pin on chip• 4 Steps required to enable interrupts:

1. Pin Change Mask2. Pin Change Interrupt Flag Register3. Pin Change Interrupt Control Register4. SEI (Global Set Interrupt Enable)

Bräunl 2021 19

Interrupt Example• We want to use PIN C4

as interrupt line• C4 = PCINT12

Bräunl 2021 20

Interrupt Example

Page 6: CHAPTER 15I/O and Interrupts

Bräunl 2021 21 Bräunl 2021 22

Interrupt Example

Bräunl 2021 23

Interrupt Example• Assembly Instructions SEI, CLI

for enabling/disabling interrupts via status register

Bräunl 2021 24ATM

ega3

28P

Inte

rrupt

Vect

ors

Page 7: CHAPTER 15I/O and Interrupts

Bräunl 2021 25

Interrupt Example ASM for Input C4.include "m328Pdef.inc"

JMP main ; 0: RESET Jump over vector tableJMP err ; 4: ext Int0JMP err ; 8: ext Int1JMP err ; 12: PCINT0 InterruptJMP intr ; 16: PCINT1 Interrupt

_______________________________________________________________

main: CLR R15...

intr: INC R15 ; count interruptRETI ; return from interrupt

err: JMP err ; error: endless loop

Bräunl 2021 26

Interrupt Example ASM for Input C4.include "m328Pdef.inc"

JMP main ; 0: RESET Jump over vector tableJMP err ; 4: ext Int0JMP err ; 8: ext Int1JMP err ; 12: PCINT0 InterruptJMP intr ; 16: PCINT1 Interrupt

_______________________________________________________________

main: LDI R16, 0x08 ; Init stack pointer to 0x08FFOUT SPH, R16LDI R16, 0xFFOUT SPL, R16

CLR R15 ; use R15 as counterLDI R16, 0x00OUT DDRC, R16 ; C all inputLDI R16, 0xFFOUT PORTC, R16 ; enable pull-up for all pinsOUT DDRB, R16 ; B all output

LDI R16, 0x10 ; PCMSK1 = 0x10LDI ZH, 0LDI ZL, PCMSK1 ; load PCMSK1 address in ZST Z, R16 ; write 0x10 to PCMSK1...

Bräunl 2021 27

Interrupt Example ASM for Input C4...LDI R16, 0x02OUT PCIFR, R16 ; clear any pending inter. bank 1

LDI ZL, PCICRST Z, R16 ; activate interrupts for bank 1

SEI ; global interrupt enable

loop: OUT PORTB, R15 ; output counter to led on B5JMP loop ; endless loop

________________________________________________________________

intr: INC R15 ; count interruptRETI ; return from interrupt

err: JMP err ; error: endless loop

Bräunl 2021 28

Interrupt Example• Enable C4/PCINT12 interrupt on PCMSK1 (pin change mask 1)

PCMSK1 = 0x10; // connection to C4

• Clear flags in PCIFR (external interrupt flag register)PCIFR = 0x02; // clear flag for PCMSK1

• Enable interrupt in PCICR (external interrupt mask register)PCICR = 0x02; //enable PCMSK1

• Interrupt service routines for pin changesISR(PCINT1_vect){ /* handle interrupts PCINT 15 ..8 */…

}

ISR(PCINT0_vect) // not used here{ /* handle interrupts PCINT 7 ..0 */…

}

Page 8: CHAPTER 15I/O and Interrupts

Bräunl 2021 29

Interrupt Example C for Input C4#include <avr/io.h>#include <avr/interrupt.h>

int count = 0; // init count

int main (void){ DDRC = 0x00; // all inputPORTC = 0xFF; // enable pull-up for all pinsDDRB = 0xFF; // all output, use LED at B5

PCMSK1 = 0x10; // interrupt line C4 (PCINT12)PCIFR = 0x02; // clear any pending interruptPCICR = 0x02; // enable interrupt for pin-change-1sei(); // global interrupt enable

while(1)PORTB = count; // endless loop – display count

}

ISR(PCINT1_vect){ count++; // count interrupts}

Bräunl 2021 30

4. Timer

• Most microcontrollers contain a number of timers that can be set by software.

• They can just increment register values or call interrupt service routines

• In the RoBIOS embedded operating system, we provide a 1ms (1kHz) system timer routine,to which subroutines can be attached / detached.

Bräunl 2021 31

TimerTimer OSAttachTimer(int scale, (*fct)(void)); // Add fct to 1000Hz/scale timerint OSDetachTimer(Timer handle) // Remove fct from timer

If “scale” is 1, then 1000Hz is being used.For “scale” > 1, 1000Hz/scale is used,e.g. scale=10 à 100 Hz timer

Bräunl 2021 32

Watchdog Timer

A watchdog is a specialized timer/counter• It is initialized to a certain value and

keeps counting down• If the watchdog counter reaches zero,

an interrupt is raised• A correctly running program will reset the

watchdog timer in regular intervals to its initial value, so no interrupt will occur

Page 9: CHAPTER 15I/O and Interrupts

Bräunl 2021 33

Watchdog Timerint count;

main(){ count=100; // resetOSAttachTimer(10, watchdog);…while(1){ count = 100; // reset/* main processing loop */…

}}

void watchdog() /* 100Hz */{ count--;if (count<0) error(“..”);

}

Bräunl 2021 34

Watchdog Timerint count;

main(){ count=100; // resetOSAttachTimer(10, watchdog);…while(1){ count = 100; // reset/* main processing loop */…

}}

void watchdog() /* 100Hz */{ count--;if (count<0) error(“..”);

}

reset

decrement

Bräunl 2021 35

Watchdog Timer

• A watchdog is a very common and very effective tool for fault detection

• Can be used to detect hardware errors and software errors

• Especially useful for if a program “hangs”• Interrupt or error routine called can reset system or

restart individual task

Bräunl 2021 36

5. Parallel Transmission

Parallel versus Serial TransmissionParallel• 8 bit concurrently ® parallel

• on µC: use digital I/O lines or add special interface chip

Serial• 8 bits consecutively ® serial

• on µC: use 2 digital I/O lines or built-in interface chip

Page 10: CHAPTER 15I/O and Interrupts

Bräunl 2021 37

Parallel Transmission

• Bi-directional send and receive over the same lines

• Half-duplex either send or receive,but not both at the same time

• Send 8 data bits concurrently® usually faster than serial transmission

• Requires additional control lines® use flat ribbon cable

• Can only be used over a limited distance~ 1-2 m

Bräunl 2021 38

Parallel Transmission

Data • Is not transmitted at a constant speed• Is transmitted with a handshake protocol using control lines• Speed depends both on computer system and external device

Strobe • Activated by computer® Tells device that data is ready

Busy • Activated by external device® Tells computer whether device is busy/ready

ComputerSystem Printer

Data[0..7]

strobe

busyGND

Minimal Configuration

Bräunl 2021 39

Parallel Transmission

D[7.0]invalid data valid invalid

Strobe

Busy

Timing Diagram

Handshake

t

each signal responsetakes at least 0.5µs

printer ready printer busy printer ready

invalid data ready invalid

40

Computer: Print Routine

wait for printer to finishprevious character

wait for printer to copycurrent character in itslocal memory

Bräunl 2021

Start (“strobe” high)

Read “busy” signal

“Busy”low?

Write data byte to parallel portSet “strobe” to low

Read “busy” signal

“Busy”high?

no

yes

no

yes

Set “strobe” to high

Page 11: CHAPTER 15I/O and Interrupts

Bräunl 2021 41

Printer: Print Routine

wait for characterto be sent from CPU

Start (“busy" low)

Read “strobe” Signal

“Strobe”low?

Read data byte from parallel portSet “busy” to high

no

yes

Set “busy” to low

Do actual printing of character

Bräunl 2021 42

HandshakesStart (“busy" low)

Read “strobe” Signal

“Strobe”low?

Read data byte from parallel portSet “busy” to high

no

yes

Set “busy” to low

Do actual printing of character

Start (“strobe” high)

Read “busy” signal

“Busy”low?

Write data byte to parallel portSet “strobe” to low

Read “busy” signal

“Busy”high?

no

yes

no

yes

Set “strobe” to high

Bräunl 2021 43

Parity for Parallel Transmission• Is a method of detecting errors in data transmission• Typically a single byte parity checksum is transmitted

after a block of bytes (e.g. several KB of data)• Checksum calculation is: (å transmitted bytes) MOD 256• Receiving side calculates checksum for transmitted

data bytes and compares with transmitted checksum• Parity generators and checkers can be implemented

in software or hardware

Bräunl 2021 44

Checksum ExampleTransmit 4 Bytes:0x120x770xA00x55

Transmit checksum:0x7E (full sum is: 0x17E)

Page 12: CHAPTER 15I/O and Interrupts

Bräunl 2021 45

Checksum ExampleTransmit 4 Bytes: Receive 4 Bytes:0x12 0x120x77 0x760xA0 0xA00x55 0x55

Re-calc checksum: 0x7D

Transmit checksum: Receive checksum:0x7E 0x7E

Compare: NOT equalè Transmission Error

Bräunl 2021 46

6. Serial Transmission• Bi-directional send and receive over different lines• Full duplex send and receive at the same time• Send single bit at a time

– usually slower than parallel transmission, but technology gets faster• Minimal configuration has only 3 wires (Transmit, Receive, Ground)

– Maximum cable length about 20 m (longer than parallel transmission)

– Optional: additional control lines• Handshake

– Software (special control characters XON, XOFF)– Hardware (requires 2 additional lines)– None (may not detect transmission errors)

• Can be used over telephone (2 wires)– then only in half duplex (send - listen - send - listen - …)

Bräunl 2021 47

Serial Transmission

Serial Connections

• RS232C standard (slow) serial connection

e.g. used on all PCs

® will be discussed here

• RS422 fast serial bus using differential data lines:

Tx+,Tx-, Rx+,Rx-

(e.g. original Macintosh)

• USB Universal Serial Bus (high speed serial connec.)

today’s standard for PCs and Macs

Bräunl 2021 48

RS232CMinimal Configuration

ComputerSystem B

ComputerSystem A

TxD TxD

RxD RxD

GND GND

TxD Transmit dataRxD Receive dataGNDRTS Request to sendCTS Clear to send

Data transmission over 2 lines, one for each direction

Hardware handshake (flow control)

Page 13: CHAPTER 15I/O and Interrupts

Bräunl 2021 49

RS232CConfiguration with Hardware Handshake

ComputerSystem B

ComputerSystem A

TxD TxD

RxD RxD

GND GND

RTS

CTS CTS

RTS

Bräunl 2021 50

RS232CConnectors

Sub D - 9 Pin

Sub D - 25 Pin

Pin AssignmentsSub D 9 Sub D 25

TxD 3 2RxD 2 3RTS 7 4CTS 8 5GND 5 7

Bräunl 2021 51

RS232C

Signals• Voltages: +12V (high), -12V (low)

• Not TTL compatible (transistor-transistor-logic: 5V, 0V)

– requires additional chip for voltage conversione.g. Maxim Max232

– or system needs power supply with 3 different voltages: +12,-12,+5

• Relatively simple for system with mains power supply

• Requires more conversion hardware for embedded system

• Idle state of line: “high”

Bräunl 2021 52

RS232C

Order of Transmissiona) 1 start bit (low)

b) 7 or 8 Bit, LSB first (least significant bit)basic ASCII code is only 7 bits, so this saves transmission time

c) 1 Parity bit (odd/even) or nonefor transmission error detection

d) 1 or 2 stop bits (high)

e) Line remains idle until next byte is sent

Page 14: CHAPTER 15I/O and Interrupts

Bräunl 2021 53

RS232C

Data Transmission Rate

• Measure in bits per second (bps)

• For binary signaling, bits-per-second (bps) equals the

Baud rate (bd), measured in symbols per second

• Typical Baud rates:

1’200, 2’400, 4’800, 9’600, 19’200, 38’400, 57’600, 115’200, …

­ ­ ­“typical” Fax AVR Butterfly EyeBot

• Note: 19.2 k Baud = 19.2 * 1000 Baud

(lower case k = 1000, capital K = 1024)

Bräunl 2021 54

Parity for Serial Transmission• A method of detecting errors in data transmission• Each data byte (8 bits) gets one additional bit appended• Algorithm for Odd Parity [Even Parity is analog.]

– Count the number of 1s in a byte– If this number is odd, then append ‘0’, else append ‘1’

• Examples:1001 0110 has 4´‘1’ (even number) ® 1001 0110 11001 1110 has 5´‘1’ (odd number) ® 1001 1110 0

• Parity generators and checkers can be implementedin software or hardware

Bräunl 2021 55

Parity

• The effect of odd parity is that the sequence of 9 bits

(8 data bits + 1 parity bit) has always an odd number of 1s• This property can be used to check whether a byte has

been transmitted correctly

• Examples:

1001 0110 1 ®transm. 1001 0110 1 has odd number of 1s è OK1001 0110 1 ®transm. 1001 0100 1 has even number of 1s è Error

• Only single bit errors can be detected

• The parity bit will be stripped after transmission

Bräunl 2021 56

ASCII Table

Page 15: CHAPTER 15I/O and Interrupts

Bräunl 2021 57

Example: RS232C Data Transfer• Settings: 9600 baud, 8 data bits, no parity,1 stop bit

• Transmit ASCII “y” = 0x79 = 0b 0111 1001 ßLSB• Character is sent bit-wise from right to left (imagine shift right)• Time for one bit at 9600 bps Þ 1 bit = 104µs

1 0 0 1 1 1 1 0Idle Start

0x79 in reverse

Stop Idle

LSB ­

+12V

–12V

time

Bräunl 2021 58

Example: RS232C Data Transfer

Timing at 9’600 bps

• Time to transmit single bit: 104µs

• Time to transmit single byte (e.g. character)

8 bits + 1 start bit +1 stop bit = 10 bits

® 10 * single bit transmission time » 1 ms

Bräunl 2021 59

Example: RS232C with ParityTransmit character sequence “OK” over serial port• Use 8 data bits, odd parity, 2 stop bits• “OK” = 4F 4BHex = 0100 11112 0100 10112

• Odd parity: 5 ´ “1” à append 0 4 ´ “1” à append 1

11 0 1111 0010 0 11 0 1101 0010 1 11 ...

idle start parity start parity

“O” = 4Freversed

“K” = 4Breversed

stop stop

1st character 2nd character