2017-10-15 103 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

谢谢,当你分解它时,它确实非常有帮助。我发布了我能够完成的最终代码。再次感谢您的帮助! –