Wednesday, September 22, 2010

An important pointer on using mikroC with PIC18s

After half a day of trying to get it to work I nearly gave up. Was trying out C pointers using an old version of mikroC on a Microchip PIC18F2321. Here's the test program (to preclude clutter I've removed the initialization routines for OSCCON, PORTx, TRISx, and ADCON1 registers):

void OnLoad(unsigned char *salad)
{
  *salad = 0xFF;
}

void OffLoad(unsigned char *greens)
{
  *greens = 0;
}

void main()
{
  while(1)
  {
    OnLoad(&PORTC);    
    Delay_100ms();
    OffLoad(&PORTC);
    Delay_100ms();
  }
}  

The firware merely toggles PORTC on and off every tenth of a second. An LED is connected to one of the PORTC pins, so it should blink when the MCU is powered up. Well, it didn't work.

After a couple of hours of racking my brain and trying out variations on the program, I decided to test the code on a PIC 16F device. I inserted a PIC12F615 into the breadboard, plugged in an LED and resistor, and hooked up the PICKit 2. Opened a new project in mikroC and used the same program, changing PORTx to GPIO, and initializing the appropriate SFRs. Guess what? Worked the first time around. No problems. That told me there's nothing wrong with the program. Went back to the PIC18.

After several more hours of checking and hair-pulling, it occured to me that there might be something in the MCU configuration bits which hasn't been set properly. Referring to the datasheet, the only one that seemed relevant was the XINST (Extended Instruction Set enable) bit in configuration word CONFIG4L. Noting that according to the datashet it's off by default, I first enabled it. I compiled the firmware, uploaded to the MCU, and powered it up. Nothing. The program still wouldn't work. Went back to mikroC, unchecked the "XINST_ON_4L" box and checked "XINST_OFF_4L."

Hallelujah! The LED finally started blinking, and at the proper rate at that. Finally found the culprit! Just to make sure it was indeed the XINST bit, I enabled it again. Sure enough the program failed again. Disabling XINST once more and the firmware worked. As a final test, I unchecked both these boxes (it was in that condition before I fiddled around with the XINST) and uploaded the compiled code. It didn't work. Therefore, regardless of what Microchip says about the default condition of the configuration words, it is quite clear that they must be explicitly set in mikroC.

So there. A nasty little trap which MikroElektronika does not state in their manual. Beware.

No comments:

Post a Comment