Arduino学习笔记---Blink without delay

Arduino学习笔记---Blink without delay

上一篇里的 delay 非常拉,delay 的时候什么都不能做

这里把它规避掉

 1 /*
 2   Blink without Delay
 3 
 4   Turns on and off a light emitting diode (LED) connected to a digital pin,
 5   without using the delay() function. This means that other code can run at the
 6   same time without being interrupted by the LED code.
 7 
 8   The circuit:
 9   - Use the onboard LED.
10   - Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA
11     and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN
12     is set to the correct LED pin independent of which board is used.
13     If you want to know what pin the on-board LED is connected to on your
14     Arduino model, check the Technical Specs of your board at:
15     https://www.arduino.cc/en/Main/Products
16 
17   created 2005
18   by David A. Mellis
19   modified 8 Feb 2010
20   by Paul Stoffregen
21   modified 11 Nov 2013
22   by Scott Fitzgerald
23   modified 9 Jan 2017
24   by Arturo Guadalupi
25 
26   This example code is in the public domain.
27 
28   https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay
29 */
30 
31 // constants won't change. Used here to set a pin number:
32 const int ledPin =  LED_BUILTIN;// the number of the LED pin
33 
34 // Variables will change:
35 int ledState = LOW;             // ledState used to set the LED
36 
37 // Generally, you should use "unsigned long" for variables that hold time
38 // The value will quickly become too large for an int to store
39 unsigned long previousMillis = 0;        // will store last time LED was updated
40 
41 // constants won't change:
42 const long interval = 1000;           // interval at which to blink (milliseconds)
43 
44 void setup() {
45   // set the digital pin as output:
46   pinMode(ledPin, OUTPUT);
47 }
48 
49 void loop() {
50   // here is where you'd put code that needs to be running all the time.
51 
52   // check to see if it's time to blink the LED; that is, if the difference
53   // between the current time and last time you blinked the LED is bigger than
54   // the interval at which you want to blink the LED.
55   unsigned long currentMillis = millis();
56 
57   if (currentMillis - previousMillis >= interval) {
58     // save the last time you blinked the LED
59     previousMillis = currentMillis;
60 
61     // if the LED is off turn it on and vice-versa:
62     if (ledState == LOW) {
63       ledState = HIGH;
64     } else {
65       ledState = LOW;
66     }
67 
68     // set the LED with the ledState of the variable:
69     digitalWrite(ledPin, ledState);
70   }
71 }

 

这里调用了函数 millis () , 返回从程序开始到当前的毫秒数

 

上一篇:Arduino Uno 舵机控制


下一篇:多线程---Task理解(四)