Xuejun Ding

Problem to convert "float" into "unsigned char"

Discussion created by Xuejun Ding on Feb 26, 2012
Latest reply on Mar 12, 2012 by Daniel Lundin

I am using MC9S12XEP100 AND CW5.1 on my automotive project,  I need to convert a mapped analog value ( this value has been mapped ranged from 3.35v – 3.65v to a new range of 0 - 5v, it is virtual rather than real, therefore it cannot be directly connected to the PAD00-PAD15 pins for A/D conversion).

part1. I have successfully built up the mapping program which is good, the part1 program is here:

 

//...map the (3.35v-3.65v) ADC output to a value between 0-5v

// Inputs: adcout = ADC result, adcmin/adcmax = min and max value of the ADC

//         rmin/rmax = min and max value in physical value

// Return outputs: mapped 0-5v value from real measured 3.35v-3.65v ADC result

float ADC_to_map (unsigned int adcout, unsigned int adcmin, unsigned int adcmax, float mapmin, float mapmax)

{

   float rslt1;

   if(adcout>adcmax) adcout = adcmax;

   else if(adcout<adcmin) adcout = adcmin;

   rslt1 = (float)(adcout-adcmin)*(mapmax-mapmin)/(float)(adcmax-adcmin) + mapmin;

   if(rslt1<mapmin) rslt1 = mapmin; else if(rslt1>mapmax) rslt1=mapmax;

   return (rslt1);

}

 

part2. however, there is a problem when convert the float to unsigned char, the part2 program is here:

 

//...Convert the mapped 0-5vl value into 8-bit quantised unsigned char for further comparison

// Inputs: rval = mapped value to be converted into an unsigned char 

//         mapmin/mapmax = min and max value of the mapped value (0v and 5v respectively)

// Return outputs: unsigned char to be used for further comparison

unsigned char Map_to_wantedchar (float rval, float mapmin, float mapmax)

{

   float rslt2 = 255*(rval-mapmin)/(mapmax-mapmin);

   return((unsigned char)rslt2);

}

The above part2 program was previously successfully compiled in my C167 Microprocessor project using Keil uvision development suite, but this time it gives a warning “C5915: Conversion of float to unsigned integral” with freescale MC9S12XEP100 and CodeWarrior5.1.

 

I read the C5919 information and tried to modify the code in part2 as:

Option A (NOT SUCCESSFUL):

 unsigned char Map_to_wantedchar (float rval, float mapmin, float mapmax)

{

   float rslt2 = 255*(rval-mapmin)/(mapmax-mapmin);

  signed char tempA = (signed char)(rslt2);

  unsigned char testA = (unsigned char)tempA;

   return((unsigned char)testA);

}

 

Option B (NOT SUCCESSFUL):

 unsigned char Map_to_wantedchar (float rval, float mapmin, float mapmax)

{

   float rslt2 = 255*(rval-mapmin)/(mapmax-mapmin);

  signed int tempB = (signed int)(rslt2);

  unsigned char testB = (unsigned char)tempB;

   return((unsigned char)testB);

}

 

Anyone please give me a hand, thanks!

Outcomes