C++ listen for keyboard events (read keyboard input)

Hits: 0

When we want to use the keyboard to control the robot, we need to read the keyboard input in real time.

The routine program is as follows:

#include <termio.h>
#include <stdio.h>

int scanKeyboard()
{

    int in;

    struct  termios  new_settings ; 
    struct  termios  stored_settings ; 
    //Set terminal parameters 
    tcgetattr( 0 ,&stored_settings);
    new_settings = stored_settings;
    new_settings.c_lflag &= (~ICANON);
    new_settings.c_cc[VTIME] = 0;
    tcgetattr(0,&stored_settings);
    new_settings.c_cc[VMIN] = 1;
    tcsetattr(0,TCSANOW,&new_settings);
    in = getchar();
    tcsetattr(0,TCSANOW,&stored_settings);

    return in;

}

//Test function 
int  main () {

    while(1){
        printf("%d\n",scanKeyboard());
    }
}

For in-depth research, please refer to the following links:

1./qqliuzhitong/article/details/120229789

2. C implements monitoring of keyboard events under linux (the program reads immediately when the keyboard is pressed) – Lend you a second – CSDN Blog

You may also like...

Leave a Reply

Your email address will not be published.