我有一个关于如何使用机械开关更改 Arduino 单元中的程序的问题。我目前正在制作一个无线跟焦设备,它将使用 xbee 连接到另一个带有电位计的 Arduino 单元,以无线方式旋转伺服器(程序 1)。然而,我还想要将一个简单的后退和前进按钮插入主单元的选项(程序 2)。因此我需要某种方法在两个程序之间切换。
我正在寻找最优雅的方式来做到这一点。最佳方案是,一旦将按钮插入代码,代码就会自动切换到按钮模式(程序 2)。但是,我不确定如何实现这一点。
如果后者不可能的话,我更喜欢机械开关。然而:
我认为可能有一个程序等待输入,无论是按下按钮 1,然后切换到程序 1 的程序逻辑,还是按钮 2 触发程序 2。
我有兴趣知道我的任何想法是否有价值,以及您能想到的最优雅的解决方案是什么。因为我很困惑。
从技术上讲,你不能在一块板上有两个草图。这并不是一个真正不同的程序。
这种方法甚至不需要任何额外的硬件。只需使用以下代码打开板上的上拉电阻即可:
pinMode(pin, INPUT); // set pin to input
digitalWrite(pin, HIGH); // turn on pullup resistors
注意:您需要一个在“未按下”时导电的开关。我一时想不起这个缩写。 使用该代码,您所要做的就是将开关的一端连接到您选择的 Arduino 引脚,另一端连接到
GND
。
不要向此按钮添加电阻,因为 Arduino 使用上述代码自动执行此操作。然后,要检查它是否被按下,只需执行标准的
digitalRead(pin);
即可返回:HIGH
或按钮未连接
LOW
HIGH
时进行切换。如果您想
确保它们已断开连接,您可能需要确保它们保持按下状态两秒钟,然后再切换,但这会增加代码的延迟。 从一种状态切换到另一种状态:
delay();
来消除抖动以增加简单性。如果你想让它更高级,请随意这样做,但我现在没有时间。此外,模式之间的切换有一点延迟。
#define button1 2
#define button2 3
boolean isManual = false;
void setup() {
pinMode(button1, INPUT);
digitalWrite(button1, HIGH);
pinMode(button2, INPUT);
digitalWrite(button2, HIGH);
//Other setup code here!
}
void loop() {
checkForChanges();
if (isManual == false) {
//Do code here for manual buttons. If there's a loop or a decently sized delay inside, call `checkForChanges` and see if it's still manual. If not, use `break;` to escape loop/if statement
} else {
//Do code here for auto. If there's a loop or a decently sized delay inside, call `checkForChanges` and see if it's still auto. If not, use `break;` to escape loop/if statement
}
//Add any code you want executed regardless of if it's manual or auto
}
void checkForChanges() {
if (isManual == false) {
if (digitalRead(button1) == LOW && digitalRead(button2) == LOW) {
isManual = true;
delay(200); //Crude debouncing; feel free to edit
}
} else {
if (digitalRead(button1) == LOW && digitalRead(button2) == LOW) {
isManual = true;
delay(1000); //Crude debouncing; feel free to edit; you need some delay here even if there's debouncing to make sure someone isn't pushing both
if (digitalRead(!(button1) == LOW && digitalRead(button2) == LOW)) {
isManual = false;
}
}
//Do one read of inputs. If
}
}