There are a few problems with your code sample:
You check for Serial.available()>0
, but then assume/grab only one character:
if (Serial.available() > 0) {
s = Serial.read();
}
It is possible that the serial receive buffer has more than one byte waiting, but you only capture one.
k[10] = s;
You assign the captured character to the last element of the byte array, regardless of all else. This presents two main problems
- A C-style string must be terminated with a null character (
'\0'
), and you have immediately put real data in the position that should contain the terminating byte.
- There is no possible way that bytes 0-9 can ever have any data written to them by this code.
Your code assumes that the entire string exists in k[]
every time through loop()
. Instead, you should assume that it might take hundreds or thousands of times through loop()
just to finish receiving your string. The input string should have some kind of end-of-string marker like a newline ('\n'
) or carriage-return ('\r'
) (or both) so that your program can look for that and know when the input is fully received.
Below is a simple program that receives a string. Note that it has a portion labeled for when to process the recieved data. That block of code is only entered once a newline and/or carriage return are received.
#DEFINE MAX_INPUT 90
char inputBuffer[MAX_INPUT+1]; // Handles up to 90 bytes in a c-style string, with a null character termination.
void setup()
{
Serial.begin(115200); // initialization
inputBuffer[0] = '\0'; //Initialize string to emtpy.
Serial.println("Begin:");
}
void loop() {
if (Serial.available()>0)
{
char input = Serial.read();
static int s_len; // static variables default to 0
if (s_len>=MAX_INPUT) {
// Have received already the maximum number of characters
// Ignore all new input until line termination occurs
} else if (input != '\n' && input != '\r') {
inputBuffer[s_len++] = input;
} else {
// Have received a LF or CR character
// INSERT YOUR CODE HERE TO PROCESS THE RECEIVED DATA //
// YOU COULD COPY TO A NEW VARIABLE WITH strncpy() OR //
// SET A FLAG TO SAY TO START SOME OTHER TASK //
Serial.print("RECEIVED MSG: ");
Serial.println(inputBuffer);
memset(inputBuffer, 0, sizeof(inputBuffer));
s_len = 0; // Reset input buffer here if you
// have already copied the data.
// If you don't reset here, then
// you can't start receiving more
// serial port data. This is your
// 'software' serial buffer, contrast
// with the hardware serial buffer.
}
}
}