how to check if sensors values are true one after another


i know i know , probably very silly question .

i wish to get something like when value of sensor come in like distnce first is 50cm then 100cm then 150 cm in this way something will happend
but when values appear oposite way 150-100-50 something else need to happend

i was trying to put while into while , but while is stoping insttruction when it met set value

thanks in advance

Subtract the new reading from the old reading. The sign of the difference tells whether there is increase or decrease. Then check the absolute value of the difference against a threshold value.

int value = readSensor();
if (value < last_value)
  //moving towards
else if (value > last_value)
  //moving away
  //not moved
last_value = value;

Of course this is a very simplistic scheme, and does take into account the fact that your sensor readings may fluctuate even in steady state. For that you’ll need to add some tolerances/hysteresis.

Thank you!

im using map for sensor , so its not that bad. map(val,1,160,1,16);

i have made it like that in first place , but it was coming back to red light beacuse of rising back distance of empty space in front of sensor (im using HCSR04 sonar sensor)
now somehow i made new one on two lines of code in loop

while (range == kon) {red();break;} // kon is maximum value of sensor
while (range == pocz){green();break;} // pocz is close to minimum value of sensor

what i was trying to achieve in last couple days was acting like

check if value is 50 cm if true check if next value is 100 cm if true check if last value is 150 if true turn red light on and wait 10 minutes (10 minutes for switch it back to green if distance will not change oposite way)
and oposite way check if distance is 150 if true check is distance drop to 100 cm if true check is distance is 50 cm , (object is pasing behind sensor, distance is rising to 180cm which should be ignore right now)
im sitting around 40 h + on it and still didnt figure out how to put it into arduino

Hi Bartezz,

first of all there are no silly questions. The questions might be simple. They only reflect your knowledge-level and by asking a question you show that you want to improve your knowledge-level. That's what really counts.

you can do this with a functionality called "statemachine".

You use the switch case function

switch (var) {
  case 1:
    // statements1
  case 2:
    // statements2
    // statements

a variable is set to different values
and depending on the value only the the statemens1, statements2 etc. are executed.

The code above is not really compilable code. It just show the principle.
The variables value is changed when a condition becomes true.

So in your case written as pseudo-code
if distance == 50 cm
stateVar = 2

switch (stateVar)
case 2
do the things that shall be done when distance is smaller than 100 cm
if distance == 100 cm
statevar = 3

case 3
do the things that shall be done when distance is smaller than 150 cm
if distance == 150 cm
statevar = 4


if everything is always going forward this would be sufficient.

if the direction can change at any time from forward to backwards you use the same principle with different conditions

in every state you can check for any kind of conditions
In the next pseudo-code I use names instead of values because the names will be selfexplaining

switch (stateVar)
case Forward_distance_50_100cm
do the things that shall be done when distance is smaller than 100 cm and movement is forward
if distance == 100 cm
statevar = Forward_distance_100_150cm

case Forward_distance_100_150cm
if distance == 50 cm // object move backwards and has reached 50 cm
stateVar = backwards_distance_50_100cm

etc. etc.

if you are almost completely new in programming. The explanation above might be difficult to understand.
If this is the case just ask again and describe what your coding-experience is. If the others know your knowledge-level they can adapt the answer to your knowledge-level.

For very good assistance we need to know all cases that can happen and what should be done for any case that could happen. You haven't described yet what happens if the distance becomes shorter bevor ten minutes passed by etc.
Anything you can measure or calculate can be used for conditions.
time passed by can be measured,
changing-speed of the distance can be measured
moving-direction forward / backward can be measured.

So anyway it is a good thing to write down what cases can occur and what should happen then
In the first step not as a program just normal words how you would explain it to your grandma

best regard Stefan

Thank You very much Stefan I really aprecitate it.

but now i need to read it couple times to understand it completely :smiley:

I already were trying to use switch case but... it didnt work very well or i mess something up with it.
my counting didnt work
switch (val)
case 50:
x =x+1;
case 100:
x =x+1;
case 150:
x =x+1;

if (x == 3)
pixels.setPixelColor(0, pixels.Color(150, 10, 0));
pixels.setPixelColor(1, pixels.Color(150, 10, 0));
pixels.setPixelColor(2, pixels.Color(150, 10, 0));
pixels.setPixelColor(3, pixels.Color(150, 0, 0));;
Serial.println("red on");}


Hi Bartezz,

please post your complete sketch. If you use the reply-button instead of the quick-reply above the textwindow is a menu.
In the left corner of this menu is a button with a symbol <|> if you click on this button a code-section is inserted into the textfield. Paste code into this code-section. Then the code is written in a constant-disctance scripting which shows all the indentions in the right way.

With the part of the code you have posted I do not understand how variable (val) gets its values.

I can only estimate that val is an integer which gets its value somehow from the sensor.
Please describe all possible situations that can happen as far as I have understood there is:

distance to the moving object is below 50cm red LED is off

  • program awaits object to move more away from sensor until it reaches distance 50 cm

if object has reached 50cm distance change to

  • red led still off
  • program awaits object to move more away from sensor until it reaches distance 100 cm

if object has reached 100cm distance change to

  • red led still off
  • program awaits object to move more away from sensor until it reaches distance 150 cm

if object has reached 150 cm

  • red LED on
  • start a timer

check time that has passed by since starting of timer and check if object stands still at 150 cm
if time that has passed by reaches ten minutes

  • red LED off
  • green LED on

if object moved backwards (i.e. measured distance becomes less than 150 cm before ten minutes has passed

  • do what?

if ten minutes has passed by with object at a distance of 150 cm
program awaits distance to go down to 100 cm
if distance has reached 100 cm change to

program awaits distance to go down to 50 cm
if distance has reached 50 cm
do what?

and in every mode what should happen if object reverses the direction
program is in mode awaiting object to reach distance 50 cm but object moves not toward the sensor
object moves away? what should happen then?

Of course we can go on with this half-abstract description and we will find a solution. But my personal experience is
of you describe the real thing. we will find the solution at half the time.

I have no idea if the real thing is

  • a conveyer-belt moving boxes into a wash and dry station
  • or cows walking towards a rotating brush giving the cows a relaxing massage :slight_smile:
  • or a liquid-level filling up a tank and pour out of the tank again

what is the real thing?? If you haven't signed a non-disclosure-act please describe the real thing.

your code checks for val exactly beeing 50, 100 etc. it might be that the measurements are taken at 49 and then the next at 51 so val does not have 50 when measuring. To overcome this you use if-conditions because if-conditions can check for val beeing equal or greater than 50

and the if-condition then sets a second variable "State" to a certain value that corresponds with a certain case

If this is nescessary to do depends on the real thing. If your object is moving quite fast this might be nescessary.
If your objects needs 1 minute to move on from 49 cm to 50 cm I guess it is not nescessary.

Maybe your way of repeat the measurings is coded unfavorable. there are a lot of reasons why it is a good idea to post the whole code and to describe the real thing.

best regards Stefan

Thanks for your last post.

I already changed whole concept of device, due to sensor itself (hcsr04) its working , but trying to measure distance in 2 seconds time became quite hard to reach . sensor sometimes is “jumping” on distance , even when i use mapping to get more stable reading , its still doing it from time to time. idea was good to measure is object, person moving forward the sensor or away from sensor, but as i said before , maybe that will work with diffirent (laser) sensor.

I needed ASAP to be honest. so its finished im using while and checking just two values one for green light one for red light, device is already in test phase, and works well, after distance adjustment .

Basicaly its simple device that indicates is toilet room in use (red light) or its free to use (green light)

heres the code :

#include <Adafruit_NeoPixel.h>
#define PIN 4
#define NUMPIXELS 4
#include <NewPing.h>
#define TRIGGER_PIN 12
#define ECHO_PIN 13
#define MAX_DISTANCE 180
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
int range = 0; //reset range value on startup
int pocz = 9; // distance for turning on green light
int srod = 7; //distance for turning on amber light 
int kon = 14 ; // distance for turning on red light

void setup()
  Serial.begin (9600);
  pixels.begin(); // This initializes the NeoPixel library.

  green(); //green light to be on when device starting up


void loop()
  int val = sonar.ping_cm();

  range = map(val, 1, 160, 1, 16);


    while (range == kon) {
      red();  //red light when person reaches max range of sensor
    while (range == srod) {
      green();  // green light when person is in the middle of sensor range
    while (range == pocz) {
      green();  // green light when person reaches min range of sensor


}//koniec loop
void green()// green led on
  pixels.setPixelColor(1, pixels.Color(0, 250, 0));
  pixels.setPixelColor(0, pixels.Color(0, 250, 0));
  pixels.setPixelColor(2, pixels.Color(0, 250, 0));
  pixels.setPixelColor(3, pixels.Color(0, 250, 0));;
void red()// red led on
  pixels.setPixelColor(0, pixels.Color(250, 0, 0));
  pixels.setPixelColor(1, pixels.Color(250, 0, 0));
  pixels.setPixelColor(2, pixels.Color(250, 0, 0));
  pixels.setPixelColor(3, pixels.Color(250, 0, 0));;
void amber()//amber light on
{ pixels.setPixelColor(0, pixels.Color(150, 40, 0));
  pixels.setPixelColor(1, pixels.Color(150, 40, 0));
  pixels.setPixelColor(2, pixels.Color(150, 40, 0));
  pixels.setPixelColor(3, pixels.Color(150, 40, 0));;

StefanL38, thanks , for your help and plenty of new information.
will use them as im planning to make another device to use as contactless tempreture check on entry of work place .


You use of “while” construct is bizarre to say the least…

    while (range == kon) {
      red();  //red light when person reaches max range of sensor
    while (range == srod) {
      green();  // green light when person is in the middle of sensor range
    while (range == pocz) {
      green();  // green light when person reaches min range of sensor

It’s like you’ve never heard of the “if”…

    if (range == kon) {
      red();  //red light when person reaches max range of sensor
    if (range == srod) {
      green();  // green light when person is in the middle of sensor range
    if (range == pocz) {
      green();  // green light when person reaches min range of sensor

pcbbc indeed it is, but, there is a reason for it, of course i heard and this was a first plan to just use a if command , but i were trying with if diffirent thing which didnt work at all now i know it didnt work for very silly reason

first code for it :

if ( distance>=40)
for (int i= 0; i<=distance; i++)

else {
if(distance <=40)
for (int i=0; i>=distance; i–)
// {

And because of used >= and this <= i was facing issue with sensor jumping from short distance when you passing sensor to full range , and it was switching straight to red from green .

Sorry for this , im still learning , to be honest its first thing i made on arduino, for last year what were using was wemos d1 with easyesp, so as you perfectly know its way simpler than this :slight_smile:


Hi bartezz,

I want to give a description in my own words to check if I understand the situation.

Your sensor is mounted on a wall inside the toilet-room. If a person enters the toilet-room and walks toward the toilet the person walks toward the sensor. Is this correct?

but trying to measure distance in 2 seconds time became quite hard to reach .

that sounds really strange to me. How did you determine that the next distance-measuring was only possible after more than 2 seconds?

I haven't worked with the newPing-library yet so I don't know what it is doing. But I would be very astonished if the measuring frequency would be as low as 0,4 Hz = one measuring every 2,5 seconds.

These sensors can measure up to 3 or 4 meters. What is the maximum-distance the soundwaves can travel to the opposite wall?

The traveltime of the sound-waves for a 4m distance is 2*4m / 343 m/sec = 0.0233 seconds = 23,3 milliseconds.
If you initiate a new measuring at less time than 23,3 milliseconds the soundwaves of two measureings get mixed up.

Just a guess: Setting the max distance to 180 cm if the maxi-distance can be bigger could cause errors two.

What is your exact hardware Arduino Uno? I have some hcsr04 laying around. If you can post a drawing of the toilet-room with door and sesnor-position I can the situation and test code under similar conditions.

What is the hardware that you have Arduino Uno? Mega2560?, ESP8266? or ESP32?
these are the boards I have at hand to do some testing.

best regards Stefan

Why 2 seconds , before you get to toilet there is a tiny corridor , total lenght 200 cm, and wide about 120cm really really tiny, when i tested this device at home in more open space , it was all fine , but on place where it goes it's starts to act weird and even was able to turn green light behind place where red only should works. But let's go back to 2 second whole corridor got two meters im able to measure person on distance of 150 cm (noboby is walking on walls), just check how long you will walk 150 cm ? . you right sensor are able to measure up to 4 meters, but the best working range i found is up to 2 meters, more than this i receiving random values. second thing people are not acting , walking as i wish they will, so they not walking perfeclty straight to sensor, and very first thing what every single person is doing is trying to trick it hehe :slight_smile: newping library quite nice, calculating for cm and inch alredy in it, also i want to use max range function , to stop sensor from jumping from short distance to high distance . this function if you set it for example to 160 cm , everything more than 160 will be returned as distance 0 . now sensor is attached to door frame on top , which is better than on side of it, no errors from walls. as you know when you deal with one issue , there is another on its way. im quite tall (195cm) so sensor "catching" me easily, device were working great until shortes lad show up (164cm) red light works ok because point of meseuring is almost on the floor(sensor is on angle about 40 degrees). Adjusted just value of green light and works great . I will post some photo so you can have a look.


OK. Knowing the real thing inspires my imagination.
So how many persons are allowed to be inside the toilet at the same time?

if only one person maybe adding an IR-motion-sensor gives more security.
Or maybe two light barriers. Two light-barriers are able to determine the walking-direction of a person.

Just out of fun some more ideas:
Using a single RFID-card and a doorlocker mechanism. You must take the RFID-Card to open the door
and to switch on the light inside. So you have to carry the card with you.

You wrote the sensor looks at an angle of 40 degrees. My experience is: the error-rate increases if the sensors sound-waves hit obstacles in an agle that deviates much from 90 degrees.

best regards Stefan

Hello Stefan.

Just one person is allowed inside (keep social distancing)
In first place i was just thinking of putting two ir barriers in place , but if this was just for this one particular toilet room with corridor , that will be great, apparently other toilets on site are without it, so theres no place to mount it, so i need device which works on one sensor and measure distance :slight_smile:

With rfid card yes brilliant that will was, but we not allowed to touch any door (all doors staying open )

Yes its 40 degrees right now, but i need to move away from wall as it was catching unlogical distance from wall. best working path for it is just in front of sensor , i agree, but no chance to mount it like this(not enough space next to the door )

To me the physical situation is still not clear. Can you provide a hand-drawing that shows the top-view of
walls, toilets, door, corridor and sensor? And maybe a sideview that whos the angle of the sensor?

It seems to be at your working place so no real pictures. Publishing such a picture would be highly problematic.

I find it exciting to find a solution. If ever possible with a single sonar sensor.
I'm really willing to re-produce the physical situation in all important details. But therefore I need information about
this toilet-room as described above.

If you can post the measured values of walking into the toilet and walk outside again will give important information
about what really happends.

best regards Stefan