理解'this'指针

时间:2014-06-11 22:15:13

标签: arduino

我正在尝试创建自己的Servo Write类,这样我就能更好地理解PWM的工作原理。我基本上从Servo.h复制了Servo :: write函数并尝试将其粘贴到我的代码中,但是我没有得到“this”错误。

#include "Servo.h"

#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4)  // minimum value in uS for this servo
#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4)  // maximum value in uS for this servo 

Servo leftServo, rightServo;

int leftServoPos = 90;
int rightServoPos = 90;
int count;

void setup()
{

 leftServo.attach(5);
 rightServo.attach(8);

 leftServo.write(90);
 rightServo.write(90); 

}

void loop()
{

  delay(3000);

  for(count = 1; count < 100; count++)
  {

      leftServo.write(leftServoPos + count);
      rightServo.write(rightServoPos - count);

  }

  delay(1000);

  for(count = 1; count < 100; count++)
  {

      leftServo.write(leftServoPos - count);
      rightServo.write(rightServoPos + count);

  }

}

void writeServo(Servo servo, int value)
{  
  if(value < MIN_PULSE_WIDTH)
  {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
    if(value < 0) value = 0;
    if(value > 180) value = 180;
    value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());      
  }
  this->writeMicroseconds(value);
}

错误:

sketch_jun11a.ino: In function 'void writeServo(Servo, int)':
sketch_jun11a:59: error: invalid use of 'this' in non-member function
sketch_jun11a:59: error: invalid use of 'this' in non-member function
sketch_jun11a:61: error: base operand of '->' has non-pointer type 'Servo'

2 个答案:

答案 0 :(得分:2)

this ->

被称为this指针,指针被隐式创建并指向调用成员函数的对象。

因为你的函数不在类中,所以指针不存在。

答案 1 :(得分:1)

this->writeMicroseconds(value);

是您复制代码的类的成员函数。 'this'指针,基本上意味着'指向我自己',所以这就是'在我的类中调用writeMicroseconds()方法'。

要修复错误,只需将writeMicroseconds()方法复制到草图上,然后删除this-&gt;来自方法调用。