Hi, im trying to send an array of char over serial to my arduino uno. My arry would be something like 12345. Im trying to only read the first character of the array. That's what i got so far.
void setup()
{
Serial.begin(9600);
}
void loop(){
char ch;
String value;
char inData [20];
char inChar;
byte index;
Serial.flush();
while(!Serial.available());
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
}
Serial.println(inData[0]);
}
But the arduino is sending the value like this:
1
2
3
4
5
and when i change the
Serial.println(inData[0]);
to
Serial.println(inData[1]);
there's nothing printing. I know its a noobie problem and the answer is not very difficult. What am i doing wrong ?
Every time through loop() your index will be reset to 0. You wait for at least one character to exist in the serial buffer, then read it in to element "index" (which is 0), then increment index. If there is only one character (which is often the case - one character arrives at a time into the serial buffer), then loop() will finish. Next time through to get the second character, index is 0 again.
uhm, i see, so is there a simple way to just store the whole array at the same time ? I could be able to work with the value stored in a string. Im on my wait out right now but, ill try to change my if(index<19) for some for loop. Would that be working ?
I juste want to be able to do somethings depending on the value of a char depending on is position in the array
If you are expecting a specific number of characters you can wait for that number of characters to be available in the serial buffer. Otherwise you will need to watch for a terminating character, like \r
You cannot read a whole array at one time, you have to read it character by character and put each in the next array position as you have tried to do. As has been pointed out, your problem is that you keep setting index back to zero on each pass through loop().
Reading Serial input works much slower that the repeat speed of the loop() function so by the time the next character has been read index has been set back to zero.
// zoomkat 7-30-11 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later
String readString;
void setup() {
Serial.begin(9600);
Serial.println("serial test 0021"); // so I can keep track of what is loaded
}
void loop() {
while (Serial.available()) {
delay(2); //delay to allow byte to arrive in input buffer
char c = Serial.read();
readString += c;
}
if (readString.length() >0) {
Serial.println(readString);
readString="";
}
}