4 IOports v21
4 IOports v21
Sepehr Naimi
www.NicerLand.com
Topics
AVR pin out
The structure of I/O pins
I/O programming
Bit manipulating
2
I/O unit in AVR
3
ATmega328 pinout
+5 V
1. Vital Pins:
1. Power
VCC
Ground
2. Crystal
XTAL1
+5 V
XTAL2 +5 V
3. Reset
2. I/O pins
PORTB, PORTC, and
PORTD
3. Internal ADC pins
AREF, AVCC, ADCn
4
The structure of I/O pins
5
Example 1
Write a program that
makes all the pins of
PORTB one.
DDRB: 1 1 1 1 1 1 1 1
PORTB: 1 1 1 1 1 1 1 1
6
Example 2
The following code will toggle all 8 bits of Port B
forever with some time delay between “on” and
“off” states:
7
Example 3
A 7-segment is connected to PORTD. Display 1
on the 7-segment.
DDRD: 1 1 1 1 1 1 1 1
PORTD: 0 0 0 0 0 1 1 0
ATmega328 0
5 1
LDI R20,0x06 ;R20 = 00000110 (binary) 8 6
PORTD
OUT PORTD,R20 ;PORTD = R20 2
4
LDI R20,0xFF ;R20 = 11111111 (binary)
OUT DDRD,R20 ;DDRD = R20 3
L1: RJMP L1
8
Example 4
A 7-segment is connected to PORTD. Display 3
on the 7-segment.
DDRD: 1 1 1 1 1 1 1 1
PORTD: 0 1 0 0 1 1 1 1
ATmega328 0
5 1
LDI R20,0x4F ;R20 = 01001111 (binary) 8 6
PORTD
OUT PORTD,R20 ;PORTD = R20 2
4
LDI R20,0xFF ;R20 = 11111111 (binary)
OUT DDRD,R20 ;DDRD = R20 3
L1: RJMP L1
9
Example 5: Input
The following code gets the data present at the pins of port C and
sends it to port B indefinitely, after adding the value 5 to it:
10
Pull-up resistor
11
Example
12
I/O bit manipulation programming
SBI and CBI instructions
SBI (Set Bit in IO register)
SBI ioReg, bit ;ioReg.bit = 1
Examples:
SBI PORTD,0 ;PORTD.0 = 1
SBI DDRC,5 ;DDRC.5 = 1
14
Example
Write a program that toggles PORTB.4
continuously.
SBI DDRB,4
L1: SBI PORTB,4
CBI PORTB,4
RJMP L1
15
Example
An LED is connected to each pin of Port D. Write a
program to turn on each LED from pin D0 to pin D7. Call
a delay module before turning on the next LED.
LDI R20, 0xFF
OUT DDRD, R20 ;make PORTD an output port
SBI PORTD,0 ;set bit PD0
CALL DELAY ;delay before next one
SBI PORTD,1 ;turn on PD1
CALL DELAY ;delay before next one
SBI PORTD,2 ;turn on PD2
CALL DELAY
SBI PORTD,3
CALL DELAY
SBI PORTD,4
CALL DELAY
SBI PORTD,5
CALL DELAY
SBI PORTD,6
CALL DELAY
SBI PORTD,7
CALL DELAY
16
SBIC and SBIS
SBIC (Skip if Bit in IO register Cleared)
SBIC ioReg, bit ; if (ioReg.bit = 0) skip next instruction
Example:
SBIC PORTD,0 ;skip next instruction if PORTD.0=0
INC R20
LDI R19,0x23
17
Example
Write a program to perform the following:
(a) Keep monitoring the PB2 bit until it becomes HIGH;
(b) When PB2 becomes HIGH, write value $45 to Port C,
and also send a HIGH-to-LOW pulse to PD3.
18
Example
A switch is connected to pin
PB0 and an LED to pin PB5.
Write a program to get the
status of SW and send it to
the LED.
19
The structure of I/O pins
DDRx.n
OUTPUT
PORTx.n
PINx.n INPUT
20
Out 0
21
Out 1
22
The structure of I/O pins
23
Input (Tri-state vs. pull up)
24