#include <stdio.h>
#include <stdlib.h>
#include <termio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <err.h>
#include <sys/poll.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>

int main(int argc, char *argv[])
{
	int baudrate=B9600;
	int fd_serial;
	struct termios options;
	FILE *s;
	int val;
	uint8_t c;
	
	if (argc != 3) {
		fprintf(stderr,"usage: %s device value\n", *argv);
		fprintf(stderr,"   ex: %s /dev/ttyS0 123\n", *argv);
		exit(1);
	} 

	val = atoi(argv[2]);
	if (val < 0 || val > 255)
		errx(1, "bad value: %s", argv[2]);

	if ((fd_serial = open(argv[1], O_RDWR|O_NOCTTY)) == -1)
		err(1, "serial device %s", argv[1]);

	fcntl(fd_serial, F_SETFL, 0);
	tcgetattr(fd_serial, &options);
	cfsetispeed(&options, baudrate);
	cfsetospeed(&options, baudrate);
	options.c_cflag |= (CLOCAL | CREAD);
	options.c_cflag &= ~PARENB;
	options.c_cflag |= CSTOPB;
	options.c_cflag &= ~CSIZE;
	options.c_cflag |= CS8;
	options.c_cflag &= ~CRTSCTS;
	options.c_oflag &= ~OPOST;
	if (tcsetattr(fd_serial, TCSANOW, &options) != 0)
		err(1, "setting serial device parameters");

	c = val;
	printf("Sending byte 0x%02x\n", c);
	write(fd_serial, &c, 1);

	close(fd_serial);
	return 0;
}
