Sunday, April 3, 2011

Our First Program

Let's write a program to simply turn on LED's.
We will use the Programmer's Notepad of WinAVR. 
WinAVR can be downloaded from this link.
Once WinAVR is installed, open Programmer's Notepad and start typing. Save the file with a .c extension. example, led.c .
We will assume that we have 8 LED's, connected to the 8 pins of Port C.

Step 1: Declare the Ports to be used as output or input (as required).
           In this case the LED’s connected to Port  C have to be turned ON, i.e a current has to be supplied to the LED. Thus, Port C should be OUTPUT.
Thus, the Data Direction Register for Port C is 

thus, we can write
 DDRC=0b1111111;

This statement makes the PortC output port. Since, we need only PortC in this particular case, we are not going to specify for other Ports.

Step 2:  Turn ON the LED
Now, to turn on the LED's, we need to give a '1' to the Port.
thus,
PORTC=0b11111111;

Thus, the program can be written like this:

#include<avr/io.h> // standard library to be included when using WinAVR
void main()
{   
   DDRC=0b11111111;   // Declare PortC as output Port
   PORTC=0b11111111;
}

This program will turn on the LED's connected to PortC.

Here we have considered 8 LED's. If, let's say 3 LED's were connected to PC0, PC1, PC2, then only these 3 pins need to be written '1', the rest can be '0' or '1' (if they are not being used anywhere else)
thus,
DDRC=0b00000111;
PORTC=0b00000111;


Once you have installed WinAVR, in the libraries folder, there will be a folder 'util' which will contain a file 'delay.h'. This file contains pre-defined functions to generate delays of the order of milli-seconds and micro-seconds.


Let's modify the program by turning the LED's ON and OFF with a delay of 500 milli-seconds.


#include<avr/io.h>
#include<util/delay.h>  // include this header file to use the functions defined 
                                  // for generating a delay
void main()

  DDRC=0b11111111;    // Declare PortC as output Port
  PORTC=0b11111111;  // Give a '1' to all the pins of PortC thus turning ON the LED's
while(1)                      // this is an infinite loop.
 {  PORTC=0b11111111;  // Give a '1' to all the pins of PortC thus turning ON the LED's
    _delay_ms(500);       // hold the LED ON for 500 millisecond
    PORTC=0b00000000;   // Turn OFF all the LED's
    _delay_ms(500);        // hold the LED OFF for 500 millisecond
  }
}


The function _delay_ms(x) generates a delay of x milli-seconds.
The above program will blink the LED's.
We used an infinite loop in the above program because we wanted the LED's to continue blinking forever. Had we not written the part for blinking the LED's inside the infinite loop, the LED's would have blinked just once.




In the video above, only 4 LED are blinking. 


In the next post we will again play around with the LED's, generating some new patterns and probably some 'disco LED'  :D



No comments:

Post a Comment