/*
	MG2ADC2.C

	Sample program to read data from ADC of the BL15xx/MicroG2.

	Each of the first four channels of the ADC is read for 20 times at ~ 2.5ms
	interval. The average readings and their standard deviations are displayed
	to the STDIO window.
*/

int get_average(int *buf, int count);
float get_stddev(int *buf, int count);

main()
{
int data0, data1, data2, data3;
float sig0, sig1, sig2, sig3;
unsigned int divider;
		
	int data[20];
	
	printf("Toggle F4 (DOS only) to make keyboard input active as STDIO.\n");
	printf("Hit any key to read A/D data from ADC4 board.\n");

	// get ~2.5ms sampling period 
	divider = (0.0025 * sysclock() * 1200)/ 20;

	for(;;)
	{
		while(!kbhit())					// wait for key from the STDIO
		{
			hitwd();							// hit the watchdog
			runwatch();               	// watch window
		}
		getchar();                                // get the key
		mg2adc_sample(0, 20, data, divider);  		// read chan 0 for 20 samples
		data0 = get_average(data, 20);            // get the average
		sig0  = get_stddev(data, 20);
		mg2adc_sample(1, 20, data, divider);  		// read chan 1 for 20 samples
		data1 = get_average(data, 20);            // get the average
		sig1  = get_stddev(data, 20);
		mg2adc_sample(2, 20, data, divider);  		// read chan 2 for 20 samples
		data2 = get_average(data, 20);            // get the average
		sig2  = get_stddev(data, 20);
		mg2adc_sample(3, 20, data, divider);  		// read chan 3 for 20 samples
		data3 = get_average(data, 20);            // get the average
		sig3  = get_stddev(data, 20);
		// Note: function mg2adc_sample(...) turns off the interrupt for the whole
		//       duration of data sampling.
		printf("\nADC Channels 0-3.\n");
		printf("Average data and standard deviations\n");
		printf("chan 0 >> %6d, %6.3f\n",	data0, sig0);
		hitwd();							// hit the watchdog
		printf("chan 1 >> %6d, %6.3f\n",	data1, sig1);
		printf("chan 2 >> %6d, %6.3f\n",	data2, sig2);
		printf("chan 3 >> %6d, %6.3f\n",	data3, sig3);
	}
}

// int get_average(int *data, int count)
// Computes the average of "count" number of readings for data array.
int get_average( int *data, int count)
{
	long sum;
	int i;

	sum = 0L;
	for(i=0;i<count;i++)
	{
		sum = sum + (long) data[i];
	}

	if(count == 0) return 0;
	
	return (int) (sum/count);
}
	
		
//float get_stddev(int *data, int count)
//Computes the standard deviation of "count" number of readings for data array.
float get_stddev( int *data, int count)
{
	long  sum;
	long  sigsqr;
	int i;

	sum = sigsqr = 0L;

	for(i=0;i<count;i++)
	{
		sum = sum + (long) data[i];
	}

	sum = sum / count;
	
	for(i=0;i<count;i++)
	{
		sigsqr = sigsqr + ( (long)data[i] - sum)*((long)data[i] - sum);
	}

	if( count == 0) return 0.0;
	return sqrt((float) sigsqr/count);
}
 
