Challenge

Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter

code:

int trigPin=11;//trigger

int echopin=12;// echo

long duration,cm ,inches;

long sum=0;

int i;

void setup()

{

//serial port begin

Serial.begin(9600);

//define inputs and outputs

pinMode(11,OUTPUT);

pinMode(12,INPUT);

}

void loop()

{

//the sensor is trigger by a high pulse of 10 secor more microseconds

//give short low pulse beforehand to ensure a cllean high pulse

digitalWrite(11,LOW);

delaymicroseconds(5);

digitalWrite(11,HIGH);

delaymicroseconds(10);

digitalWrite(11,LOW);

//read signal from sensor

pinMode(12,INPUT);

duration=pulseln(12,HIGH);

//convert time into distance

cm=(duration/2)/29.1;//divideby29.1or multiplyby 0.0343

inches=(duration/2)/74;

//divideby 74 or multiply by0.0135

Serial.print(cm);

Serial.print("cm");

Serial.println();

Serial.print(inches);

Serial.print("in");

Serial.println();

delay(250);

}

output;

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.