I got two infrard sensors, just want the motor to turn using a list of angles when the infrard sensor detects a signal, and stop turning immediate once the signal gone. However I can't break out the loop and motor continues to turn until the list ends.
#include <Servo.h>
Servo servoJaw;
int servoPin1 = 3;
int IRSensor1 = 2;
int IRSensor2 = 7;
int time=0;
int jawlist[] = {
0,0,90,0,90,0,90,0,180,180, //18
0,90,0,90,0,180,180,0,90,180, //28
};
void setup() {
servoJaw.attach(servoPin1);
pinMode (IRSensor1, INPUT);
pinMode (IRSensor2, INPUT);
}
void loop() {
int statusSensor1 = digitalRead (IRSensor1);
int statusSensor2 = digitalRead (IRSensor2);
if (statusSensor1 == 0){
while (time< 20){
servoJaw.write(jawlist[time]);
delay(1000);
time++ ;
if (statusSensor2 == 1){
break;
}
}
}
}
Your topic has been moved to a more suitable location on the forum. Installation and Troubleshooting is not for problems with (nor for advice on) your project See About the Installation & Troubleshooting category.
Your description mentions one sensor, your code uses two sensors; maybe a better description is in place explaining the second sensor.
the main loop runs the code over and over again, right? i think it is breaking out of the loop, but just entering it again in the next cycle. this is the simplest fix i could think of.
#include <Servo.h>
Servo servoJaw;
int servoPin1 = 3;
int IRSensor1 = 2;
int IRSensor2 = 7;
int time=0;
bool stopMotor = false;
int jawlist[] = {
0,0,90,0,90,0,90,0,180,180, //18
0,90,0,90,0,180,180,0,90,180, //28
};
void setup() {
servoJaw.attach(servoPin1);
pinMode (IRSensor1, INPUT);
pinMode (IRSensor2, INPUT);
}
void loop() {
int statusSensor1 = digitalRead (IRSensor1);
int statusSensor2 = digitalRead (IRSensor2);
if ((statusSensor1 == 0) && !stopMotor){
while (time< 20){
servoJaw.write(jawlist[time]);
delay(1000);
time++ ;
if (statusSensor2 == 1){
stopMotor = true;
break;
}
}
}
}