Week 9 Assignment – AakifR

For this week I wanted to experiment with the Ultraviolet Distance Sensor that was provided in the Starter Kit. I hooked it up to the Arduino and then tried to create a sort of system that turns a red light on if the distance of the object becomes too little or too big from the sensor. Some of the applications could be, for example, to alert an automated robot vehicle if it’s getting too close to an obstacle and similarly if it’s moving too far apart.

Video Demonstration:

Code:

// defines pins numbers
const int trigPin = A0;
const int echoPin = A1;

const int pushButton = A2;

const int greenLEDPin = 13;
const int redLEDPin =  12;


// defines variables
long duration;
int distance;
void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  pinMode(greenLEDPin, OUTPUT);

  Serial.begin(9600); // Starts the serial communication
}
void loop() {


int buttonState = digitalRead(pushButton);

  if (buttonState == HIGH) {
   
    digitalWrite(greenLEDPin, HIGH);
  }
  else{
    digitalWrite(greenLEDPin, LOW);
  }

// print out the state of the button:
  Serial.println(buttonState);
  delay(1);  // delay in between reads for stability



  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);

  if (distance >= 10 && distance <=  20){
    digitalWrite(redLEDPin, HIGH);
  }
  else{
    digitalWrite(redLEDPin, LOW);
  }

}

 

Leave a Reply