How to convert a string into an uint8_t array on Arduino?

Engo picture Engo · Mar 31, 2016 · Viewed 12k times · Source

I have a string that contains both numbers and character values like "p1200" for example. I need to convert this string into a uint8_t array, because I need to send it from my xBee.

How can I convert

String dataString = "p1200"

into

uint8_t dataArray[]

?

I tried to send this string using the following code:

power = ((360 * pulseCount) / 60);
String dataString = "p" + power;
char dataArray[sizeof(dataString)];
dataString.toCharArray(dataArray, sizeof(dataString));
XBeeAddress64 addr64 = XBeeAddress64();
addr64.setMsb(0x13A200);
addr64.setLsb(0x406A42B7);
ZBTxRequest zbTx = ZBTxRequest(addr64, (uint8_t *)dataArray, sizeof(dataArray));
xbee.send(zbTx);

And receive the string using the following code:

String incomingData;
xbee.readPacket();
if (xbee.getResponse().isAvailable()) {
    Serial.println(xbee.getResponse().getApiId());
    if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE) {
        xbee.getResponse().getZBRxResponse(rx);
        for (int i = 0; i < rx.getDataLength(); i++) {
            incomingData += (char)rx.getData(i); 
        }
    }
}

When I print incomingData, I get a strange ouput... I thought it was caused by the conversion from string to uint8_t

Answer

LPs picture LPs · Mar 31, 2016

Take a look HERE

uint8_t dataArray[dataString.length()];
dataString.toCharArray(dataArray, dataString.length())