cchartransformuint8tuint16

Convert char* data to uint16_t* or uint16_t array in C


My Arduino program receives a char* text message like this:

char* messageFromWebSocket = "4692\n4408\n656\n358\n662\n356\n658\n376\n656\n358\n662\n1394\n660\n1392\n636\n378\n632\n382\n638\n1418";

Now the IRremoteESP8266 library I used controls the IR LED through the sendRaw() function using this data, but in uint16_t form. Example:

uint16_t rawData[39] = {9064, 4408, 580, 4408,  580,  2152, 578, 2150,
                          580,  4408, 580, 30622, 9066, 2148, 580};
irsend.sendRaw(rawData, 39, 39);

Is there any way to convert my char* to uint16_t ?

I have:

char* messageFromWebSocket = "4692\n4408\n656\n358\n662\n356\n658\n376\n656\n358\n662\n1394\n660\n1392\n636\n378\n632\n382\n638\n1418";

I want get:

uint16_t* rawData = {4692, 4408,  656, 358,  662, 356,  658, 376,  656, 358,  662, 1394,  660, 1392,  636, 378,  632, 382,  638, 1418};

The size of the rawData will vary depending on the messageFromWebSocket, because each time the program passes, there is different data there. Thank you in advance for your help because I have no idea how to solve this.


Solution

  • below I show how I managed to do the conversion:

    #define LENGTH 200
    uint16_t rawData[LENGTH];
    
    void parseCharToUint16WithIrSend(char* textData){
        Serial.printf("Parsing '%s':\n", textData);
        char *end;
        int sizeArray = 0;
    
        for (unsigned long i = strtoul(textData, &end, 10);
             textData != end;
             i = strtoul(textData, &end, 10))
        {
            textData = end;
            rawData[sizeArray] = i;
            Serial.printf("Value = %d\n", rawData[sizeArray]);
            sizeArray++;
        }
        
        printf("Actual array data size: %d\n", sizeArray);
        irsend.sendRaw(rawData,sizeArray,38); // here in rawData we have converted all values from char* to uint16_t
        Serial.println("=> DATA WAS SEND BY IR LED");
        
        sizeArray=0; // set index to 0
        memset(rawData, 0, LENGTH); // clear array
    }
    

    (I guess it may not be the best solution but it works)