/************************************************
 * Universal Library Demo Program		*
 *                                              *
 * James Tandon, Nilesh Modi, 10/29/2004        *
 * 					        *
 ************************************************/

/* Include files */
#include <stdio.h>
#include <time.h>
#include <conio.h>
#include "cbw.h"

void wait(int ticks);

void wait(ticks)
{	clock_t t1;

	t1 = clock();
	while (clock() - t1 < ticks) ;
}

void main()
{	// Local Variables
	const int BoardNum = 0;
        char cmd = 0;
        int count = 0;
	float RevLevel = (float) CURRENTREVNUM;
	clock_t t1, t2;
    USHORT portA_val, portCL_val;
	int done;
        int errorcode;

	// I/O Board Initialization
	cbDeclareRevision(&RevLevel);
	cbErrHandling(PRINTALL, STOPALL);
	errorcode=cbDConfigPort(BoardNum, FIRSTPORTA, DIGITALOUT);
        if(errorcode!=0)
                printf("ERROR");

        printf("Lab 4 Demo program (press Q to quit)\n\n");

        printf("Keys:\n");
        printf("\tClock\t(bit 0 auto)\n");
        printf("0\tReset\t(bit 1)\n");
        printf("I\tLights\t(bit 2)\n");
        printf("L\tLeft\t(bit 3)\n");
        printf("R\tRight\t(bit 4)\n");
        printf("h\tHazard\t(bit 5)\n");
        printf("B\tBrakes\t(bit 6)\n\n");
 	// Run until some key hit
 	while (toupper(cmd) != 'Q') {
                if (kbhit()) { // get key command
                        cmd = getch();
                        switch (toupper(cmd)) {
                        case '0': portA_val ^= 0x2; break; // reset
                        case 'I': portA_val ^= 0x4; break; // lights
                        case 'L': portA_val ^= 0x8; break; // left
                        case 'R': portA_val ^= 0x10; break; // right
                        case 'H': portA_val ^= 0x20; break; // hazard
                        case 'B': portA_val ^= 0x40; break; // brake
                        }
                }

		// Wait for 1/5th second
		wait(CLOCKS_PER_SEC / 5);

                portA_val ^= 0x1; // clock
                printf("Output: %2xh\tClock=%d\tCycle=%d\r",portA_val,portA_val&0x1,count++);
               
		// Output current status to FPGA board
		errorcode=cbDOut(BoardNum, FIRSTPORTA, portA_val);
                if(errorcode!=0)
                printf("ERROR");
	}
        printf("\n\nQuitting...\n\n");
}

