Saturday, September 20, 2014

Third Arduino Project

This time it was influenced by my younger brother to write a code that will detect the distenation and if it is more than 100 cm to light up a green light, if it is less than 100 but more than or equal 50 to light up a blue LED and if it is less than 50 to light up a red LED. If the distance is critically small (less than or equal 10 cm) to start flashing the red LED and play a long alarming tone. Then we modified the code to play a smaller alarming tone on other distenations too.

Shown is the circuit and below is the code.









#include

#define TRIG_PIN 5
#define ECHO_PIN 6

#define RED_LED 8
#define GREEN_LED 9
#define BLUE_LED 10

#define SPEAKER_PIN 12

void setup ()
{
  Serial.begin (9600);
 
  PinMode (TRIG_PIN, OUTPUT);
  PinMode (ECHO_PIN, INPUT);
 
  PinMode (RED_LED, OUTPUT);
  PinMode (GREEN_LED, OUTPUT);
  PinMode (BLUE_LED, OUTPUT);

  PinMode (SPEAKER_PIN, OUTPUT);
}

void loop ()
{
  DigitalWrite (TRIG_PIN, HIGH);
  delayMicroseconds (100);
  DigitalWrite (TRIG_PIN, LOW);
  delayMicroseconds (100);
  DigitalWrite (TRIG_PIN, HIGH);

  int iPulseLength = pulseIn (ECHO_PIN, HIGH);
  float fDistance = iPulseLength / 29.387 / 2;

 Serial.print ("The distance in Centimeters is: ");
 Serial.println (fDistance);

 if (fDistance <= 10.0)
 {
    DigitalWrite (GREEN_LED, LOW);
    DigitalWrite (BLUE_LED, LOW);
   
    DigitalWrite (RED_LED, HIGH);
    PlayTone (SPEAKER_PIN, NOTE_B6, 2);
    delay (500);
    DigitalWrite (RED_LED, LOW);
    //PlayTone (SPEAKER_PIN, NOTE_G3, 4);
    //delay (500);
 }
 else if (fDistance > 10 && fDistance <= 50.0)
 {
   DigitalWrite (RED_LED, HIGH);
   DigitalWrite (GREEN_LED, LOW);
   DigitalWrite (BLUE_LED, LOW);

   PlayTone (SPEAKER_PIN, NOTE_B6, 4);
   delay (500);
 }
 else if (fDistance > 50.0 && fDistance <= 100.0)
 {
   DigitalWrite (RED_LED, LOW);
   DigitalWrite (GREEN_LED, LOW);
   DigitalWrite (BLUE_LED, HIGH);

   PlayTone (SPEAKER_PIN, NOTE_B6, 8);
   delay (500);
 }
 else //fDistance > 100
 {
   DigitalWrite (RED_LED, LOW);
   DigitalWrite (GREEN_LED, HIGH);
   DigitalWrite (BLUE_LED, LOW);
 }

 delay (1000);
}

No comments: