/*
 
  Original Author: David Souder - souder.d@gmail.com
  Date de dernière modification : 27/05/2016
  
*/

#ifndef Duinoedu_Utility_ANALOG_H
#define Duinoedu_Utility_ANALOG_H

//==== ANALOG WRITE AVR/ESP8266/ESP32
class AnalogWriteSmart{
	public :
	static void set(uint8_t _pin, uint16_t _freq=12000, uint8_t _resolution=8){
		#if   defined(__AVR__) || defined(ESP8266)     
			pinMode(_pin, OUTPUT);
		#elif defined(ESP32)
			uint8_t channel = translateInChanel(_pin);
			ledcAttachPin(_pin, channel); // Channel = pin par choix 
			ledcSetup(channel, _freq, _resolution); // channel, 12 kHz PWM, 8-bit resolution
		#endif
	}	
	
	static void action(uint8_t _pin, uint16_t _pwm){
		uint8_t channel = translateInChanel(_pin);
		#if   defined(__AVR__) || defined(ESP8266) 
			analogWrite(_pin, _pwm);
		#elif defined(ESP32)
			ledcWrite(channel, _pwm); // Channel, valeur PWM
		#endif
	}
	
	static uint8_t translateInChanel(uint8_t _pin){
	// Permet de convertir des pins D2,D3... en n de canal. On a 15 canaux et certains n° de broche sont associés à un n° plus grand que 15.
		
		int8_t channel=-1;
		#if defined(ESP32)
		switch (_pin){
			case D0: channel=0;break;
			case D1: channel=1;break;
			case D2: channel=2;break;
			case D3: channel=3;break;
			case D4: channel=4;break;
			case D5: channel=5;break;
			case D6: channel=6;break;
			case D7: channel=7;break;
			case D8: channel=8;break;
			case D9: channel=9;break;
			case D10:channel=10;break;
			case D11:channel=11;break;
			case D12:channel=12;break;
			case D13:channel=13;break;
			//case D14:channel=14;break;
		}
		#endif
	return channel;
	}

};
#endif