//=============================================================================
// (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.
//
// File: PulseWidthModulation.c   v5.9
// Desc: Sample program that demonstrates how to use pulse width modulation
// 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

// 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"
#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 HERCPulseWidthModulation
#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
ERRPARAMS errorParams; // structure for returning error code and error string
DSCPWM pwmstruct;  // structure for setting up the pulse width modulation 
int intBuff;	   // temp variable of size int
float floatBuff;   // temp variable of size float
double doubleBuff; // temp variable of size double
float dc;          // duty cycle
char option;

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. Program Pulse Width Modulation
//	    IV. Start Pulse Width Modulation
//		 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 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 (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. PROGRAM PULSE WIDTH MODULATION
	//
	//	    Program the pulse width modulation. There are two sets of functions 
	//		for programming the PWM. The dscPWM function takes in a structure 
	//		calculates the counter values based on the frequency and duty cycle.
	//		The second set of functions, dscPWMLoad, dscPWMConfig, dscPWMClear
	//		are for more advanced programmers who wish to PWM by themselves.
	//
	//=========================================================================

	memset(&pwmstruct, 0, sizeof(DSCPWM));

	printf("Enter the PWM circuit to use (0-3): ");
	scanf("%d", &intBuff);
	pwmstruct.pwm_circuit = (BYTE) intBuff;

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

	printf("Enter whether output is enabled (0 for FALSE, 1 for TRUE): ");
	scanf("%d", &intBuff);
	pwmstruct.output_enab = (BOOL) intBuff;

	printf("Enter the output frequency in hertz: ");
	scanf("%lf", &doubleBuff);
	pwmstruct.output_freq = (DFLOAT) doubleBuff;

	printf("Enter the duty cycle in % (range 0-100): ");
	scanf("%f", &floatBuff);
	pwmstruct.duty_cycle = (FLOAT) floatBuff;

	dc = floatBuff ;
	
	getchar();

	//=========================================================================
	// IV. START PULSE WIDTH MODULATION
	//
	//    Start pulse width modulation
	//
	//=========================================================================

	printf( "\nStarting Pulse Width Modulation\nEnter 'q' to quit\n" );
	
	do {
		if( dscPWMFunction(dscb, &pwmstruct) != DE_NONE)
		{
			dscGetLastError(&errorParams);
			fprintf( stderr, "dscPWMFunction error: %s %s\n", dscGetErrorString(errorParams.ErrCode), errorParams.errstring );	
			return 0;		
		}

		//note, for PWM signals to output please set base + 12, bit 4, DIOCTR0 to 1. 

		printf("Enter 'q' to quit\n");
		printf("Enter 'u' to increase duty cycle by 3%%,\n'd' to decrease duty cycle by 3%% ");

		option = getchar();
		
		if( option == 'u')
			dc += 3.0f;
		else if( option == 'd')
			dc -= 3.0f;

		pwmstruct.duty_cycle = dc;

	} while ( option != 'q');
	//=========================================================================
	// 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( "\nPulse Width Modulation completed.\n" );

	return 0;
} // end main()



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

	return 0;
}

#endif
