//========================================================================
// (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.
//
//	DSCADAutoAC.c	v5.9
//	Sample program that does AD auto-autocal and verifies correctness
//	Created by  KL
//========================================================================

#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 DMM32XDSCADAutoAC
#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
DSCADSETTINGS dscadsettings;	// structure containing A/D conversion settings
DSCAUTOCAL dscautocal;			// structure containing auto-calibration settings
DSCAACSTATUS status;			// structure that reads back AAC status
ERRPARAMS errorParams; // structure for returning error code and error string
int i;	     // miscellaneous counter
int intBuff; // temporary variable with size int

//=============================================================================
// 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. AD SETTINGS INITIALIZATION
//	    IV. Auto 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 DMM-32X-AT board. This function passes the various
	//	   hardware parameters to the driver and resets the hardware.
	//
	//=========================================================================

	printf( "\nDMM32X BOARD INITIALIZATION:\n" );
	
	printf("Enter the base address (default 0x300) : ");
	scanf("%hx", &dsccb.base_address );

	dsccb.int_level = 3;

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


	//=========================================================================
	// III. AD SETTINGS INITIALIZATION
	//
	//	    Initialize the structure containing the AD conversion settings and
	//		then pass it to the driver.
	//
	//=========================================================================

	/* PRE-FILLED EXAMPLE
	dscadsettings.range = RANGE_10;
	dscadsettings.polarity = BIPOLAR;
	dscadsettings.gain = GAIN_1;
	dscadsettings.load_cal = (BYTE)TRUE;
	dscadsettings.current_channel = 0;
	dscadsettings.scan_interval = SCAN_INTERVAL_10; // allows the channel switching to be 10 microseconds
	*/

	printf( "\nAD SETTINGS INITIALIZATION\n" );

	memset(&dscadsettings, 0, sizeof(DSCADSETTINGS));

	printf( "Enter the range (0 for 5V range, 1 for 10V range): " );
	scanf("%d", &intBuff);
	dscadsettings.range = (BYTE) intBuff;

	printf( "Enter the polarity (0 for BIPOLAR, 1 for UNIPOLAR): " );
	scanf("%d", &intBuff);
	dscadsettings.polarity = (BYTE) intBuff;

	printf( "Enter the gain (0 for GAIN 1, 1 for GAIN 2, 2 for GAIN 4, 3 for GAIN 8): " );
	scanf("%d", &intBuff);
	dscadsettings.gain = (BYTE) intBuff;

	printf( "Enter the load calibration flag (0 for FALSE, 1 for TRUE): " );
	scanf("%d", &intBuff);
	dscadsettings.load_cal = (BYTE) intBuff;

	dscadsettings.current_channel = 0;

	printf("Enter the scan interval \n(0 for 20 microsec, 1 for 15 microsec, 2 for 10 microsec, 5 for 4 microsec): ");
	scanf("%d", &intBuff);
	dscadsettings.scan_interval = (BYTE) intBuff;

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

	//=========================================================================
	// IV. AUTO AUTO-CALIBRATION
	//
	//     Perform the actual AD auto-calibration of the board. This process 
	//     requires the following steps:
	//
	//     1. Release the A/D hold bit
	//     2. Manually force a A/D auto autocal execution
	//     3. Check status bit and wait until A/D is not active
	//
	//=========================================================================

		printf( "\nAUTO AUTO-CALIBRATION:\n" );
		printf( "Starting AD auto-calibration...\n" );

		
		if( dscAACCommand(dscb, AAC_CMD_REL) != DE_NONE ) //release the A/D hold bit
		{
			dscGetLastError(&errorParams);
			fprintf( stderr, "dscAACCommand error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
			return 0;
		}
	

		if( dscAACCommand(dscb, AAC_CMD_TRIG) != DE_NONE ) //force a A/D auto autocalibration
		{
			dscGetLastError(&errorParams);
			fprintf( stderr, "dscAACCommand error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
			return 0;
		}

		memset(&status, 0, sizeof(status) );

		i=0;
		do{
			if( dscAACGetStatus(dscb, &status) != DE_NONE ) //read back the status of the autocalibration
			{
				dscGetLastError(&errorParams);
				fprintf( stderr, "dscAACCommand error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
				return 0;
			}

			dscSleep(10);
			i++;
		
		} while( (i < 100) && (status.aac_active) );

	
	//=========================================================================
	// V. CALIBRATION VERIFICATION
	//
	//	  To verify that the auto-calibration was successfully completed, you
	//	  should run dscADCalVerify() 
	//
	//=========================================================================

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

		i = (dscadsettings.range << 3) | (dscadsettings.polarity << 2) | dscadsettings.gain;

		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: %9.3f, Gain Error: %9.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" );


	//=========================================================================
	// 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( "\nDSCADAutoAC completed. \n" );
	return 0;
} // end main()



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

	return 0;
}

#endif