//=============================================================================
// (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: DSCADScan.c   version 6.01
// Description: Sample program that demonstrates how to perform an AD scan
// Contributors: KL, James Moore, Bhavin Shah, Jonathan Miller
//=============================================================================

#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

// DOS
#ifdef __BORLANDC__
#include <conio.h>
#include <dos.h>
#include <stdlib.h>
#include <math.h>
#include <mem.h>
// diamond driver includes
//#include "../../../../current/dev/source/dscud.h"
#include "..\..\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>
#include <string.h>
// diamond driver includes
#include "dscud.h"


#ifdef _WRS_VXWORKS_5_X
#include <selectLib.h>
#define main HeliosDSCADScan
#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 HELIOS_DEFAULT_BASE_ADDRESS 0x280

// 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
DSCADSCAN dscadscan; // structure containing A/D scan settings
DSCSAMPLE* samples;  // sample readings
DFLOAT voltage;      // actual voltage
ERRPARAMS errorParams;  // structure for returning error code and error string
int intBuff;            // temp variable of size int
int i;       // counter for the samples
int k;       // counter for the channels

char input_buffer[20]; // Buffer to keep user character input
int user_input_reset = 0;
char temp_char = 0;

//=============================================================================
// 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.
//
//     STEPS TO FOLLOW:
//
//	     I. Driver Initialization
//	    II. Board Initialization
//	   III. AD Settings Initialization
//		IV. AD Scan Initialization
//	     V. Scanning and Output
//	    VI. Cleanup
//
//=============================================================================

int main(int argc, char ** argv  )
{

	//=========================================================================
	// I. DRIVER INITIALIZATION
	//
	//    Initializes the DSCUD library.
	//
	//    STEPS TO FOLLOW:
	//
	//	  1. initialize the driver, using the driver version for validation
	//=========================================================================

	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 HELIOS board. This function passes the various
	//	   hardware parameters to the driver and resets the hardware.
	//
	//     STEPS TO FOLLOW:
	//
	//	   1. set the board type to DSC_HELIOS for HELIOS board
	//	   2. set the base address to 0x280
	//	   3. set the interrupt level to 5
	//	   4. intialize and register the board with the driver, after which
	//		  the struct, dscb, now holds the handle for the board
	//=========================================================================

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

	dsccb.boardtype = DSC_HELIOS;

	// This program uses command-line arguments as a convenience; they are not required.
	if(argc == 1)
	{
	    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 );
	    }
	}
	else
	{
		sscanf(argv[1], "%hx", &dsccb.base_address );
	}
	dsccb.int_level = 5;

	if(dscInitBoard(DSC_HELIOS, &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.
	//
	//      STEPS TO FOLLOW:
	//
	//		1. set the polarity (must be BIPOLAR or UNIPOLAR)
	//		2. set the gain (must be GAIN_1, GAIN_2, GAIN_4, or GAIN_8)
	//		3. set the current channel to be sampled (must be between 0-15)
	//		4. initialize the AD conversion with these settings
	//=========================================================================

	/* PRE-FILLED EXAMPLE
	dscadsettings.range = RANGE_10;
	dscadsettings.polarity = BIPOLAR;
	dscadsettings.gain = GAIN_1;
	dscadsettings.current_channel = 0;
	*/

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

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

	if(argc <= 2)
	{
		printf( "Enter the polarity (0 for BIPOLAR, 1 for UNIPOLAR): " );
		scanf("%d", &intBuff);
	}else
	{
		sscanf(argv[2], "%d", &intBuff);
	}
	dscadsettings.polarity = (BYTE) intBuff;

	if(argc <= 3)
	{
		printf( "Enter 0 for Single-Ended, 1 for Differential: " );
		scanf("%d", &intBuff);
	}else
	{
		sscanf(argv[3], "%d", &intBuff);
	}
	dscadsettings.addiff = (BYTE) intBuff;

	// The Helios only has one physical 10V range.
	dscadsettings.range = RANGE_10;

	if(argc <= 4)
	{
		printf( "Enter the gain (0 for GAIN 1, 1 for GAIN 2, 2 for GAIN 4, 3 for GAIN 8): " );
		scanf("%d", &intBuff);
	}else
	{
		sscanf(argv[4], "%d", &intBuff);
	}
	dscadsettings.gain = (BYTE) intBuff;

	// This feature will load the A/D calibration settings from the EEPROM

	if(argc <= 5)
	{
		printf( "Load corresponding A/D Calibration settings? (0: no,1: yes): " );
		scanf("%d", &intBuff);
		dscadsettings.load_cal = intBuff;
	}
	else
	{
		sscanf(argv[5], "%d",&intBuff); 
	}
	dscadsettings.load_cal = (BYTE) intBuff;

	dscadsettings.current_channel = 0;

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

	//=========================================================================
	// IV. AD SCAN INITIALIZATION
	//
	//	   Initialize the structure containing the AD scan setting and allocate
	//	   memory for our buffer containing sample values.
	//
	//     STEPS TO FOLLOW:
	//
	//	   1. set low channel (must be between 0-15)
	//	   2. set high channel (must be between 0-15)
	//	   3. set gain (must be GAIN_1, GAIN_2, GAIN_4, or GAIN_8; certain
	//		  SMM boards use GAIN_1, GAIN_10, GAIN_100, and GAIN_1000)
	//	   4. allocate memory for the sample values
	//=========================================================================

	/* PRE-FILLED EXAMPLE
	dscadscan.low_channel = 3;
	dscadscan.high_channel = 6;
	dscadscan.gain = GAIN_1;
	*/

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

	printf ( "(Single-Ended/Differential (0-7))\n" );	
	if(argc <= 6)
	{
		printf( "Enter the lowest channel in the scan range (0-15): " );
		scanf("%d", &intBuff);
	}else
	{
		sscanf(argv[6], "%d",&intBuff);
	}
	dscadscan.low_channel = (BYTE) intBuff;

	if(argc <= 7)
	{
		printf( "Enter the highest channel in the scan range (0-15): " );
		scanf("%d", &intBuff);
		getchar();
	}else
	{
		sscanf(argv[7], "%d",&intBuff);
	}
	dscadscan.high_channel = (BYTE) intBuff;

	dscadscan.gain = dscadsettings.gain;

	samples = (DSCSAMPLE*)malloc( sizeof(DSCSAMPLE) * ( dscadscan.high_channel - dscadscan.low_channel + 1 ) );


	//=========================================================================
	// V. SCANNING AND OUTPUT
	//
	//    Perform the actual sampling and then output the results. To calculate
	//	  the actual input voltages, we must convert the sample code (which
	//	  must be cast to a short to get the correct code) and then plug it
	//	  into one of the formulas located in the manual for your board (under
	//	  "A/D Conversion Formulas"). For example, if you are using a bipolar
	//	  input range and 32-bit signed integers:
	//
	//	  Input voltage = (AD Code / 32768) x Full-Scale Voltage
	//
	//    STEPS TO FOLLOW:
	//
	//    1. get the samples from the board
	//    2. convert the results to a signed short to obtain a readout from
	//       -32768 to +32767 which scales to a range from -10V to +10V and
	//	     output the sample codes and the actual voltages to console
	//    3. calculate the input voltages by converting the sample code and
	//		 output the results
	//	  4. repeat steps 1-3 until a key is pressed
	//=========================================================================

	printf( "\nSCANNING AND OUTPUT\n" );

	do 
	{

	if ( temp_char == 'i' ) user_input_reset = 1;

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

		printf( "Enter 0 for Single-Ended, 1 for Differential: " );
		scanf("%d", &intBuff);
		dscadsettings.addiff = (BYTE) intBuff;

		// The Helios only has one physical 10V range.
		dscadsettings.range = RANGE_10;

		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;

		// This feature will load the A/D calibration settings from the EEPROM

		printf( "Load corresponding A/D Calibration settings? (0: no,1: yes): " );
		scanf("%d", &intBuff);
		dscadsettings.load_cal = (BYTE)intBuff;

		dscadsettings.current_channel = 0;

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

	//=========================================================================
	// IV. AD SCAN INITIALIZATION
	//
	//	   Initialize the structure containing the AD scan setting and allocate
	//	   memory for our buffer containing sample values.
	//
	//     STEPS TO FOLLOW:
	//
	//	   1. set low channel (must be between 0-15)
	//	   2. set high channel (must be between 0-15)
	//	   3. set gain (must be GAIN_1, GAIN_2, GAIN_4, or GAIN_8; certain
	//		  SMM boards use GAIN_1, GAIN_10, GAIN_100, and GAIN_1000)
	//	   4. allocate memory for the sample values
	//=========================================================================

	/* PRE-FILLED EXAMPLE
	dscadscan.low_channel = 3;
	dscadscan.high_channel = 6;
	dscadscan.gain = GAIN_1;
	*/

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

		printf ( "(Single-Ended/Differential (0-7))\n" );	
		printf( "Enter the lowest channel in the scan range (0-15): " );
		scanf("%d", &intBuff);
		dscadscan.low_channel = (BYTE) intBuff;
	
		printf( "Enter the highest channel in the scan range (0-15): " );
		scanf("%d", &intBuff);
		getchar();
		dscadscan.high_channel = (BYTE) intBuff;

		dscadscan.gain = dscadsettings.gain;
		user_input_reset = 0;
	}

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

		printf("\nChannel  A/D Code    Voltage\n");

		for( i = 0, k = dscadscan.low_channel; i < dscadscan.high_channel - dscadscan.low_channel + 1; i += 1, k += 1 )
		{
			if(dscadsettings.polarity)
				printf("%2d\t%6.3hd\t",k, dscadscan.sample_values[i] + 32768);
			else
				printf("%2d\t%6.3hd\t",k, dscadscan.sample_values[i] );
			if( dscADCodeToVoltage(dscb, dscadsettings, dscadscan.sample_values[i], &voltage) != DE_NONE)
			{
				dscGetLastError(&errorParams);
				fprintf( stderr, "dscADCodeToVoltage error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
				free(samples);
				return 0;
			}

			printf( "%6.3lfV\n", voltage );
		}

		printf("Press 'q' for quit; ENTER to continue; 'i' to start over: ");
	
	}
	while ( (temp_char = 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 memory allocated for sample values
	//	   2. free the driver resources
	//=========================================================================

	free( samples );

	// Setting single-ended mode, so as to avoid confusion in other demos.
	dscadsettings.addiff = 0;

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

	
	dscFree();

	printf( "\nDSCADScan completed.\n" );

	return 0;
} // end main()


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

	return 0;
}

#endif
