cancel
Showing results for 
Search instead for 
Did you mean: 

Problem with scanf in STM32F4, it is scanning only the first char even I am requesting to scan an int or float. Details in description

bassem.saleh93
Associate II

here is the code I am using to scan

int ScanConfig(__const char * format, va_list args) {
    unsigned i=0;
    char ch = 0;
    char buffer[256];
    int ret = 0;
    while((i<sizeof(buffer))&&(ch!='\n')&&(ch!='\r')){
        HAL_StatusTypeDef status = HAL_TIMEOUT;
        while (status == HAL_TIMEOUT) {
            status =  HAL_UART_Receive(&UartHandle1, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
            if (status == HAL_TIMEOUT) {
                /*HAL_UART_DeInit(&rxHandle);
                  HAL_UART_Init(&rxHandle);*/
            }
            else
                break;
        }
 
        buffer[i]=ch;
        i++;
        ret = vsscanf(buffer, format, args);
        if (ret > 0)
            break;
    }
    buffer[i]=0;
    return ret;
}
int Scan(__const char * format, ...) {
    va_list args;
    va_start(args, format);
    int size = ScanConfig(format, args);
    va_end(args);
    return size;
}

I am calling the function like this:

Scan("%f",&InVar);

The problem that if I try to enter 4.5 for example, I can't and it saves only 4.

3 REPLIES 3

Which tools/libraries are you using? Are floating point libraries for printf()/scanf() included, or lightweight alternatives?

Do you properly NUL terminate the buffer before calling vsscanf() ? Do you, or should you, clear the buffer[] as it is a local/auto variable holding whatever junk is currently on the stack.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
bassem.saleh93
Associate II

I am using HAL library on Eclipse IDE. Yes, floating point is included for printf and scanf. The problem is not that it does print or scan garbage. The problem that it just scans one character.

Does it actually fill the buffer?

As I already noted you need to NUL terminate the buffer.

Otherwise, perhaps step with the debugger to understand why it is finishing the scan early.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..