I am quite new to Arduino. Anyway, I am trying to program a robot arm to do a certain action. I want the action I programmed to start when I enter something in the serial port. When I tried to use the "if (Serial.available() > 0)," the action would constantly loop over and over. I want to press the key once and have the action play out once, and then press it again when I want the action to play out again. Sorry, I do not have the code with me now, but here is how my code roughly looks:
void loop() {
//The starting position is programmed here. Whenever the action finishes, it loops back to the
//this position.
if (Serial.available() > 0) {
//The action I want to use is programmed here
}
}
char buf[256];
int number_of_chars_in_buf = 0; // buffer starts empty
void loop() {
if(!Serial.available()) return;
// we have a character on the serial!
buf[number_of_chars_in_buf++] == Serial.read();
buf[number_of_chars_in_buf] = '\0'; // nul terminate the string
work out if the buffer now contains a command I recognize.
usually, we just see if the final character is some sort of command terminator, like '\n'
if(it doesn't) {
return;
}
parse the command, splitting it up into its parts;
string manipulation, use atoi(), put parts of the command into
different variables;
do the thing - whatever it may be.
this will probably be a big switch() statement;
number_of_chars_in_buf = 0; // set the buffer back to empty.
}
You can call it 'command' instead of 'buf'. If you are using newlines to delimit commands, then 'ln' or 'inputLine' might be appropriate.
Also look at how to organize your code into functions in Planning and Implementing a Program. That will make it much easier to manage and extend your program.