Pacific-Design.com

    
Home Index

1. Caltech

2. Serial Port Tester

Caltech / Serial Port Tester /


#include <stdio.h>
#include <termio.h>
#include <sys/fcntl.h>
#include <sys/file.h>

/*
 * Serial port tester
 * Caltech: Kevin T. Duraj
 * 38400 baud by default, settable via -19200 or -9600 flags
 * first non-baud argument is tty (e.g. /dev/term/a)
 * second argument is file name (e.g. /etc/hosts)
 */
main(int argc, char *argv[]) 
{
	struct termios tp;
	int fd;
	int file;
	char io[BUFSIZ];
	int rdsz;
	long baud;

	if (strcmp(argv[1], "-9600") == 0) {
		baud = B9600;
		argv++; argc--;
	} else if (strcmp(argv[1], "-19200") == 0) {
		baud = B19200;
		argv++; argc--;
	} else
		baud = B38400;

	if ((fd = open(argv[1], O_RDWR)) < 0) {
		perror("bad terminal device, try another");
		exit(-1);
	}
	
	if (tcgetattr(fd, &tp) < 0) {
		perror("Couldn't get term attributes");
		exit(-1);
	}
	/* 8 bits + baud rate + local control */
	tp.c_cflag = CS8|CLOCAL|baud;
	tp.c_oflag = 0;
	/* XON/XOFF flow control, ignore CR, ignore parity */
	tp.c_iflag = IXON|IGNBRK|IGNCR|IGNPAR;
	tp.c_lflag = 0;
	/* set output and input baud rates */
	cfsetospeed(&tp, baud);
	cfsetispeed(&tp, baud);
	if (tcsetattr(fd, TCSANOW, &tp) < 0) {
		perror("Couldn't set term attributes");
		exit(-1);
	}

	file = 0;
	/* open file to send to port */
	if ((file = open(argv[2], O_RDONLY)) < 0) {
		perror("couldn't open file");
		exit(1);
	}

	/* dump it to the port */
	while ((rdsz = read(file, io, BUFSIZ)) > 0) 
		write(fd, io, rdsz);
	exit(0);
}