AnsweredAssumed Answered

Scanf-Retarget Problem

Question asked by anlauf.christoph on Nov 14, 2011
Latest reply on May 4, 2018 by wong.chii_lok

Hello Forum!

While trying to retarget the printf() and scanf() functions, with printf everything worked well. 
However, with scanf occured a weird problem.

First here are the overwrited low-level functions :

size_t __write(int handle, const unsigned char * buffer, size_t size)
{
  size_t nChars = 0;

  if (buffer == 0)
  {
    /*
     * This means that we should flush internal buffers.  Since we
     * don't we just return.  (Remember, "handle" == -1 means that all
     * handles should be flushed.)
     */
    return 0;
  }

  for (/* Empty */; size != 0; --size)
  {
    
    while(!(USART1->SR & USART_FLAG_TXE));
      USART1->DR = ((*buffer++) & 0x01FF);

    ++nChars;
  }

  return nChars;
}

size_t __read(int handle, unsigned char * buffer, size_t size)
{
  int nChars = 0;

  for (/* Empty */; size > 0; --size)
  {
    
    while(!(USART1->SR & USART_FLAG_RXNE));
    int c = USART1->DR & 0x01FF;
    if (c < 0)
      break;

    *buffer++ = c;
    ++nChars;
  }

  return nChars;
}

 while (1)
 {
    scanf("%i \n",&iNumb);
    printf("%i\n",iNumb);
 }


I set a breakpoint into the __read-method() and I noticed something,I think that's the point:

Sending '1', the while-loop becomes true and the integer 'c' equals '1'. (Everythings fine)
The failure is, that the program jumps a second time into the function and get stuck in the while-loop because there's no second character. The result is : sending a second character, the first one is displayed and so on...

For better understanding, here's the Terminal output:

1
2
Echo from STM32: 1
3
Echo from STM32: 2
4
Echo from STM32: 3
5
Echo from STM32: 4
6
Echo from STM32: 5
7
Echo from STM32: 6
8
Echo from STM32: 7
10
Echo from STM32: 8
11
12
Echo from STM32: 1011

The behavior with two-digit numbers is a little different...

Hope you can help me with this one! :)

Thank you in advance!
Chris

Outcomes