IEEE 802.15.4 subsystem
Sign in or create your account | Project List | Help
IEEE 802.15.4 subsystem Git Source Tree
Root/
Source at commit 49e7c83796bc04941e9dbcec69bc0751563ff4d4 created 7 years 6 days ago. By Werner Almesberger, atusb/: use ""VDD" symbol from kicad-libs | |
---|---|
1 | /* |
2 | * lib/getkey.c - Get single characters from standard input |
3 | * |
4 | * Written 2011 by Werner Almesberger |
5 | * Copyright 2011 Werner Almesberger |
6 | * |
7 | * This program is free software; you can redistribute it and/or modify |
8 | * it under the terms of the GNU General Public License as published by |
9 | * the Free Software Foundation; either version 2 of the License, or |
10 | * (at your option) any later version. |
11 | */ |
12 | |
13 | |
14 | #include <stdlib.h> |
15 | #include <stdio.h> |
16 | #include <unistd.h> |
17 | #include <fcntl.h> |
18 | #include <termios.h> |
19 | #include <errno.h> |
20 | |
21 | |
22 | |
23 | static struct termios old_term; |
24 | |
25 | |
26 | static void restore_term(void) |
27 | { |
28 | if (tcsetattr(0, TCSAFLUSH, &old_term) < 0) |
29 | perror("tcsetattr"); |
30 | } |
31 | |
32 | |
33 | void get_key_init(void) |
34 | { |
35 | static int initialized = 0; |
36 | struct termios term; |
37 | |
38 | if (initialized) |
39 | return; |
40 | initialized = 1; |
41 | |
42 | if (tcgetattr(0, &old_term) < 0) { |
43 | perror("tcgetattr"); |
44 | exit(1); |
45 | } |
46 | term = old_term; |
47 | cfmakeraw(&term); |
48 | if (tcsetattr(0, TCSAFLUSH, &term) < 0) { |
49 | perror("tcsetattr"); |
50 | exit(1); |
51 | } |
52 | atexit(restore_term); |
53 | if (fcntl(0, F_SETFL, O_NONBLOCK) < 0) { |
54 | perror("fcntl"); |
55 | exit(1); |
56 | } |
57 | } |
58 | |
59 | |
60 | char get_key(void) |
61 | { |
62 | ssize_t got; |
63 | char ch; |
64 | |
65 | get_key_init(); |
66 | got = read(0, &ch, 1); |
67 | if (got == 1) |
68 | return ch; |
69 | if (got >= 0) { |
70 | fprintf(stderr, "unexpected read() return value %d\n", |
71 | (int) got); |
72 | exit(1); |
73 | } |
74 | if (errno == EAGAIN) |
75 | return 0; |
76 | perror("read"); |
77 | exit(1); |
78 | } |
79 |