我的课程中的对象宣言与adafruit Motor库

时间:2014-11-09 01:10:53

标签: c++ arduino

 class JAAmtr {
  private:
    boolean lefton;
  public:
    JAAmtr();
    void turnleft();
    void turnright();
    boolean getLefton();
 };

您好, 我正在写这个课程,让我的arduino机器人向左或向右转。

我在哪里放置电机分配的代码(我希望它进入我的班级):

 AF_DCMotor motor1(1);
 AF_DCMotor motor2(2);
 AF_DCMotor motor3(3);
 AF_DCMotor motor4(4); 

我尝试将其作为私有变量,但它无法正常工作。 谢谢你的回答

这是我的代码:

#include <AFMotor.h>


 // pin assignments
 int PhotoR1 = 1;
 int PhotoR2 = 5;

     **//Following 4lines into my class**
     AF_DCMotor motor1(1);
     AF_DCMotor motor2(2);
     AF_DCMotor motor3(3);
     AF_DCMotor motor4(4); 


 class JAAmtr {
  private:
    boolean lefton;
  public:
    JAAmtr();
    void turnleft();
    void turnright();
    boolean getLefton();
 };

void setup(){

 JAAmtr viermotor; 

 pinMode(PhotoR1, INPUT);
 pinMode(PhotoR2, INPUT);
 Serial.begin(9600);  


}

//LOOP:
void loop(){
 int light0 = analogRead(PhotoR1);
 int light1 = analogRead(PhotoR2);
 Serial.print(light0);
 Serial.print(" <-R1 R5-> ");
 Serial.println(light1);
 if( light0 > light1 )
 {

 } else {


}
  delay(500);
}
//END LOOP

JAAmtr::JAAmtr(){  
 motor1.setSpeed(200); //Turn on the Motor
 motor1.run(RELEASE);
 motor2.setSpeed(200); //Turn on the Motor
 motor2.run(RELEASE);
 motor3.setSpeed(200); //Turn on the Motor
 motor3.run(RELEASE);
 motor4.setSpeed(200); //Turn on the Motor
 motor4.run(RELEASE);

}

void JAAmtr::turnleft(){
    if(lefton == false)
    {
        motor1.run(RELEASE);
        motor2.run(RELEASE);
        motor3.run(RELEASE);
        motor4.run(RELEASE);
        delay(500);
        lefton = true;
    }
        motor1.run(BACKWARD);
        motor2.run(BACKWARD);
        motor3.run(FORWARD);
        motor4.run(FORWARD);

}

void JAAmtr::turnright(){
    if(lefton == true)
    {
        motor1.run(RELEASE);
        motor2.run(RELEASE);
        motor3.run(RELEASE);
        motor4.run(RELEASE);
        delay(500);
        lefton = false;
    }
        motor3.run(BACKWARD);
        motor4.run(BACKWARD);
        motor1.run(FORWARD);
        motor2.run(FORWARD);

}

//MOVE FORWARD FUCNTION

1 个答案:

答案 0 :(得分:2)

在私有部分中,声明成员变量

AF_DCMotor motor1;
AF_DCMotor motor2;
AF_DCMotor motor3;
AF_DCMotor motor4; 

然后在构造函数中初始化它们

JAAmtr::JAAmtr() : motor1(1), motor2(2), motor3(3), motor4(4)
{  
    motor1.setSpeed(200); //Turn on the Motor
    motor1.run(RELEASE);
    motor2.setSpeed(200); //Turn on the Motor
    motor2.run(RELEASE);
    motor3.setSpeed(200); //Turn on the Motor
    motor3.run(RELEASE);
    motor4.setSpeed(200); //Turn on the Motor
    motor4.run(RELEASE);

}