使用 uart_write_bytes 从 cJSON 转换 valuestring 或 valueint 以发送失败

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

因此,目前,我正在发送一条 JSON 消息,其中包含我需要从 ESP32 UART uart_write_bytes 发送的值,但我不确定我在转换过程中哪里出错了。 目前,如果我发送 234,它会作为 50、51、52 ​​而不是 234 离开 UART。 想法? 我正在使用带有 GCC 编译器的 esp-idf 而不是 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));

那是因为字符2('2')的ASCII码是50,字符3('3')是51,字符4('4')是52。

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

如果您观察到上面的行,您已经明确地将 hex 类型转换为 const char*,本质上是将数据编码为 ASCII(假设是 gcc 编译器),这是通过 UART 传输的。

在UART 接收设备或程序中,您需要将传入数据视为ASCII 编码数据。您可以使用 CoolTerm 等终端程序查看 booth ASCII 编码 and/or RAW 数据。

要发送原始数据,您可以使用 const char * 避免显式类型转换,假设存储在十六进制中的数据是 [0x02, 0x03, 0x04] 而不是 ['2', '3', '4']

我通过以下更改让它工作: 我忘了提到我想一次发送一个字符,所以这意味着将“234”作为一个字符发送,然后将其转换为一个整数,然后进行有趣的数学运算,将其分解为 1、10 和 100发送到串行。

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));