#include <stdio.h>
#include <unistd.h>

#include "../hubolib.h"

using namespace HuboLib;

/*
Compile and link: 
	g++ AnalogInput3.cpp -L../ -lhubo -lpthread -lrt -o AnalogInput3.out
Run:
	sudo ./AnalogInput3.out
Purpose:
	Lets see how much we can use oversampling in order to increase the resolution of our ADC sample value.
*/

int main(void)
{
	// Initialize the library once in your program.
	if (!Initialize())
	{
		printf ("Error: Initialize\n");
		return 1;
	}
	
	// Define channel 0 to be oversampled 40 times (set to 40) all other channels (set to 0) are not read from the ADC.
	unsigned short overSampling[MAX_MCP3x08_CHANNELS] = { 40, 0, 0, 0, 0, 0, 0, 0 };
	Set_MCP3x08_Oversampling (overSampling);
	
	int 			channel = 0;
	unsigned long 	adcCount; 
	double	 		volt;
	for (int i=0; i<20; i++)
	{
		// Read channel 0 and output its value.
		if (Get_AI_Channel (channel, adcCount, volt))
		{
			printf ("Channel=%d   ADC count=0x%02lX   Volts=%lf\n", channel, adcCount, volt);
		}
		else 
		{
			printf ("Error: Get_AI_Channel\n");
		}

		usleep(1000);
	}

	// Let's try 41 oversamples for channel 0.
	unsigned short overSampling2[MAX_MCP3x08_CHANNELS] = { 41, 0, 0, 0, 0, 0, 0, 0 };
	if (!Set_MCP3x08_Oversampling (overSampling2))
		printf ("41 oversamples for channel 0 failed.\n");

	// Ok, let's then try to oversample channel 0 and channel 1 for 40 times.
	unsigned short overSampling3[MAX_MCP3x08_CHANNELS] = { 40, 40, 0, 0, 0, 0, 0, 0 };
	if (!Set_MCP3x08_Oversampling (overSampling3))
		printf ("40 oversamples for channel 0 and 40 oversamples for channel 1 failed.\n");
	
	// Well, how many times can I the oversample a channel?
	// This depends on the following things:
	// - the number of channels to be oversampled,
	// - the number of oversamples for each channel and
	// - the cycle time which should be kept.
	// Of cause it also depends on the CPU load of the Raspi...
	
	// Test 30 oversamples for channel 0 and 10 for channel 1.
	unsigned short overSampling4[MAX_MCP3x08_CHANNELS] = { 30, 10, 0, 0, 0, 0, 0, 0 };
	if (Set_MCP3x08_Oversampling (overSampling4))
		printf ("30 oversamples for channel 0 and 10 oversamples for channel 1 worked.\n");

	// Test 8 oversamples for channel 0, 12 for channel 1, 10 for channel 5 and 10 for channel 7.
	unsigned short overSampling5[MAX_MCP3x08_CHANNELS] = { 8, 12, 0, 0, 0, 10, 0, 10 };
	if (Set_MCP3x08_Oversampling (overSampling5))
		printf ("Oversampling 8/12/10/10 for several channels worked.\n");
		
	// Conclusion: For the given cycle time we can have a total of 40 oversamples shared amongst 
	// all of our 8 analog input channels.
	
	// Free library resources.
	Uninitialize();
	
	return 0;
}
