[英]How can I convert a String to a uint8_t in C++ (Arduino/C++)?
我有一個字符串: String outputValue = ""
,然后將其附加到其中以構建一個類似於JSON的結構以發送到遠程設備。 該代碼使用Arduino引導程序在ATMEGA328P上運行。 我通過執行outputValue += "hello"
。
我用來發送值的庫需要一個uint8_t *
來作為其有效負載以及相關的有效負載長度。 有什么方法可以將此String強制轉換/轉換為uint8_t數組,還是有一種首選的生成方法而不是使用String? 我願意接受任何建議
我用來測試庫的工作代碼如下。 注意,這只是我將原始outputValue復制到Notepad,將每個字符括在單引號中,然后對該新數組進行硬編碼以進行測試的結果:
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);
就在這里。
做這樣的事情:
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);
您可以這樣編寫數組:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.