Hi,
I'm using an arduino to send commands to a servo controller - but am having some difficulty in setting up a set of commands that won't continually loop - or be usable only once (I would like the set of commands to be usable more than one time).
The way I want it to work:
The arduino reads a value and stores it in "val".
If "val" = 'A', go through a programmed routine one time (an action I am calling "forward")
if I don't use the "while" function, the routine keeps looping.
if I use the "while" function as it is written below, the routine will perform once - but never again when I send 'A' again.
I think the key is to figure out how to reset "var" after going through the commands (which is what I am not sure on how to do)
Helpful advice on this would be greatly appreciated
char val; //to store serial read
char var; //to use with 'while'
void setup() {
Serial.begin(115200);
}
void loop() {
if( Serial.available() ) // if data is available to read
{
val = Serial.read(); // read it and store it in 'val'
}
// forward
if( val == 'A' ) // if 'A' was received
{
while(var < 1)
imoveD(1, 1500, 1000); //commands to control servo 1
imoveD(1, 2100, 1000); // commands to control servo 1
var++;
}
}
void imoveD(int servo, int position, int time) {
Serial1.print("#");
Serial1.print(servo);
Serial1.print(" P");
Serial1.print(position);
Serial1.print(" T");
Serial1.println(time);
delay(time);
}
Establish a boolean var, using it like a flag bit.
So. some condition makes the boolean TRUE, so execute a function and before you leave that function, reset the boolean FALSE.
You read the 'A' you sent via serial and set val = A. Until you change that, val will always = A. So at some point you have to reset that variable. That is where the boolean flag explained above would come in handy. Either way you have to set that val variable to something other than A because it will try to do your 'If' loop everytime.
It loops constantly without the While statement because it sees 'A' everytime as explained above.
Now introduce the While loop. The same thing is happening. In your While loop you look at your var variable. The very first time it sees an 'A', it runs that code, at the end of your function calls you increment the variable by 1. Therefore var will never again be <1. In fact it will forever be 1. Since you never reset this var variable, it will never do the while loop again.
You can change your loop as follows to get rid of your problem:
void loop() {
if( Serial.available() ) // if data is available to read
{
val = Serial.read(); // read it and store it in 'val'
}
// forward
if( val == 'A' ) // if 'A' was received
{
imoveD(1, 1500, 1000); //commands to control servo 1
imoveD(1, 2100, 1000); // commands to control servo 1
}
val = 'B';
}
I set the val to B because I am not certain how to set it to nothing. It really doesn't matter. As long as it is anything but 'A' it will work.