0
votes

I was trying to modify a program i got on the internet, which i found here:

Interfacing Ultrasonic distance sensor ASCII output using PIC Microcontroller

I need to do some calculations on the distance before i can output it to the LCD display.I successfully converted the string to float. Its code is here:

// LCD module connections
sbit LCD_RS at RB7_bit;
sbit LCD_EN at RB6_bit;
sbit LCD_D4 at RB5_bit;
sbit LCD_D5 at RB4_bit;
sbit LCD_D6 at RB3_bit;
sbit LCD_D7 at RB2_bit;
sbit LCD_RS_Direction at TRISB7_bit;
sbit LCD_EN_Direction at TRISB6_bit;
sbit LCD_D4_Direction at TRISB5_bit;
sbit LCD_D5_Direction at TRISB4_bit;
sbit LCD_D6_Direction at TRISB3_bit;
sbit LCD_D7_Direction at TRISB2_bit;
// End LCD module connections

void main()
{
    int i,temp;
    char dist[] = "000.0";
    float v,h,l=25,b=25;
    Lcd_Init(); // Initialize LCD
    UART1_Init(9600); //Initialize the UART module
    Lcd_Cmd(_LCD_CLEAR); // Clear display
    Lcd_Cmd(_LCD_CURSOR_OFF); // Cursor off
    Lcd_Out(1,1,"Distance= cm");
    do
    {
        if(UART1_Data_Ready()) //if data ready
        {
            if(UART1_Read() == 0x0D) //check for new line character
            {
                for(i=0;i<5;)
                {
                    if(UART1_Data_Ready()) // if data ready
                    {
                        dist[i] = UART1_Read();  // read data
                        i++;
                    }
                }
            }
         }
         h=(100*(dist[0]-48))+(10*(dist[1]-48))+(dist[2]-48)+(0.1*(dist[4]-48));
         v=l*b*h*0.001;
         //sprintf(dist,"%f",v);
         Lcd_Out(1,10,dist);
    }while(1);
}

Would sprintf() work if i added stdio? or would i have to write the logic from scratch?Or can i use some other library functions?

1

1 Answers

0
votes

Yes sprintf() should convert the floating point value into a string.

Some microcontroller libraries come with different versions of sprintf(). The minimal version, designed to conserve code space, may not support the %f format field. So ensure you are linking with the library version that supports the %f format field.

Are you sure that your char array, dist, is long enough? You don't want sprintf() to overflow the char array. You can limit the number of decimal places output by sprintf() to one by changing the format specifier from "%f" to "%.1f". That will protect you on one end but then you still need to protect from overflow when v >= 1000.0. Consider using sprintfn() instead of sprintf().