LED’s will change state when analog input is five or six numbers from the threshold, making accurate transitions impossible. Is there some better way to resolve this problem?
unsigned long starTime;
int flashRed = 20000;
const int numReadings = 3;
int readings[numReadings]; // the readings from the analog input
int index = 0; // the index of the current reading
int total = 0; // the running total
int average = 0;
#define blueLED 11
#define redLED 12
#define greenLED 13
#define AnIn 1
#define redThresh 670
#define blueThresh 660
#define greenThresh 0
int val;
void setup()
{
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
starTime = millis(); //timer
pinMode(redLED,OUTPUT);
pinMode(blueLED,OUTPUT);
pinMode(greenLED,OUTPUT);
Serial.begin(9600);
}
void loop()
{
// subtract the last reading:
total= total - readings[index];
// read from the sensor:
readings[index] = analogRead(AnIn);
// add the reading to the total:
total= total + readings[index];
// advance to the next position in the array:
index = index + 1;
// if we're at the end of the array...
if (index >= numReadings)
// ...wrap around to the beginning:
index = 0;
// calculate the average:
average = total / numReadings;
starTime = millis(); //timer
//val = analogRead(AnIn);
// val = val/2;
if(average >= redThresh){
digitalWrite(redLED,HIGH);
digitalWrite(blueLED,LOW);
digitalWrite(greenLED,LOW);
delay(1000);
}
else {
digitalWrite(redLED,LOW);
if((average>= blueThresh) && (average <= redThresh))
{
digitalWrite(blueLED,HIGH);
digitalWrite(redLED,LOW);
digitalWrite(greenLED,LOW);
delay(1000);
}
else {
digitalWrite(blueLED,LOW);
if((average>= greenThresh) && (average <= blueThresh))
{
digitalWrite(greenLED,HIGH);
digitalWrite(blueLED,LOW);
digitalWrite(redLED,LOW);
delay(1000);
}
else {
digitalWrite(greenLED,LOW);
}
}
Serial.println(average);
}
}