Hi, I am not very used to coding in this language so I'm running into all kinds of problems. I'm currently using this code which was used in a previews forum.
char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character
char Comp(char* This) {
while (Serial.available() > 0) // Don't read unless
// there you know there is data
{
if(index < 19) // One less than the size of the array
{
inChar = Serial.read(); // Read a character
inData[index] = inChar; // Store it
index++; // Increment where to write next
inData[index] = '\0'; // Null terminate the string
}
}
if (strcmp(inData,This) == 0) {
for (int i=0;i<19;i++) {
inData*=0;*
}*
index=0;*
return(0);*
}*
else {*
return(1);*
}* } void loop() {
if (Comp("m1 on")==0) {*
Serial.write("Motor 1 -> Online\n");*
}*
if (Comp("m1 off")==0) {*
Serial.write("Motor 1 -> Offline\n");*
}*
if (Comp("m1 on")==1 & Comp("m1 on")==1 & Serial.available() > 0){*
Serial.write("Dance\n");*
}* } # For some reason if you type anything other then "m1 on" or "m1 off" the Arduino stop responding. any help as to how I can fix this? thank you.
if (Comp("m1 on")==1 & Comp("m1 on")==1 & Serial.available() > 0)
Should more likely be:
if (Comp("m1 on")==1 && Comp("m1 off")==1 && Serial.available() > 0)
There is a more fundamental issue however. If you type something that matches, you clear the indata array. If you have something that doesn't match, it stays in your array for ever. An end of packet marker (CR? LF?) would help you identify that the matching is done.
Thanks for the correction at the end, that was me trying to fix the problem without any luck. What do you mean by "An end of packet marker (CR? LF?)" how do I use this? thank you
You need to send some character at the end of the command string so that your code knows that you've received a complete message and that it's worth trying to match it. If all your matches fail at that point, you can clear out the buffer and start looking for a new command that you do recognize.
Doesn't much matter what that end character is as long as it doesn't appear in any command.
I recently wrote a pair of demo programs showing how to send data between a PC and an Arduino using Python on the PC. The Arduino sketch should illustrate the sort of thing you need. In my system I used the characters 254 and 255 as delimiters. If I was just sending stuff from the Serial Monitor I would change them to two Ascii characters (say X and Z) that I was not going to include in my message.
The files are attached at the bottom of the first post on this Thread