最近,我尝试使用我的 Arduino Uno (AtMega328) 板通过中断服务程序检测一系列三个开关的按下。
如果有三个开关分别称为 R、G 和 B。每当按下这些开关中的至少一个时,RGB-Led 应将其状态切换为红色、绿色或蓝色。
现在,只有两个开关 R 和 G 没问题,因为 Arduino Uno 板有两个可中断的引脚(2 和 3)。
但是,对于开关 B,我缺少另一个中断引脚来检测三个开关中至少一个的按下。
是否有一种可能的电路,可以很容易地检测到三个开关中至少一个的按下,这样我就可以只使用一个具有中断功能的引脚来检测任何开关的按下?
使用 Arduino IDE 的两个 LED 的代码非常简单,只需两个开关:
const int buttonRed = 2; // the number of the pushbutton pin
const int ledRed = 13; // the number of the LED pin
const int buttonGreen= 3;
const int ledGreen=12;
// variables will change due to ISR
volatile int redState = 0;
volatile int greenState=0;
void setup() {
// initialize the LED pin as an output:
pinMode(ledRed, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonRed, INPUT);
pinMode(ledGreen, OUTPUT);
pinMode(buttonGreen, INPUT);
// Attach an interrupt to the ISR vector
attachInterrupt(digitalPinToInterrupt(buttonRed), redButton_ISR, CHANGE);
attachInterrupt(digitalPinToInterrupt(buttonGreen), greenButton_ISR, CHANGE);
}
void loop() {
// Nothing to do here
}
void greenButton_ISR() {
greenState=digitalRead(buttonGreen);
digitalWrite(ledGreen, greenState);
}
void redButton_ISR() {
redState = digitalRead(buttonRed);
digitalWrite(ledRed, redState);
}