2017-10-15 1127 views
0

首先,對於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); 
     } 

    } 

回答

2

是,delay(8000);void timeDelay() {...}塊上的循環。

要改變它疏通必須在循環中,在每一輪:

  • 如果BTN按下店pressMillis,點燃了領導
  • 比較,如果currentMillis-pressMillis> 8000,如果再關上了領導
  • 做其他動作

希望這是不是過於抽象,但不會爲你寫的代碼;)

還要注意,檢查可以根據led狀態進行優化,但可能不會帶來任何性能變化,只是檢查而不是io寫入和額外的代碼。

更新:也可以使用一些多線程庫,如ProtoThreads。取決於編程技巧和程序的複雜性/並行任務的數量,這可能也是不錯的選擇,但不一定。

搜索此網站的地址爲arduino thread

+0

謝謝,當你分解它時,它確實非常有幫助。我發佈了我能夠完成的最終代碼。再次感謝您的幫助! –