/*	PONTECH Copyright 1996
 *	Sample SV200 interface
 *  GETAD.C
 *  	Read the A/D port and send back to the servos
 */

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "comm.h"
#include "comm.c"		/* don't need this line if include in project */
#include "sv_lib.h"
#include "sv_lib.c"	/* don't need this line if include in project */

#define ESC_KEY 	27
#define BS_KEY 		8
#define ENTER_KEY 13

void plotPos(int pos);

int main()
{
	int i, port;
	char key;
	unsigned char pos, savePos1, savePos2;

	clrscr();

	port = COM1;
	serlSetIntr(port);
	if ((serlPortInit(port,9600,0,8,1)) == -1)
	{
		printf("Can not connect to the SV200\n");
		return 0;
	}

	selectBoard(1);

	MasterDelay = 0; /* no delay between moves */

	printf("*** SV200 ****\n\n");
	printf(" This program reads the A/D value from channel 1 and\n");
	printf(" outputs it to a selected servo\n\n");

	printf(" Once started...\n\n");
	printf(" Press 1) through 8) to select the servo to control\n");
	printf("\n\n");
	printf("      <ESC> to quit.\n");
	printf("\n\n");

	printf("<press any key to start>\n");
	while (!kbhit())
		;

	selectServo(1);
	while(key != ESC_KEY)
	{
		if (kbhit())
		{
			key = getch();
			if ((key >= '1') && (key <= '8'))
				selectServo(key-'0');
		}

		pos = adjADJoystick(getAD(1));
		if ((savePos1 != pos) && (savePos2 != pos))	/* send back out if different */
		{
			moveSelect(pos);
			printf("%3d ", pos);
			plotPos(pos);
			savePos2 = savePos1;
			savePos1 = pos;
		}
	}

	serlClosePort(port);
	return 1;
}

void plotPos(int pos)
{
	int i, bar;

	int min = 68;
	int max = 200;

	bar = 74 * ((float)(pos-min)/(max-min));
	for(i = 0; i < bar; i++)
	{
		printf(" ");
  }
	printf("*\n");
}