MCU Lecture 2
Digital I/O Port Operations in AVR
Pin Configuration
● Pins are
organized into
8-bit “Ports”
● PORTB 8 bit
“Ports”
● PORTC 7 bits /
Ports
● PORTD 8 bit
“Ports”
Register
● A processor register is a memory space within
the CPU itself so that they can be accessed
very frequently and fast.
● These registers are linked with the operation of
the MCU.
Port Operation Registers
● DDRx – Data Direction Register
● PORTx – Pin Output Register
● PINx – Pin Input Register
● where x = GPIO port name ( B, C or D)
DDRx - Data Direction Register
● The GPIO pins are the digital I/O pins i.e. they can act as both
input and output.
● Now, how do we know that the pin is an output pin or input?
● The DDRx (Data Direction Register) controls one pin with each
bit.
● 1 stands for output and 0 stands for input.
PORTx - Pin Output Register
● Also one pin per bit
● If configured as an output:
– 0 -> the pin is held at 0 V
– 1 -> the pin is held at +5 V
PINx - Pin Input Register
● One pin per bit
● Reading from the register:
– 0 -> the voltage of the pin is near 0 V
– 1 -> the voltage of the pin is near +5 V
● If nothing is connected to the pin, then the pin
will appear to be in a random state
Hello World
● It's customary to write hello world whenever we
are learning something new.
● In case of embedded system.. BLINK a Light
Emitting Diode (L.E.D.)...
The Circuit
Blink v. 1.00
#include <avr/io.h> // for register name
#include <util/delay.h> //for _delay_ms built-in
function
int main(void)
{
DDRB = 0b00100000; // Set PB5 as ouput
PORTB = 0x00; //clear PortB
while(1) //Run for-ever
{
PORTB = 0b00100000; // Turn on
_delay_ms(1000); //wait for 1 second
PORTB =0b00000000;// Turn off
_delay_ms(1000);//wait for 1 second
}
}
Blink v. 1.10
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
DDRB |= 1<<DDB5;//PB5 as output
PORTB = 0x00;
while(1)
{
PORTB|=1<<PORTB5; //turn on
_delay_ms(5000);
PORTB&=~(1<<PORTB5);//turn off
_delay_ms(5000);
}
}
//Good tutorial on bit shift operations
//
http://www.robotplatform.com/howto/blinker/blinker_8
.html
Blink v. 1.20
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
DDRB |= _BV(DDB5)//PB5 as output
PORTB = 0x00;
while(1)
{
PORTB|=_BV(PORTB5); //turn on
_delay_ms(5000);
PORTB&=~_BV(PORTB5);//turn off
_delay_ms(5000);
}
}
Blink in Arduino Processing
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;
// the setup routine runs once when you press reset:
void setup() {
pinMode(led, OUTPUT); // initialize the digital pin as an output.
}
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}