This example calculates the distance from the response from the sensor, graphs it on the NeoPixels, beeps with a pitch based on distance and logs the value.

The video (animated gif) below shows the sensor measuring the distance to a moving piece of paper and indicating this via the number of NeoPixels illuminated. The paper doesn't move far enough away to light up the tenth NeoPixel. There is a brief reading over the expected value, this could be due to the first reflection being missed and the sensor picking up sound from the the third reflection.

Description and Discussion

The code is a simple loop sending a pulse to A1 output pin and then measuring the pulse on A2 input pin with the MakeCode pulse in pin block. The division by 58 converts the timed value into centimetres and this value is then shown on the NeoPixels up to a value of 30cm (12"). The distance is also represented by a short beep with frequency (pitch) between 50Hz (for 0.25cm) and 10kHz (for 50cm). The distance is also logged but this is only visible if you are using the Windows 10 app version of MakeCode.

It's not clear if this sensor has a maximum measuring rate or a required pause after the Echo pulse before the next measurement. If it does then the code has a minor flaw as it's relying on the console log as a delay if the distance is out of range for the beep to occur.

The value of 58 or 58.2 is often seen in example code. It's worth exploring where this "magic" number comes from. The Echo high pulse duration represents the time for the first detected reflection. The speed of sound varies mainly with temperature and to a far lesser degree by humidity. The chirp travels to the target and is reflected back, its journey is twice as long as the distance. 58 represents an assumption that the speed of sound is 1000000 / 58 * 2 / 100 = 344.8 metres per second. 344.8m/s would equate to a 21.6 degrees Celsius (70.8 Fahrenheit), 40% relative humidity day.

The graph block logs the distance value to the console as an unnamed value making the use of console log value block a little superfluous.

This guide was first published on Sep 17, 2018. It was last updated on Sep 17, 2018.

This page (Simple MakeCode) was last updated on Sep 15, 2018.

Text editor powered by tinymce.