Ultrasonic Sensor Code

From STEAMwiki
Jump to: navigation, search
// this program works with the HC-SR04 ultrasonic sensor & Photon Particle
// it will turn on an LED if an object is within 50 cm of the sensor

#define trigPin D0
#define echoPin D1
#define ledPin D2

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(ledPin, OUTPUT);
 
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);  //set ultrasonic sensor trigger pin low
  delayMicroseconds(2); // wait 2 us for pin reset
  digitalWrite(trigPin, HIGH); //trigger ultrasonic pulse
  delayMicroseconds(10); //make trigger pulse 10 us long
  digitalWrite(trigPin, LOW); //turn off trigger pulse
  duration = pulseIn(echoPin, HIGH); //measure time before echo is received
  distance = (duration/2) / 29; //calculate one way distance
  if (distance < 50) {  // turn on an LED if distance is less than 50 cm
    digitalWrite(ledPin, HIGH); // 
 
}
  else {
    digitalWrite(ledPin,LOW); // turn off LED if distance greater than 50 cm
  
  }
  if (distance >= 400 || distance <= 0){
    Serial.println("Out of range"); // out of range message if less than 0 or more than 400 cm
  }
  else {
    Serial.print(distance);
    Serial.println(" cm"); // display distance readings on serial monitor
  }
  delay(500);
}