首先,對於Arduino來說是非常新穎的,我已經搜遍了一些教程來努力完成這項工作,似乎沒有任何東西能夠幫助我。我試圖做的是當按下按鈕時,LCD背光啓動8秒鐘。實現非阻塞定時操作 - 沒有延遲() - 對於Arduino
我有輕微的成功與我的代碼第一次嘗試:
const int buttonPin = 13; // the number of the pushbutton pin
const int ledPin = 9; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void timeDelay(){
digitalWrite (ledPin, HIGH);
delay(8000);
digitalWrite (ledPin, LOW);
}
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// 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) {
// turn LED on:
timeDelay();
}
}
這個偉大的工程,我按下按鈕,它調用腳本,唯一的問題是,它使得一切就暫停。似乎我需要使用'millis'來實現解決方案,但是我所看到的所有內容都是基於BlinkWithoutDelay草圖,而我似乎無法做到這一點。
任何意見或相關教程將是偉大的。
編輯:
我想感謝pirho下面的解釋。這是我的代碼能夠使工作感謝他們的指導:
// constants won't change. Used here to set a pin number :
const int ledPin = 9;// the number of the LED pin
const int buttonPin = 13; // the number of the pushbutton pin
// Variables will change :
int ledState = LOW; // ledState used to set the LED
int buttonState = 0; // variable for reading the pushbutton status
// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0; // will store last time LED was updated
unsigned long currentMillis = 0;
unsigned long ledTimer = 0;
// constants won't change :
const long interval = 8000; // interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
// digitalWrite(ledPin, ledState);
pinMode(buttonPin, INPUT);
}
void loop() {
// here is where you'd put code that needs to be running all the time.
currentMillis = millis();
buttonState = digitalRead(buttonPin);
ledTimer = (currentMillis - previousMillis);
if (buttonState == HIGH) {
digitalWrite (ledPin, HIGH);
previousMillis = millis();
}
if (ledTimer >= interval) {
// save the last time you blinked the LED
digitalWrite (ledPin, LOW);
} else {
digitalWrite (ledPin, HIGH);
}
}
謝謝,當你分解它時,它確實非常有幫助。我發佈了我能夠完成的最終代碼。再次感謝您的幫助! –