Timers, interrupts, PWM, part 1 of 2 Part 1: Timers and Interrupts on the PIC32MZPart 2: Pulse Width Modulation (PWM) and servos on the PIC32MZ

Timers and Interrupts on the PIC32MZ

All 2 posts in Timers, interrupts, PWM
  1. Timers and Interrupts on the PIC32MZ
  2. Pulse Width Modulation (PWM) and servos on the PIC32MZ
On this page

Code for this post

Using timers on the PIC32MZ

Timers overview

Timers are one of the things that the PIC32MZ does really well. It has 9 independent 16-bit timers, some of which can be combined to make 32-bit timers. It also has an awesome Output Compare module, which I'll cover next time with Pulse Width Modulation (PWM). All the timers work as follows:

  • On every PBCLK3 clock cycle, the value of the timer counter (TMR) is increased.
  • This value is compared to the Period Register (PR) value.
  • If the value is bigger or equal to PR, an interrupt is generated and the value of the counter is reset.

From this it can be seen that the most important registers for us are the Timer Register (TMR) and Period Register (PR).

IMPORTANT: The timers on the PIC32MZ are all controlled by Peripheral Bus Clock 3 (PBCLK3), so whatever you set that to will directly affect all the timers.

TL;DR

16-bit? 32-bit? As you likely know, 16-bit unsigned variables can store a maximum value of 2^16 - 1, or 65535, and 32-bit unsigned variables can store 2^32 -1, or 4,294,967,295 (~4 billion). This can become very important when we are either wanting super precision or extremely low frequency timers, as I will show later.
For 32-bit timers, timers 2 and 3, timers 4 and 5, timers 6 and 7 and timers 8 and 9 can be combined to form the 32-bit timers.

Calculating the value to put into the Period Register (PR)

Say for example we want to generate a timer that runs at 10kHz. We calculate the period like this:
Period Register = Peripheral Bus Clock 3 Frequency / 10000.
In my examples, PBCLK3 runs at 100MHz, so this gives us: PR = 100,000,000 / 10,000 = 10,000.
10000 is much smaller than the maximum value of 65,535, so no problems there.
Now let's try that again but at 1kHz:
PR = 100,000,000 / 1,000 = 100,000.
Uh oh. 100,000 cannot fit into 65,535 so we're going to have the timer running at a frequency we don't expect. What can we do about this? Well, two things:

  • Change over to a 32-bit timer, which is overkill of the highest degree, OR
  • Use the timer's built-in pre-scaler

Using the pre-scaler

OK before I start this section, be careful which timer number you use. Timer 1 has some differences to Timers 2 to 9 and as such I recommend using Timers 2 to 9 unless you know what you're doing. In my example today I'll be using Timer 2. Anyway, the timer has a kind of built-in divider circuit called a pre-scaler. It works like this:

  • On every PBCLK3 clock cycle, the value of an internal counter is increased.
  • This value is compared to pre-scaler setting (TCKPS) in the Timer 2 Control Register (T2CON).
  • If the value is bigger or equal to TCKPS, then the internal counter TMR is incremented.

Examination of the TxCON register in the datasheet shows this:
PIC32MZ - Pre-scaler settings

So, bringing this back to my example of a 1kHz timer, I can now accomplish it as follows:

  • Set the pre-scaler to 8 (TCKPS = 011)
  • Calculate the period as follows: PR = 100,000,000 / 1,000 / 8 = 12500.

12500 fits neatly into a 16-bit register, so no problems there. Do be aware that some pre-scaler values will lead to fractional numbers, which will just be truncated and lead to inaccurate timing. For example, a pre-scaler value of 64 would lead to a required PR of 1562.5.

Setting up a timer

OK, phew. Theory out the way, let's see how to do this in code:

void init_timer2(int period)
{
    T2CON   = 0x0;      // Disable timer 2 when setting it up
    TMR2    = 0;        // Set timer 2 counter to 0

    /* Set up the period. Period = PBCLK3 frequency, which is SYS_FREQ / 2, divided by the frequency we want and then divided by 8 for our chosen pre-scaler. */
    PR2 = SYS_FREQ / 2 / period / 8;

    // Set up the pre-scaler
    T2CONbits.TCKPS = 0b011; // Pre-scale of 8

    // Turn on timer 2
    T2CONbits.TON   = 1;
}

Bam, that's it! It's incredibly simple to do. Of course, now the timer is running and that's great and all but we want to use the timer for something. For that, we need to discuss interrupts.

Interrupts on the PIC32MZ

The PIC32MZ is a fast processor but it is still a single core, single threaded processor. This is important because if we are running a while() loop and our timer keeps interrupting our code every 1/1000 times a second, the PIC32MZ will leave what we are doing in the while() loop, jump to the code for doing whatever we told it to do when the timer ticks, complete that, and then jump back to the while loop until it is interrupted again. These interruptions are called interrupts, funnily enough.

The PIC32MZ has a very deep interrupt system. In short, each interrupt can be assigned a priority from 1 to 7 and a further sub-priority of 0 to 3.
A higher interrupt priority gets handled first and a lower interrupt priority gets handled later. Further, a higher priority interrupt can actually interrupt a lower priority interrupt but the reverse is not true. Sub-priorities can be used when interrupts have the same priority, as a further way of sub-dividing which of these interrupts is more important.

First, before we begin, you should generally enable Multi Vectored interrupt mode. This will save you many headaches when working with interrupts and you're finding they don't work and you can't work out why. It basically tells the PIC32 to allow use of a different handler for each different type of interrupt (Timer 2, Timer 3, etc). Thankfully, this is very easy to do:

    INTCONbits.MVEC = 1;

The timer 2 interrupts have four important bits associated with them:

  • Timer 2 Interrupt Enable (T2IE)
  • Timer 2 Interrupt Flag (T2IF)
  • Timer 2 Interrupt Priority (T2IP)
  • Timer 2 Interrupt Sub-priority (T2IS)

Searching the infamous datasheet reveals that T2IE is in the IEC0 register, T2IF is in the IFS0 register and both T2IP and T2IS are in the IPC2 register. It is left as an exercise to the student to search the datasheet to find where the other timer interrupt bits are located :)

OK. let's re-visit that init_timer2() function from before, but this time let's enable the Timer 2 Interrupt with a priority of 3 and a sub-priority of 1.

void init_timer2(int frequency)
{
    T2CON   = 0x0;      // Disable timer 2 when setting it up
    TMR2    = 0;        // Set timer 2 counter to 0
    IEC0bits.T2IE = 1;  // Disable Timer 2 Interrupt

    // Set up the period. Period = PBCLK3 frequency, which is SYS_FREQ / 2, divided by the frequency we want and then divided by 8 for our chosen pre-scaler.
    PR2 = SYS_FREQ / 2 / frequency / 8;

    // Set up the pre-scaler
    T2CONbits.TCKPS = 0b011; // Pre-scale of 8

    IFS0bits.T2IF = 0;  // Clear interrupt flag for timer 2
    IPC2bits.T2IP = 3;  // Interrupt priority 3
    IPC2bits.T2IS = 1;  // Sub-priority 1
    IEC0bits.T2IE = 1;  // Enable Timer 2 Interrupt

    // Turn on timer 2
    T2CONbits.TON   = 1;
}

OK, that was a lot of explaining for very little code. There's one final step, writing the interrupt handler. Almost done, bear with me!

Writing an interrupt handler on the PIC32MZ

I want my timer interrupt handler to toggle pin RH0 every time it is called. Let's take a look at how I write this:

void __attribute__((vector(_TIMER_2_VECTOR), interrupt(ipl3soft), nomips16)) timer2_handler()
{
    IFS0bits.T2IF = 0;  // Clear interrupt flag for timer 2
    LATHINV = 1 << 0;   // Toggle pin RH0
}

OK, the code itself is very simple but hoo boy that declaration. Let's break it down:

  • __attribute__ tells the compiler we are going to give it specific instructions for how to handle this function.
  • The interrupt vector _TIMER_2_VECTOR is defined by the include file p32mz2048efh144.h. You can also use the IRQ number found in the datasheet directly, in this case 9.
  • The ipl3soft refers to Interrupt Priority Level 3 (yes, that's a lowercase L). If you want to know what the soft part means, refer to the <TL;DR> below.
  • nomips16 forces the compiler to generate code using the MIPS32 instruction set and not the MIPS16 instruction set. This is required for interrupts on the PIC32.
  • timer2_handler() is just what I named the function, you can name it whatever you want.

Inside the function itself, there are only two lines. The first line clears the interrupt flag for timer 2. If you do not clear this flag, the interrupt handler will immediately and repeatedly get called again until it is cleared. It is recommended that you clear this flag immediately, and that your code inside an interrupt handler does not take too long. Keep interrupt handler code short and simple, don't write files or anything inside an interrupt because by the time the file writing is done the PIC32MZ will have missed the timing of several interrupts and things will go pear-shaped. And that's it, interrupt handler done!

Let's take a look with an oscilloscope to see if this gives us what we want:

PIC32MZ - 1kHz timer scope verification

And there it is, just what we expect. The signal is high for 1ms, low for 1ms, high for 1ms, etc, which means it's changing at a rate of 1kHz. Unlike the FatFs disasters, it seems to have worked out this time! :)

TL;DR

There is a rather large problem with interrupts in general. The processor needs to temporarily pause what it was doing, jump to the interrupt handler and then go back to what it was doing. This means, of course, that it needs to first save what it was doing so it can go back to it later. In case of the PIC32MZ, this means it needs to save the contents of some important registers before it can actually call the interrupt handler. This delay is called interrupt latency. For almost all of the stuff I do, which is not time-critical, this delay doesn't make much difference but for time critical stuff it can be a huge problem. The PIC32MZ combats this by having a Shadow Register Set (SRS) that you can use to minimize this latency. Today's post is long enough, however, perhaps in the next post. Or you're welcome to Google it for yourself :)

To summarise:

  • Setting it to soft forces it to use software context switching, i.e. manually save all the registers. This is the slowest option.
  • Setting it to srs forces it to use the shadow register set, which is much faster. It will also crash your program if you haven't set it up.
  • Setting it to auto tells it to choose because software context switching and using the shadow register set. I've had issues with this when I hadn't set up the shadow register set so be warned!

Here's the code

Work it out: timer period

All the calculators

60 comments
  1. Nic

    Thanks for blog Aidan,

    I have the explorer16/32 development board with PIM pic32mz2048efh100. Wow, what a pain. But then I found you, makes me a believer again.

    I used your configuration settings with a little modifications. Because the explorer16/32 only has 8 MHz on board, had to change FPLLIDIV = DIV_1 & FPLLICLK = PLL_FRC to run your program. However, now the LED blinks at one second leading me to believe the Bus is running at 100MHz.

    Moving on, I used your timer / interrupt program, I compiled it and gave me this warning;
    Blink_LCD1.c:317:1: warning: IPLnSOFT context saving used on a selected '32MZ2048EFH100' device with 8 Shadow Register Sets, consider IPLnSRS
    [enabled by default]
    }
    ^
    Oh the LED did not energize / blink in the interrupt function just stayed off even if I turn it on. I also changed pins.

    I wonder if the warning has something to do with the LED not blinking. I looked in the datasheet from what I'm getting pic32mz family would have the same interrupt function;
    void __attribute__((vector( _TIMER_2_VECTOR), interrupt(ipl3soft),nomips16))

    If you have time, What do you think???

    pic32mz drives me crazy

    Nic

    1. Aidan Author

      Hi Nic,

      Thanks for stopping by. The PIC32MZ continues to drive me crazy :) It frustrates me because it has so much potential. Anyway, onto your problem.

      My code contains a bug in setting CPU speed, so it only sets it to 100MHz. In set_performance_mode() please change the line:
      PB7DIVbits.PBDIV = 1; // Peripheral Bus 7 Clock Divisor Control (PBCLK7 is SYSCLK divided by 1)

      to

      PB7DIVbits.PBDIV = 0; // Peripheral Bus 7 Clock Divisor Control (PBCLK7 is SYSCLK divided by 1)

      Sorry about the bug, it slipped in early and I didn't notice it. My newer posts have corrected this.

      As to that warning about IPLnSOFT, it's only warning you because it's not the most efficient way of doing interrupts. It does work fine but it wastes quite a few cycles saving registers before calling the interrupt routine. You can try using the Shadow Register Set (SRS) mode like this:

      void __attribute__((vector( _TIMER_2_VECTOR), interrupt(ipl3srs),nomips16))

      If you do this, please add the following line to main(), after set_performance_mode() is called:

      PRISS = 0x76543210;

      This tells the Shadow Register Sets to work with interrupt priorities 1 to 7. In my example the LED should just appear to stay on because it's running at 1kHz, Can you post your code so I can have a look?

      Good luck!

      1. Nic

        Quoting Disqus <notifications@disqus.net>:

      2. Nic

        Quoting Disqus <notifications@disqus.net>:

        1. Nic

          Just change the LED from RA1 TO RB1 still not blinking.

          1. Aidan Author

            Did you try adding the line of code I suggested?

            1. Nic

              Yes I changed POSCMOD = EC to OFF

            2. Nic

              Ok I added init_timer2 before the while loop. Now RA0 stopped blinking and no change in the interrupt RB1 still not blinking.

      3. Nic

        Hi Aidan
        Sure here the code. The LED still does not blink after changes.

        Header file

        // PIC32MZ_1.c - An introduction to PIC32MZ configuration
        // by Aidan Mocke 2018-04-03

        // PIC32MZ2048EFH144 Configuration Bit Settings

        // Modified
        // By Nick Jock 2018-12-30
        // PIC32MZ2048EFH100 Configuration Bit Settings
        // Explorer 1632 (DM240001-2)

        // DEVCFG3
        // USERID = No Setting
        #pragma config FMIIEN = ON // Ethernet RMII/MII Enable (MII Enabled)
        #pragma config FETHIO = ON // Ethernet I/O Pin Select (Default Ethernet I/O)
        #pragma config PGL1WAY = OFF // Permission Group Lock One Way Configuration (Allow multiple reconfigurations)
        #pragma config PMDL1WAY = OFF // Peripheral Module Disable Configuration (Allow multiple reconfigurations)
        #pragma config IOL1WAY = OFF // Peripheral Pin Select Configuration (Allow multiple reconfigurations)
        #pragma config FUSBIDIO = OFF // USB USBID Selection (Controlled by Port Function)

        // DEVCFG2
        #pragma config FPLLIDIV = DIV_1 // System PLL Input Divider (3x Divider)
        #pragma config FPLLRNG = RANGE_5_10_MHZ // System PLL Input Range (5-10 MHz Input)
        #pragma config FPLLICLK = PLL_FRC // System PLL Input Clock Selection (POSC is input to the System PLL)
        #pragma config FPLLMULT = MUL_50 // System PLL Multiplier (PLL Multiply by 50)
        #pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (2x Divider)
        #pragma config UPLLFSEL = FREQ_24MHZ // USB PLL Input Frequency Selection (USB PLL input is 24 MHz)

        // DEVCFG1
        #pragma config FNOSC = SPLL // Oscillator Selection Bits (System PLL)
        #pragma config DMTINTV = WIN_127_128 // DMT Count Window Interval (Window/Interval value is 127/128 counter value)
        #pragma config FSOSCEN = OFF // Secondary Oscillator Enable (Disable SOSC)
        #pragma config IESO = OFF // Internal/External Switch Over (Disabled)
        #pragma config POSCMOD = EC // Primary Oscillator Configuration (External clock mode)
        #pragma config OSCIOFNC = OFF // CLKO Output Signal Active on the OSCO Pin (Disabled)
        #pragma config FCKSM = CSECME // Clock Switching and Monitor Selection (Clock Switch Enabled, FSCM Enabled)
        #pragma config WDTPS = PS1048576 // Watchdog Timer Postscaler (1:1048576)
        #pragma config WDTSPGM = STOP // Watchdog Timer Stop During Flash Programming (WDT stops during Flash programming)
        #pragma config WINDIS = NORMAL // Watchdog Timer Window Mode (Watchdog Timer is in non-Window mode)
        #pragma config FWDTEN = OFF // Watchdog Timer Enable (WDT Disabled)
        #pragma config FWDTWINSZ = WINSZ_25 // Watchdog Timer Window Size (Window size is 25%)
        #pragma config DMTCNT = DMT31 // Deadman Timer Count Selection (2^31 (2147483648))
        #pragma config FDMTEN = OFF // Deadman Timer Enable (Deadman Timer is disabled)

        // DEVCFG0
        #pragma config DEBUG = OFF // Background Debugger Enable (Debugger is disabled)
        #pragma config JTAGEN = OFF // JTAG Enable (JTAG Disabled)
        #pragma config ICESEL = ICS_PGx1 // ICE/ICD Comm Channel Select (Communicate on PGEC1/PGED1)
        #pragma config TRCEN = OFF // Trace Enable (Trace features in the CPU are disabled)
        #pragma config BOOTISA = MIPS32 // Boot ISA Selection (Boot code and Exception code is MIPS32)
        #pragma config FECCCON = OFF_UNLOCKED // Dynamic Flash ECC Configuration (ECC and Dynamic ECC are disabled (ECCCON bits are writable))
        #pragma config FSLEEP = OFF // Flash Sleep Mode (Flash is powered down when the device is in Sleep mode)
        #pragma config DBGPER = PG_ALL // Debug Mode CPU Access Permission (Allow CPU access to all permission regions)
        #pragma config SMCLR = MCLR_NORM // Soft Master Clear Enable bit (MCLR pin generates a normal system Reset)
        #pragma config SOSCGAIN = GAIN_2X // Secondary Oscillator Gain Control bits (2x gain setting)
        #pragma config SOSCBOOST = ON // Secondary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
        #pragma config POSCGAIN = GAIN_2X // Primary Oscillator Gain Control bits (2x gain setting)
        #pragma config POSCBOOST = ON // Primary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
        #pragma config EJTAGBEN = NORMAL // EJTAG Boot (Normal EJTAG functionality)
        #pragma config CP = OFF // Code Protect (Protection Disabled)

        #define SYS_FREQ 200000000 // Running at 200MHz

        Source File

        #include <xc.h>
        #include <stdio.h>
        #include <stdlib.h>
        #include <stdbool.h>
        #include <proc p32mz2048efh100.h="">
        #include <sys attribs.h="">
        #include "32confi1632.h"
        #include "tux_display_header.h"

        void set_performance_mode()
        {
        unsigned int cp0;

        // Unlock Sequence
        asm volatile("di"); // Disable all interrupts
        INTCONbits.MVEC = 1; // Multi vectored interrupts

        SYSKEY = 0xAA996655;
        SYSKEY = 0x556699AA;

        // PB1DIV
        // Peripheral Bus 1 cannot be turned off, so there's no need to turn it on
        PB1DIVbits.PBDIV = 1; // Peripheral Bus 1 Clock Divisor Control (PBCLK1 is SYSCLK divided by 2)

        // PB2DIV
        PB2DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
        PB2DIVbits.PBDIV = 1; // Peripheral Bus 2 Clock Divisor Control (PBCLK2 is SYSCLK divided by 2)

        // PB3DIV
        PB3DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
        PB3DIVbits.PBDIV = 1; // Peripheral Bus 3 Clock Divisor Control (PBCLK3 is SYSCLK divided by 2)

        // PB4DIV
        PB4DIVbits.ON = 1; // Peripheral Bus 4 Output Clock Enable (Output clock is enabled)
        while (!PB4DIVbits.PBDIVRDY); // Wait until it is ready to write to
        PB4DIVbits.PBDIV = 0; // Peripheral Bus 4 Clock Divisor Control (PBCLK4 is SYSCLK divided by 1)

        // PB5DIV
        PB5DIVbits.ON = 1; // Peripheral Bus 5 Output Clock Enable (Output clock is enabled)
        PB5DIVbits.PBDIV = 1; // Peripheral Bus 5 Clock Divisor Control (PBCLK5 is SYSCLK divided by 2)

        // PB7DIV
        PB7DIVbits.ON = 1; // Peripheral Bus 7 Output Clock Enable (Output clock is enabled)
        PB7DIVbits.PBDIV = 0; // Peripheral Bus 7 Clock Divisor Control (PBCLK7 is SYSCLK divided by 1)

        // PB8DIV
        PB8DIVbits.ON = 1; // Peripheral Bus 8 Output Clock Enable (Output clock is enabled)
        PB8DIVbits.PBDIV = 1; // Peripheral Bus 8 Clock Divisor Control (PBCLK8 is SYSCLK divided by 2)

        // PRECON - Set up prefetch
        PRECONbits.PFMSECEN = 0; // Flash SEC Interrupt Enable (Do not generate an interrupt when the PFMSEC bit is set)
        PRECONbits.PREFEN = 0b11; // Predictive Prefetch Enable (Enable predictive prefetch for any address)
        PRECONbits.PFMWS = 0b010; // PFM Access Time Defined in Terms of SYSCLK Wait States (Two wait states)

        // Set up caching
        cp0 = _mfc0(16, 0);
        cp0 &= ~0x07;
        cp0 |= 0b011; // K0 = Cacheable, non-coherent, write-back, write allocate
        _mtc0(16, 0, cp0);

        // Lock Sequence
        SYSKEY = 0x33333333;
        asm volatile("ei"); // Enable all interrupts
        }

        void delay_us(unsigned int us)
        {
        // Convert microseconds us into how many clock ticks it will take
        us *= SYS_FREQ / 1000000 / 2; // Core Timer updates every 2 ticks

        _CP0_SET_COUNT(0); // Set Core Timer count to 0

        while (us > _CP0_GET_COUNT()); // Wait until Core Timer count reaches the number we calculated earlier
        }

        void delay_ms(int ms)
        {
        delay_us(ms * 1000);
        }

        void main()
        {
        //Set max performance mode
        set_performance_mode();

        INTCONbits.MVEC = 1;

        PRISS = 0x76543210;

        ANSELACLR = 0xFFFF; //Disable all analog ANx input pins
        ANSELBCLR = 0xFFFF; //Disable all analog ANx input pins
        ANSELCCLR = 0xFFFF; //Disable all analog ANx input pins
        ANSELDCLR = 0xFFFF; //Disable all analog ANx input pins
        ANSELECLR = 0xFFFF; //Disable all analog ANx input pins
        ANSELFCLR = 0xFFFF; //Disable all analog ANx input pins
        ANSELGCLR = 0xFFFF; //Disable all analog ANx input pins

        TRISACLR = (1 << 0); // Clear bit 0 of TRISA. which makes PORT A bit 0 an output
        TRISACLR = (1 << 1); // Clear bit 0 of TRISA. which makes PORT A bit 0 an output

        LATASET = 1 << 0;
        LATASET = 1 << 1;

        // Main loop
        while (1)
        {
        LATAINV = 1 << 0; // Toggle LAT 0 bit 0
        delay_ms(1000); // Delay 1 second

        //LATAINV = 1 << 1; // Toggle LAT 0 bit 0

        }
        }
        void init_timer2(int frequency)
        {
        //LATASET = 1 << 1;
        T2CON = 0x0; // Disable timer 2
        TMR2 = 0; // set timer 2 counter to 0
        IEC0bits.T2IE = 1; // disable timer interrupt

        // set up pre-scale

        T2CONbits.TCKPS = 0b011; //pre-scale of 8

        PR2 = SYS_FREQ / 2 / frequency / 8; // setup period 1000

        // T2CONbits.TCS = 0; // Internal NEW
        // T2CONbits.T32 = 0; // 16-bit timer NEW

        IFS0bits.T2IF = 0; // clear interrupt flag for timer2
        IPC2bits.T2IP = 3; // interrupt priority 3
        IPC2bits.T2IS = 1; // sub priority 1
        IEC0bits.T2IE = 1; // enable timer 2 interrupt

        // turn on timer 2 interrupt
        T2CONbits.ON = 1;

        //LATAINV = 1<<1; // toggle pin RA1
        }

        void __attribute__((interrupt(ipl3srs), vector( _TIMER_2_VECTOR), nomips16)) timer2_handler()
        {
        IFS0bits.T2IF = 0; // clear interrupt flag for timer2
        LATAINV = 1<<1; // toggle pin RA1

        }

        1. Aidan Author

          Hi Nic,

          I think I see the problem.

          You need to change this line:
          #pragma config POSCMOD = EC // Primary Oscillator Configuration (External clock mode)

          to
          #pragma config POSCMOD = OFF

          Otherwise it won't be able to generate a system clock and the code won't run. Give that a go and let me know if it works please.

          1. Nic

            Hey Aidan,

            That rascal still is not blinking.

            1. Aidan Author

              Hi Nic,

              Hmmm... is the LED on RA0 blinking? I see the one on RA1 will never blink because you never call init_timer2() in main(). Try adding init_timer2(); before the while loop starts.

              1. Nic

                I know right, Hmmm... Yes RA0 is blinking. I move it here how it looks.

                void init_timer2(int frequency)
                {
                //LATASET = 1 << 1;
                T2CON = 0x0; // Disable timer 2
                TMR2 = 0; // set timer 2 counter to 0
                IEC0bits.T2IE = 1; // disable timer interrupt

                // set up pre-scale

                T2CONbits.TCKPS = 0b011; //pre-scale of 8

                PR2 = SYS_FREQ / 2 / frequency / 8; // setup period 1000

                // T2CONbits.TCS = 0; // Internal NEW
                // T2CONbits.T32 = 0; // 16-bit timer NEW

                IFS0bits.T2IF = 0; // clear interrupt flag for timer2
                IPC2bits.T2IP = 3; // interrupt priority 3
                IPC2bits.T2IS = 1; // sub priority 1
                IEC0bits.T2IE = 1; // enable timer 2 interrupt

                // turn on timer 2 interrupt
                T2CONbits.ON = 1;

                //LATAINV = 1<<1; // toggle pin RA1
                }

                // Main loop
                while (1)
                {
                LATAINV = 1 << 0; // Toggle LAT 0 bit 0
                delay_ms(1000); // Delay 1 second

                //LATAINV = 1 << 1; // Toggle LAT 0 bit 0

                }
                }

                void __attribute__((vector( _TIMER_2_VECTOR), interrupt(ipl3srs), nomips16)) timer2_handler()
                {
                IFS0bits.T2IF = 0; // clear interrupt flag for timer2
                LATBINV = 1<<1; // toggle pin RA1

                }

                1. Aidan Author

                  Hi Nic,

                  At least RA0 is working. Sorry, I didn't mean add the whole init_timer2() function inside main, I just meant add 1 line where you call it. Move it back where it was and then try replacing your void main() function with this:

                  void main()
                  {
                  //Set max performance mode
                  set_performance_mode();

                  INTCONbits.MVEC = 1;

                  PRISS = 0x76543210;

                  ANSELACLR = 0xFFFF; //Disable all analog ANx input pins
                  ANSELBCLR = 0xFFFF; //Disable all analog ANx input pins
                  ANSELCCLR = 0xFFFF; //Disable all analog ANx input pins
                  ANSELDCLR = 0xFFFF; //Disable all analog ANx input pins
                  ANSELECLR = 0xFFFF; //Disable all analog ANx input pins
                  ANSELFCLR = 0xFFFF; //Disable all analog ANx input pins
                  ANSELGCLR = 0xFFFF; //Disable all analog ANx input pins

                  TRISACLR = (1 << 0); // Clear bit 0 of TRISA. which makes PORT A bit 0 an output
                  TRISACLR = (1 << 1); // Clear bit 0 of TRISA. which makes PORT A bit 0 an output

                  LATASET = 1 << 0;
                  LATASET = 1 << 1;

                  init_timer2();

                  // Main loop
                  while (1)
                  {
                  LATAINV = 1 << 0; // Toggle LAT 0 bit 0
                  delay_ms(1000); // Delay 1 second

                  //LATAINV = 1 << 1; // Toggle LAT 0 bit 0

                  }

                  1. Nic

                    Aidan thanks for the help, Where are you located in the world if you not mine me asking. I'm in Michigan, nice day here.
                    When I add just that line, it will not compile.

                    nbproject/Makefile-default.mk:117: recipe for target 'build/default/production/Blink_LCD1.o' failed
                    make[2]: Leaving directory 'C:/Users/nicol/MPLABXProjects/32LED.X'
                    nbproject/Makefile-default.mk:90: recipe for target '.build-conf' failed
                    make[1]: Leaving directory 'C:/Users/nicol/MPLABXProjects/32LED.X'
                    nbproject/Makefile-impl.mk:39: recipe for target '.build-impl' failed
                    Blink_LCD1.c: In function 'main':
                    Blink_LCD1.c:124:6: warning: conflicting types for 'init_timer2' [enabled by default]
                    void init_timer2(int frequency)
                    ^
                    Blink_LCD1.c:124:6: error: static declaration of 'init_timer2' follows non-static declaration
                    Blink_LCD1.c:113:5: note: previous implicit declaration of 'init_timer2' was here
                    init_timer2();

                    1. Aidan Author

                      Hi Nic,

                      Yeah we have a big time difference then, I'm in South Korea. Freezing cold here.

                      You need to move the entire init_timer2() function to above main(). I will try get your code working on my board later today and post some code for you.

                      1. Nic

                        I moved init_timer2() above main(). However, there is no change. I reading

                        void __attribute__((interrupt(ipl3soft), vector( _TIMER_2_VECTOR), nomips16)) timer2_handler()

                        because of the warning (ipl3soft). but that LED will come on,

                        1. Aidan Author

                          OK, now that I'm sitting at my computer the problem is easy to see!

                          When you call init_timer2(1000) it tells the timer2 to tick once every 1/1000th of a second, so the speed is 1000Hz. The LED *is* blinking, it's just turning on and off so fast that you can't see it.

                          I've changed your code a bit so that RA0 and RA1 now blink once a second but not together, you can find it here

                          Took me way too long to realise that :)

                          1. Nic

                            Thank you so much Aidan, it's work. The counter worked well. My skill with programming need more experience. Have you been writing code for a long time?

                            1. Aidan Author

                              I'm glad to hear that it works Nic. Don't worry about it, just keep programming and you'll improve. It's been my hobby for about 25 years and I'm still making lots and lots of mistakes.

                              1. Nic

                                More great news! My ADC program compiles, I will work on the input/output electronics today. I like the size of the LCD touch screen in your example.

                                I LIKE YOUR PRAGRAMMING board also, are you going to make that board available? It seem to me the board along with the sample programming would a great help to programmer hobbyist.

                                Does your LCD program have any new updates?

                                1. Aidan Author

                                  Hi Nic,

                                  Excellent! Now good luck with the hardware :)

                                  I will have a post on my board when it's finished, sometime in the next few weeks I'll be uploading the files too. The board isn't perfect but I've tried to cram as much as I could onto it. I hope it'll be useful to those who are using the code on this site.

  2. Nic

    Hi Aidan,
    The site reads I have a 1 response However I can not find it.

    1. Aidan Author

      You can try clicking on the speech bubble with the 1 in it, it should take you to your disqus profile where you can see your replies.

      1. Nic

        Hey, I posted the program but it had to post in two part I will try again. Your write ups on DMA are very informative. Here's the code on ADC. The pragma have be changed to run my explorer1632.

        // *********************************************************************************************
        // PIC32MZ Family 12.5msps Interleaved ADC sample code example
        //
        // SUMMARY:
        // TARGET CPU: PIC32MZxxEFxx >= 100 pin
        // OSC INPUT TYPE = 24 MHz Clock oscillator (EC Mode)
        // SYSCLK=200 MHz
        // PBCLK = 100 MHz
        // ADC TAD = SYSCLK / 4 = 50 MHz = 20ns
        // ADC SAMC=3 TAD
        // Interleaved ADC SAMPLE RATE = 12.5msps(max)
        // INTERLEAVED ADCS
        // ADC 0: 12bit mode, ADCTRG1<trgsrc0> Output Compare 1
        // ADC 1: 12bit mode, ADCTRG1<trgsrc1> Output Compare 3
        // ADC 2: 12bit mode, ADCTRG1<trgsrc2> Output Compare 5
        // ADC 3: 12bit mode, ADCTRG1<trgsrc3> Timer3
        //
        // interleaved ADC0/1/2/3 with AN0/AN1/AN2/AN3 inputs respectively
        // (12.5 msps combined throughput rate)
        //
        // USER NOTE:
        // Although the number of interleaved ADC's the user wishes to use is selectable, it is required
        // "FOR THIS CODE ONLY" that those ADCx modules be sequential starting from AN0 to the last sequential
        // ANx to be used for interleaving. In different code than below, any combination of interleaved ADC are allowed
        //
        // NOTE: (FYI only)
        // A user could configure the PIC32MZ to have multiple sets of
        // interleaved ADC's to measure multiple different analog input streams like:
        // ----------------------------- EXAMPLE 1 CONFIGURATION -----------------------------
        // 1) AN0-AN1 pair with triggers OC5 and TMR3 @ 6.25msps(max)
        // 2) AN2-AN3 pair with triggers OC1 and TMR5 @ 6.25msps(max)
        // ----------------------------- EXAMPLE 2 CONFIGURATION -----------------------------
        // 3) ADC0-ADC2 (3) ADCs with triggers OC1, OC3 and TMR5 @ 8.333333 msps(max) combined
        // 4) ADC3-ADC4 (2) ADCs with triggers OC5 and TMR3 @ 6.25msps(max)
        // ----------------------------- EXAMPLE 3 CONFIGURATION -----------------------------
        // 5) ADC0-ADC3 (4) ADCs with triggers OC1, OC3, OC5 and TMR3 @ 12.5msps(max) combined
        // *********************************************************************************************
        //
        // *********************************************************************************************
        // USER NOTE:
        // Although the number of interleaved ADC's the user wishes to use is selectable in this code
        // example, it is required "FOR THIS CODE ONLY" that those ADCx modules be sequential starting
        // from AN0 to the last sequential ANx to be used for interleaving.
        // In a user’s own original code however they can define any combination
        // of ADC's they prefer.
        //
        // ****************************************************************************
        // F I L E I N C L U D E S
        // ****************************************************************************
        #include <xc.h>
        #include <stdint.h>
        #include <stdbool.h>
        #include <sys attribs.h="">

        // ****************************************************************************
        // C O N F I G U R A T I O N W O R D S
        // ****************************************************************************
        //
        //----------------------------------------------------------
        // DEVCFG0
        //----------------------------------------------------------
        #pragma config DEBUG = OFF
        #pragma config JTAGEN = OFF
        #pragma config ICESEL = ICS_PGx2
        #pragma config TRCEN = OFF
        #pragma config BOOTISA = MIPS32
        #pragma config FECCCON = OFF_UNLOCKED
        #pragma config FSLEEP = OFF
        #pragma config DBGPER = PG_ALL
        #pragma config SMCLR = MCLR_NORM
        #pragma config SOSCGAIN = GAIN_2X
        #pragma config SOSCBOOST = ON
        #pragma config POSCGAIN = GAIN_2X
        #pragma config POSCBOOST = ON
        #pragma config EJTAGBEN = NORMAL
        #pragma config CP = OFF

        //----------------------------------------------------------
        // DEVCFG1
        //----------------------------------------------------------
        #pragma config FNOSC = SPLL
        #pragma config DMTINTV = WIN_127_128
        #pragma config FSOSCEN = OFF
        #pragma config IESO = OFF
        #pragma config POSCMOD = EC //24 Mhz External clock osc
        #pragma config OSCIOFNC = OFF
        #pragma config FCKSM = CSECME
        #pragma config WDTPS = PS1048576
        #pragma config WDTSPGM = STOP
        #pragma config FWDTEN = OFF
        #pragma config WINDIS = NORMAL
        #pragma config FWDTWINSZ = WINSZ_25
        #pragma config DMTCNT = DMT31
        #pragma config FDMTEN = OFF

        //----------------------------------------------------------
        // DEVCFG2
        // EC Ext OSC in =24Mhz
        // SYSCLK=200Mhz, PBxCLK=100Mhz
        //----------------------------------------------------------
        #pragma config FPLLIDIV = DIV_3
        #pragma config FPLLRNG = RANGE_5_10_MHZ
        #pragma config FPLLICLK = PLL_POSC
        #pragma config FPLLMULT = MUL_50
        #pragma config FPLLODIV = DIV_2
        #pragma config UPLLFSEL = FREQ_24MHZ

        //----------------------------------------------------------
        // DEVCFG3
        //----------------------------------------------------------
        #pragma config USERID = 0x0ADC
        #pragma config FMIIEN = OFF
        #pragma config FETHIO = OFF
        #pragma config PGL1WAY = OFF
        #pragma config PMDL1WAY = OFF
        #pragma config IOL1WAY = OFF
        #pragma config FUSBIDIO = OFF

        //----------------------------------------------------------
        // BF1SEQ0
        //----------------------------------------------------------
        #pragma config TSEQ = 0x0000
        #pragma config CSEQ = 0xFFFF

  3. Nic

    I need to send in parts. It wouldn't send the complete program in one part. Part 2

    // *************************************************************************************************
    // U S E R D E F I N E S
    // Note: User must configure as required
    // *************************************************************************************************
    #define TAD_TRIGGER_SOURCE_SPACING 4 // TAD trigger spacing value from ADC Table 13 or 15 accordingly w/12bit & 4 interleaved ADCs
    #define INTERLEAVED_ADC_COUNT 4 // Number of interleaved ADC (Cannot be <2 or >4). Changing this value will
    // automatically scale the number of interleaved ADC and triggers utilized in this code.
    #define ADC_DMA_BUFF_SIZE 2048 //ADC DMA buffer size

    //
    // *************************************************************************************************
    // EQUATION #1: (Assumptions: INTERLEAVED_ADC_COUNT=4)
    // (Fastest Triggering possible)
    // TAD_TRIGGER_SOURCE_SPACING(min) =
    // = ((SAMC(min) + (((#bits Resolution+1) + ADJ) * TAD)) / INTERLEAVED_ADC_COUNT)
    // = (3+12+1) + ADJ) * TAD)) / 4 ADCs)
    // = (16 + ADJ) * TAD)) / 4 ADCs
    // = (16 + 0) * TAD)) / 4 ADCs
    // = 4.0 TAD (minimum trigger spacing possible)
    //
    // NOTE: "ADJ" term = A user selected whole number adjustment factor between 0-4
    // that must yield a Minimum TAD Trigger interval that equates to an exact
    // multiple of a ½ TAD. This represents the minimum TAD_TRIGGER_SOURCE_SPACING
    // and therefore the fastest throughput possible. Additional TAD_TRIGGER_SOURCE_SPACING
    // and hence ADC Throughput Rates are possible in ½ TAD trigger spacing increments.
    // (See examples 1-3 below)
    //
    // NOTE: Once the minimum, TAD trigger spacing possible is determined, the user can configure for any
    // additional sampling frequency required if needed in 0.5 TAD trigger spacing increments.
    //
    // Example 1: (INTERLEAVED_ADC_COUNT=4)
    // TAD_TRIGGER_SOURCE_SPACING(min) = 4
    // interleaved ADC Throughput rate = TAD clock freq / TAD_TRIGGER_SOURCE_SPACING
    // = 50Mhz / 4.0(min)
    // = 12.5msps
    //
    // Example 2: (INTERLEAVED_ADC_COUNT=4)
    // TAD_TRIGGER_SOURCE_SPACING = 4.5
    // interleaved ADC Throughput rate = TAD clock freq / TAD_TRIGGER_SOURCE_SPACING
    // = 50Mhz / 4.5
    // = 11.111111msps
    //
    // Example 3: (INTERLEAVED_ADC_COUNT=4)
    // TAD_TRIGGER_SOURCE_SPACING = 5.0
    // interleaved ADC Throughput rate = TAD clock freq / TAD_TRIGGER_SOURCE_SPACING
    // = 50Mhz / 5.0
    // = 10msps
    //
    // *************************************************************************************************
    //
    // *************************************************************************************************
    // P R O G R A M D E F I N E S
    // (User Do Not Change)
    // Note:
    // TAD_TRIGGER_SOURCE_SPACING is multiplied by (2) because
    // OCx and TMR3 trigger source time base is 2x faster than an ADC TAD clock.
    // 2 TMR3 clocks = 1 ADC TAD Clock
    // **************************************************************************************************
    // ------------------------------------------------------------------------------------------------------------------
    // NOTE: Remember that the peripheral trigger clock frequency is 2x TAD clock frequency.
    // This is why the 2x. The -1 is because the Si peripheral triggers are always
    // on (match+1), so to compensate for correct timing subtract 1.
    //

    #define ADC_TRIG (TAD_TRIGGER_SOURCE_SPACING * 2) //
    #define OC1_ADC_TRIG (ADC_TRIG - 1) //
    #define OC3_ADC_TRIG ((2 * ADC_TRIG) - 1) //
    #define OC5_ADC_TRIG ((3 * ADC_TRIG) - 1) //
    #define T3_ADC_TRIG ((INTERLEAVED_ADC_COUNT * ADC_TRIG) - 1) //

    #define ADC0_IRQ 59 //PIC32MZxxEFxx ADC0 Data_0 IRQ number
    #define ADC1_IRQ 60 //PIC32MZxxEFxx ADC1 Data_1 IRQ number
    #define ADC2_IRQ 61 //PIC32MZxxEFxx ADC2 Data_2 IRQ number
    #define ADC3_IRQ 62 //PIC32MZxxEFxx ADC3 Data_3 IRQ number

    #define VirtAddr_TO_PhysAddr(v) ((unsigned long)(v) & 0x1FFFFFFF)

    #if ((INTERLEAVED_ADC_COUNT < 2) | (INTERLEAVED_ADC_COUNT > 4))
    #error INTERLEAVED_ADC_COUNT error, it is either less than 2 or greater than 4
    #endif

  4. Nic

    Part 3
    // *************************************************************************************************
    // F U N C T I O N P R O T O T Y P E S
    // *************************************************************************************************
    void init_ADC(void);
    void init_DMA(void);
    void init_TMR3(void);
    // *************************************************************************************************
    // G L O B A L V A R I A B L E S
    // *************************************************************************************************
    uint32_t __attribute__((coherent)) adc_bufA[INTERLEAVED_ADC_COUNT * ADC_DMA_BUFF_SIZE];
    uint32_t __attribute__((coherent)) adc_bufB[INTERLEAVED_ADC_COUNT * ADC_DMA_BUFF_SIZE];
    uint32_t adc_buf_index = 0;
    bool adc_dma_buf_full_flg = 0;
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    // $ M A I N R O U T I N E $
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    int main(void)
    {
    // ******************************************************************************
    // CPU Performance Optimization:
    // ******************************************************************************
    register unsigned long tmp_cache; //KSEG0 cache enable
    asm("mfc0 %0,$16,0" : "=r"(tmp_cache));
    tmp_cache = (tmp_cache & ~7) | 3;
    asm("mtc0 %0,$16,0" :: "r" (tmp_cache));

    PRECONbits.PFMWS=2; //Flash wait states = 2 CPU clock cycles @ 200Mhz
    PRECONbits.PREFEN = 2; //Enable predictive prefetch for CPU instructions and CPU data
    PRISSbits.PRI7SS = 7; //DMA Interrupt with priority level of 7 uses Shadow Set 7
    PRISSbits.PRI6SS = 6; //Interrupt with priority level of 6 uses Shadow Set 6
    PRISSbits.PRI5SS = 5; //Interrupt with priority level of 5 uses Shadow Set 5
    PRISSbits.PRI4SS = 4; //Interrupt with priority level of 4 uses Shadow Set 4
    PRISSbits.PRI3SS = 3; //Interrupt with priority level of 3 uses Shadow Set 3
    PRISSbits.PRI2SS = 2; //Interrupt with priority level of 2 uses Shadow Set 2
    INTCONbits.MVEC = 1; //Enable multi-vector interrupts
    __builtin_mtc0(12,0,(__builtin_mfc0(12,0) | 0x0001)); // Global Interrupt Enable

    // ******************************************************************************
    // * Disable all ANx pins that are enabled by default on reset
    // ******************************************************************************
    ANSELACLR = 0xFFFF; //Disable all analog ANx input pins
    ANSELBCLR = 0xFFFF; //Disable all analog ANx input pins
    ANSELCCLR = 0xFFFF; //Disable all analog ANx input pins
    ANSELDCLR = 0xFFFF; //Disable all analog ANx input pins
    ANSELECLR = 0xFFFF; //Disable all analog ANx input pins
    ANSELFCLR = 0xFFFF; //Disable all analog ANx input pins
    ANSELGCLR = 0xFFFF; //Disable all analog ANx input pins
    ANSELHCLR = 0xFFFF; //Disable all analog ANx input pins
    ANSELJCLR = 0xFFFF; //Disable all analog ANx input pins
    // ******************************************************************************
    // Initialize and enable ADC(s) followed by ADC trigger sources 2nd
    // ******************************************************************************
    init_ADC(); //Initialize and enable interleaved ADCs first before PWM ADC triggers are enabled
    while(1)
    {
    if(adc_dma_buf_full_flg) //If current DMA buffer is full
    {
    adc_dma_buf_full_flg = 0; //Clr DMA buff full flag
    //***********************************************************************
    // In main(), "adc_buf_index" represents the current active buffer being
    // filled as the companion buffer is already full.
    //***********************************************************************
    if(adc_buf_index == 0) //if "adc_bufA" active then "adc_bufB" full
    {
    //-----------------------------------------------------------------------------------------------------------------------
    // User must process here previously filled ADC DMA Buffer B ptr starting at "adc_bufB"
    //-----------------------------------------------------------------------------------------------------------------------
    }
    else //if "adc_bufB" active then "adc_bufA" full
    {
    //-----------------------------------------------------------------------------------------------------------------------
    // User must process here previously filled ADC DMA Buffer A ptr starting at "adc_bufA"
    //-----------------------------------------------------------------------------------------------------------------------
    }
    }
    //*******************************************************
    //* USERS OTHER MAIN CODE GOES HERE
    //*******************************************************
    }
    }

  5. Nic

    Part 4

    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    // $ F U N C T I O N S U B - R O U T I N E S $
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

    // *********************************************************************************
    // * init_ADC(void)
    // * I N T E R L E A V E D A D C I N I T I L I Z A T I O N R O U T I N E
    // * Used analog inputs if:
    // * INTERLEAVED_ADC_COUNT = 2 (Analog inputs, AN0 and AN1 only)
    // * INTERLEAVED_ADC_COUNT = 3 (Analog inputs, AN0, AN1 and AN2 only)
    // * INTERLEAVED_ADC_COUNT = 4 (Analog inputs, AN0, AN1, AN2 and AN3 only)
    // *********************************************************************************
    // *********************************************************************************
    // These steps are already done in this code example, this is just a reminder
    // to the user for any new original code development.
    //
    // CAUTION:(Required)
    // 1) The user SHOULD always set the minimum sampling time of each Class_1 ADC
    // equal to 3TAD as defined by ADCxTIME<samc>.
    // 2) The user should insure that the selected trigger source time base clock rate is
    // exactly 2x faster than the ADC clock TAD rate. This will provide the highest
    // timing resolution along with the most sampling rate options as defined in
    // Table 13 or 15 accordingly in this app note.
    // 3) The user selected trigger sources have to be able to be mapped to a single
    // synchronized time base.
    // For example:
    // a) TMR3 & OCx (x=1,3,5 PIC32MZxxxx)
    // b) TMR3 & OCx (x=1-4 PIC32MKxxGPxx)
    // c) PTMRx & TRIGx ( x=1-12 PIC32MKxxMCxx PWM)
    // d) PTMRx & STRIGx ( x=1-12 PIC32MKxxMCxx PWM)
    // 4) In a same group of interleaved ADC’s a user “MUST NOT” use two separate timer trigger sources.
    // Example: ADC0, ADC1 and ADC2 are being used in an interleaved group.
    // Trigger sources can be any combination of valid ADC OCx edge triggered sources synchronized to a SINGLE TMRx.
    // It would not be allowed to use in the same group of interleaved ADCs OCx, TMR3 & TMR5 for example.
    // Separate TMRx in different interleaved ADC groups is OK.
    // 5 If using the DMA for the ADC the user “MUST” use SYSCLK as the ADC
    // source clock, (i.e. ADCCON3<adcsel>).
    // 6) User must configure ADC for 512 TAD warm-up time
    // (ADCANCONbits.WKUPCLKCNT = 0x9) "BEFORE" enabling ADC.
    // 7) Users SW must wait for ADC BANGAP and ADC warm-up time "AFTER"
    // enabling ADC and before activating the ADC trigger sources.
    // 8) ADC must always be initialized 1st “BEFORE” activating the ADC trigger sources
    //
    // NOTE: Failure to follow these recommendations will result in inaccurate ADC
    // data acquisition and poor performance.
    //******************************************************************************
    void init_ADC(void)
    {
    ADC0CFG = DEVADC0; //Load ADC0 Calibration values
    ADC1CFG = DEVADC1; //Load ADC1 Calibration values
    ADC2CFG = DEVADC2; //Load ADC2 Calibration values
    ADC3CFG = DEVADC3; //Load ADC3 Calibration values
    ADC4CFG = DEVADC4; //Load ADC4 Calibration values
    ADC7CFG = DEVADC7; //Load ADC7 Calibration values
    ADCANCONbits.WKUPCLKCNT = 0x9; // ADC Warm up delay = (512 * TADx)
    ADCCON1bits.AICPMPEN = 0; //Disable ADC charge pump
    CFGCONbits.IOANCPEN = 0; //Disable ADC I/O charge pump
    // ******************************************************************************
    // * If using the DMA the user MUST use SYSCLK as the ADC source clock
    // ******************************************************************************
    ADCCON1bits.FSSCLKEN = 1; //Fast synchronous SYSCLK to ADC control clock is enabled
    ADCCON3bits.ADCSEL = 1; // Select ADC input clock source = SYSCLK 200Mhz
    ADCCON3bits.CONCLKDIV = 1; // Analog-to-Digital Control Clock (TQ) Divider = SYSCLK/2
    // ******************************************************************************
    // * ADC0 Module setup:
    // * TAD = SYSCLK/4, 12bit, SAMC=3TAD, OC1 Trigger
    // ******************************************************************************
    ANSELBSET = 0x1; //Enable analog AN0 input
    ADC0TIMEbits.ADCDIV = 1; // ADCx Clock Divisor, Divide by 2, 50Mhz
    ADC0TIMEbits.SAMC = 1; // 3 TAD (Hardware enforced sample time)
    ADC0TIMEbits.SELRES = 3; // ADC0 12bit resolution mode
    ADCTRG1bits.TRGSRC0 = 8; // Set AN0 to trigger from OC1
    ADCANCONbits.ANEN0 = 1; // Enable ADC0 analog bias/logic
    ADCCON3bits.DIGEN0 = 1; // Enable ADC0 digital logic
    ADCGIRQEN1bits.AGIEN0 = 1; //Enb ADC0 AN0 interrupts for DMA
    // ******************************************************************************
    // * ADC1 Module setup:
    // * TAD = SYSCLK/4, 12bit, SAMC=3TAD
    // * if(INTERLEAVED_ADC_COUNT == 2) TMR3 trigger else OC3 Trigger
    // ******************************************************************************
    ANSELBSET = 0x2; //Enable analog AN1 input
    ADC1TIMEbits.ADCDIV = 1; // ADCx Clock Divisor, Divide by 2, 50Mhz
    ADC1TIMEbits.SAMC = 1; // 3 TAD
    ADC1TIMEbits.SELRES = 3; // ADC1 12bit resolution mode
    if(INTERLEAVED_ADC_COUNT == 2) ADCTRG1bits.TRGSRC1 = 6; // Set ADC1 to trigger from TMR3
    else ADCTRG1bits.TRGSRC1 = 9; // Set ADC1 to trigger from OC3
    ADCANCONbits.ANEN1 = 1; // Enable ADC1 analog bias/logic
    ADCCON3bits.DIGEN1 = 1; // Enable ADC1 digital logic
    ADCGIRQEN1bits.AGIEN1 = 1; //Enb ADC1 AN1 interrupts for DMA
    // ******************************************************************************
    // * ADC2 Module setup:
    // * TAD = SYSCLK/4, 12bit, SAMC=3TAD, OC5 Trigger
    // * if(INTERLEAVED_ADC_COUNT == 3) TMR3 trigger else OC5 Trigger
    // ******************************************************************************
    if(INTERLEAVED_ADC_COUNT > 2)
    {
    ANSELBSET = 0x4; //Enable analog AN2 input
    ADC2TIMEbits.ADCDIV = 1; // ADCx Clock Divisor, Divide by 2, 50Mhz
    ADC2TIMEbits.SAMC = 1; // 3 TAD
    ADC2TIMEbits.SELRES = 3; // ADC2 12bit resolution mode
    if(INTERLEAVED_ADC_COUNT == 3) ADCTRG1bits.TRGSRC2 = 6; // Set ADC2 to trigger from TMR3
    else ADCTRG1bits.TRGSRC2 = 10; // Set ADC2 to trigger from OC5
    ADCANCONbits.ANEN2 = 1; // Enable ADC2 analog bias/logic
    ADCCON3bits.DIGEN2 = 1; // Enable ADC2 digital logic
    ADCGIRQEN1bits.AGIEN2 = 1; //Enb ADC2 AN2 interrupts for DMA
    }
    // ******************************************************************************
    // * ADC3 Module setup:
    // * if(INTERLEAVED_ADC_COUNT == 4)
    // * TAD = SYSCLK/4, 12bit, SAMC=3TAD, TMR3 Trigger
    // ******************************************************************************
    if(INTERLEAVED_ADC_COUNT > 3)
    {
    ANSELBSET = 0x8; //Enable analog AN3 input
    ADC3TIMEbits.ADCDIV = 1; // ADCx Clock Divisor, Divide by 2, 50Mhz
    ADC3TIMEbits.SAMC = 1; // 3 TAD
    ADC3TIMEbits.SELRES = 3; // ADC3 12bit resolution mode
    ADCTRG1bits.TRGSRC3 = 6; // Set ADC3 to trigger from TMR3
    ADCANCONbits.ANEN3 = 1; // Enable ADC3 analog bias/logic
    ADCCON3bits.DIGEN3 = 1; // Enable ADC3 digital logic
    ADCGIRQEN1bits.AGIEN3 = 1; //Enb ADC3 AN3 interrupts for DMA
    }
    ADCCON1bits.ON = 1; // Turn the ADC on

  6. Nic

    Part 5
    // ******************************************************************************
    // * Waiting for ADC warm-up time and ADC bandgap reference to stabilize
    // ******************************************************************************
    while(!ADCCON2bits.BGVRRDY); // Wait until the reference voltage is ready
    while(!ADCANCONbits.WKRDY0); // Wait until ADC0 is ready
    while(!ADCANCONbits.WKRDY1); // Wait until ADC1 is ready
    if(INTERLEAVED_ADC_COUNT > 2) while(!ADCANCONbits.WKRDY2); // Wait until ADC2 is ready
    if(INTERLEAVED_ADC_COUNT > 3) while(!ADCANCONbits.WKRDY3); // Wait until ADC3 is ready
    ADCDATA0; // Read ADC data to make sure that data ready bits are clear.
    ADCDATA1; //
    ADCDATA2; //
    ADCDATA3; //

    init_DMA(); //Initialize DMA
    init_TMR3(); //Initialize and enable ADC interleaved triggers
    }

    // ***************************************************************
    // * D M A I N I T I A L I Z A T I O N R O U T I N E *
    // ***************************************************************
    void init_DMA(void)
    {
    // **********************************************************
    // * Set the DMA trigger source. Each interrupt on the indicated
    // * ADC_DATA_VECTOR begins a DMA transfer.
    // **********************************************************
    if(INTERLEAVED_ADC_COUNT == 2)DCH0ECONbits.CHSIRQ = ADC1_IRQ; //DMA_TRIGGER_ADC0_DATA0;
    if(INTERLEAVED_ADC_COUNT > 2)DCH0ECONbits.CHSIRQ = ADC2_IRQ; //DMA_TRIGGER_ADC2_DATA2;
    if(INTERLEAVED_ADC_COUNT > 3)DCH0ECONbits.CHSIRQ = ADC3_IRQ; //DMA_TRIGGER_ADC3_DATA3;
    // **********************************************************
    // * Enable DMA Channel Start IRQ.
    // **********************************************************
    DCH0ECONbits.SIRQEN = 1; //DMA Chan_0 Start IRQ Enable
    // **********************************************************
    // * Set DMA Source Starting Address
    // **********************************************************
    DCH0SSA = (uint32_t) VirtAddr_TO_PhysAddr((const void *)&ADCDATA0);
    // **********************************************************
    // * Set DMA Source Size in bytes
    // **********************************************************
    if(INTERLEAVED_ADC_COUNT == 2) DCH0SSIZ = 8; // ADC0 + ADC1, 4+4bytes = 8bytes
    if(INTERLEAVED_ADC_COUNT > 2) DCH0SSIZ = 12; //ADC0 + ADC1 + ADC2 = 12bytes
    if(INTERLEAVED_ADC_COUNT > 3) DCH0SSIZ = 16; //ADC0 + ADC1 + ADC2 + ADC3 = 16bytes
    // **********************************************************
    // * Set DMA Destination Starting Address
    // **********************************************************
    DCH0DSA = (uint32_t) VirtAddr_TO_PhysAddr((const void *)&adc_bufA[0]);
    // **********************************************************
    // * Set DMA Destination Size
    // **********************************************************
    DCH0DSIZ = (uint16_t) INTERLEAVED_ADC_COUNT*(ADC_DMA_BUFF_SIZE)*sizeof(adc_bufA[0]);
    // **********************************************************
    // * Set Cell Size
    // **********************************************************
    DCH0CSIZ = (uint16_t) sizeof(adc_bufA[0]);
    DCH0INTbits.CHDDIF = 0; //Clr Chan Dest Done Int Flg
    DCH0INTbits.CHDDIE = 1; //Enable DMA Destination Interrupt

    // **********************************************************
    // * Enable DMA channel 0
    // **********************************************************
    DCH0CONbits.CHEN = 1; //DMA Chan 0 enable
    // **********************************************************
    // * Enable DMA and DMA interrupts
    // **********************************************************
    IFS4bits.DMA0IF = 0; //Clr DMA Chan0 int flg
    IPC33bits.DMA0IP = 7; //Set DMA Chan0 int priority 7
    IPC33bits.DMA0IS = 3; //Set DMA Chan0 sub priority 3
    IEC4bits.DMA0IE = 1; //Enable DMA Chan0 interrupt

    DMACONbits.ON = 1; //Enb DMA
    }

  7. Nic

    Part 6 Complete program

    // ******************************************************************************
    // * Waiting for ADC warm-up time and ADC bandgap reference to stabilize
    // ******************************************************************************
    while(!ADCCON2bits.BGVRRDY); // Wait until the reference voltage is ready
    while(!ADCANCONbits.WKRDY0); // Wait until ADC0 is ready
    while(!ADCANCONbits.WKRDY1); // Wait until ADC1 is ready
    if(INTERLEAVED_ADC_COUNT > 2) while(!ADCANCONbits.WKRDY2); // Wait until ADC2 is ready
    if(INTERLEAVED_ADC_COUNT > 3) while(!ADCANCONbits.WKRDY3); // Wait until ADC3 is ready
    ADCDATA0; // Read ADC data to make sure that data ready bits are clear.
    ADCDATA1; //
    ADCDATA2; //
    ADCDATA3; //

    init_DMA(); //Initialize DMA
    init_TMR3(); //Initialize and enable ADC interleaved triggers
    }

    // ***************************************************************
    // * D M A I N I T I A L I Z A T I O N R O U T I N E *
    // ***************************************************************
    void init_DMA(void)
    {
    // **********************************************************
    // * Set the DMA trigger source. Each interrupt on the indicated
    // * ADC_DATA_VECTOR begins a DMA transfer.
    // **********************************************************
    if(INTERLEAVED_ADC_COUNT == 2)DCH0ECONbits.CHSIRQ = ADC1_IRQ; //DMA_TRIGGER_ADC0_DATA0;
    if(INTERLEAVED_ADC_COUNT > 2)DCH0ECONbits.CHSIRQ = ADC2_IRQ; //DMA_TRIGGER_ADC2_DATA2;
    if(INTERLEAVED_ADC_COUNT > 3)DCH0ECONbits.CHSIRQ = ADC3_IRQ; //DMA_TRIGGER_ADC3_DATA3;
    // **********************************************************
    // * Enable DMA Channel Start IRQ.
    // **********************************************************
    DCH0ECONbits.SIRQEN = 1; //DMA Chan_0 Start IRQ Enable
    // **********************************************************
    // * Set DMA Source Starting Address
    // **********************************************************
    DCH0SSA = (uint32_t) VirtAddr_TO_PhysAddr((const void *)&ADCDATA0);
    // **********************************************************
    // * Set DMA Source Size in bytes
    // **********************************************************
    if(INTERLEAVED_ADC_COUNT == 2) DCH0SSIZ = 8; // ADC0 + ADC1, 4+4bytes = 8bytes
    if(INTERLEAVED_ADC_COUNT > 2) DCH0SSIZ = 12; //ADC0 + ADC1 + ADC2 = 12bytes
    if(INTERLEAVED_ADC_COUNT > 3) DCH0SSIZ = 16; //ADC0 + ADC1 + ADC2 + ADC3 = 16bytes
    // **********************************************************
    // * Set DMA Destination Starting Address
    // **********************************************************
    DCH0DSA = (uint32_t) VirtAddr_TO_PhysAddr((const void *)&adc_bufA[0]);
    // **********************************************************
    // * Set DMA Destination Size
    // **********************************************************
    DCH0DSIZ = (uint16_t) INTERLEAVED_ADC_COUNT*(ADC_DMA_BUFF_SIZE)*sizeof(adc_bufA[0]);
    // **********************************************************
    // * Set Cell Size
    // **********************************************************
    DCH0CSIZ = (uint16_t) sizeof(adc_bufA[0]);
    DCH0INTbits.CHDDIF = 0; //Clr Chan Dest Done Int Flg
    DCH0INTbits.CHDDIE = 1; //Enable DMA Destination Interrupt

    // **********************************************************
    // * Enable DMA channel 0
    // **********************************************************
    DCH0CONbits.CHEN = 1; //DMA Chan 0 enable
    // **********************************************************
    // * Enable DMA and DMA interrupts
    // **********************************************************
    IFS4bits.DMA0IF = 0; //Clr DMA Chan0 int flg
    IPC33bits.DMA0IP = 7; //Set DMA Chan0 int priority 7
    IPC33bits.DMA0IS = 3; //Set DMA Chan0 sub priority 3
    IEC4bits.DMA0IE = 1; //Enable DMA Chan0 interrupt

    DMACONbits.ON = 1; //Enb DMA
    }

  8. Nic

    Ok let me know if you received 6 parts. Thanks Aidan!

    1. Aidan Author

      OK for some reason it took a while to all get here but I see it now. I'll have a look at that today and see if I can help you get it to compile.

      1. Nic

        Afternoon Aidan,
        The great thing is, the 6 part program does compile by it's self. However, when I add another program to the source file tree, of the project, it give me the errors I show you yesterday.

        This is my plan, buy your evaluation board, and use LCD you use (will the LCD come with the evaluate board?).

        However, I need to display Analog input on the screen (hint the ADC program). So I'm hopping you think this ADC program works well. Then I can have two source files. One LDC file an one ADC file on the project source file tree.

        1. Aidan Author

          Hi Nic,

          Looking in main(), it seems the program isn't actually doing anything with the data it retrieves. If you could send me the file via dropbox or something it'd be much easier. It seems to be missing big sections and some of it doesn't make sense.

          As for my evaluation board, I don't have a shop or anything so I don't sell stuff, this is just my blog I write in my free time. I think that unfortunately the PIC32MZ market might be too small to go through all that effort. I design my PIC32MZ development boards for myself in my free time. I will be writing a post on designing a PIC32MZ board fairly soon and I'll upload all my schematics and files at that time but as far as selling stuff I'm sorry to say I don't think I can help you. My day job keeps me really busy :) The best I can do is tell you where I bought my LCDs and components.

    2. Aidan Author

      Hi Nic,

      I put it all into mplabx but it seems to be a bit jumbled. Is there somewhere you can upload the file to (like dropbox or whatever) so I can download it? I'm missing the init_TMR3 function and some other stuff.

  9. Nic

    Hello Aidan,
    I opened my new dropbox. It shows anyone on notifications@disqus.net can view the file, Can you see it? PIC32MZ_12_5msps_App_Note_C…xample.txt

    1. Aidan Author

      Hi Nic, good job on that but I don't know your dropbox username or the URL :) Can you send me a link to the file or the dropbox?

      1. Nic

        https://www.dropbox.com/s/2...
        see if this link will work

        1. Aidan Author

          Yep, it works Nic, I have it now. What are you wanting to do exactly? It looks like it reads from the ADCs and alternatively fills two buffers. You can check the one buffer in main while it is working on the other one. Is that what you want?

          1. Nic

            Thanks Aidan,
            So exactly , I would like to read two inputs from a transducer using DMA. Display it on an LCD in PSI. However, I have not made it to the LCD yet. So instead of a LDC or transduce. I would like to read a pot, an at a give programmed voltage, turn on a LED.

            1. Aidan Author

              I read the program and it seems to make sense. What other files are you trying to add to the project?

              If the other files also have a bunch of "pragma config" lines with the same contents then you will get errors.

              Are you trying to add in something like another example program?

              1. Nic

                Morning Aidan,
                Great question! I put the "pragma config" in the projects Header Files ".h" and don't have any "pragma config" in the Source Files ".c" The ".c" would compile one ".c" at a time. However not two ".c" together.

                Also, the ".c" will not compile without an "# include"
                So, all my ".c" have "# include" Therefore each ".c" I have;

                #include <xc.h>
                #include <stdio.h>
                #include <stdlib.h>
                #include <stdbool.h>
                #include <proc p32mz2048efh100.h="">
                #include <sys attribs.h="">
                #include "32confi1632.h"
                #include "tux_display_header.h"

                I read some of MPLAB® X IDE USER’S GUIDE. I will try to finishing tonight. I haven't read anything yet about this problem. The File pane is an interesting place.

                So, I'm not crazy there can be more then one ".c" in the Source Files. In the Source Files I will need;
                LCD.c
                Airpressure.c It will have to read transducer voltage change to psi and display on the LCD

                1. Aidan Author

                  Hmmm I see. Yes there definitely can be more than one .C and one
                  H file :) Can you upload your H file (that you made to put pragmas into) to the dropbox and share a link? I suspect the problem may be there.

                  1. Nic

                    Aiden, I just sent it to you via dropbox

                    1. Aidan Author

                      Hi Nic, I still don't know your dropbox name, can you send a shortcut to the file like last time?

                      1. Nic

                        1. Aidan Author

                          Hi Nic,

                          Good news, I think we've found your problem!

                          In C header files, because they're included in lots of C files in the same project all the variables get redefined each time you include the .h file, leading to errors. To prevent this, you have to add some code to your .h file. Start the file with these two lines:

                          #ifndef NICS_CONFIG_H
                          #define NICS_CONFIG_H

                          (Put all your pragma config lines, defines and variables here)

                          #endif

                          For every .H file you make I recommend you start it like that, but don't call them all NICS_CONFIG_H give each one a different name. Remember: Start the .h file with the #ifndef and #define lines and then put in your code and the last line of the file must be #endif.

                          I hope this fixes your problem, let me know!

                          1. Nic

                            Hey Aidan,
                            This makes a great deal of sense. I'm working on It !!
                            Thank You.

                          2. Nic

                            Thanks Aidan,
                            Yes! That fixed the problem, both .c files are compiling.

  10. Aniket Mazumder

    Hi Aidan, I may be wrong, but I think there is a small bug in the code. The third line in the code which reads IEC0bits.T2IE = 1; // Disable Timer 2 Interrupt, should be IEC0bits.T2IE = 0; initially to disable the interrupt. I was using timer 6 and timer 7 to generate timed loops of certain frequencies, and this line was causing problems. I changed it and voila, it worked as desired.

    1. Aidan Author

      Hi Aniket,

      You're right, thanks for finding that :)

  11. Abhishek Kasaudhan

    Hi Aidan, hope u r good. i am writing this post just to tell u that i really enjoyed your all the posts related to pic32mz and it helped me alot digging through it.
    This is my earliest request to you that plzz keep adding posts especially adc of pic 32mz.
    Thanks in advance.

    1. Aidan Author

      Hi there Abhishek,

      Thanks for stopping by. I'm actually working on the ADC post right now, I hope to upload it this week.

  12. HENRY

    Hi
    The timer can be configured to operate at a frequency of 25.2 MHz ?

    1. Aidan Author

      Hi HENRY,

      It might be tough generating that frequency exactly. You may have better luck using the Reference Clock to generate that.

  13. Hamdane

    Hi Aidan

    Are you intending to tackle once the Input Capture aspects on the PIC32MZ? I am having trouble using this PIC32MZ feature, that's why I am asking this question.

    1. Aidan Author

      Hi Hamdane,

      I do plan to tackle it some time but not at the moment. Sorry :)

  14. Carlos789

    Hello :
    Very good the different examples and the description of the PIC32MZ peripherals, I am making my first steps with the PIC32 MHZ144 board and your contributions are invaluable,
    Greetings
    Carlos

    1. Aidan Author

      Thanks for stopping by Carlos

  15. Iarley Conceição dos Santos

    Hello. My name is Iarley. I'm a student of Control and Automation Engineering. I'm starting my studies with PIC, and your posts are helping me. Thank you.
    I'm having a hard time implementing an interrupt. Can you help me?
    Here's the code I'm using:

    // PIC32MZ2048EFM144 Configuration Bit Settings

    // 'C' source line config statements

    // DEVCFG3
    #pragma config USERID = 0xFFFF // Enter Hexadecimal value (Enter Hexadecimal value)
    #pragma config FMIIEN = ON // Ethernet RMII/MII Enable (MII Enabled)
    #pragma config FETHIO = ON // Ethernet I/O Pin Select (Default Ethernet I/O)
    #pragma config PGL1WAY = ON // Permission Group Lock One Way Configuration (Allow only one reconfiguration)
    #pragma config PMDL1WAY = ON // Peripheral Module Disable Configuration (Allow only one reconfiguration)
    #pragma config IOL1WAY = ON // Peripheral Pin Select Configuration (Allow only one reconfiguration)
    #pragma config FUSBIDIO = ON // USB USBID Selection (Controlled by the USB Module)

    // DEVCFG2
    #pragma config FPLLIDIV = DIV_2 // System PLL Input Divider (2x Divider)
    #pragma config FPLLRNG = RANGE_5_10_MHZ // System PLL Input Range (5-10 MHz Input)
    #pragma config FPLLICLK = PLL_POSC // System PLL Input Clock Selection (POSC is input to the System PLL)
    #pragma config FPLLMULT = MUL_60 // System PLL Multiplier (PLL Multiply by 60)
    #pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (2x Divider)
    #pragma config UPLLFSEL = FREQ_24MHZ // USB PLL Input Frequency Selection (USB PLL input is 24 MHz)

    // DEVCFG1
    #pragma config FNOSC = SPLL // Oscillator Selection Bits (System PLL)
    #pragma config DMTINTV = WIN_127_128 // DMT Count Window Interval (Window/Interval value is 127/128 counter value)
    #pragma config FSOSCEN = ON // Secondary Oscillator Enable (Enable SOSC)
    #pragma config IESO = ON // Internal/External Switch Over (Enabled)
    #pragma config POSCMOD = OFF//EC // Primary Oscillator Configuration (External clock mode)
    #pragma config OSCIOFNC = OFF // CLKO Output Signal Active on the OSCO Pin (Disabled)
    #pragma config FCKSM = CSECME // Clock Switching and Monitor Selection (Clock Switch Enabled, FSCM Enabled)
    #pragma config WDTPS = PS1048576 // Watchdog Timer Postscaler (1:1048576)
    #pragma config WDTSPGM = STOP // Watchdog Timer Stop During Flash Programming (WDT stops during Flash programming)
    #pragma config WINDIS = NORMAL // Watchdog Timer Window Mode (Watchdog Timer is in non-Window mode)
    #pragma config FWDTEN = OFF // Watchdog Timer Enable (WDT Disabled)
    #pragma config FWDTWINSZ = WINSZ_25 // Watchdog Timer Window Size (Window size is 25%)
    #pragma config DMTCNT = DMT31 // Deadman Timer Count Selection (2^31 (2147483648))
    #pragma config FDMTEN = OFF // Deadman Timer Enable (Deadman Timer is disabled)

    // DEVCFG0
    #pragma config DEBUG = OFF // Background Debugger Enable (Debugger is disabled)
    #pragma config JTAGEN = ON // JTAG Enable (JTAG Port Enabled)
    #pragma config ICESEL = ICS_PGx1 // ICE/ICD Comm Channel Select (Communicate on PGEC1/PGED1)
    #pragma config TRCEN = ON // Trace Enable (Trace features in the CPU are enabled)
    #pragma config BOOTISA = MIPS32 // Boot ISA Selection (Boot code and Exception code is MIPS32)
    #pragma config FECCCON = OFF_UNLOCKED // Dynamic Flash ECC Configuration (ECC and Dynamic ECC are disabled (ECCCON bits are writable))
    #pragma config FSLEEP = OFF // Flash Sleep Mode (Flash is powered down when the device is in Sleep mode)
    #pragma config DBGPER = PG_ALL // Debug Mode CPU Access Permission (Allow CPU access to all permission regions)
    #pragma config SMCLR = MCLR_NORM // Soft Master Clear Enable bit (MCLR pin generates a normal system Reset)
    #pragma config SOSCGAIN = GAIN_2X // Secondary Oscillator Gain Control bits (2x gain setting)
    #pragma config SOSCBOOST = ON // Secondary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
    #pragma config POSCGAIN = GAIN_2X // Primary Oscillator Gain Control bits (2x gain setting)
    #pragma config POSCBOOST = ON // Primary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
    #pragma config EJTAGBEN = NORMAL // EJTAG Boot (Normal EJTAG functionality)

    // DEVCP0
    #pragma config CP = OFF // Code Protect (Protection Disabled)

    // SEQ3
    #pragma config TSEQ = 0xFFFF // Boot Flash True Sequence Number (Enter Hexadecimal value)
    #pragma config CSEQ = 0xFFFF // Boot Flash Complement Sequence Number (Enter Hexadecimal value)

    // #pragma config statements should precede project file includes.
    // Use project enums instead of #define for ON and OFF.

    #include <xc.h>
    #include <sys/attribs.h>
    #include <p32xxxx.h>

    int cont = 0;

    void __attribute__((vector(_TIMER_2_VECTOR), interrupt(ipl3srs), nomips16)) timer2_handler()
    {
    IFS0bits.T2IF = 0; // Clear interrupt flag for timer 2
    cont+=1;
    if(cont > 1373){
    cont = 0;
    LATJbits.LATJ7 = 0;
    }
    //LATJbits.LATJ7 = 0;
    }

    int main(){

    INTCONbits.MVEC = 1;
    PRISS = 0x76543210;

    // Configurando a porta RJ7 como saída
    TRISJbits.TRISJ7 = 0;

    INTCONbits.MVEC = 1;

    LATJbits.LATJ7 = 1;

    // Configuração do Timer 2
    T2CON = 0x0; // Disable timer 2 when setting it up
    TMR2 = 0; // Set timer 2 counter to 0
    IEC0bits.T2IE = 0; // Disable Timer 2 Interrupt

    // Set up the period. Period = PBCLK3 frequency, which is SYS_FREQ / 2, divided by the frequency we want and then divided by 8 for our chosen pre-scaler.
    PR2 = 65535;

    // Set up the pre-scaler
    T2CONbits.TCKPS = 0; // Pre-scale

    IFS0bits.T2IF = 0; // Clear interrupt flag for timer 2
    IPC2bits.T2IP = 3; // Interrupt priority 3
    IPC2bits.T2IS = 1; // Sub-priority 1
    IEC0bits.T2IE = 1; // Enable Timer 2 Interrupt

    // Turn on timer 2
    T2CONbits.TON = 1;

    return 0;
    }

Comments are hosted by Disqus, which loads only when you ask for it.