0

编程语言:c++

当我编译我的程序时,我得到这个错误:
/Button.cpp:50:18: error: '_pin' was not declared in this scope

它告诉我该变量_pin没有在函数范围内声明
bool longPush(unsigned log interval),但它已声明,我什_pin至在其他函数中使用也没问题。

Button这是给我带来麻烦的库文件:

按钮.h:

#ifndef Button_h
#define Button_h
#include <Arduino.h>

class Button
{
private:
  byte _pin;
  byte _anti_bounce;
  bool _est_ant;
  bool _push;

public:
  enum PullRes : bool {FLOATING = false, PULLUP = true,};

  Button(byte pin, byte anti_bounce, PullRes = FLOATING);

  bool falling();
  bool rissing();
  bool check();
  bool longPush(unsigned long interval);    
};
#endif

按钮.cpp:

#include <Arduino.h>
#include <Button.h>
#include <Timer.h>

Button::Button(byte pin, byte anti_bounce, PullRes mode = FLOATING) {
  _pin = pin;
  _anti_bounce = anti_bounce;
  if(mode == PULLUP) pinMode(pin,INPUT_PULLUP);
  else pinMode(pin,INPUT);

}

  bool Button::rissing() {                                          //Funcion que retorna un 1 cuando se detecta un rissing en el pin <_pin>
  bool puls;
  if ((digitalRead(_pin) == 1) && (_est_ant == 0)) {
    puls = 1;
    _est_ant = 1;
  }
  else {
    puls = 0;
    _est_ant = digitalRead(_pin);
  }
  delay(_anti_bounce);
  return puls;
}

bool Button::falling() {                                          //Funcion que retorna un 1 cuando se detecta un falling en el pin <_pin>
  bool puls;
  if ((digitalRead(_pin) == 0) && (_est_ant == 1)) {
    puls = 1;
    _est_ant = 0;
  }
  else {
    puls = 0;
    _est_ant = digitalRead(_pin);
  }
  delay(_anti_bounce);
  return puls;
}

bool Button::check(){                                             //Funcion que retorna el estado actual del pin <_pin>
  return digitalRead(_pin);
}

bool longPush(unsigned long interval){
  static Timer timer(interval);
  timer.setInterval(interval);
  static bool released = true;

  if(digitalRead(_pin)){ 
    timer.end();
    released = true;
    return false;
  } else if (!timer.isRunning() && released){
    released = false;
    timer.init();
    return false;
  } else if (timer.read()){
    timer.end();
    released = false;

    return true;
  }
  return false;
}

.cpp 文件中的错误:

bool longPush(unsigned long interval){
  static Timer timer(interval);
  timer.setInterval(interval);
  static bool released = true;
////////////////////////////////////////
  if(digitalRead(_pin)){// <--- right here
    timer.end();
    released = true;
    return false;
  } else if (!timer.isRunning() && released){
    released = false;
    timer.init();
    return false;
  } else if (timer.read()){
    timer.end();
    released = false;

    return true;
  }
return false;
}
4

1 回答 1

2

_pin不是全局变量;它是一个成员变量。

您尝试将其用作全局变量,因为您定义的是longPush(全局函数)而不是Button::longPush(成员函数)。

这里:

   bool Button::longPush(unsigned long interval){
//      ^^^^^^^^

其他函数没有这个问题,因为它们的定义没有这个错字。

不过,这是一个容易犯的错误:我今天至少做了两次!

于 2018-10-30T16:47:23.317 回答