Search code examples
ctimerdelaypic

Using the Timer2 of a PIC32 to Set a Delay


I'm pretty much brand new to the PIC32 and its programming in C, so I'm a bit stumped on how to go about the following problem. I've been asked to toggle an LED of the PIC32 on and off, which I can do fine; however, I now wish to add a 0.25s delay between toggling. I've been told to assume that I'm making use of a 72MHz system clock and a 36MHz peripheral bus clock. I know now that Timer2 is a Type B Timer, and that I should configure it for 16 bit ungated operation. I figured I can first set the initial values of TMR2, PR2 and other bits in T2CON as needed before setting TON to start the time, ending it by clearing TON and resetting the initial values.

Well, if that above sounds right, how might I do this with C? What I can gather from the reference manual is that it might look something like the following:

T2CON = 0x0;           // Stop Timer and clear control register,
                       // set prescaler at 1:1, internal clock source
TMR2 = 0x0;            // Clear timer register
PR2 = 0xFFFF;          // Load period register
T2CONSET = 0x8000;     // Start Timer

Now, how might I set the prescale and what not so that I can achieve my 0.25s delay? I'm just not good at covering what I need to C, and I'm still not that great at performing this kind of thing in assembly to begin with... Any guidance is appreciated. Here's my code thus far:

#include <p32xxxx.h>

int main()
{
    while(1)
    {
        PORTDbits.RD0 = 1;    // Turns LED On?
        // Delay...?
        PORTDbits.RD0 = 0;    // Turns LED Off?
        // Delay...?
    }
    return 0;
}

Header File: p32mx360f512l.h, if that is of any use.


Solution

  • the name of the header file IS of use ... based on that filename i guess this is the chip you have to work with ... http://www.microchip.com/wwwproducts/Devices.aspx?dDocName=en532441

    on that page you can find some code samples in c, so that should cover questions like "how to work with this chip in c"

    so for your general approach:

    a loop is a nice idea, but since you are given a type b timer in ungated mode, i think that should be a hint to use interrupt handlers to do the work ... have a look at http://ww1.microchip.com/downloads/en/DeviceDoc/61105E.pdf (section 14.4) on how to set this up

    in the ISR compare the timer/counter value with a value you will have to calculate based on the clock freq and the prescaler setting, so you will know when the desired time has come to flip the bit

    after the bit is flipped, reset the timer for the next cycle