0

I have tried using getch() to no avail. I am using geany ide and gcc compiler on Rasbian linux. I have the ncurses library installed and I am using it.

int input(){
int in;
in = getch();
printf("%i", in);
if(in == 'w'){
    return 1;
}
else if(in == 's'){
    return 0;
}
else{
    return 3;
}

}

  • Maybe some help here: [How to implement getch() ... in Linux](https://stackoverflow.com/q/3276546/10871073)? – Adrian Mole Sep 07 '20 at 01:21
  • You'll have to set the [kernel] TTY driver into raw mode. See `man termios` Or, look at what `ncurses` does – Craig Estey Sep 07 '20 at 01:58
  • Are you talking about raw mode ? Something like that : https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html – Goozzi Sep 07 '20 at 02:27

1 Answers1

0

For getch() to work, you need to initialize ncurses at the start of your program. This is done by calling at least initscr() and to disable line buffering, calling cbreak(). From the cbreak man page:

Normally, the tty driver buffers typed characters until a newline or carriage return is typed. The cbreak routine disables line buffering and erase/kill character-processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program. The nocbreak routine returns the terminal to normal (cooked) mode.

Initially the terminal may or may not be in cbreak mode, as the mode is inherited; therefore, a program should call cbreak or nocbreak explicitly. Most interactive programs using curses set the cbreak mode. Note that cbreak overrides raw.

Or instead or cbreak(), another way to disable line buffering is by setting "raw mode" with raw().

For a complete example of reading keys in ncurses, see for instance
https://tldp.org/HOWTO/NCURSES-Programming-HOWTO/keys.html

Pascal Getreuer
  • 2,906
  • 1
  • 5
  • 14
  • `initscr(); clear(); noecho(); cbreak(); int input(){ int in; in = getch(); printf("%i", in); if(in == 119){ return 1; } else if(in == 115){ return 0; } else{ return 3; } }` This is my code but I get this error when compiling. Motor1.c:22:1: error: conflicting types for ‘initscr’ In file included from Motor1.c:13: /usr/include/curses.h:667:33: note: previous declaration of ‘initscr’ was here extern NCURSES_EXPORT(WINDOW *) initscr (void); /* implemented */ ^~~~~~~ – TheChair55 Sep 07 '20 at 16:02
  • @TheChair55 I may be misreading your snippet, but initscr(), etc. need to be called from within your main() function. Writing initscr(); out in the open in the global scope will be interpreted as a redefinition of initscr(), but with int return type, which could explain the "conflicting types" error message. If you still have errors, try building [this "hello world" ncurses example](https://tldp.org/HOWTO/NCURSES-Programming-HOWTO/helloworld.html#COMPILECURSES) to test your ncurses installation. – Pascal Getreuer Sep 07 '20 at 16:33