#include <cmath>
int inPin = 17;
double result=0;
double readSensor(int PIN)
{
int32_t measurement[10];
double scaled[10];
double average=0; //Initialization of the variable
int validation[10];
int error=0; //Initialization of the variable
int i=0;
int val=0;
Serial.println("Introduce 10 values between 0 and MAXINT of the measurements of the sensor");
while(Serial.available()==0){ //The program waits until the user writes the values of the measurements through the serial port
}
for (i=0;i<10; i++)
{
measurement[i]=Serial.parseInt();
scaled[i]=(60.0/(INT32_MAX))*measurement[i]-10.0; //The introduced values are scaled into the [-10,50] range in double format
average=average+scaled[i];
}
average = average/10; //The average value of the 10 scaled values is done
for (i=0;i<10; i++)
{
if (scaled[i]-average>1 || scaled[i]-average<-1) //It is considered that the sensor is giving invalid data readings if the value of any of the scaled measurement and the average value of the 10 scaled measurements differ in more than 1
validation[i] = 1;
else
validation[i] = 0;
error=error+validation[i];
}
if (error==0)
digitalWrite(PIN,HIGH);
else
digitalWrite(PIN,LOW);
val = digitalRead(PIN);
if(val==1)
return average; //If the sensor´s reading value is correct, the function retuns the average of the 10 measurements
else
return -INFINITY; //If the sensor´s reading value is incorrect, the function retuns -INFINITY
}
void setup()
{
Serial.begin(115200);
pinMode(inPin, INPUT);
}
void loop()
{
result=readSensor(inPin);
Serial.println(result,16);
delay(10); // this speeds up the simulation
}