我回来了另一个与家庭作业无关的问题。我正在和我的兄弟一起玩 arduino,我们正在尝试附加一个按钮,以便在按下按钮时,他的传感器保持开启并执行它必须做的事情。当再次按下它时,它什么也不做并关闭。现在当按钮被按住时它会保持打开状态,但是当它未按下时它会保持关闭状态。我们正在尝试制作一些东西,当它被扔出建筑物时会持续拍照。它会在超声波传感器读数 <= 5 时停止。按住按钮时我不能从屋顶上跳下来 XD 这是一个 2 针按钮。
这是我们现在拥有的代码:
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 11;
const int ledPin = 13;
const int buttonPin = 2;
// defines variables
long duration;
int distance;
int safetyDistance;
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
pinMode(echoPin, INPUT);// Sets the echoPin as an Input
pinMode(buttonPin, INPUT);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(buzzer, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600); // Starts the serial communication
myservo.attach(8); // attaches the servo on pin 9 to the servo object
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(buttonPin, HIGH);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
safetyDistance = distance;
if (digitalRead(buttonPin) == HIGH)
{
if (safetyDistance <= 5){
digitalWrite(buzzer, HIGH);
digitalWrite(ledPin, HIGH);
}
else{
digitalWrite(buzzer, LOW);
digitalWrite(ledPin, LOW);
for(pos = 0; pos <= 180; pos += 20) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(10); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=0; pos-=2) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(10); // waits 15ms for the servo to reach the position
}
}
}
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}
现在,我们遇到的问题是,我知道按钮必须有状态。但是当我们在互联网上寻求帮助时,我们遇到了诸如去抖动之类的术语,我们只是不明白这意味着什么。我们非常接近最终完成我们的迷你项目。伺服器运转良好,超声波传感器工作良好。我们只需要帮助找出这个按钮。任何建议和帮助将不胜感激,因为我们都在这个问题上摸不着头脑。谢谢!!
——赞恩