Delay Loop LED Blinker

Stephen Friederichs April 2, 2013 Coded in C for the ATMega328P

This code implements a delay loop to blink an LED at 1Hz.  The code assumes a clock frequency of 8MHz.  The LED is located on Port D, pin 7.

/**@file led_blink.c
   @brief The most basic approach to blinking an LED on AVR microcontrollers - specifically the ATMega328P
   @author Stephen Friederichs
   @date 3/28/13
   @note This code assumes that the LED is active high (pin sources current)   
*/   

/**@def F_CPU
   @brief Clock frequency = 8MHZ - this is set by fuses and registers, not by this define
   @note Always define this before including delay.h!
*/
#define F_CPU 8000000
	
/**@include io.h
   @brief Include for AVR I/O register definitions
*/
#include <avr/io.h>

/**@include stdint.h
   @brief Include for standard integer definitions (ie, uint8_t, int32_t, etc)
*/
#include <stdint.h>

/**@include delay.h
   @brief Include for delay functions such as _delay_ms() and _delay_us()
*/
#include <util/delay.h>

/* Basic bit manipulation macros - everyone should use these.  Please, steal these! Don't not use them and
 don't rewrite them yourself!
*/
#define SET(x,y) x |= (1 << y)
#define CLEAR(x,y) x &= ~(1<< y)
#define READ(x,y) ((FALSE == ((x & (1<<y))>> y))?FALSE:TRUE)
#define TOGGLE(x,y) (x ^= (1<<y))

int main(void)
{
	/*Initialization Code*/
	
	/*	ATMega328 Datasheet Table 14-1 Pg 78
		Configure PD7 for use as Heartbeat LED
		Set as Output Low (initially)
	*/
	SET(DDRD,7);	//Direction: output
	CLEAR(PORTD,7);	//State: Lo

	/*	Flash the LED for a second to show that initialization has successfully 
		occurred
	*/
	SET(PORTD,7);
	_delay_ms(1000);
	CLEAR(PORTD,7);
	
	while(1)
	{
		/*Set PD7 low for 500ms*/
		CLEAR(PORTD,7);
		_delay_ms(500);
		
		/*Then set it high for 500ms*/
		SET(PORTD,7);
		_delay_ms(500);
		
		/*Before repeating the process forever...*/
	
	}

}

Comments:

There are no comments yet!


Sorry, you need javascript enabled to post any comments.