#include "ADC.h"

#include <limits>

namespace
{
	const int8_t calibrationNumValues = sizeof(ADC_calibration)/sizeof(ADC_calibration[0]);
}

ADC::ADC(int8_t gpioPin)
	: pin_(gpioPin)
{
}

float ADC::read()
{
	int16_t rawValue = analogRead(pin_);

	for(int8_t i = 1; i < calibrationNumValues; ++i)
	{
		if(i == calibrationNumValues - 1 || ADC_calibration[i].ADC_Value >= rawValue)
		{
			const auto& p = ADC_calibration[i - 1];
			const auto& n = ADC_calibration[i];
			return (float)(rawValue - p.ADC_Value) / (float)(n.ADC_Value - p.ADC_Value) * (n.MeasuredVoltage - p.MeasuredVoltage) + p.MeasuredVoltage;
		}
	}

	// This should never happen if the calibration array contains at least 2 entries
	return -std::numeric_limits<float>::max();
}
