-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathkbhit.c
95 lines (76 loc) · 2.41 KB
/
kbhit.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
Written and maintained by the IR TOY Project and http://dangerousprototypes.com
WIKI page: http://dangerousprototypes.com/usb-ir-toy-manual/
Forum page: http://dangerousprototypes.com/forum/viewforum.php?f=29&sid=cdcf3a3177044bc1382305a921585bca
********************************************************************************************************************
Copyright (C) 2011 Where Labs, LLC (DangerousPrototypes.com/Ian Lesnet)
This work is free: you can redistribute it and/or modify it under the terms of Creative Commons Attribution ShareAlike license v3.0
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more details. You should have received a copy of the License along with this program. If not, see <http://creativecommons.org/licenses/by-sa/3.0/>.
Contact Details: http://www.DangerousPrototypes.com
Where Labs, LLC, 208 Pine Street, Muscatine, IA 52761,USA
********************************************************************************************************************* */
#ifndef _WIN32
#include "kbhit.h"
#include <termios.h>
#include <unistd.h>
static struct termios init_settings, new_settings;
static int peek_char = -1;
void init_keyboard()
{
tcgetattr(0, &init_settings);
new_settings = init_settings;
new_settings.c_lflag &= ~ICANON;
new_settings.c_lflag &= ~ECHO;
new_settings.c_lflag &= ~ISIG;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_settings);
}
void close_keyboard()
{
tcsetattr(0, TCSANOW, &init_settings);
}
int kbhit()
{
struct termios save_settings;
cc_t vmin;
unsigned char ch;
int nread;
int ret = 0;
if (peek_char != -1) {
ret = 1;
} else {
tcgetattr(0, &save_settings);
new_settings.c_cc[VMIN] = 0;
tcsetattr(0, TCSANOW, &new_settings);
nread = read(0, &ch, 1);
new_settings.c_cc[VMIN] = 1;
tcsetattr(0, TCSANOW, &new_settings);
if (nread == 1) {
peek_char = ch;
ret = ch;
}
tcsetattr(0, TCSANOW, &save_settings);
}
return ret;
}
int get_ch()
{
char ch;
if (peek_char != -1) {
ch = peek_char;
peek_char = -1;
return ch;
}
read(0, &ch, 1);
return ch;
}
#endif
int get_char() {
#ifdef _WIN32
return getch();
# else
return get_ch();
//return getchar_unlocked();
# endif
}