EEVblog Electronics Community Forum

Electronics => Microcontrollers => Topic started by: arul on March 30, 2019, 02:13:28 pm

Title: Calculation mismatch in C
Post by: arul on March 30, 2019, 02:13:28 pm
Hi All,

I have trouble with calculation mismatch. The following is the  program .

////data type declaration//////
unsigned int edge1, edge2, edge3, ED21, ED31;
float freq1, freq2;
double prt, pulse, PRT,PULSE;

#define timer_freq 16000000

void main()
{
    if(edge2 > edge1)
    {
        ED21 = edge2 - edge1;
        freq1 = (float) timer_freq /  (float) ED21;         
        pulse = (double) (1000000 /  freq1) ;

    }

    if(edge3 > edge2)
    {
        ED31 = edge3 - edge1;
        freq2 = (float) timer_freq / (float) ED31; ////(float) (float)
        prt   = (double) (1000000 /   freq2) ;
    }

}


The output of the program:(using UART)
ED21:   +8002.00
freq1:   +1999.50
pulse:   +500.124
ED31:   +16005.0
freq2:   +999.687
prt:   +1000.31
(The above is correct calculation)


ED21:   +8002.00
freq1:   +1999.50
pulse:   +3595.56
ED31:   +16005.0
freq2:   +999.687
prt:   +1000.31
(The above is wrong calculation)


The above calculation values are changing depends on the value of ED21, ED31. But the value of ED21 & ED31 are same. But the calculation gave different values. Which one make different calculation , please let me know...

Advance in thanks...
Title: Re: Calculation mismatch in C
Post by: sokoloff on March 30, 2019, 03:12:04 pm
Is something somewhere else in the program setting the global variable pulse and then the if statement for edge2 > edge1 not firing on that time through the code? To check for this, search around in your code or make a new variable "double TOTALLY_NEW_VARIABLE_NO_ONE_IS_USING_THIS;" and use that in place of pulse.

Secondly, are you meaning to test edge3 > edge2 in the second if and then subtract edge3 - edge1? As the code is written, if edge1 and edge3 are equal and edge3 is greater than edge2, your code will do a divide by zero.

Third, I'd recommend that you cast to double before doing the MHz division rather than after. That's not going to fix your issue, but is good practice.
Code: [Select]
pulse = ((double) 1000000 / (double) freq1) ;

If you're still stuck, I'd recommend copy pasting the code into a program that we can all run (meaning that has variable assignments along the way and doesn't depend on guessing what else is in the program). In trying to write that, you'll often discover the issue on your own. (often called Rubber Duck Debugging (https://en.wikipedia.org/wiki/Rubber_duck_debugging))
Title: Re: Calculation mismatch in C
Post by: Nerull on March 30, 2019, 04:36:36 pm
The code you posted doesn't function, so clearly it is not all of the code in question.

Is any of this code interrupt driven?
Title: Re: Calculation mismatch in C
Post by: bson on March 30, 2019, 06:13:47 pm
Add edge1, edge2, edge3 to the output to make sure they're set correctly.