Saturday, May 19, 2012

Working With GPIO

Now that we have our tools, we are now ready to start! For our first lesson we will learn how to turn an LED on and off. Writing and reading a port in SDCC can be directly done. So to write to a PORT is simply writing 1 to turn it on or 0 to turn it off.

To write to the whole 8 bits of the PORT, its simply "Px = value;" where x is the port number and value is an 8 bit data, and to write to a specific pin its "Px_y", where x is the port number and y is bit number.

   Examples:

     Write 0x05 to Port 1
  
                    P1 = 0x05;

     Make Port3.4 high

                     P3_4 = 1;


Now that we know the basic syntax, Lets keep going!

For the following examples, we will be using the following connections to the microcontroller.


Example 1:

   Turn on LED connected at Port 2-0.

  1. Open M-IDE and create a new file called led.c and save to your working folder.
  2. Copy and paste the following codes:
 #include <at89x52.h>

void main (void)
{

  P2 = 0; //initially turn off PORT2
 
         while(1)
         {
            P2_0 = 1;
         }
}
 3. Build the program and load the hex to the microcontroller to see the result.

 Example 2:

  1. Create a new file called blink.c and save to your working folder.
  2. Copy paste the following codes:

      To blink a LED we turn it on and off, but since the microcontroller is running fast that we cannot see, we will introduce a delay in between.We will introduce a software delay. This delay routine is just a counter that will waster CPU process before doing another instruction. Now lets make the LED connected to P2_0 blink.

#include <at89x52.h>

void delay (void)
{
    unsigned int i;                 //this for loop will just count up to 0xFFFF

     for(i=0; i<0xFFFF; i++)
     
}

void main (void)
{
    P2 = 0; //initially turn off all LEDs

    while(1)
       {
              P2_0 = 1;
              delay();
              P2_0 = 0;
              delay();
      }
}
 3. Build the program and load the hex to the microcontroller to see the result.


Led Blink Demo









No comments:

Post a Comment