基于Arduino IDE 野火ESP8266模块 定时器 的开发

2024-03-30 10:28

本文主要是介绍基于Arduino IDE 野火ESP8266模块 定时器 的开发,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、delay函数实现定时

 如果不需要精确到微秒级别的控制,可以使用Arduino的内置函数 millis()和delay() 来创建简单的定时器。millis()函数返回Arduino板启动后的毫秒数,而delay()函数会暂停程序的执行一段时间。

示例代码如下:
delay()函数

#include <Arduino.h>unsigned long currentTestTime;void setup(){Serial.begin(115200);
}
void loop(){Serial.print("Arduino has been running this sketch for ");currentTestTime = millis();//输出程序运行时间Serial.print(currentTestTime);Serial.println(" milliseconds.");delay(1000);currentTestTime = millis();//输出程序运行时间Serial.print(currentTestTime);Serial.println(" milliseconds.");delay(1000);
}

运行效果
在这里插入图片描述

二、millis函数实现定时

millis()函数

#include <Arduino.h>
unsigned long previousMillis = 0;  
const long interval = 1000; // 间隔1秒(1000毫秒)void setup() {  Serial.begin(115200);  
}  void loop() {  unsigned long currentMillis = millis();  if (currentMillis - previousMillis >= interval) {  previousMillis = currentMillis;  // 更新上一次的时间  Serial.println("1 second has passed");  // 在这里执行你的定时任务  }  // 其他代码...  
}
#include <Arduino.h>int testInterval = 1000; //时间间隔
unsigned long previousTestTime;void setup() {Serial.begin(115200);
}void loop() {  unsigned long currentTestMillis = millis(); // 获取当前时间//检查是否到达时间间隔if (currentTestMillis - previousTestTime >= testInterval ) {    //如果时间间隔达到了Serial.println("currentTestMillis:"); Serial.println(currentTestMillis);Serial.println("previousTestTime:");    Serial.println(previousTestTime);    Serial.println("currentTestMillis - previousTestTime:");   Serial.println(currentTestMillis - previousTestTime);   Serial.println("testInterval");  Serial.println(testInterval);   Serial.println("1s passed");previousTestTime= currentTestMillis;         }  else if (currentTestMillis - previousTestTime <= 0) {   // 如果millis时间溢出}}

运行效果
在这里插入图片描述

三、Ticker函数

测试程序


/*Basic Ticker usageTicker 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 statestatic int state =0;state=!state;Serial.println(state);++count;// when the counter reaches a certain value, start blinking like crazyif (count == 20) { flipper.attach(0.1, flip); }// when the counter reaches yet another value, stop blinkingelse if (count == 120) {flipper.detach();}
}void setup() {// pinMode(LED_BUILTIN, OUTPUT);// digitalWrite(LED_BUILTIN, LOW);Serial.begin(115200);Serial.println();// flip the pin every 0.3sflipper.attach(0.3, flip);
}void loop() {}

运行效果
在这里插入图片描述

四、ESP8266硬件定时器

安装库文件 ESP8266TimerInterrupt
在这里插入图片描述
测试代码:

/****************************************************************************************************************************Argument_None.inoFor ESP8266 boardsWritten by Khoi HoangBuilt by Khoi Hoang https://github.com/khoih-prog/ESP8266TimerInterruptLicensed under MIT licenseThe ESP8266 timers are badly designed, using only 23-bit counter along with maximum 256 prescaler. They're only better than UNO / Mega.The ESP8266 has two hardware timers, but timer0 has been used for WiFi and it's not advisable to use. Only timer1 is available.The timer1's 23-bit counter terribly can count only up to 8,388,607. So the timer1 maximum interval is very short.Using 256 prescaler, maximum timer1 interval is only 26.843542 seconds !!!Now with these new 16 ISR-based timers, the maximum interval is practically unlimited (limited only by unsigned long milliseconds)The accuracy is nearly perfect compared to software timers. The most important feature is they're ISR-based timersTherefore, their executions are not blocked by bad-behaving functions / tasks.This important feature is absolutely necessary for mission-critical tasks.
*****************************************************************************************************************************//* Notes:Special design is necessary to share data between interrupt code and the rest of your program.Variables usually need to be "volatile" types. Volatile tells the compiler to avoid optimizations that assumevariable can not spontaneously change. Because your function may change variables while your program is using them,the compiler needs this hint. But volatile alone is often not enough.When accessing shared variables, usually interrupts must be disabled. Even with volatile,if the interrupt changes a multi-byte variable between a sequence of instructions, it can be read incorrectly.If your data is multiple variables, such as an array and a count, usually interrupts need to be disabledor the entire sequence of your code which accesses the data.
*/#if !defined(ESP8266)#error This code is designed to run on ESP8266 and ESP8266-based boards! Please check your Tools->Board setting.
#endif// These define's must be placed at the beginning before #include "ESP8266TimerInterrupt.h"
// _TIMERINTERRUPT_LOGLEVEL_ from 0 to 4
// Don't define _TIMERINTERRUPT_LOGLEVEL_ > 0. Only for special ISR debugging only. Can hang the system.
#define TIMER_INTERRUPT_DEBUG         0
#define _TIMERINTERRUPT_LOGLEVEL_     0// Select a Timer Clock
#define USING_TIM_DIV1                false           // for shortest and most accurate timer
#define USING_TIM_DIV16               false           // for medium time and medium accurate timer
#define USING_TIM_DIV256              true            // for longest timer but least accurate. Default#include "ESP8266TimerInterrupt.h"#ifndef LED_BUILTIN#define LED_BUILTIN       2         // Pin D4 mapped to pin GPIO2/TXD1 of ESP8266, NodeMCU and WeMoS, control on-board LED
#endifvolatile uint32_t lastMillis = 0;void IRAM_ATTR TimerHandler()
{static bool toggle = false;static bool started = false;if (!started){started = true;//pinMode(LED_BUILTIN, OUTPUT);Serial.println(started);}#if (TIMER_INTERRUPT_DEBUG > 0)Serial.print("Delta ms = ");Serial.println(millis() - lastMillis);lastMillis = millis();
#endif//timer interrupt toggles pin LED_BUILTIN//digitalWrite(LED_BUILTIN, toggle);toggle = !toggle;Serial.println(toggle);
}#define TIMER_INTERVAL_MS        1000// Init ESP8266 timer 1
ESP8266Timer ITimer;void setup()
{Serial.begin(115200);while (!Serial && millis() < 5000);delay(500);Serial.print(F("\nStarting Argument_None on "));Serial.println(ARDUINO_BOARD);Serial.println(ESP8266_TIMER_INTERRUPT_VERSION);Serial.print(F("CPU Frequency = "));Serial.print(F_CPU / 1000000);Serial.println(F(" MHz"));// Interval in microsecsif (ITimer.attachInterruptInterval(TIMER_INTERVAL_MS * 1000, TimerHandler)){lastMillis = millis();Serial.print(F("Starting  ITimer OK, millis() = "));Serial.println(lastMillis);}elseSerial.println(F("Can't set ITimer correctly. Select another freq. or interval"));
}void loop()
{}

运行效果
在这里插入图片描述

参考:
https://arduino-esp8266.readthedocs.io/en/2.4.2/reference.html#timing-and-delays

https://arduino-esp8266.readthedocs.io/en/2.4.2/

https://arduino-esp8266.readthedocs.io/en/2.4.2/libraries.html#ticker

https://github.com/esp8266/Arduino/tree/master/libraries/Ticker/examples

这篇关于基于Arduino IDE 野火ESP8266模块 定时器 的开发的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/861239

相关文章

基于Python开发电脑定时关机工具

《基于Python开发电脑定时关机工具》这篇文章主要为大家详细介绍了如何基于Python开发一个电脑定时关机工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 简介2. 运行效果3. 相关源码1. 简介这个程序就像一个“忠实的管家”,帮你按时关掉电脑,而且全程不需要你多做

Java中的Opencv简介与开发环境部署方法

《Java中的Opencv简介与开发环境部署方法》OpenCV是一个开源的计算机视觉和图像处理库,提供了丰富的图像处理算法和工具,它支持多种图像处理和计算机视觉算法,可以用于物体识别与跟踪、图像分割与... 目录1.Opencv简介Opencv的应用2.Java使用OpenCV进行图像操作opencv安装j

多模块的springboot项目发布指定模块的脚本方式

《多模块的springboot项目发布指定模块的脚本方式》该文章主要介绍了如何在多模块的SpringBoot项目中发布指定模块的脚本,作者原先的脚本会清理并编译所有模块,导致发布时间过长,通过简化脚本... 目录多模块的springboot项目发布指定模块的脚本1、不计成本地全部发布2、指定模块发布总结多模

Python中构建终端应用界面利器Blessed模块的使用

《Python中构建终端应用界面利器Blessed模块的使用》Blessed库作为一个轻量级且功能强大的解决方案,开始在开发者中赢得口碑,今天,我们就一起来探索一下它是如何让终端UI开发变得轻松而高... 目录一、安装与配置:简单、快速、无障碍二、基本功能:从彩色文本到动态交互1. 显示基本内容2. 创建链

基于Qt开发一个简单的OFD阅读器

《基于Qt开发一个简单的OFD阅读器》这篇文章主要为大家详细介绍了如何使用Qt框架开发一个功能强大且性能优异的OFD阅读器,文中的示例代码讲解详细,有需要的小伙伴可以参考一下... 目录摘要引言一、OFD文件格式解析二、文档结构解析三、页面渲染四、用户交互五、性能优化六、示例代码七、未来发展方向八、结论摘要

Node.js 中 http 模块的深度剖析与实战应用小结

《Node.js中http模块的深度剖析与实战应用小结》本文详细介绍了Node.js中的http模块,从创建HTTP服务器、处理请求与响应,到获取请求参数,每个环节都通过代码示例进行解析,旨在帮... 目录Node.js 中 http 模块的深度剖析与实战应用一、引言二、创建 HTTP 服务器:基石搭建(一

在 VSCode 中配置 C++ 开发环境的详细教程

《在VSCode中配置C++开发环境的详细教程》本文详细介绍了如何在VisualStudioCode(VSCode)中配置C++开发环境,包括安装必要的工具、配置编译器、设置调试环境等步骤,通... 目录如何在 VSCode 中配置 C++ 开发环境:详细教程1. 什么是 VSCode?2. 安装 VSCo

python中的与时间相关的模块应用场景分析

《python中的与时间相关的模块应用场景分析》本文介绍了Python中与时间相关的几个重要模块:`time`、`datetime`、`calendar`、`timeit`、`pytz`和`dateu... 目录1. time 模块2. datetime 模块3. calendar 模块4. timeit

Python模块导入的几种方法实现

《Python模块导入的几种方法实现》本文主要介绍了Python模块导入的几种方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录一、什么是模块?二、模块导入的基本方法1. 使用import整个模块2.使用from ... i

C#图表开发之Chart详解

《C#图表开发之Chart详解》C#中的Chart控件用于开发图表功能,具有Series和ChartArea两个重要属性,Series属性是SeriesCollection类型,包含多个Series对... 目录OverviChina编程ewSeries类总结OverviewC#中,开发图表功能的控件是Char