Computer Club Sample 20180417

/*
*Kellenberg Computer Club
*Sonar Demonstration
*/
// defines pins numbers
const int TriggerPin = 9;
const int EchoPin = 10;
const int GreenLight = 5;
const int RedLight = 6;
 
// defines variables
long duration;
int distance;
 
int LoopCount=0;
int FirstTime=1;
 
 
/*This is the Setup Routine.  The Setup Routine will only execute one time per power cycle
 * or reset of the Arduion device
 */
void setup() {
           
          /*First we configure our pins as INPUT and OUTPUT*/
          pinMode(TriggerPin, OUTPUT); // Sets the pin (9) as output.  It is sending a signal
          pinMode(EchoPin, INPUT); // Sets the pin (10) as Input.  Gets the signal
          pinMode(GreenLight,OUTPUT);
          pinMode(RedLight,OUTPUT);
           
          /*Now we are opening the serial line so that we can
           * Send messages to the serial Monitor
           */
          Serial.begin(9600); // We will us the serial port to monitor what is happening in the serial monitor
          
          /*Now we set the TriggerPin Low in initialize it*/
          digitalWrite(TriggerPin, LOW);
          delayMicroseconds(2);
}
 
/*After setup is called, the loop function is called.  once loop gets to the bottom, starts over again.
 * 
 */
void loop() {
                  
           
          // Sets the TriggerPin on HIGH state for 10 micro seconds
          digitalWrite(TriggerPin, HIGH);
          delayMicroseconds(10);
          digitalWrite(TriggerPin, LOW);
           
          // Reads the echoPin, returns the sound wave travel time in microseconds
          duration = pulseIn(EchoPin, HIGH);
 
          // Calculating the distance
          distance= duration*0.034/2;

          if(distance<100){
            Serial.println("Getting too close");
            digitalWrite(GreenLight,LOW);
            digitalWrite(RedLight,HIGH);
          }else{
            digitalWrite(GreenLight,HIGH);
            digitalWrite(RedLight,LOW);
          }
          delay(500); 
          // Prints the distance on the Serial Monitor
          Serial.print("Distance: ");
          Serial.println(distance);
}

mrcampbell / April 17, 2018 / Uncategorized