Search code examples
pointersuartesp32

Converting valuestring or valueint from cJSON to send using uart_write_bytes is failing


So, currently, I am sending a JSON message containing a value I need to send from an ESP32 UART uart_write_bytes, but am not sure where I am going wrong in the conversion. Currently, if I send 234, it goes out the UART as 50, 51, 52, and not 234. Thoughts? I am using esp-idf with GCC Compiler not Arduino.

char hex[8] = {0xff, 0xff, 0xff, 0xff};
cJSON* message'
int intValue = 0;
char *stringValue= "999";

if ((message = cJSON_GetObjectItem(root->child, "msg")) != NULL)
{
    if((intValue = cJSON_GetObjectItem(message, "Number")->valueint) != NULL)
    {
        ESP_LOGI(LOG_TAG, " this is the Number %i ", intValue);
    }
    if((stringValue = cJSON_GetObjectItem(message, "Number")->valuestring) != NULL)
    {
       ESP_LOGI(LOG_TAG, " This is NumberString %s ", stringValue);
    }   
}

char numStrStr[3];
sprintf(numStrStr, "%s", stringValue );
for(int j = 0; j < sizeof(str); j++)
{
    hex[j] = numStrStr[j];
}

int checkIt = uart_write_bytes(UART_NUM_2, (const char *)hex, strlen(hex));

Solution

  • I got it to work with the following changes: I forgot to mention that I want to send one character at a time, so that means sending in '234' as a char, then converting it to an int, then doing the fun math of breaking it into 1's, 10's, and 100's for sending to serial.

    cJSON *message;
    int intValue = 0;
    const char *buffValue = "999";
    
    hex[0] = 0xfe;
    hex[1] = 0x01;
    hex[2] = 0x01;
    hex[3] = 0x00;
    
    if((buffValue = cJSON_GetObjectItem(message, "NUmber")->valuestring) != NULL)
    {
       ESP_LOGI(LOG_TAG, " This is Value String %s ", buffValue);
       ESP_LOGI(LOG_TAG, "strtol %ld ", strtol(buffValue, NULL, 10));
       intValue = strtol(buffValue, NULL, 10);
    
        int valueArray[3] = {0};
        int increment = 0;
        while(intValue > 0)
        {
            int digitValue = intValue % 10;
            valueArray[increment] = digitValue;
            intValue /= 10;
            increment ++;
        }
        hex[3] = valueArray[2];
        hex[4] = valueArray[1];
        hex[5] = valueArray[0];
    }   
    
    
    int checkIt = uart_write_bytes(UART_NUM_2, (const char *)hex, strlen(hex));