user7187418 user7187418 - 14 days ago 5
C Question

Display floating point numbers on an LCD

How do I get the variable, volts, to display floating point numbers on a LCD?

The LCD only displays floating point values with a lot of decimal places with E at the end. I only need 2 decimal places, so how do I display it?

int main (void){

adcinit();

lcd_init();//initializes LCD
lcd_clear();//clear screen
lcd_home();


uint16_t value;
float volts;
while(1){
ADCSRA |= (1<<ADSC);//start ADC conversion
delay_ms(54);//delay 54 millisecond
value = ADCW;//assign ADC conversion to value
volts=(value*5)/1023;
lcd_goto_xy(0,0);// coordinates of the cursor on LCD Display
lcd_printf("ADC Value: %d ",value);//display on LCD
lcd_goto_xy(0,1);// coordinates of the cursor on LCD Display
lcd_printf("Volts: %f ",volts);//display on LCD
}
}

Answer

If the function lcd_printf() is based to the same library than the function sprintf() for Arduino, the format specifier '%f' is not well managed even when used as '%.2f'.

Step 1: Before proposing alternate solutions, it is necessary to get a well-computed float value from the numerical value read from the Analog-To-Digital Converter.

If the ADC is a 10-bits, the range should be 1024 (instead of 1023).

value = ADCW;//assign ADC conversion to value
volts=((float)value*5.0f)/(1024.0f); 

Step2.1: A first and quick solution to display a 2-decimals fixed float value is to convert it in 2 integers.

lcd_printf("Volts: %d.%02d ",(int)volts, (int)(volts*100)%100));//display on LCD

Instead of

lcd_printf("Volts: %.2f ",volts);//display on LCD

Step 2.2: A more 'official' solution to display a 2-decimals fixed float value is to use the dtostrf() function as proposed in "Arduino sprintf float not formatting".

char str_volts[15]; // to store the float-to-string converted value
lcd_printf("Volts: %s ",dtostrf(volts, 4, 2, str_volts));//display on LCD
// 4 = minimum number of char ('X.XX'), 2 = number of decimals

Instead of

lcd_printf("Volts: %.2f ",volts);//display on LCD
Comments