2
\$\begingroup\$

I have a 12F683 micro and this is my first program using the new MPLAB with XC8 compiler.

I have configured Timer1 to trigger about every ms. For now I would need an LED to flash on and off but need to do this with an IF statement because later I will add other actions in there. Here is the interrupt code:

#define PWM GPIObits.GP5

void interrupt High_Priority_Interrupt(void) {
  if (CCP1IF) {
      if (PWM) {
          PWM = 0; //NEVER excuted
      }
      else {
          PWM = 1; //ALWAYS executed
      }
      CCP1IF = 0;
  }
}

For some reason the output is never set to 1. If I replace the whole code with PWM^=1; it works like a charm. But I need to do it with the if statement. What am I doing wrong?

\$\endgroup\$
4
  • \$\begingroup\$ How exactly is PWM declared? \$\endgroup\$
    – Dave Tweed
    Commented Jun 9, 2014 at 11:53
  • \$\begingroup\$ At this point, the most direct approach would be to look at the code that the compiler is generating for this function. \$\endgroup\$
    – Dave Tweed
    Commented Jun 9, 2014 at 12:19
  • \$\begingroup\$ You should at least show a minimally compilable example of the problem. Your PWM setup, timer setup, GPIO setup, and interrupt setup are ALL involved, not just the little snippet you show here. \$\endgroup\$ Commented Jun 9, 2014 at 14:45
  • \$\begingroup\$ I second what Dave suggests. Open the lst file and have a look. If PWM is never set to 1 then perhaps CCP1IF is never true. Also, since interrupts are non-deterministic, you need to (at least in my experience with AVR) declare any variable as volatile that is used in the ISR or the compiler will optimize it into read-only as it never changes in regular program flow and your interrupt routine is never called by software. \$\endgroup\$
    – sherrellbc
    Commented Jul 9, 2014 at 17:24

1 Answer 1

1
\$\begingroup\$

This is a problem with input/output registers on baseline and mid-range cores. Both input and output registers of ports are read from input buffer and if you configured pin as analog input or output, digital input is disconnected and you can't read output port register. In your case, pin is configured as output and every time you try to read it to check it's value, you get zero (from input buffer).

To solve this, either configure pin as input and add button to control input signal and toggle LED on another pin or change PWM to variable and it will work.

Also, in same document there's another issue regarding IO ports and read-modify-write instruction answered here

You can read more here (Page 2, READ-MODIFY-WRITE INSTRUCTIONS ON PORT REGISTERS)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.