Trouble stopping my while loop

I am trying to write a code where if boolean = true/1 then my sensor starts reading. And when my boolean = false/0 it doesn't read.

To do the continues reading, but I can't break the loop when I press may button for a second time.

Is there another way to loop or a way to fix my while loop?

#include "Ultrasonic.h"
Ultrasonic ultrasonic(A0);

int motor1a = 5;
int motor1b = 6;
int motor2a = 9;
int motor2b = 10;

int knop;
boolean flag = true;

void setup() {
  // put your setup code here, to run once:

  pinMode(motor1a, OUTPUT);
  pinMode(motor1b, OUTPUT);
  pinMode(motor2a, OUTPUT);
  pinMode(motor2b, OUTPUT);

  pinMode(knop, INPUT);

  Serial.begin(9600);

}

void loop() {
  if(digitalRead(A2)==LOW){
    delay(5);

  while(digitalRead(A2) == LOW);
  delay(50);

  flag = !flag;
  Serial.print("flag =   " );   Serial.println(flag);

  long RangeInCentimeters;

  while (flag){
    a();
  }

  if (flag == false){
    analogWrite(motor1a, 00);
    analogWrite(motor1b, 00);
    analogWrite(motor2a, 00);
    analogWrite(motor2b, 00);
  }
  }
}


void a() {   
  long RangeInCentimeters;
  RangeInCentimeters = ultrasonic.MeasureInCentimeters();
  Serial.print(RangeInCentimeters);
  Serial.println(" cm");

  delay(50);

  if (RangeInCentimeters <= 30) {

    analogWrite(motor1a, 250);
    analogWrite(motor1b, 00);
    analogWrite(motor2a, 250);
    analogWrite(motor2b, 00);
  }
  
  if (RangeInCentimeters >= 30){

    analogWrite(motor1a, 250);
    analogWrite(motor1b, 00);
    analogWrite(motor2a, 00);
    analogWrite(motor2b, 250);
  }
}

robot_met_sensor.ino (1.24 KB)

Could you restate your issue?

Do you have the motor(s) directly connected to the micro controller?

SimonRedfox:
Is there another way to loop or a way to fix my while loop?

Your code seems to call a function called a() (what an unhelpful name) but there is no code for the function.

In general if you need to stop a WHILE loop you should not be using WHILE. In most cases IF is much better and allow loop() to do the repetition.

...R

Of course it will not. Only thing you do in that while() is run a() (whatever that ridiculous name means..) in which you never ever touch 'flag'. So how and when should it change?

Pro tip: use while() (or any loop actually) only for things that happen fast. Use the loop() to do the rest so loop() can run as often as possible as well.
Pro tip 2: never ever use delay() :slight_smile: