Reputation: 553
I have a string: String outputValue = ""
that I then append to to build a JSON-like structure to send to a remote device. This code runs on an ATMEGA328P using the Arduino bootloader. I append values by doing outputValue += "hello"
.
The library I am using to send the values needs a uint8_t *
for it's payload with the associated length of that payload. Is there any way to cast/convert this String to a uint8_t array or is there a preferred way to do a builder rather than using String? I'm open to any suggestions
My working code that I used to test the library has the following. Note, this is just the result of me copying the raw outputValue to Notepad, enclosing each character in single quotes, then hardcoding this new array to test:
uint8_t testCmd[] = { '{', '"', 'T', '"', ':', '"', 'A', '1', '"', ',', '"', 'E', '"', ':', '-', '1', ',', '"', 'I', '"', ':', '[', '[', '1', ',', '[', '[', '[', '[', '2', '5', '0', ',', '2', ']', ',', '[', '0', ',', '4', ']', ']', ']', ']', ']', ']', '}' };
ZBTxRequest txReq = ZBTxRequest(coordinatorAddr64, testCmd, sizeof(testCmd));
ZBTxStatusResponse txResp = ZBTxStatusResponse();
xbee.send(txReq);
Upvotes: 1
Views: 3630
Reputation: 6240
You can write your array like this:
uint8_t testCmd[] = R"({"T":"A1","E":-1,"I":[[1,[[[[250,2],[0,4]]]]]]})";
The difference is that it will have 48 elements instead of 47 like your original one, because of terminating 0. Since you are providing the length of packet you could -1 it:
ZBTxRequest txReq = ZBTxRequest(coordinatorAddr64, testCmd, sizeof(testCmd) - 1);
ZBTxStatusResponse txResp = ZBTxStatusResponse();
xbee.send(txReq);
Looking at Arduino reference. String
object has c_str() method as well as length(). So you can simply try:
String testCmd R"({"T":"A1","E":-1,"I":[[1,[[[[250,2],[0,4]]]]]]})";
ZBTxRequest txReq = ZBTxRequest(coordinatorAddr64, (uint8_t *)testCmd.c_str(), (uint8_t)testCmd.length());
ZBTxStatusResponse txResp = ZBTxStatusResponse();
xbee.send(txReq);
Upvotes: 1
Reputation: 1121
Yes there is.
Do something like this:
String testString = "Test String";
uint8_t* pointer = (uint8_t*)testString.c_str();
int length = testString.length();
EDIT:
You should apply it to your problem as follows:
String testString = "Test String";
uint8_t* pointer = (uint8_t*)testString.c_str();
int length = testString.length();
ZBTxRequest txReq = ZBTxRequest(coordinatorAddr64, pointer, length);
ZBTxStatusResponse txResp = ZBTxStatusResponse();
xbee.send(txReq);
Upvotes: 3