I am sending some data over an NRF24 link, using the RF24Network library. So far I have only sent numbers, now I also want to send a string, so I have set up my payload struct as
struct payload_t { // Structure of our payload
unsigned long data;
unsigned long datatype;
char sensorid[20];
unsigned long counter;
};
As far as I do understand, I can not use string here, since I need to know the length of the data I am sending.
At the moment I am using sensors without an internal ID, so in loop()
, I am calling:
writeToNetwork(voltage,'v',"nosid",packets_sent++);
My writeToNetwork
function is defined as
bool writeToNetwork(unsigned long data,unsigned long type,char sid[20],unsigned long package){
and within that, I am setting up the payload with
payload_t payload = { data,type,sid, package };
Which gives me an
error: invalid conversion from ‘char*’ to ‘char’ [-fpermissive]
Clearly, I have no interest of the address the pointer is referencing, so I need to somehow dereference the sid
- pointer to get my array into the struct. How can I do that?
Or am I barking up the wrong tree? I tried to transfer the id as a string:
#include <string.h>
bool writeToNetwork(unsigned long data,unsigned long type,String sid,unsigned long package){
char sidchar[20];
sid.toCharArray(sidchar,20);
payload_t payload = { data,type,sidchar, package };
Which gives me the error
array must be initialized with a brace-enclosed initializer
Which I do not understand. Doing
char sidchar[20]={0};
gives me the same error.
1 Answer 1
In your situation, your best bet is probably to use the standard C function strcpy
:
payload_t payload;
char* source = "abcdef";
strcpy(payload.sensorid, source);
Note that source string does not have to be declared as char source[20]
and can be declared as the rather standard C string char*
.
Also, since you are limiting the size of the string to be passed in payload
, you may prefer to use strncpy
which will ensure no more than 20 characters get copied:
payload_t payload;
char* source = "abcdef";
strncpy(payload.sensorid, source, 20);
// Explicitly add a string termination to the end of string
payload.sensorid[19] = 0;
In the snippet above, please notice the last line, it is necessary in the situation where source
string length is 20 or more non-null characters, as in this case, strncpy
will copy all 20 characters but will not add the terminating 0 at the end of the string.
-
I deleted my comment as I was wrong with the missing
0円
.ott--– ott--2016年02月22日 16:25:14 +00:00Commented Feb 22, 2016 at 16:25
I can not use string here
- do you mean a "string" or a "String
" object? I only ask, because you are using a "string" withchar sensorid[20];
... Also, have I linked to the correct RF24Network library?