首先,对Arduino来说是非常新的,我已经搜索了教程以努力使这项工作,似乎没有任何东西可以帮助我。我想要做的是按下按钮时LCD背光激活8秒钟。
我第一次尝试代码时取得了一些小小的成功:
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);
}
}
答案 0 :(得分:2)
是的,delay(8000);
void timeDelay() {...}
阻止了循环。
要改变它解锁,你必须在循环中,在每一轮:
希望这不是太抽象,但不会为你编写代码;)
另请注意,可以根据led状态优化检查,但可能不会仅仅检查任何性能更改而不是io write和额外代码。
更新:还可以使用一些多线程库,如ProtoThreads。根据编程技巧和程序/并行任务数量的复杂性,这可能是一个很好的选择,但不一定。
在此网站上搜索arduino thread