Saturday, 25 November 2017

Water level indicator with different colour lights

This is a simple water level indicator. The ultrasonic sensor measures the water and then turns on the different leds according to the water level.

The sketch
#define COMMON_ANODE
int redPin = 4;
int greenPin = 5;
int bluePin = 6;
int trigPin1 = 7;
int echoPin1 = 8;

void setup()
{
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  Serial.begin(9600);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void firstsensor(){ // This function is for first sensor.
int duration1, distance1;
  digitalWrite (trigPin1, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin1, LOW);
  duration1 = pulseIn (echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

      Serial.print("1st Sensor: ");
      Serial.print(distance1);
      Serial.print("cm    ");

  if (distance1 >=8 && distance1 < 9) {  // Change the number for long or short distances.
  setColor(0, 255, 0); // green
 }

  if (distance1 >=6 && distance1 < 7){
  setColor(0, 255, 255);// aqua

  }
 
 if (distance1 <=5){
 setColor(255, 0, 0); // red
  }
}



void loop() {
Serial.println("\n");
firstsensor();
delay(100); 
}


void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
#endif
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}