Measuring in a digital system is always tricky. Values dance between some values just because noise in the environment, lack of accurracy of the sensor or maybe because the analogue to digital converter "jumps" between too close values.
To solve these situations in a easy and cheap way we use digital filters. There are many ways to do digital filters from taking the mean to the median or more sophisticated ones.
Using the mean is adding up a number of samples together (let´s say d1, d2 and d3) and dividing by the number of them (3 in this example). It´s easy and fast, but can deliver wrong results if samples are very different.
An approach more fine but still simple and fast enough is using the median. In brief the median of a series of numbers is the number in the middle when all of them are ordered from the smalles to the highest. In this way, very different samples can be treated as a group and take the sample more similar to the mayority of them. It´s still not perfect but is a good compromise between the quality of the filter and its speed.
With mBot we can do it easily by:
- Get some samples and put into a row matrix.
- Ordered them.
- Pick the sample in the middle of the matrix.
I know it sounds a bit difficult, but Scratch (the language where the mBlock mBot programing environment comes form) is very well documented so it makes things easier. I invite you to check how to create and manage lists and sort values in Scratch.
The final software is like this:
Note: there is a final part which displays values on the PC screen, also in the LED matrix and generates a sound which pitch is proportional to the distance, so we can not only read the distance but also hear it. You can see it really working in my video attached to this review and here:
The software for only the filter is here. The software with the sound is here.
This was a project I had in mind from some time ago and took me only an hour to solve it even I´m not used to program anymore. I think this mBlock software plus mBot, and try and error is a very nice combination to learn in robotics development.