How to blink LEDs with different frequency

cmicrochipmicrocontrollerpictimer

I have a pic32mx and three LEDs.
[datasheet pic32mx] (http://hades.mech.northwestern.edu/images/2/21/61132B_PIC32ReferenceManual.pdf)

I need a function that gets the number of LEDs and frequency, and then blinking the LED with that frequency.

For example I need to blink 1, 2, 4 and 8 times per second.
I have some code, but I don't know how to make it blink with the given frequency. Can somebody explain?

void main() {
T2CON = 0x0;                     // Stop and clean Control Register
T2CONSET = 0x0070;       // 16 bit timer, prescaler at 1:256,  internal clock source
PMR = 0x0;                        // Clean Timer Register
PR2 = 0xFFFF;                    //  Load value
IPC2SET = 0x0000000C;  // Set priority level=3
IPC2SET = 0x00000001;  //  Set subpriority level=1
IFS0CLR = 0x00000100;  // Clear the Timer2 interrupt status flag
IEC0SET = 0x00000100;  // Enable Timer2 interrupts
T2CONSET = 0x8000;      // START TIMER2
}

void __ISR(8,ipl3) TimerHandler {

//somecode

IFS0CLR = 0x00000100;
}

Best Answer

Lets say your led's connected to RD0 RD1 & RD2. First you need a exact 1sec delay. Following function will provide you 1sec delay

void Delayms( unsigned t)
{
  T1CON = 0x8000; 
  while (t--)
  { 
    TMR1 = 0;
    while (TMR1 < FPB/1000);
  }
} 

Now you said that blink led for 1,2,4 or 8 times per second.That means to blink led 1 times per second means half of the 1sec, led will be on and half of 1sec led will be off, which you can do it like this:

int main()
{
  TRISD = 0; //making all led's output
  while(1)
  {
    PORTD = 1; //led's will be on
    Delayms(500) //led's will be on for 500ms
    PORTD = 0;//led's will be off
    Delayms(500); //led's will be off for 500ms
  }
}

Now blinking led's 2 times per second means led will be on for 250ms then led off for 250ms and again the same thing. You can do it by replacing the delay by 250ms. So in this way you can blink led's for 4 or 8 times per second.