Sunday, April 24, 2011

Playing with LED

 .

In this post we'll make a scrolling pattern on the LED's (watch the video).

Just like last time, we'll consider that we have 8 LED's connected to PortC.

Now, the LED have to be turned ON, only one at a time, and they should remain ON for some time (say, 500 milliseconds).

#include<avr/io.h>
#include<util/delay.h>   // header file for generating delay
void main()
{ DDRC=0b11111111;    // Since, PortC is output, thus, all 8 bits are declared 1
  PORTC=0x00;             // initially all LED will be off. 

/*
Note: If on your development board, the LED are connected in Active Low configuration, they will turn ON when a '0' is given. If the LED are active high, they will turn ON when '1' is given. If you are not sure whether your LED are active high or active low, just give 1 and see what happens.
Here, I am assuming that LED are active high.

*/

  while(1)   // infinite loop so that the process inside is executed all the time.
 {  
   PORTC=0b00000001;
   _delay_ms(500);
   PORTC=0b00000010;
   _delay_ms(500);
   PORTC=0b00000100;
   _delay_ms(500);

   PORTC=0b00001000;
   _delay_ms(500);

   PORTC=0b00010000;
   _delay_ms(500);

   PORTC=0b00100000;
   _delay_ms(500);
    PORTC=0b01000000;

   _delay_ms(500);
    PORTC=0b10000000;

   _delay_ms(500);
 }
}

In the above program, we make only one LED on at a time, give a delay, and then turn on the next LED and switch off the other LED by writing 1 to the LED which we want to turn ON and the rest are 0.

The above program, though simple, is cumbersome to write.
We'll write the above program in a different way utilizing the vast potential of C.

#include<avr/io.h>
#include<util/delay.h>
volatile unsigned char x=0;  
void main() 
{
DDRC=0b11111111;   // Declare entire PortC as output
PORTC=0b00000000;   // Make PortC initially 0.
while(1)
{ x=0;
  while(x<8)               // execute this part till x is less than 8
  { PORTC=(1<<x);    // shift 1 by 'x' spaces.
    _delay_ms(500);
x=x+1;           // increment x.
  }
}

We would like to point out one very important thing about Embedded C at this point. 
Notice the 'volatile unsigned char x=0' before the main() ?
In embedded C, all variables that are to be used should be defined and initialized before the main() starts.





No comments:

Post a Comment