How do you plan to solve it?
I am tired buddy, It`s night late but my code works just fine hahah
I used a mechanical switch to select the voltage reference thus the voltage range, also I developed a simple function to average and smooth the final value
/*Paste your code here*/
const char CincoVolts = 3;
const char UnVolt = 2;
const char AnalogPin = A0;
int estado5 = HIGH;
int estado1 = LOW;
int adc = 0;
float tension = 0.0;
int muestras = 20;
float resultado = 0.0;
byte referenciaActual = 0;
void descarte_lecturas(void);
void lecturas1v(float Vref);
void lecturas5v(float Vref);
float promedio(int muestras, float Vref);
void setup(){
Serial.begin(9600);
pinMode(CincoVolts, INPUT_PULLUP);
pinMode(UnVolt, INPUT_PULLUP);
delay(5);
}
void loop(){
estado5 = digitalRead(CincoVolts);
estado1 = digitalRead(UnVolt);
if(estado5 == HIGH && estado1 == LOW){
if(referenciaActual !=1){ // Configuramos la referencia a 5v y deshechamos las primeras 10 lecturas
analogReference(DEFAULT);
descarte_lecturas();
referenciaActual = 1;
}
lecturas5v(5);
}
else{
if(referenciaActual !=2){ // Configuramos la referencia a 1.1v y deshechamos las primeras 10 lecturas
analogReference(INTERNAL);
descarte_lecturas();
referenciaActual = 2;
}
lecturas1v(1.1);
}
}
void descarte_lecturas(void){
// Funcion empleada para leer y descartar las primeras 10 lecturas tras cambiar la referencia de tension del ADC
for(int i = 0; i <10; i++){
analogRead(AnalogPin);
delay(5);
}
}
void lecturas1v(float Vref){
resultado = promedio(muestras, Vref);
Serial.print("Ref 1.1V Tension = ");
Serial.print(resultado, 4);
Serial.println(" V");
delay(400);
}
void lecturas5v(float Vref){
resultado = promedio(muestras, Vref);
Serial.print("Ref 5V Tension = ");
Serial.print(resultado, 4);
Serial.println(" V");
delay(400);
}
float promedio(int muestras, float Vref){
float suma = 0.0;
float promedio = 0.0;
for(int i = 0; i<muestras; i++){
adc = analogRead(AnalogPin);
tension = (adc * (Vref / 1023));
suma += tension;
delay(10); }
promedio = (suma / muestras);
return promedio;
}
Add video of output (know more)
Add a photo of your hardware showing the output.
