基于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开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

Python基于wxPython和FFmpeg开发一个视频标签工具

《Python基于wxPython和FFmpeg开发一个视频标签工具》在当今数字媒体时代,视频内容的管理和标记变得越来越重要,无论是研究人员需要对实验视频进行时间点标记,还是个人用户希望对家庭视频进行... 目录引言1. 应用概述2. 技术栈分析2.1 核心库和模块2.2 wxpython作为GUI选择的优

利用Python开发Markdown表格结构转换为Excel工具

《利用Python开发Markdown表格结构转换为Excel工具》在数据管理和文档编写过程中,我们经常使用Markdown来记录表格数据,但它没有Excel使用方便,所以本文将使用Python编写一... 目录1.完整代码2. 项目概述3. 代码解析3.1 依赖库3.2 GUI 设计3.3 解析 Mark

Python使用date模块进行日期处理的终极指南

《Python使用date模块进行日期处理的终极指南》在处理与时间相关的数据时,Python的date模块是开发者最趁手的工具之一,本文将用通俗的语言,结合真实案例,带您掌握date模块的六大核心功能... 目录引言一、date模块的核心功能1.1 日期表示1.2 日期计算1.3 日期比较二、六大常用方法详

利用Go语言开发文件操作工具轻松处理所有文件

《利用Go语言开发文件操作工具轻松处理所有文件》在后端开发中,文件操作是一个非常常见但又容易出错的场景,本文小编要向大家介绍一个强大的Go语言文件操作工具库,它能帮你轻松处理各种文件操作场景... 目录为什么需要这个工具?核心功能详解1. 文件/目录存javascript在性检查2. 批量创建目录3. 文件

Springboot如何配置Scheduler定时器

《Springboot如何配置Scheduler定时器》:本文主要介绍Springboot如何配置Scheduler定时器问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录Springboot配置Scheduler定时器1.在启动类上添加 @EnableSchedulin

基于Python开发批量提取Excel图片的小工具

《基于Python开发批量提取Excel图片的小工具》这篇文章主要为大家详细介绍了如何使用Python中的openpyxl库开发一个小工具,可以实现批量提取Excel图片,有需要的小伙伴可以参考一下... 目前有一个需求,就是批量读取当前目录下所有文件夹里的Excel文件,去获取出Excel文件中的图片,并

python中time模块的常用方法及应用详解

《python中time模块的常用方法及应用详解》在Python开发中,时间处理是绕不开的刚需场景,从性能计时到定时任务,从日志记录到数据同步,时间模块始终是开发者最得力的工具之一,本文将通过真实案例... 目录一、时间基石:time.time()典型场景:程序性能分析进阶技巧:结合上下文管理器实现自动计时

基于Python开发PDF转PNG的可视化工具

《基于Python开发PDF转PNG的可视化工具》在数字文档处理领域,PDF到图像格式的转换是常见需求,本文介绍如何利用Python的PyMuPDF库和Tkinter框架开发一个带图形界面的PDF转P... 目录一、引言二、功能特性三、技术架构1. 技术栈组成2. 系统架构javascript设计3.效果图