There are multiple problems with your code. They suggest, that you don't know what strings really are.
In C/C++ strings are actually arrays of characters (char
). A uint8_t
is the same size of a single character, so you can only save a single character in it. For saving a string, you would need an array of them. So buffer
should be declared like
uint8_t buffer[20] = "";
Now buffer
can hold a string of 19 characters. The 20th character is the terminating null character \0
, which marks the end of a string. You must always leave enough space for the null character to terminate your strings correctly.
Serial reading: There are many ways how you can read from Serial. Look at the Serial.readStringUntil()
function, which will read from Serial until it reaches a specified character. This way you can easily divide the continuous stream of bytes from Serial into distinct messages. It is common to end all ASCII encoded messages with a newline \n
character to mark the end of the message. With Serial.readStringUntil('\n')
(note the single quotes for a single character) you will read until it reaches the newline character (or it times out). You can then process the read string as a full message.
Providing a string as parameter to a function: In C/C++ you cannot just provide an array as parameter to a function as other variables. It is a bit more complex. That is because internal the array consists just of a few bytes in a row and the variable just points to the first element of it. It is a pointer (thats a specific C/C++ term). Pointers are marked with *
, which you already did with your
void printReceivedMessage(const uint8_t* buf)
function. So the parameter is just a pointer to a uint8_t
. That also explains the error message, because you provided an uint8_t
, but the function expects a pointer to uint8_t
instead. While you still can access the array data through this parameter (given you have implemented what I wrote above about the array), sizeof(buf)
will only give you the size of the pointer (2 bytes on most Arduino platforms). So you need to add a parameter and also provide the size of the array. Or you can utilize the correct termination of strings with the null character and get the length of the string with strlen()
. That functions iterates the pointer of the array, until it finds the null character and gives you the resulting length.