Actions

AVR Lesson: Output Pins I: Difference between revisions

From HacDC Wiki

Line 16: Line 16:


#include <avr/io.h> /* Defines pins, ports, etc */
#include <avr/io.h> /* Defines pins, ports, etc */
#define F_CPU 1000000UL   /* Sets up the chip speed for delay.h */
#define F_CPU 1000000UL   /* Sets up the chip speed for delay.h -- 1MHz for Tiny13*/
#include <util/delay.h> /* Functions to waste time */
#include <util/delay.h> /* Functions to waste time */



Revision as of 22:47, 28 May 2008

Goals

In this lesson, you'll program the micro-controller version of "hello world", letting you fire up your programmer, compiler, chip, LED, and test them all out. You'll learn how to setup and use pins for output, and along the way get some exposure to AVR-specific coding practice.


The Circuit

Possibly the simplest circuit you can imagine: plug an LED into pins PB4 and ground. PB4 is going to go the positive leg of the LED to source current across the LED and light it up.

If you want, you can include a current-limiting resistor inline with the LED. I've done it both ways -- the AVR will drive the LED at ~50mA, which will burn out the LED over the long run, but for this demo, it'll be fine.

The Code


/* Blinker Demo */

#include <avr/io.h>		/* Defines pins, ports, etc */
#define F_CPU 1000000UL	   /* Sets up the chip speed for delay.h -- 1MHz for Tiny13*/
#include <util/delay.h>		/* Functions to waste time */

#define LED PB4			/* Defines pin PB4 for the LED.  I
				 often include a bunch of the circuit
				 info in the code this way, which
				 makes porting the code to another
				 chip easier and reminds you of how to
				 hook it up. */

int main(void){

  DDRB = _BV(LED);		      /* Data Direction Register B:
				       writing a one to the bit
				       enables output.  More on the
				       _BV() macro in the next
				       lesson.*/
	
  while(1){			/* the main loop, from which we never return */

    PORTB = _BV(LED); 		/* Turn on the LED bit/pin in PORTB */
    _delay_ms(400);		/* wait */

    PORTB &= ~_BV(LED);		/*  Turn off the LED bit/pin in PORTB */
   _delay_ms(400);		/* wait */

  }

  return(0);			/* never reached */
}

Trouble?

Programmer woes:

Is the LED in the correct polarity? (Positive to pin PB4, negative to GND).



Back to AVR Tutorial