代码之家  ›  专栏  ›  技术社区  ›  Phillip McMullen

如何在C++(Arduino/C++)中将字符串转换为uint8\t?

  •  1
  • Phillip McMullen  · 技术社区  · 7 年前

    我有一个字符串: String outputValue = "" 然后我将其附加到以构建类似JSON的结构以发送到远程设备。此代码使用Arduino引导加载程序在ATMEGA328P上运行。我通过执行以下操作附加值 outputValue += "hello"

    我用来发送值的库需要 uint8_t * 因为它是有效载荷和该有效载荷的相关长度。是否有任何方法可以将此字符串强制转换/转换为uint8\t数组,或者有没有更好的方法来执行生成器而不是使用字符串?我愿意接受任何建议

    我用来测试库的工作代码如下所示。注意,这只是我将原始输出值复制到记事本的结果,将每个字符括在单引号中,然后对这个新数组进行硬编码以测试:

    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);
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Ricardo Alves    7 年前

    是的,有。

    执行以下操作:

    String testString = "Test String";
    uint8_t* pointer = (uint8_t*)testString.c_str();
    int length = testString.length();
    

    编辑:

    您应该将其应用于您的问题,如下所示:

    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);
    
        2
  •  1
  •   Killzone Kid    7 年前

    可以这样编写数组:

    uint8_t testCmd[] = R"({"T":"A1","E":-1,"I":[[1,[[[[250,2],[0,4]]]]]]})";
    

    不同之处在于,由于终止0,它将有48个元素,而不是像原来的47个元素。由于您提供的是数据包的长度,因此您可以-1它:

    ZBTxRequest txReq = ZBTxRequest(coordinatorAddr64, testCmd, sizeof(testCmd) - 1);   
    ZBTxStatusResponse txResp = ZBTxStatusResponse();
    
    xbee.send(txReq);
    

    查看Arduino参考。 String 对象具有 c_str() 方法以及 length() 。因此,您可以简单地尝试:

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