DT131B Embedded Systems Programming
Tutorial Supplement
Dawit Mengistu (dawit.mengistu@hkr.se)
ATMega 168 μC Pin Diagram
4
Arduino Board Pin Diagram
AREF
GND
13
12
11
10
9
8
7
6
5
4
3
2
1
0
Arduino
PB5
PB4
PB3
PB2
PB1
PB0
PD7
PD6
PD5
PD4
PD3
PD2
PD1
PD0
Atmga168
SW1
RGB-G
RGB-B
RGB-R
LED6
LED5
LED4
LED3
LED2
LED1
SW2
Prototyp
21
22
19
18
17
16
15
14
13
12
11
6
5
4
3
2
Atmga168
0
1
2
3
4
5
Arduino
PC0
PC1
PC2
PC3
PC4
PC5
Atmga168
L
P
Prototyp
23
25
25
26
27
28
Atmga168
P= Potentio meter, L = LDR sensors
5
LED3 LED2 LED1
LED6 P LED7 LED5
SW1
SW2
LED4 L
R
Parallel (digital) I/O
• There are three 8-bit I/O ports: B (8bits), C (7bits), D (8bits)
• Port registers:
– Data Direction Register (DDRx) – Data Register (PORTx)
– Input pins address (PINx)
DDRx
Portx
PORTx PINx
6
Parallel I/O (cont’)
• The names of the registers (and several others) are defined in the header file named avr/io.h
e.g. PINB, PINB0, PINB1, … PINB7 for the input data register and individual pins.
• For input, the ports can be programmed to use internal pull up resistor.
The respective bit of PORTx should be set to 1.
7
Example 1
• Write a binary 0 to output pin 6, 1 to other pins of port D. DDRD = 0b1111 1111; //set data direction register PORTD = 0b1011 1111; // write output
• On port D, set the 4 left most bits as input, the 4 right most bits for output, and write 12 decimal on the output.
DDRD = 0b0000 1111; //set data direction register PORTD = 0b0000 1100; // write output
8
Reading Input from Digital IO pins
Pull-down resistor
Vin is the input we intend to read through a pin. When Vin is HIGH, a logic 1 can be read from the pin.
Pull-up resistor
When Vin is set to HIGH (logic 1) Vout will be LOW (logic 0), if/when the switch is closed (grounded).
Vin can be set to HIGH programmatically. This is a typical use case to detect button press, keyboard input, etc.
9
Example 2
• Read two push button inputs through the rightmost 2 pins of Port B and show which button is pressed by lighting LEDs connected to the left most pins of Port B.
– Pins 0 and 1 are connected to the push buttons.
– Pins 6 and 7 are connected to LEDs and show the status of pins 0 and 1
respectively.
– Pins 0 and 1 are initialized for input while pins 6 and 7 are initialized for output as follows.
• DDRB = 0b11000000; //bit 7 & 6 are output, 0 & 1 input
– Internal pull up resistors should be programmatically inserted at pins 0 and 1 as follows:
• PORTB = 0b00000011; // pin0 and 1 are set to logic 1 to pull up
– We shall then continuously monitor for the status of pins 0 and 1 as follows:
• while (PINB & (1<