在C中动态创建对象(使用radiohead库)

时间:2014-10-02 07:23:49

标签: c arduino

我正在尝试使用NRF24l01 +在我的arduino上实现动态地址分配,但是在我的单元收到它的指定地址之后我无法全局初始化RHReliableDatagram

这就是我所拥有的(由于某种原因,它不起作用:

manager = new RHReliableDatagram(driver, ID);

错误:

sketch_oct02b.ino: In function 'void setup()':
sketch_oct02b:47: error: no match for 'operator=' in 'manager = (((RHReliableDatagram*)operator new(267u)), (<anonymous>->RHReliableDatagram::RHReliableDatagram(((RHGenericDriver&)(& driver.RH_NRF24::<anonymous>.RHNRFSPIDriver::<anonymous>)), ((uint8_t)ID)), <anonymous>))'
C:\Users\****\Documents\HAS\HAS-mc\libraries\RadioHead/RHReliableDatagram.h:66: note: candidates are: RHReliableDatagram& RHReliableDatagram::operator=(const RHReliableDatagram&)

这是可行的代码,但我无法在运行时更改地址。

RHReliableDatagram manager(driver, DHT1_ADDRESS);

这里我的问题的最小再现:

#include <RHReliableDatagram.h>
#include <RH_NRF24.h>
#include <SPI.h>
#include <DHT.h>

RH_NRF24 driver(8,10);

int ID = 255; //init ID, will be reassigned by server
RHReliableDatagram manager(driver,ID);//255 is the ID before init


void setup() 
{
  ID = 15;
  manager = new RHReliableDatagram(driver, ID);//NOTE added this
  //spi.setPins(13, 4, 3); //miso mosi sck
  if (!manager.init()){
    Serial.println("NRF failed to initialise");
    digitalWrite(PIN_NRF_ERROR,HIGH);
  } else {
    Serial.println("NRF succesfully initialized");
  }
}

void loop()
{

}

无线电头库的文档在这里: http://www.airspayce.com/mikem/arduino/RadioHead/classRHReliableDatagram.html

2 个答案:

答案 0 :(得分:1)

您需要将动态分配的对象分配给该对象类型的指针,例如

type *p_var = new type(initializer)

在您的代码中应删除

RHReliableDatagram manager(driver,ID);//255 is the ID before init

并更改

manager = new RHReliableDatagram(driver, ID);//NOTE added this

RHReliableDatagram *manager = new RHReliableDatagram(driver, ID);//NOTE added this

此外,您需要记住使用delete()释放管理员不再需要的内存。

答案 1 :(得分:0)

我迟到但是 - 有一个功能可以做到这一点。

使用:

manager.setThisAddress(ID);

void RHDatagram::setThisAddress(uint8_t thisAddress)
{
    _driver.setThisAddress(thisAddress);
    // Use this address in the transmitted FROM header
    setHeaderFrom(thisAddress);
    _thisAddress = thisAddress;
}