Hi All,
I need some help dynamically assigning elements to an Array. Let me explain part of the project:
- PC will send a series of "commands" to the Arduino
- The Arduino will store these commands in an array
- The Arduino will then loop through the array and process each command
As an example, the PC might send the following commands "pin1high", "pin2high", "pin1low", "pin2low", etc...
As each command is received, it needs to be stored in an array. If I were to hard code the array with the commands it would look like this:
char* commands[]={"pin1high","pin2high","pin1low","pin2low"};
However, I need it to be dynamic and the array filled up with whatever I send to it.
The Arduino would then loop through the array and based on my code logic do certain things based on the command.
Here is my code:
#include <WString.h>
String serialBuffer = String(500);
String sendcmd=String(50);
long previousMillis = 0;
char* chaseBufferA[50]={};
int bufferSequence=0;
void setup() {
Serial.begin(9600);
serialBuffer="";
}
void loop() {
if (Serial.available() > 0) {
char inChar = Serial.read();
if (inChar!='^') {
serialBuffer.append(inChar);
} else {
processBuffer(serialBuffer);
serialBuffer="";
}
}
}
void processBuffer(String processCommand) {
if (processCommand.equals("test")) {
Serial.println("testok^");
} else if (processCommand.equals("forcestart")) {
Serial.println("getbuffer^");
} else if (processCommand.equals("init")) {
Serial.println("initok^");
} else if (processCommand.equals("getbuffer")) {
for (int i=1; i<=10; i++) {
Serial.println(chaseBufferA[i]);
delay(200);
}
} else {
bufferSequence++;
sendcmd="Unrecognised Command: ";
sendcmd.append(processCommand);
sendcmd.append("^");
chaseBufferA[bufferSequence]=sendcmd;
Serial.println(chaseBufferA[bufferSequence]);
}
}
Essentially what this code does is when it receives the command "getbuffer" it will dump the contents of the array - otherwise it adds the command to the array and dumps what it just added.
In the section that adds it to the array, it echoes it back correctly. However when I loop through the array to show everything stored in it, each element of the array seems to be the last command it received.
So for example, if i send "pin1high","pin2high","pin1low","pin2low" - chaseBufferA[0] should equal "pin1high", chaseBufferA[1] should equal "pin2high", etc... But when I loop through the array, every element is the last command received, in this case "pin2low"
Does this make sense...? Help please.