【Arduino】一份简单的(伪)多线程示例 - print "Hello World" 和 echo 功能

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_29757283/article/details/85390121

Arduino 上运行(伪)多线程示例 - print “Hello World” 和 echo 功能

Demo

/**
 * Reference:
 *   N/A
 */

void setup(){
	Serial.begin(9600);
	// Serial1.begin(9600);
}

void loop(){
	/**
	 * scheduling
	 */
	int count = 0;
	while (1){
		if (count == 10){
			count = 0;
		}

		if (1){
			thread_echo();
		}
		if (count == 9){
			thread_hello();
		}

		delay(100);
		count ++;
	}
}


void thread_hello(){
	Serial.println("Hello world");  // print "Hello World" to the Serial Monitor
}

void thread_echo(){
	while (Serial.available()){
		Serial.write( Serial.read() );  // echo
	}
}

Note

仅在接收端不会出现不断地发送数据的情况下有效。

如果接收端会一直发送数据,则程序会在 thread_echo 函数(伪线程)中停留过长时间,则 thread_hello 函数(另一个伪线程)的每秒打印一次 “hello world” 就会不准确。

相关

Arduino 定时器(delay()

Arduino 上的 delay 占用了一个定时器。如果你的板子有两个定时器,或许你可以写出更精确的线程调度。
在单片机开发板上,如果不适用实时系统的话,个人的理解,实现多线程就是时分复用。可以简单做成每个“注册线程”都轮询运行一定的时间,并且保证该线程内不要使用定时器即可。

Arduino Serial

  1. Serial.available() 不会 block。
  2. UART 的中断已经在底层被 Arduino 封装过了(Serial 类),所以它有 Serial 中断,但是你编写上层代码是不能使用这个中断的。

    但是这一点其实无需在意,UART 的中断收取数据后保存在一个 FIFO 中,除非接收端不断发送,而程序又一直不去读取,或者太久之后才读取,才有可能发生 FIFO 溢出,数据丢失的情况。但是这个时候一般都是上层应用写得有问题。或者发送端发送的数据太快,已经超出了 Arduino 单片机的处理能力。

  3. Serial.serialEvent() 不是中断

    正如前面所言,UART 的中断已经被封装使用过了,所以这个 Serial.serialEvent() 实际上不是中断。
    它会在每两个 loop() 之间调用。
    也就意味着这么写:

    bool led_blink_flag = false;
    void led_blink(the_bind_ping){
        digitalWrite(the_bind_ping, led_blink_flag);
        led_blink_flag = !led_blink_flag;
        sleep(1000);
    }
    void setup(){ Serial.begin(9600); pinMode(13, OUTPUT); }
    void loop(){
        led_blink(13);
    }
    void serialEvent() {
        while (Serial.available())
            Serial.write( Serial.read() );  // echo
    }
    

    和这样写:

    [......]
    void loop(){
        led_blink(13);
        mySerailEvent();
    }
    void mySerailEvent() {
        while (Serial.available())
            Serial.write( Serial.read() );  // echo
    }
    

    效果是完全一样的。

猜你喜欢

转载自blog.csdn.net/qq_29757283/article/details/85390121