2

I'm trying a simple code that using wiringPi as here:

#include<wiringPi.h>
#include<stdio.h>

int main(void){
    int i;

    wirintPiSetup();
    pinMode(0,OUTPUT);   //a single LED
    pinMode(8,INPUT);    //tactile switch

    for(;;){
        delay(500);
        //push tactile switch and LED is turning on
        if(digitalRead(8)) digitalWrite(0,0);
        else digitalWrite(0,1);
        printf("%d",digitalRead(8));
    }
}

I expected a result of printf() is output to console, but it doesn't work. printf() couldn't run in same time with wiringPi APIs?

no warnings at compile. and CPU consumption is always under 4%. running on Raspbian.

Thanks for your time!

Nagitch
  • 23
  • 1
  • 5
  • The `printf` function should definitely work. – meskobalazs Jun 08 '15 at 14:24
  • Have you tried put printf in start of your code to check if your program crashes before entering the loop? Else try with gdb – MrSykkox Jun 08 '15 at 14:27
  • Thanks for a mention! now i tried put printf hello in start of code, and it doesn't work! suppose, something went wrong out of logic. I'll try gdb. – Nagitch Jun 08 '15 at 14:44

1 Answers1

7

stdout by default is typically line-buffered, meaning it tries to put off writing data to the underlying file until a newline. But since you never print a newline, stdout will just buffer your text until it runs out of space.

You can fix this by either adding a newline in the format string (i.e. "%d\n"), or calling fflush on stdout after printing.

Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
  • it solved! I'm Japanese, so using Japanese keyboard and it can't type backslash...lol copy and paste backslash from website, and it works well. thank you so much! – Nagitch Jun 08 '15 at 15:00
  • I originally used "/n", not "\n". Your answer helped me figure that out. I get a "hello world\n" from the VS2019 remote console connected a raspberry pi target. – Julian Pechacek Nov 30 '21 at 03:21
  • Drew McGowen, "stdout by default is line-buffered" --> Hmmm. What spec says that? Certainly not the C spec. – chux - Reinstate Monica Nov 30 '21 at 03:28
  • 1
    @chux-ReinstateMonica you're right - the C standard only says "the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device." Based on https://stackoverflow.com/q/3723795/2478565, it seems like line-buffered stdout is the most common. – Drew McGowen Nov 30 '21 at 14:23