0

I want to use printf on STM32F107 and I have the problem that my program sends the printf messages just after 1024bytes.

Here is my overwrite code:

int __io_putchar(int ch) {
    uint8_t c[1];
    c[0] = ch & 0x00FF;
    HAL_UART_Transmit(&huart1, &*c, 1, 10);
    return ch;
}

int _write(int file, char *ptr, int len) {
    int DataIdx;
    for (DataIdx = 0; DataIdx < len; DataIdx++) {
        __io_putchar(*ptr++);
    }
    return len;
}

And here the sample Code for output:

while (1) {
    printf("Test %d", testcnter++);
    //HAL_UART_Transmit(&huart1, "TEST", 4, 100); <-- Works prints every loop
    HAL_Delay(250);
}

Here is the Output:

hterm output

Tarick Welling
  • 3,119
  • 3
  • 19
  • 44
vt1111
  • 71
  • 3
  • 12
  • Probably a buffering issue. Either use `fflush` after every `printf` or change the buffering first with `setvbuf`. If the output is linhe-buffered, appending a newline would also write the output. see also https://stackoverflow.com/q/16182554/10622916 – Bodo Sep 25 '20 at 09:26
  • Thanks. You're right. – vt1111 Sep 25 '20 at 09:38

1 Answers1

0

Here is the Answer for all who have the same problem:

Its a buffer issue.

setvbuf(stdout, NULL, _IONBF, BUFSIZ); // Disables buffer completly 

Or:

fflush(stdout); // Clears the buffer 

Thanks to @Bodo

vt1111
  • 71
  • 3
  • 12
  • Why `BUFSIZ`? Just `setvbuf(stdout, NULL, _IONBF, 0);` – KamilCuk Sep 25 '20 at 09:39
  • 2
    STM32F107 does not buffers - so setvbuf and fflush do nothing :) It is not hosted system and it does not have filesystem. So it is not the solution. – 0___________ Sep 25 '20 at 11:14
  • Hmm, well both lines works on STM32 and lead to the desired result. – vt1111 Sep 25 '20 at 12:08
  • Just jump into the `fflush` function what does it's definition do that makes it output it's data? There's your answer as to why it works. Please add it to your answer – Tarick Welling Sep 27 '20 at 11:23