Hi - I am having problems using a flag in my sketch to switch from going forward to going backward (programming a robot). Essentially, my code is:
int direction = 0; //flag that tells my direction
void setup()
{
}
void loop()
{
if (direction == 0)
{
<>
direction = 1;
}
if (direction == 1)
{
<>
direction = 0;
}
}
The problem is, it never gets to the second part of the program. By using Serial.println, I confirm the it does set direction = 1, but then it immediately gets set back to 0. What I am wondering is if somehow it is the original declaration of the variable, at the beginning, which is constantly setting it back to zero before the second IF statement gets run. Any ideas?
There is always the small change that your system 'crashes' and resets when you do something in that second loop, maybe the powersupply i loaded too much by a load you activate in the second loop.
Put a serial print line statement in your setup function like "starting sketch" and monitor the sketch running in your serial monitor. If you see the setup function getting called over and over you know you are likely having a reset condition being forced on your board, possibly from something drawing too much current? If not you will have to post your complete sketch to see what might be happening.
void loop()
{
if (direction == 0) // this is the initial condition, so true
{
direction = 1; // this assignment makes the following condition true
}
if (direction == 1) // so this will be true as well
{
direction = 0; // this restores the initial condition
}
I would expect whatever action to be done and undone very often.
An else instead of the second if would stop the direction immediately flipping back of course, but it will still change back on the next pass through loop() unless action is taken to prevent it.
robotcanuck:
basically, I would want one function to continue looping until a condition is met, then jump to another function and loop it.
Yes, you need to define a condition, you didn't state it and we have been guessing what it could be. And no, you don't need another loop:
void loop()
{
if (condition_is_met)
{
flag_to_do_other_function = true;
}
else // maybe you need another condition to return to the normal state?
{
}
if (flag_to_do_other_function)
{
do_other_function();
}
else
{
do_normal_function();
}
}