diff options
-rwxr-xr-x | include/uart_api.h | 189 |
1 files changed, 189 insertions, 0 deletions
diff --git a/include/uart_api.h b/include/uart_api.h new file mode 100755 index 0000000..cfa6473 --- /dev/null +++ b/include/uart_api.h @@ -0,0 +1,189 @@ +#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <termios.h>
+
+int set_com_config(int fd, int baud_rate, int data_bits, char parity, int stop_bits)
+{
+ struct termios new_cfg, old_cfg;
+ int speed;
+
+ /*save old config*/
+ if (tcgetattr(fd, &old_cfg) != 0)
+ {
+ perror("tcgetattr");
+ return -1;
+ }
+
+ new_cfg =old_cfg;
+
+ /*enable local connection and read function*/
+ new_cfg.c_cflag |= CLOCAL | CREAD;
+
+ /*disable bit mask*/
+ new_cfg.c_cflag &= ~CSIZE;
+
+ /*disable hardware dataflow control*/
+ new_cfg.c_cflag &= ~CRTSCTS;
+
+ /*ignore parity error*/
+ new_cfg.c_iflag |= IGNPAR;
+
+ /*do not transform CR to NL, enable output software data flow control*/
+ new_cfg.c_iflag &= ~(ICRNL | IXON);
+
+ /*set baud rate*/
+ switch (baud_rate)
+ {
+ case 2400:
+ {
+ speed = B2400;
+ break;
+ }
+ case 4800:
+ {
+ speed = B4800;
+ break;
+ }
+ case 9600:
+ {
+ speed = B9600;
+ break;
+ }
+ case 19200:
+ {
+ speed = B19200;
+ break;
+ }
+ case 38400:
+ {
+ speed = B38400;
+ break;
+ }
+
+ default:
+ case 115200:
+ {
+ speed = B115200;
+ break;
+ }
+ }
+
+ cfsetispeed(&new_cfg, speed);
+ cfsetospeed(&new_cfg, speed);
+
+ /*set data bits*/
+ switch (data_bits)
+ {
+ case 7:
+ {
+ new_cfg.c_cflag |= CS7;
+ break;
+ }
+
+ default:
+ case 8:
+ {
+ new_cfg.c_cflag |= CS8;
+ break;
+ }
+ }
+
+ /*set parity*/
+ switch (parity)
+ {
+ default:
+ case 'n':
+ case 'N':
+ {
+ new_cfg.c_cflag &= ~PARENB;
+ new_cfg.c_iflag &= ~INPCK;
+ break;
+ }
+
+ case 'o':
+ case 'O':
+ {
+ new_cfg.c_cflag |= (PARODD |PARENB);
+ new_cfg.c_iflag |= INPCK;
+ break;
+ }
+
+ case 'e':
+ case 'E':
+ {
+ new_cfg.c_cflag |= PARENB;
+ new_cfg.c_cflag &= ~PARODD;
+ new_cfg.c_iflag |= INPCK;
+ break;
+ }
+
+ case 's':
+ case 'S':
+ {
+ new_cfg.c_cflag &= ~PARENB;
+ new_cfg.c_cflag &= ~CSTOPB;
+ break;
+ }
+ }
+
+ /*set stop bits*/
+ switch (stop_bits)
+ {
+ default:
+ case 1:
+ {
+ new_cfg.c_cflag &= ~CSTOPB;
+ break;
+ }
+
+ case 2:
+ {
+ new_cfg.c_cflag |= CSTOPB;
+ break;
+ }
+ }
+
+ new_cfg.c_oflag = 0;
+ new_cfg.c_lflag = 0;
+
+ if ((tcsetattr(fd, TCSANOW, &new_cfg)) != 0)
+ {
+ perror("tcsetattr");
+ return -1;
+ }
+
+ return 0;
+}
+
+int open_port(char *com_port)
+{
+ int fd;
+
+ /*open port*/
+ fd = open(com_port, O_RDWR|O_NOCTTY|O_NDELAY);
+ if (fd < 0)
+ {
+ perror("open serial port");
+ return -1;
+ }
+
+ /*jam port*/
+ if (fcntl(fd, F_SETFL, 0) < 0)
+ {
+ perror("jam port");
+ }
+
+ /*check if it is a terminal device*/
+ if (isatty(fd) == 0)
+ {
+ perror("check terminal device");
+ }
+
+ return fd;
+}
|