diff rvinterf/lowlevel/openport.c @ 0:e7502631a0f9

initial import from freecalypso-sw rev 1033:5ab737ac3ad7
author Mychaela Falconia <falcon@freecalypso.org>
date Sat, 11 Jun 2016 00:13:35 +0000
parents
children e7d5ce499693
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rvinterf/lowlevel/openport.c	Sat Jun 11 00:13:35 2016 +0000
@@ -0,0 +1,82 @@
+/*
+ * This module takes care of opening the serial port and setting the
+ * proper "raw" termios modes, including the baud rate.
+ */
+
+#include <sys/types.h>
+#include <sys/file.h>
+#include <sys/ioctl.h>
+#include <termios.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <unistd.h>
+
+int target_fd;
+char *baudrate_name = "115200";
+
+static struct baudrate {
+	char	*name;
+	speed_t	termios_code;
+} baud_rate_table[] = {
+	{"19200",	B19200},
+	{"38400",	B38400},
+	{"57600",	B57600},
+	{"115200",	B115200},
+	/* non-standard high baud rates "remapped" by CP2102 usb2serial IC */
+	{"203125",	B230400},
+	{"406250",	B460800},
+	{"812500",	B921600},
+	/* table search terminator */
+	{NULL,		B0}
+};
+
+static speed_t
+get_baud_rate()
+{
+	struct baudrate *br;
+
+	for (br = baud_rate_table; br->name; br++)
+		if (!strcmp(br->name, baudrate_name))
+			break;
+	if (!br->name) {
+		fprintf(stderr, "baud rate \"%s\" unknown/unsupported\n",
+			baudrate_name);
+		exit(1);
+	}
+	return br->termios_code;
+}
+
+open_target_serial(ttydev)
+	char *ttydev;
+{
+	struct termios target_termios;
+	speed_t br_code;
+
+	br_code = get_baud_rate();
+	target_fd = open(ttydev, O_RDWR|O_NONBLOCK);
+	if (target_fd < 0) {
+		perror(ttydev);
+		exit(1);
+	}
+	target_termios.c_iflag = IGNBRK;
+	target_termios.c_oflag = 0;
+	target_termios.c_cflag = CLOCAL|HUPCL|CREAD|CS8;
+	target_termios.c_lflag = 0;
+	target_termios.c_cc[VMIN] = 1;
+	target_termios.c_cc[VTIME] = 0;
+	cfsetispeed(&target_termios, br_code);
+	cfsetospeed(&target_termios, br_code);
+	if (tcsetattr(target_fd, TCSAFLUSH, &target_termios) < 0) {
+		perror("initial tcsetattr on target");
+		exit(1);
+	}
+	return 0;
+}
+
+set_serial_nonblock(state)
+	int state;
+{
+	ioctl(target_fd, FIONBIO, &state);
+}