不工作的指针返回地址不值

时间:2017-04-13 15:55:56

标签: c++ class pointers

让我疯了。我看不出以下不起作用的原因。它总是返回值的地址,而不是值本身。

我已经尝试了十几种不同的方法来初始化指针并引用指针无济于事。

Init和Loop

  //INIT the Motors 
  //Motor MOTORNAME(PWM_SHIELD_POSITION, POINTER TO PWM SHIELD)
    Motor LFUpper;
    Motor* ptr1 = &LFUpper;
    Motor LFLower;
    Motor* ptr2 = &LFUpper;
    Motor RFUpper;
    Motor* ptr3 = &LFUpper;
    Motor RFLower;
    Motor* ptr4 = &RFLower;
    Motor BRUpper;
    Motor* ptr5 = &BRUpper
    Motor BRLower;
    Motor* ptr6 = &BRLower
    Motor BLUpper;
    Motor* ptr7 = &BLUpper
    Motor BLLower;
    Motor* ptr8 = &BLLower


    //Init The Menu System
    Menu MenuSys( ptr1, ptr2, ptr3, ptr4, ptr5, ptr6, ptr7, ptr8);


void setup() {
  // put your setup code here, to run once:
    Serial.begin(9600);
    Serial2.begin(9600);
    Serial.print("HELLO");
    ptr1->INIT(FRONT_UPPER_LEFT_MOTOR);
    ptr1->INIT(FRONT_LOWER_LEFT_MOTOR);
    ptr1->INIT(FRONT_UPPER_RIGHT_MOTOR);
    ptr1->INIT(FRONT_LOWER_RIGHT_MOTOR);
    ptr1->INIT(BACK_UPPER_RIGHT_MOTOR);
    ptr1->INIT(BACK_LOWER_RIGHT_MOTOR);
    ptr1->INIT(BACK_UPPER_LEFT_MOTOR);
    ptr1->INIT(BACK_LOWER_LEFT_MOTOR);
}

void loop() {
  // put your main code here, to run repeatedly:
  // Poll The Menu For Changes

  MenuSys.MenuPoll();
}

菜单处理程序

Menu::Menu(Motor *LFUpper1, Motor *LFLower1, Motor *RFUpper1, Motor *RFLower1, Motor *RBUpper1, Motor *RBLower1, Motor *LBUpper1, Motor *LBLower1)
{
  LFUpper = LFUpper1;
  LFLower = LFLower1;
  RFUpper = RFUpper1;
  RFLower = RFLower1;
  LBUpper = LBUpper1;
  LBLower = LBLower1;
  RBUpper = RBUpper1;
  RBLower = RBLower1;
}

void Menu::MenuPoll()
{
  if (Serial2.available())
  {
    String readVal;
    int rw = 0;
    readVal = Serial2.readString();
    Serial.println(readVal);
    if (readVal.startsWith("W"))
    {
      rw = 1;
    }
    else
    {
      rw = 0;
    }
    int MenuCommand = readVal.substring(1, 4).toInt();
    int Value =  readVal.substring(4, readVal.length()).toInt();

    MenuHandler(rw, MenuCommand, Value);
  }
}

void Menu::MenuHandler(int rw, int MenuCommand, int Value)
{
  Serial.println(rw);
  Serial.println(MenuCommand);
  Serial.println(Value);
  switch (MenuCommand) {
      case 111:
      if (rw == 1)
       {
        Serial.print(LFUpper->pwmMIN);
        LFUpper->pwmMIN = Value;
       }

Serial.print(LFUpper->pwmMIN);行无法打印正确的值

2 个答案:

答案 0 :(得分:0)

看起来你正在处理错误对象的地址。

Motor LFUpper;
Motor* ptr1 = &LFUpper;
Motor LFLower;
Motor* ptr2 = &LFUpper;
Motor RFUpper;
Motor* ptr3 = &LFUpper;

可能应该是

Motor LFUpper;
Motor* ptr1 = &LFUpper;
Motor LFLower;
Motor* ptr2 = &LFLower;
Motor RFUpper;
Motor* ptr3 = &RFUpper;

同样,您的ptr1->INIT()屏蔽了INIT上的所有电话ptr1

答案 1 :(得分:0)

我发现了一些其他的问题,我认为会解决这个问题,并且实际上是这样做的,所以它第一次通过循环然后它会中断...例如,如果它看到的值是第一次通过我的123会得到123而下一个我得到529000而且我没有对周期之间的数据做任何操作。所以我回到方块1并删除了作为函数参数传递的所有嵌套指针,现在它可以正常工作