I am Trying to Understand the Code
int readline(int readch, char *buffer, int len)
{
static int pos = 0;
int rpos;
if (readch > 0) {
switch (readch) {
case '\n': // Ignore new-lines
break;
case '\r': // Return on CR
rpos = pos;
pos = 0; // Reset position index ready for next time
return rpos;
default:
if (pos < len-1) {
buffer[pos++] = readch;
buffer[pos] = 0;
}
}
}
// No end of line has been found, so return -1.
return -1;
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
static char buffer[80];
if (readline(Serial.read(), buffer, 80) > 0) {
Serial.print("You entered: >");
Serial.print(buffer);
Serial.println("<");
}
}
The Functions Returns The Value of POS.
buffer Is Available to Print in the Loop?
It is not declared as Global Variable And the function is not returning it?
Read up on pointers. The array 'buffer' is passed to the function as a pointer, its memory location. Pointers can be used in code similar to arrays.
http://www.cplusplus.com/doc/tutorial/pointers/
http://www.cplusplus.com/doc/tutorial/arrays/
Once you can understand pointers, I have written an article here focused on passing arrays to functions. Its not directly what you need, but hopefully it might make understanding the concepts easier. You can also see how you might modify the function to accept a reference rather than a pointer.
anilkunchalaece:
buffer Is Available to Print in the Loop?
It is not declared as Global Variable And the function is not returning it?
Yes, 'buffer' is declared in loop() so it is available to print in loop().
The function can access it because a pointer to 'buffer' is passed as an argument. THE FUNCTION CAN'T DETERMINE THE SIZE OF 'buffer' BECAUSE ALL IT HAS IS THE ADDRESS. That i why the length of 'buffer' is passed as another argument: so that the function can protect against a buffer overflow.
Of course since separate constants are used in the declaration and function call they could get out of sync in an edit. Better to use a named constant:
const int BUFFER_SIZE = 80;
static char buffer[BUFFER_SIZE];
if (readline(Serial.read(), buffer, BUFFER_SIZE) > 0)