如何修复digitalRead

时间:2019-04-30 18:39:31

标签: arduino arduino-c++

所以我的问题是,在两次读取数字引脚6,7之后,该引脚由于某种原因一直保持开启状态,这是我的代码。我似乎无法找到为什么会发生这种情况,因此尝试添加一些delay(x);但这并没有帮助..针脚5从未发生过,这对我来说更奇怪...任何帮助将不胜感激

#include <Stepper.h>

int obstaclePin = A0;
int obstaclePin2 = A1;
int obstaclePin3 = A2;

const int button1Pin = 5;
const int button2Pin = 6;
const int button3Pin = 7; 

const int stepsPerRevolution = 80;

Stepper myStepper(stepsPerRevolution, 50, 51, 52, 53);
Stepper myStepper2(stepsPerRevolution, 46, 47, 48, 49);
Stepper myStepper3(stepsPerRevolution, 42, 43, 44, 45);

void setup() {
  myStepper.setSpeed(100);
  myStepper2.setSpeed(100);
  myStepper3.setSpeed(100);

  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);

  pinMode(obstaclePin, INPUT);    // sets the sensor pin
  pinMode(obstaclePin2, INPUT);    // sets the sensor pin
  pinMode(obstaclePin3, INPUT);    // sets the sensor pin

  pinMode(button1Pin, INPUT_PULLUP);    // declare pushbutton as input
  pinMode(button2Pin, INPUT_PULLUP);
  pinMode(button3Pin, INPUT_PULLUP);

  Serial.begin(9600);    // initialize the serial port:
}
int counter = 0;
void loop() {
  while(true){
    if(digitalRead(button1Pin)==0){
      counter = 1;
      break;
    }
    else if(digitalRead(button2Pin)==0){
      counter = 2;
      break;
    }
    else if(digitalRead(button3Pin)==0){
      counter = 3;
      break;
    }
  }
  while(counter!=0){
    digitalWrite(2,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(4,HIGH);
//*******************************************************************************************************************************************************
    if(counter==1){
      if(analogRead(obstaclePin)<=400){
        counter=0;
        delay(100);
        break;
      }
      Serial.println("Motor 1");
      myStepper.step(1);
    }
//*******************************************************************************************************************************************************
    else if(counter==2){
      if(analogRead(obstaclePin2)<=400){
        counter=0;
        delay(100);
        break;
      }
      Serial.println("Motor 2");
      myStepper2.step(1);
    }
//*******************************************************************************************************************************************************
    else if(counter==3){
      if(digitalRead(obstaclePin3)==0){
        counter=0;
        delay(100);
        break;
      }
      Serial.println("Motor 3");
      myStepper3.step(1);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

去抖输入是这里的解决方法。