零知WIFI教程-定时器Ticker使用示例

定时器在单片机中是非常常用的,在这里使用定时器Ticker库在零知开源平台上进行演示定时器的基本操作。

一、软件和硬件

硬件我们本次使用零知-ESP8266;

软件使用零知开发工具,自带示例:

二、方法步骤

(1)先在零知开发工具中打开TickerBasic示例,或者复制下面的代码到零知开发工具中:


							
	/**********************************************************
	*    文件: x.ino      by 零知实验室([url=http://www.lingzhilab.com]www.lingzhilab.com[/url])
	*    -^^- 零知开源,让电子制作变得更简单! -^^-
	*    时间: 2019/05/28 12:22
	*    说明: 定时器基本应用
	************************************************************/
	/*
	  Basic Ticker usage
	  
	  Ticker is an object that will call a given function with a certain period.
	  Each Ticker calls one function. You can have as many Tickers as you like,
	  memory being the only limitation.
	  
	  A function may be attached to a ticker and detached from the ticker.
	  There are two variants of the attach function: attach and attach_ms.
	  The first one takes period in seconds, the second one in milliseconds.
	  
	  The built-in LED will be blinking.
	*/
	  
	#include <Ticker.h>
	  
	Ticker flipper;
	  
	int count = 0;
	  
	void flip() {
	int state = digitalRead(LED_BUILTIN);  // get the current state of GPIO1 pin
	digitalWrite(LED_BUILTIN, !state);     // set pin to the opposite state
	  
	++count;
	// when the counter reaches a certain value, start blinking like crazy
	if (count == 20) {
	flipper.attach(0.1, flip);
	}
	// when the counter reaches yet another value, stop blinking
	else if (count == 120) {
	flipper.detach();
	}
	}
	  
	void setup() {
	pinMode(LED_BUILTIN, OUTPUT);
	digitalWrite(LED_BUILTIN, LOW);
	  
	// flip the pin every 0.3s
	flipper.attach(0.3, flip);
	}
	  
	void loop() {
	}
							
						

(2)验证后上传到零知-ESP8266;

(3)上传成功后,我们可以看到ESP8266的板载LED先0.3s的速度闪烁,然后0.1s的速度进行闪烁,最后常亮;符合我们的软件预设。

(4)其他更多的定时器的应用可以参考相关的示例Ticker目录。