面向过程编程中的阻塞和非阻塞 – 从闪烁LED说起

目录 Content
[hide]

Arduino 入门的教程,都会拿一个闪烁LED的程序作为示例,然而这个程序却有两个版本,他们代表不同的编程思路。

阻塞模式

Blink 程序如下

void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

程序在循环体内,点亮->等待->熄灭->等待,如此周而复始,在等待阶段,CPU完全被进程独占,不能处理其他过程。

非阻塞模式

BlinkWithoutDelay 程序如下

// constants won't change. Used here to set a pin number :
const int ledPin =  13;      // the number of the LED pin

// Variables will change :
int ledState = LOW;             // ledState used to set the LED

// Generally, you shuould 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

// constants won't change :
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();
 
  if(currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED 
    previousMillis = currentMillis;   

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

在这种代码中,没有使用等待延时函数,而是用了一个计时器,不断查询时间是否大于间隔时间,如果大于才进行亮灯和灭灯的过程,不大于间隔时间时则可以处理其他过程。

可能用阻塞和非阻塞在这里并不合适,或许用独占和非独占的说法合理些。不过,也可以说delay阻塞了程序主体的循环,使得程序结构不能处理其他过程。

亲爱的读者,读到这里,对于你在控制上的编程思路有什么启发?

扩展阅读

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.