Hey guys,
I'm having some trouble with some math code used for my PIC16F684.
Don't worry about the A/D conversion, I just deleted the other code. The problem I'm having is that I don't believe the second if statement is working properly. I want to take the absolute value of "gain" but my compiler doesn't have the absolute function. Instead I just put "-gain" which compiles fine and I think works.Code:int16 PV, SP; int16 E0; uns8 gain; int16 output; uns16 temp; SP = 128; PV = ADRESH; // ADC value = ADRESH (8 MSbs) E0 = PV - SP; output = gain*E0; if(output > 0){ P1M1 = 0; temp = output; temp /= 4; // Shift bits 3 to 10 of temp twice to the right CCPR1L = temp; } if(output < 0){ P1M1 = 1; temp = -output; temp /= 4; // Shift bits 3 to 10 of temp twice to the right CCPR1L = temp; }
When output > 0, the PIC outputs a PWM square wave which shows up fine on the oscilloscope. It's when output should be < 0, the output on the oscilloscope is a very strange square wave, that looks noisy and has weird superimposing square waves. I think the problem is with the math though.
Can someone verify if the way I initialized the variables will properly store data? I get confused when I'm doing math with mixes of signed and unsigned numbers. Keep in mind CCPR1L and ADRESH can only store 8 bit numbers.
I'd appreciate the help a lot. Thanks!