I am using an embedded system to send data from 25 sensors to a putty terminal on my computer. Works great.
I wanted to add a read from terminal functionality to the embedded system (so I can send commands). So I tried using getchar() to read whatever I would write on my putty terminal. First I just wanted to getchar and print the character back on putty. It kinda works, but my sensor data, which is supposed to print every 500ms, does not print until I type a char in putty. It is as if my code was stuck on getchar() and stuck in a while loop until getchar() reads something.
Here is my forever loop in my int main(). I am not sharing the rest as it is not really needed and too bulky (its just initializing modules). In this loop I am reading a sensor, trying to read from putty, writing to putty, and starting my next scan:
for(;;)
{
CapSense_ProcessAllWidgets(); // Process all widgets
CapSense_RunTuner(); // To sync with Tuner application
read_sensor(curr_elem); //read curr_elem
(curr_elem < RX4_TX4)?(curr_elem++):(curr_elem = 0, touchpad_readings_flag++);
// Here is the part to read I added which blocks until I type in something.
// If I remove this if and all of what's in it, I print to putty every 500ms
if(touchpad_readings_flag)
{
char received_char = getchar();
if (received_char) //if something was returned, received_char != 0
{
printf("%c", received_char);
}
}
//Here I write to putty. works fine when I remove getchar()
if (print_counter_flag && touchpad_readings_flag)
{
print_counter_flag = 0;
touchpad_readings_flag = 0;
for (int i = 0; i < 25; i++)
{
printf("\n");
printf("%c", 97 + i);
printf("%c", val[i] >> 8);
printf("%c", val[i] & 0x00ff); // For raw counts
printf("\r");
}
}
/* Start next scan */
CapSense_UpdateAllBaselines();
CapSense_ScanAllWidgets();
}
Apparently, your getchar()
call is blocking unless there is input data to retrieve.
One solution to change this behaviour has been given by another article on different SE board.
Please also note that getchar()
is a wrapper for getc()
that is acting on stdin
as this site1 describes.
For getc()
you find further discussions.
In one of those, it is pointed out that some important implementations even wait for a newline character until input is delivered to your function. I think this depends on standard libraries/kind of embedded system you actually use - please check the documentation of your toolchain vendor.2
1 I didn't look up a normative source, this is just my first google hit.
2 The question doesn't specify the kind of embedded system, so a generic answer is wanted instead of a discussion of particular target/toolchain combinations, IMO.