Sunday, 17 November 2013

Ultrasonic distance sensor

The aim of this session is to become familiar with the HC-SR04 distance measuring sensor and have it control a servo.

Original code taken from here


So wired it up and pasted the code in... 

It worked, its only really accurate up to 50 cm's (possibly because of the material it was reflecting off, it was pointed towards my window and a curtain) and the "wall" a of piece of paper i was using to test the distances must be at right angles to the sensor otherwise you get a wrong value . How it works is explained here.  

Add a servo...

When i added the servo it would jump around a lot because of the random values returned from the sensor. I wanted a smooth motion i.e. as an object is brought closer to the servo, the servo would move in one direction and vice versa.

How to make it smooth...

I found a smoothing code in the arduino IDE examples i used this to average the values from the sensor so as an object is brought closer to the sensor the values sent from it dont jump from one to another causing the servo to move to quickly from one position to another. I also multiplied the averaged value (the distance in cm) by 1000 then increased the scale to map it with the servo, this made the servo move even smoother. 

The circuit

The three wires leading off go to the servo 


This could be used for obstacle avoidance, proximity applications etc.
The readings could be made even more accurate by adding a temperature pin and changing the value for the speed of sound through the air and using more code.

User manual for HC-SR04
My Code for Arduino ive left the comments as they a relevant if not related.

No comments:

Post a Comment