//=============================================================================
// (c) Copyright 2009 Diamond Systems Corporation. Use of this source code
// is subject to the terms of Diamond Systems' Software License Agreement.
// Diamond Systems provides no warranty of proper performance if this
// source code is modified.
//
// File: DSCDAAutoCal.c   version 6.01
// Description: Performs a software-controlled D/A Calibration
//              (A/D Calibration should be completed first), and verifies
//              Least Significant Bit (LSB) error falls within user-defined tolerance.
// Contributors: KL, James Moore
//=============================================================================

#include <stdio.h>

#ifdef _WIN32
#ifndef _WIN32_WCE
#include <conio.h>
#endif

#include <windows.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
// diamond driver includes
#include "dscud.h"
#endif


#ifdef _WIN32_WCE

#include <string.h>
#include <Winsock2.h>

static int kbhit()
{
	int i;
	int result=0;

	
	result |= GetAsyncKeyState(VK_RETURN);
	result |= GetAsyncKeyState(VK_SPACE);

	if (result != 0)
	{
		getchar();
		return 1;
	}

	//number keys, 0-9
	for (i=48; i<=57; i++)
		result |= GetAsyncKeyState(i);

	if (result != 0)
	{
		getchar();
		return 1;
	}

	//capital character keys, A-Z
	for (i=65; i<=90; i++)
		result |= GetAsyncKeyState(i);

	if (result != 0)
	{
		getchar();
		return 1;
	}

	//lower case keys, a-z
	for (i=97; i<=122; i++)
		result |= GetAsyncKeyState(i);

	if (result != 0)
	{
		getchar();
		return 1;
	}

	return result;
}

#endif


// DOS
#ifdef __BORLANDC__
#include <conio.h>
#include <dos.h>
#include <stdlib.h>
#include <math.h>
// diamond driver includes
#include "../../../../current/dev/source/dscud.h"
#endif

// Linux and QNX
#if defined(linux) || defined(__QNXNTO__) || defined(_WRS_VXWORKS_5_X)
#include <stdlib.h>
#include <math.h>
#include <time.h>
// diamond driver includes
#include "dscud.h"

#ifdef _WRS_VXWORKS_5_X
#include <selectLib.h>
#define main HELIOSDSCADAutoCal
#else
#include <sys/time.h>
#endif


static int kbhit()
{
	struct timeval timeout;
	fd_set rfds;

	timeout.tv_sec = 0;
	timeout.tv_usec = 0;

	FD_ZERO(&rfds);
	FD_SET(0, &rfds);

	if ( select(0+1, &rfds, NULL, NULL, &timeout) > 0 )
		return getchar();

	return 0;
}
#endif

#define OFFSET_LSB_TOLERANCE 2
#define GAIN_LSB_TOLERANCE 2

// var declarations
BYTE result; // returned error code
DSCB board;  // handle used to refer to the board
DSCCB dsccb; // structure containing board settings
DSCADSETTINGS dscadsettings; // structure containing A/D conversion settings
DSCDACALPARAMS dacalparams; // structure containing auto-calibration settings
ERRPARAMS errorParams; // structure for returning error code and error string
int i;	     // miscellaneous counter
int intBuff; // temporary variable with size int

#define HELIOS_DEFAULT_BASE_ADDRESS 0x280

char input_buffer[20]; // Buffer for parsing user character input.

//=============================================================================
// Name: main()
// Desc: Starting function that calls the driver functions used
//
//		 NOTE: By convention, you should capture the BYTE return value for each
//		 driver API call, and check the error code.
//
//	     I. Driver Initialization
//	    II. Board Initialization
//	   III. AutoCal Settings Initialization
//	    IV. Auto-Calibration
//		 V. Calibration Verification
//	    VI. Cleanup
//
//=============================================================================

int main( void )
{
	//=========================================================================
	// I. DRIVER INITIALIZATION
	//
	//    Initializes the DSCUD library.
	//
	//=========================================================================

	if( dscInit( DSC_VERSION ) != DE_NONE )
	{
		dscGetLastError(&errorParams);
		fprintf( stderr, "dscInit error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
		return 0;
	}

	//=========================================================================
	// II. BOARD INITIALIZATION
	//
	//	   Initialize the AthenaII board. This function passes the various
	//	   hardware parameters to the driver and resets the hardware.
	//
	//=========================================================================

	printf( "\nHELIOS BOARD INITIALIZATION:\n" );
	
	printf ( "Enter the base address (default 0x280, hit ENTER) : " );
	fgets ( input_buffer, 20, stdin );
	if ( input_buffer[0] == '\n' )
	{
		dsccb.base_address = HELIOS_DEFAULT_BASE_ADDRESS;
	}
	else
	{
		sscanf ( input_buffer, "%hx", &dsccb.base_address );
	}

	dsccb.int_level = 5;

	if(dscInitBoard(DSC_HELIOS, &dsccb, &board)!= DE_NONE)
	{
		dscGetLastError(&errorParams);
		fprintf( stderr, "dscInitBoard error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
		return 0;
	}


	//=========================================================================
	// III. AUTOCAL SETTINGS INITIALIZATION
	//
	//		Initialize the structure containing the DA autocal settings. 
	//		Set dacalparams.darange_calibrate for the MODE to calibrate. Set boot range
	//		for the mode the board to be in upon power up.
	//
	//=========================================================================

	/* PRE-FILLED EXAMPLE
	dacalparams.darange_calibrate = 0xFF;
	dacalparams.boot_darange = 0;
	*/

	do {
		printf( "\n\nAUTOCAL SETTINGS INITIALIZATION:\n" );

		printf( "Enter the range to calibrate (0-7) or 255 to calibrate all ranges: " );
		scanf( "%d", &intBuff);
		dacalparams.darange_calibrate = (BYTE) intBuff;

		printf( "Enter the DA range to boot up in (0-7): " );
		scanf( "%d", &intBuff);
		dacalparams.boot_darange = (BYTE) intBuff;

		getchar();

	//=========================================================================
	// IV. AUTO-CALIBRATION
	//
	//	   Perform the actual DA auto-calibration of the board.
	//
	//=========================================================================

		printf( "\nAUTO-CALIBRATION:\n" );
		printf( "Starting DA auto-calibration...this will take a few seconds\n" );

		if( dscDAAutoCal( board, &dacalparams ) != DE_NONE )
		{
			dscGetLastError(&errorParams);
			fprintf( stderr, "dscADAutoCal error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
			return 0;
		}

		printf( "Completed\n\n" );

	//=========================================================================
	// V. CALIBRATION VERIFICATION
	//
	//	  To verify that the auto-calibration was successfully completed, you
	//	  should run dscADCalVerify() on the 15 possible configuration modes to
	//	  ensure that the gain and offset errors meet a specified tolerance (2
	//	  in this example). You can obtain the possible combinations by writing
	//	  a for loop and bit-wise operations similar to those used below.
	//
	//=========================================================================

		printf( "\nCALIBRATION VERIFICATION:\n" );

if ( dacalparams.darange_calibrate == 255 )
{
		for( i = 0; i < 8; i++ )
		{
			if ( i == 2 || i == 3 || i == 7 )
			{
				continue;
			}

			dacalparams.darange_calibrate = i;
			if( ( result = dscDACalVerify( board, &dacalparams) ) != DE_NONE )
			{
				dscGetLastError(&errorParams);
				fprintf( stderr, "dscDACalVerify error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
				return 0;
			}

			printf( "Configuration Mode: %d, Offset Error: %9.3f, Gain Error: %9.3f\n", i, dacalparams.offset, dacalparams.gain ); 

			if ( fabs( dacalparams.offset ) > OFFSET_LSB_TOLERANCE || 
				 fabs( dacalparams.gain ) > GAIN_LSB_TOLERANCE )
				printf( "Value for offset or gain exceeded specified tolerance\n" );
			else printf( "Values for offset and gain met specified tolerance\n" );
		}
}
else
{
			if( ( result = dscDACalVerify( board, &dacalparams) ) != DE_NONE )
			{
				dscGetLastError(&errorParams);
				fprintf( stderr, "dscDACalVerify error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
				return 0;
			}

			printf( "Configuration Mode: %d, Offset Error: %9.3f, Gain Error: %9.3f\n", dacalparams.darange_calibrate , dacalparams.offset, dacalparams.gain ); 

			if ( fabs( dacalparams.offset ) > OFFSET_LSB_TOLERANCE || 
				 fabs( dacalparams.gain ) > GAIN_LSB_TOLERANCE )
				printf( "Value for offset or gain exceeded specified tolerance\n" );
			else printf( "Values for offset and gain met specified tolerance\n" );

}
			printf("\nPress 'q' to exit or ENTER to continue : ");
	} while( getchar() != 'q');


	//=========================================================================
	// VI. CLEANUP
	//
	//	   Cleanup any remnants left by the program and free the resources used
	//	   by the driver.
	//
	//     STEPS TO FOLLOW:
	//
	//	   1. free the driver resources
	//=========================================================================

	dscFree();

	printf( "\nDSCDAAutoCal completed. \n" );
	return 0;
} // end main()



#ifdef _WIN32_WCE
int WINAPI WinMain(	HINSTANCE hInstance,
					HINSTANCE hPrevInstance,
					LPTSTR    lpCmdLine,
					int       nCmdShow)
{
	main();

	return 0;
}

#endif
