I am using a gyroscope sensor. When I rotate the sensor it turns the led on or off. With the following code:
if (normAccel.XAxis > 1) {
digitalWrite(led, HIGH);
}
else if (normAccel.XAxis < 1) {
digitalWrite(led, LOW);
}
My problem comes when I place a for loop. If I rotate the sensor, the led does not turn on or off until the loop ends. My code is:
if (normAccel.XAxis > 1) {
digitalWrite(led, HIGH);
digitalWrite(dirPin, HIGH);
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(600);
digitalWrite(stepPin, LOW);
}
}
else if (normAccel.XAxis < 1) {
digitalWrite(led, LOW);
digitalWrite(dirPin, LOW);
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(600);
digitalWrite(stepPin, LOW);
}
}
**Simply put, I want the loop to break. **
I tried the following code, but it didn't work:
if (normAccel.XAxis > 1) {
digitalWrite(led, HIGH);
digitalWrite(dirPin, HIGH);
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(600);
digitalWrite(stepPin, LOW);
if (normAccel.XAxis < 1) {
break; //With this I get an error: "Break statement not within loop or swich"
return 1;
}
}
}
uint8_t someVariable;
uint8_t led = 13;
uint8_t dirPin = 12;
uint8_t stepPin = 11;
uint8_t someOtherVariable = 10;
uint8_t stepsPerRevolution;
void setup() {
}
void loop() {
if (someVariable > 1) {
digitalWrite(led, HIGH);
digitalWrite(dirPin, HIGH);
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(600);
digitalWrite(stepPin, LOW);
if (someOtherVariable < 1) {
break; //With this I get an error: "Break statement not within loop or swich"
return 1;
}
}
}
}
Compiles.
I had to invent some variables to replace the ones you didn't post in the code you didn't show us. I conclude that if your code does not compile then the problem is in the secret part.
It was my mistake to explain. Excuse me. I already tried, when I put the following I did not get any error:
if (normAccel.XAxis > 1) {
digitalWrite(led, HIGH);
digitalWrite(dirPin, HIGH);
for (int i = 0; i < stepsPerRevolution; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(600);
digitalWrite(stepPin, LOW);
if (normAccel.XAxis < 1) {
break;
}
}
}
The problem is that the break is not executed. That is, first end the loop and then execute the next line. I want to end the loop before the loop ends only if I rotate the sensor.
if (normAccel.XAxis > 1)
{
digitalWrite(led, HIGH);
digitalWrite(dirPin, HIGH);
for (int i = 0; i < stepsPerRevolution; i++)
{
digitalWrite(stepPin, HIGH);
delayMicroseconds(600);
digitalWrite(stepPin, LOW);
if (normAccel.XAxis < 1)
{
break;
}
}
}
How is normAccel updated? You get in with the condition "if (normAccel.XAxis > 1)" and want to get out on the condition that "if (normAccel.XAxis < 1)":
Is there unseen interrupt-driven code updating normAccel behind the scenes? If not, as far as the code is concerned normAccel.XAxis will always be > 1.