从库中获取函数的问题和奇怪的转换错误

Issue getting functions from library and strange conversion error

我正在尝试编写一个 arduino 库。我之前写过一些 类 但没有写给 arduino。我 运行 经常犯一个错误。首先让我向您展示代码:

代码

Main.ino(arduino 项目)

#include <Wire.h>
#include "Mobility.h"

Mobility mol = new Mobility();
void setup() {
  Serial.begin(9600);
  Wire.begin();
}

void loop() {
  Serial.println("loop");
  mol.move(true, 125, false, 125, 10);
  delay(2000);
}

Mobility.h

#ifndef MOBILITY_H
#define MOBILITY_H

#if (ARDUINO >= 100)
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif


const int DEFAULT_MOBILITY_ADD  = 4;

class Mobility
{
public:
    void begin();
    void begin(int address);
    int i2cAdd;
    int move(bool lPos, unsigned char leftPower, bool rPos, unsigned char rightPower, unsigned char msec);
private:

};
/**/
#endif

Mobility.cpp

#if (ARDUINO >= 100)
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif
#include "Mobility.h"
#include "Wire.h"


void Mobility::begin(){
    Wire.begin();
    this.i2cAdd = DEFAULT_MOBILITY_ADD;
}

void Mobility::begin(int address){
    Wire.begin();
    this.i2cAdd = address;
}

int Mobility::move(bool lPos, unsigned char leftPower,bool rPos, unsigned char rightPower, unsigned char msec){
  if (leftPower < -255 || leftPower > 255){
    return -1;
  }
  if (rightPower < -255 || rightPower > 255){
    return -2;
  }
  if(msec <= 0){
    return -3;
  }

  Wire.beginTransmission(this.i2cAdd);
  Wire.write(lPos);
  Wire.write(leftPower);
  Wire.write(rPos);
  Wire.write(rightPower);
  Wire.write(msec);
  Wire.endTransmission();
  return 0;
}

错误

我在尝试修复代码时遇到了两个大错误。第一个是: 错误:请求从 'Mobility*' 到非标量类型 'Mobility' 的转换 流动性 mol = new Mobility();

问题是由这一行引起的:

 Mobility mol = new Mobility();

第一部分是静态内存分配:Mobility mol - 为对象静态分配内存mol

第二部分使用动态内存分配:new - 动态分配内存。

所以你可以这样做:

Mobility mol;// static allocation

Mobility *mol = new Mobility(); //dynamic allcocation

但不是两者的混合。无论哪种方式,构造函数都会在创建对象时被调用。