。
从"byte*"到"byte"的转换无效
我写了这个Arduino函数
byte receiveMessage(AndroidAccessory acc,boolean accstates){
if(accstates){
byte rcvmsg[255];
int len = acc.read(rcvmsg, sizeof(rcvmsg), 1);
if (len > 0) {
if (rcvmsg[0] == COMMAND_TEXT) {
if (rcvmsg[1] == TARGET_DEFAULT){
byte textLength = rcvmsg[2];
int textEndIndex = 3 + textLength;
byte theMessage[textLength];
int i=0;
for(int x = 3; x < textEndIndex; x++) {
theMessage[i]=rcvmsg[x];
i++;
delay(250);
}
return theMessage;
delay(250);
}
}
}
}
}
这是错误
In function byte receiveMessage(AndroidAccessory, boolean) invalid conversion from byte*' to 'byte"
这个函数是从安卓接收数据,并以字节数组的形式返回
您需要使用动态分配,或者将数组作为参数传递给函数,这在您的情况下是更好的解决方案
void receiveMessage(AndroidAccessory acc, boolean accstates, byte *theMessage){
if (theMessage == NULL)
return;
if(accstates){
byte rcvmsg[255];
int len = acc.read(rcvmsg, sizeof(rcvmsg), 1);
if (len > 0) {
if (rcvmsg[0] == COMMAND_TEXT) {
if (rcvmsg[1] == TARGET_DEFAULT){
byte textLength = rcvmsg[2];
int textEndIndex = 3 + textLength;
int i=0;
for(int x = 3; x < textEndIndex; x++) {
theMessage[i]=rcvmsg[x];
i++;
delay(250);
}
return;
}
}
}
}
}
有了这个,您将调用将数组传递给它的函数,例如
byte theMessage[255];
receiveMessage(acc, accstates, theMessage);
/* here the message already contains the data you read in the function */
但是你不能返回局部变量,因为数据仅在变量有效的范围内有效,事实上它在if (rcvmsg[0] == COMMAND_TEXT)
块之外是无效的,因为你在该块的本地定义了它。
注意:请阅读 Wimmel 的评论,或者如果只是文本,您可以将最后一个字节设置为 ' '
,然后将数组用作字符串。
就错误而言,您返回的值不正确。
theMessage is a byte array not a byte
最后的答案也解释了为什么你不能返回局部变量指针