#include <fcntl.h>
#include <sys/ioctl.h>
#define FULL_SPEED 127 // actual value to send  to the motor to go full speed (- is full backwards)
#define MIN_SPEED 25   // minimum stall speed

int main() {
	int c, res;
	struct termios tty; // will be used for new port settings
	char buf[255];      // buffer used to store received characters

	// set up serial port
	fd_serial = open("/dev/ttyS0", O_RDWR | O_NOCTTY ); 
	tcgetattr(fd_serial, &oldtty); // save current port settings
	bzero(&tty, sizeof(tty));
	tty.c_iflag = 0; tty.c_lflag = 0; tty.c_oflag = 0; tty.c_cc[VTIME] = 0; tty.c_cc[VMIN] = 1;
	tty.c_cflag = BAUDRATE | CS8 | CLOCAL;
	tcflush(fd_serial, TCIFLUSH);
	tcsetattr(fd_serial, TCSANOW, &tty);
	
	int new_speed = (int)((FULL_SPEED - MIN_SPEED) * ((double)val/100.0));
	unsigned char out[4];
	out[0] = 0x80; // start byte
	out[1] = 0x00; // deviceid (0=motor)
	out[2] = (num*2)+0; // msb(7) = motor num, lsb = direction
	//cout << "val=" << val << "; dir=" << direction << "; out2=" << (int)out[2] << ";" << endl;
	out[3] = abs(new_speed); // max 0x7f

	write(fd_serial, val, sizeof(out));
	return 1;
}

