我想在arduino中制作一个5秒计时器,更详细一点,我有一个RGB led,我希望点亮一个颜色按下按钮的次数(我也有一个按钮),比如,在那5秒内led必须保持不亮,如果我按下按钮一次5秒钟,在计时器结束后(5秒),LED将变为红色,如果我按下按钮两次LED变为蓝色或不管。
const int buttonPin = 2; // the number of the pushbutton pin
const int ledbPin = 13; // the number of the LED pin
const int ledgPin = 12; // the number of the LED pin
const int ledrPin = 11; // the number of the LED pin
int count = 0; // Count the button presses
unsigned long currentTime;
unsigned long loopTime;
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledrPin, OUTPUT);
pinMode(ledgPin, OUTPUT);
pinMode(ledbPin, OUTPUT);
currentTime = millis();
loopTime = currentTime;
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
count++; // add 1 to the count
if (count >= 1) {
currentTime = millis();
if(currentTime >= (loopTime + 5000)){
if (count == 1) {
digitalWrite(ledrPin, HIGH);
}
if (count == 2) {
digitalWrite(ledgPin, HIGH);
}
if (count == 3) {
digitalWrite(ledbPin, HIGH);
}
}
}
}
}
这是我到目前为止写的:
计时器结束后,如果按下按钮,所有指示灯都会亮起,呈现白色。
答案 0 :(得分:0)
这是因为你在循环中创建了一个if语句。循环太快了。当您按下并释放按钮时,它已经多次循环。在那些多次,你的伯爵仍然越来越高。我会在按钮的If语句中添加一个millis。 我刚刚在这里做了一个例子。你可以按照自己的方式去做。
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH && currentTime == 500 (didnt look which one your timer is)) {
count++; // add 1 to the count
if (count >= 1) {
currentTime = millis();
if(currentTime >= (loopTime + 5000)){
if (count == 1) {
digitalWrite(ledrPin, HIGH);
}
if (count == 2) {
digitalWrite(ledgPin, HIGH);
}
if (count == 3) {
digitalWrite(ledbPin, HIGH);
}
}
}
}
}