-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuart.c
63 lines (54 loc) · 1.54 KB
/
uart.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
#include "uart.h"
#include "debug.h"
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <errno.h>
#define UART_MSG_MAX 0xFF
static int uart_fd = -1;
int uart_init(const char *path) {
dbg(DBG_UART|DBG_VERBOSE,"Openining %s\n",path);
uart_fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (uart_fd == -1) {
dbg(DBG_UART|DBG_ERROR,"Failed to open UART device!\n");
return uart_fd;
}
struct termios options;
tcgetattr(uart_fd, &options);
options.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(uart_fd, TCIFLUSH);
tcsetattr(uart_fd, TCSANOW, &options);
return uart_fd;
}
void uart_close() {
dbg(DBG_UART|DBG_VERBOSE,"Closing.\n");
close (uart_fd);
uart_fd = -1;
}
int uart_read(uint8_t *buf, int size) {
int ret;
ret = read(uart_fd, (void*)buf, size);
if (ret<0) {
if (errno==EAGAIN) return 0;
perror("UART: Error reading");
}
else if (ret>0) {
dbg(DBG_UART|DBG_VERBOSE,"rx: \"%s\", len: %i\n",dbg_printHEX(buf,ret),ret);
}
return ret;
}
int uart_write(uint8_t *buf, int count) {
int ret;
ret=write(uart_fd, buf, count);
if (ret<0) {
perror("UART: Error writing");
}
else {
dbg(DBG_UART|DBG_VERBOSE,"tx: \"%s\", len: %i\n",dbg_printHEX(buf,count),count);
}
return ret;
}