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)