Need code for ultrasonic sensor


I am buliding an inovative project but i need some help for coding f ultrasonic sensor.
i want to design my sensor in such a way that whenever the circuit it turnred ON the distance marked ny sensor will be the inital value and any change in initial value will respond. if nyone could help me with this please let me know as soon as possible.



Hmm… @bhofmann might be the person for you.

From aidancuckoo



If we start with a simple circuit with an ultrasonic sensor such as this one:,11022,13959

You can see from the same code that the distance is measured with the following code:

// Ultrasonic Sensor - HC-SR04 - Test Code
// Read distance measurment from UltraSonic sensor           
int hcsr04Dist = hcsr04.ping_cm();

The way to achieve what you asked is to read the distance in the setup() method and keep a record of that in a variable. In the loop() method you would compare the distance you read to the one you kept a record of to see if it’s changed.

Please share your code if you have difficulties so we can edit it.