PIC18F4620 float to int convertion

Thread Starter


Joined Nov 3, 2007

I have a problem with my code. When I simulate it in MPLAB it works but when I put the program in uC it behaves strange. The code is:

#define A (3.9083e-3)
#define B (-5.775e-7)

float c, qc, c1, c2, c3, ttla;
signed int temperatura_tla;
unsigned short int tRef, tRsen; // values from a counter
char templ, temph;

//usually couter gives tRef=0x0A0A, tRsen= 0x0AEE;

//some calculations
c1 = 1 - ((float)tRsen)/((float)tRef);
c2 = 4*B*c1;
c3 = A*A;
c = c3-c2;
qc= sqrt(c);
ttla = (-A + qc)/(2*B);
temperatura_tla = (int)ttla; //converting float to int????
if (ttla > 0) temperatura_tla++;

// Simulation gives for temperatura_tla= 0x0016, what is ok

templ = (temperatura_tla & 0xFF); // LSB
temph = (temperatura_tla >> 8) & 0xFF;

ConsolePutROMString( (ROM char *)"Izmjerena temperatura tla je ");
ConsolePutROMString( (ROM char *)"\r\n");

//after this I get on console for temperatura_tla=0x7FFF or sometimes 0xFF0A
//that's wrong

Ok, now, it's maybe problem in shifting the signed int, or in converting float to int? I don't now how temperatura_tla becomes 0X7FFF... Can somebody give me advice what to do? :)


Joined Oct 14, 2005
Several things for you to try:
1. Print the value of temperature_tla, or watch it with debug.
2. See that the (int) casting work as it should be (through printing or watching). There are implementations that behave strangely in some compilers.
3. Cast the temperature_tla to char to get the low bit.
4. Cast the shifting block to int to make sure the shifting is done in 16 bits.

The printing or debugging would show you where the calculation went wrong.

Thread Starter


Joined Nov 3, 2007
Thanks, I've already solved the problem...
Reading the timer value wasn't good implemented.

Maybe, it will be useful to somebody...

1. you must read fist low byte, then high byte from timer (writing to timer register goes other way, high and than low).

2. I had 2 variables for storing TMRL and TMRH, and one for making one 16-bit number from TMRL and TMRH. All variables were unsigned int

3. What I did was
TMR3ON = 0;
tRefl=TMR3L; //for example tRefl= 0x00AA
tRefh=TMR3H; //for example tRefh= 0x00BB
tRef = tRefh<<8 + tRefl; //in simulation (Watch window) I've achieve
wanted result tRef =0xBBAA
While in uC program didn't worked(the value to tRef was always 0). I printed values of tRefl, tRefh they were what I expected, and the thing that didn' come to my mind was to print tRef.

4. Corect code is
TMR3ON = 0;
tRef = (tRsenh<<8);
tRef |= tRsenl;

I'm starting to learn PIC programing! :)