从'byte *'到'byte'的无效转换

时间:2015-01-17 22:27:34

标签: android c arduino adk

来自'字节的无效转换*'到'字节'

我已经写过这个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"

这个函数是从android接收数据并将其作为字节数组返回

2 个答案:

答案 0 :(得分:2)

您需要使用动态分配,或将数组作为参数传递给函数,这是您案例中更好的解决方案

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 的评论,或者您可以将最后一个字节设置为'\0'(如果它只是文本),然后将数组用作一个字符串。

答案 1 :(得分:0)

就错误而言,您返回的值不正确。

theMessage is a byte array not a byte 

最后的答案也解释了为什么你不能返回局部变量指针