从字符串转换为unsigned char *会留下垃圾

时间:2014-11-06 13:29:40

标签: c++ casting arduino unsigned-char

这是C ++的新手问题。我有一个Arduino草图,下面的代码用于传输蓝牙低能耗UART通知。

command为5个字符时,我会在蓝牙接收器端获得5个字符。但是,当我使用单个字符命令跟随5个字符command时,收到的是单个字符,后跟前一个command的最后3个字符。

实施例,

command-1,0t。我收到的是-1,0t。但是下一个command只是r。我收到的是r,0t

这里发生了什么?我如何得到“r”?

int BLEsend(String command){
    byte length = sizeof(command);    
    unsigned char* notification = (unsigned char*) command.c_str(); // cast from string to unsigned char*
    Serial.print(length);
    BLE.sendData(UART_SEND, notification, length);
    Serial.print("Notification Sent: "); Serial.println(command);
    delay(100);
    return 1;
}

2 个答案:

答案 0 :(得分:0)

sizeof( )没有给你字符串的长度。

您可以改为使用int length = command.length( );

同样command.size( );也应该有用。

答案 1 :(得分:0)

您还需要将字符串command.c_str()复制到notification

notification = new char[length + 1];
strcpy(notification , command.c_str());