首页 > 解决方案 > 没有调用回调函数?

问题描述

我在 Arduino 文件(.ino,c++)中有 2 个回调函数:

void incomingPacket(const char* subject, const char* message){
  Serial.print("subject: ");
  Serial.println(subject);
  Serial.print("message: ");
  Serial.println(message);
}

void connectedProtocol(bool connected){
  if(connected){
    Serial.println("protocol server connected");  
  }else{
    Serial.println("protocol server disconnected");  
  }
}

在我的 Arduino 文件中,我有一个自定义类UDPProtocol protocol(Udp),它在某些事件之后调用回调函数,例如:

 _connectedcb(setTo);    //this calls connectedProtocol callback in Arduino from UDPProtocol class

以上工作正常,它调用connectedProtocol()具有正确布尔值的回调函数。但是,当尝试调用incomingPacket()回调函数时,我的 Arduino 文件中没有任何反应。调用回调的方法:

//this is from UDPProtocol class
void UDPProtocol::readPacketContents(char* content){
        if(strlen(content)){                                //if content size is greater than 0
        const char* somemessage = "Hellomessage";
        const char* subject;
        const char* message;
        subject = &somemessage[0];                          //this depends on the actual format of udp packet
        message = &somemessage[1];
        _packetcb(subject,message);
        }
        _buffer[0] = 0;
    }

每当此方法运行时,不会在 Arduino 中调用回调。即使我尝试伪造消息,例如:

void UDPProtocol::readPacketContents(char* content){
        if(strlen(content)){                                //if content size is greater than 0
            const char* somemessage = "Hellomessage";
            const char* subject;
            const char* message;
            subject = &somemessage[0];                          //this depends on the actual format of udp packet
            message = &somemessage[1];
            _packetcb(subject,message);
        }
        _buffer[0] = 0;
    }

仍然没有任何反应(if(strlen(content)) 确实等于 true)。有什么建议么?

编辑:

UDPProtocol.h 文件:

typedef void (*PackedCallback)(const char* subject, const char* message);
PackedCallback _packetcb;

UDPProtocol.cpp 文件:

void UDPProtocol::setPacketCallback(PackedCallback func){
    this->_packetcb = func;
}

在 Arduino.ino 中:

protocol.setPacketCallback(incomingPacket);    //defined in this question above

编辑2:

我用完整的代码创建了一个要点:

https://gist.github.com/aliamid93/64ba2ed0e06b1f9b4401474646f8083e

标签: c++arduino

解决方案


推荐阅读