Mittwoch, 30. November 2011

Idiots Guide to AVR programming I

Bildschirmfoto_2011-11-30_um_2

So you have your Arduino and are curious to get to know "real" AVR-C
programming using all the cool tool chains, but do not quite know
where to start?
Ok, start your Arduino IDE, load the simple Blink sketch into your IDE
and upload it to your board to verify that all your connections are
working. After the upload you can observe the sketch size: mine is
1018 byte.

Now, when you program the Atmel chips all the pin assignments will be
slightly different. They are organized in ports and on the Arduino
site there is a nice overview where you find which pin on the Arduino
on the actual chip:

Media_httparduinoccen_dhnrd

Looking for digital pin 13 (your blinking LED pin) gives us PB5. That
is Pin 5 on port B.
Now we change our sketch, and changes one line only: change
digitalWrite(13, HIGH);
to
PORTB |= _BV(PIN5);

Recompile, et voila: a blinking LED and a file size of 1012 bytes. 6
bytes were optimized! But what happened? PORTB is a register variable
which "contains" the on and off states of the pins which are
associated with this port. And we simply say that we want to set Pin5
to 1 leaving all other pins unchanged. To fully comprehend this, you
need to know about bit manipulation and boolean logic. Again there is
a good intro on the Arduino site:
http://www.arduino.cc/en/Reference/PortManipulation

Now it is time to change the other digitalWrite command, this time we
need to turn the LED off. We achieve this by rewriting the line with:

PORTB &= ~_BV(PIN5);

Recompile and sweet: because we got entirely rid of the digitalWrite
function, the size of the sketch was reduced to 830 bytes.

Now, we turn towards the setup routine. Here Pin 13 is declared as
output pin. Again there is a register for each port which controls
whether pins belong to this port are inputs or outputs. The register
is DDR (data direction) and we use the register DDRB for port B.
Let's replace the pinMode function by:

DDRB |= _BV(DD5);

And - whoopee: 658 bytes! We almost reduced the size of the sketch,
leaving us with much more space to do stuff.

Once again the complete source:
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.

This example code is in the public domain.
*/

void setup() {
// initialize the digital pin as an output.
// Pin 13 has an LED connected on most Arduino boards:
DDRB |= _BV(DD5);
}

void loop() {
PORTB |= _BV(PIN5); // set the LED on
delay(1000); // wait for a second
PORTB &= ~_BV(PIN5); // set the LED off
delay(1000); // wait for a second
}


Back to index: http://justjoheinz.posterous.com/idiots-guide-to-avr-programming-index

Keine Kommentare: