//=============================================================
// (c) Copyright 2005 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.
//
//	DSCADAutoCal.c	v5.9
//	Sample program that does the AD auto calibration and verifies
//	Created by  KL
//=============================================================

#include <stdio.h>

#ifdef _WIN32
#ifndef _WIN32_WCE
#include <conio.h>
#endif
#include <windows.h>
#include <stdlib.h>
#include <math.h>
// diamond driver includes
#include "dscud.h"
#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 HERCDSCADAutoCal
#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

// var declarations
BYTE result;  // returned error code
DSCB dscb;    // handle used to refer to the board
DSCCB dsccb;  // structure containing board settings
WORD sample;  // sample reading
DSCAUTOCAL dscautocal; // structure containing auto-calibration settings
ERRPARAMS errorParams; // structure for returning error messages
int intBuff;	       // integer variable
float floatBuff;       // float variable

int i;	               // miscellaneous counter

//=============================================================================
// 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 HERCULES board. This function passes the various
	//	   hardware parameters to the driver and resets the hardware.
	//
	//=========================================================================

	printf( "\nHERCULES BOARD INITIALIZATION:\n" );

	dsccb.boardtype = DSC_HERCEBX;
	
	printf("Enter the base address in hex (default 0x240): ");
	scanf("%hx", &dsccb.base_address );

	dsccb.int_level = 5;

	if(dscInitBoard(dsccb.boardtype, &dsccb, &dscb)!= 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 AD autocal settings. 
	//
	//=========================================================================

	/* PRE-FILLED EXAMPLE
	dscautocal.adrange = 0xFF;
	dscautocal.boot_adrange = 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);
		dscautocal.adrange = (BYTE) intBuff;

		printf( "Enter the AD boot range (0-7): " );
		scanf( "%d", &intBuff);
		dscautocal.boot_adrange = (BYTE) intBuff;

		getchar();

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

		printf( "\nAUTO-CALIBRATION:\n" );
		printf( "Starting AD auto-calibration...This will take a moment\n" );

		if( dscADAutoCal( dscb, &dscautocal ) != 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 8 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" );

		for( i = 0; i < 8; i++ )
		{
			dscautocal.adrange = i;
			if( ( result = dscADCalVerify( dscb, &dscautocal ) ) != DE_NONE )
			{
				dscGetLastError(&errorParams);
				fprintf( stderr, "dscADCalVerify error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );		
				return 0;
			}

			printf( "Configuration Mode: %d, Offset Error: %10.3f, Gain Error: %10.3f\n", i, dscautocal.ad_offset, dscautocal.ad_gain ); 

			if ( fabs( dscautocal.ad_offset ) > 2 || 
				 fabs( dscautocal.ad_gain ) > 2 )
				printf( "Value for offset or gain exceeded specified tolerance\n" );
			else printf( "Values for offset and gain met specified tolerance\n" );
		}

			printf("\nEnter 'q' to exit or any key 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( "\nDSCADAutoCal completed. \n" );
	return 0;
} // end main()



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

	return 0;
}

#endif
