//========================================================================
// (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.
//
//	DSCDAWave.c	v5.9
//	Sample program that performs D/A wave form generation using
//	the on-board circuit and D/A buffer
//
//	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 DMM32XDSCDAWave
#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
DSCWGCONFIG config;
ERRPARAMS errorParams; // structure for returning error code and error string
int i;	     // miscellaneous counter
int intBuff; // temporary variable with size int
long longBuff; // temporary variable with size long

//=============================================================================
// 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. D/A Wave Form Initialization
//	    IV. D/A Wave Start
//	     V. 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. D/A WAVE FORM INITIALIZATION
	//
	//		Initialize the D/A wave form generator. The following steps initialize
	//      the D/A settings:
	//
	//      1. obtain user input to buffer size/number of D/A conversion to output
	//      2. obtain user input to number D/A channels to output
	//      3. obtain user input to D/A wave form clock source
	//      4. obtain user input to D/A conversion code
	//      5. initialize D/A wave form
	//
	//============================================================================


	printf("\nD/A WAVE FORM INITIALIZATION\n\n");

	printf("Enter number of D/A conversions (64, 128, 256, etc to 1024): "); 
	scanf("%d", &intBuff);

	config.depth = (DWORD)intBuff; //number of D/A conversions

	printf("Enter number of D/A channels to output (1, 2, and 4): "); 
	scanf("%d", &intBuff);

	config.ch_per_frame = (DWORD)(intBuff - 1); //channels per frame. Refer to defines WG_CH_PER_FRAME_X

	printf("Enter D/A input src (0 manual, 1 Ctr 0, 2 Ctr 1&2, 3 external): "); 
	scanf("%d", &intBuff);

	config.source = (DWORD)intBuff; //input source. Refer to defines WG_SRC_XXX

	if( dscWGCommand(dscb, WG_CMD_RESET) != DE_NONE ) //reset the pointer to the D/A buffer
	{
		dscGetLastError(&errorParams);
		fprintf( stderr, "dscWGCommand error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
		return 0;
	}

	
	if( dscWGConfigSet(dscb, &config) != DE_NONE ) //initialize the configuration
	{
		dscGetLastError(&errorParams);
		fprintf( stderr, "dscWGConfigSet error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
		return 0;
	}


	//============================================================================
	// IV. D/A WAVE START
	//
	//     Program the D/A conversion code into D/A buffer and start D/A wave 
	//     form generator
	//
	//=============================================================================

	printf("Enter D/A conversion value (0-4095): "); 
	scanf("%d", &intBuff);


	for (i=0; i<config.depth; i++)
	{
		//the following stores the D/A conversion value into the D/A buffer. 
		if( dscWGBufferSet(dscb, i, (DSCDACODE)intBuff, i%(config.ch_per_frame + 1), 1) != DE_NONE )
		{
			dscGetLastError(&errorParams);
			fprintf( stderr, "dscWGBufferSet error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
			return 0;
		}
	}

	if( dscWGCommand(dscb, WG_CMD_START) != DE_NONE ) //start D/A conversions
	{
		dscGetLastError(&errorParams);
		fprintf( stderr, "dscWGCommandSet error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );
		return 0;
	}


	/*  //////////////////////////////////////
		// the following demonstrates how 
		// setup and run the D/A input sources
		///////////////////////////////////////
	
	if ( config.source == WG_SRC_MANUAL ) 
	{
		dscWGCommand(dscb, WG_CMD_INC);	//this will increment buffer and force D/A output. 
										//it will output config.ch_per_frame number of conversions
										//per increment
	}
	else if( config.source == WG_SRC_CTR0 ) 
	{
		printf("Enter ctr 0 rate (eg. 1000): "); 
		scanf("%d", &longBuff);
		
		dscCounterSetRateSingle(dscb, (float) longBuff, COUNTER_0);
	}
	else if( config.source == WG_SRC_CTR12 )
	{
		printf("Enter ctr 0 rate (eg. 1000): "); 
		scanf("%d", &longBuff);
		
		dscCounterSetRateSingle(dscb, (float) longBuff, COUNTER_1_2);
	}
	*/


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



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

	return 0;
}

#endif