fox32/src/serial.c

60 lines
1.0 KiB
C
Raw Normal View History

#include <stdio.h>
#ifndef WINDOWS
2023-02-01 20:12:21 +01:00
#include <sys/select.h>
#include <unistd.h>
#include <termios.h>
#include <stdbool.h>
#include <stdlib.h>
static struct termios saved_tios;
static bool is_terminal = false;
static void exit_handler(void) {
2023-04-02 04:09:36 +02:00
if (is_terminal)
tcsetattr(0, TCSANOW, &saved_tios);
2023-02-01 20:12:21 +01:00
}
void serial_init(void) {
2023-04-02 04:09:36 +02:00
struct termios tios;
2023-02-01 20:12:21 +01:00
2023-04-02 04:09:36 +02:00
if (tcgetattr(0, &tios) != -1) {
is_terminal = 1;
saved_tios = tios;
2023-02-01 20:12:21 +01:00
atexit(exit_handler);
2023-04-02 04:09:36 +02:00
}
2023-02-01 20:12:21 +01:00
2023-04-02 04:09:36 +02:00
if (is_terminal) {
tios.c_lflag &= ~(ICANON|ECHO);
tcsetattr(0, TCSANOW, &tios);
}
2023-02-01 20:12:21 +01:00
}
int serial_get(void) {
fd_set readfds;
int fd = STDIN_FILENO;
struct timeval tm = { 0, 0 };
FD_ZERO(&readfds);
FD_SET(fd, &readfds);
int ready = select(fd + 1, &readfds, NULL, NULL, &tm);
if (ready == 1 && FD_ISSET(fd, &readfds)) {
char c;
int ret = read(fd, &c, 1);
if (ret == 1)
return c;
}
return 0;
}
#endif
2023-02-01 20:12:21 +01:00
void serial_put(int value) {
putchar((int) value);
fflush(stdout);
}