CS计算机代考程序代写 DT131C Embedded Systems Programming

DT131C Embedded Systems Programming
Tutorial 5
Dawit Mengistu (dawit.mengistu@hkr.se)

ATMega 168 μC Pin Diagram
2

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
10

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.
11

Example 1
• Write a binary 0 to output pin 6, 1 to other pins of port D. DDRD = 0b1111 1111; //set data direction register on all pins
//or better DDRD = 0xFF; PORTD = 0b1011 1111; // write output
// or PORTD = ~(1 << PD6); • 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 12 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. 13 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<