Obstacle sensing using ultrasonic sensor

int trig = 8;
int echo = 7;
int buzzer = 6;
float distance;
int duration;

void setup()
{
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  pinMode(buzzer, OUTPUT);//enable buzzer pin
}

void loop()
{
  float result = 0;
  int i;

  //this loop creates for making the average of 100 items
  for (i = 1; i <= 100; i++)
  {

    //giving a pulse to enable ultrasonic sensor
    digitalWrite(trig, LOW);
    delayMicroseconds(2);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);
    digitalWrite(echo, LOW);
    duration = pulseIn(echo, HIGH);//getting the time from ultrasonic sensor

    //equation for getting distance from time
    distance = (float)((duration * 0.34) / 2);
    result = (result * (i - 1) + distance) / i;
  }

  if (result < 100)// this check whether the obstacle in range or not
  {
    digitalWrite(buzzer, HIGH);//buzzer on
  }
  else
  {
    digitalWrite(buzzer, LOW);//buzzer off
  }
}

Post a Comment

0 Comments