基于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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/290628.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

docker中配置交互式的JupyterLab环境的问题

【报错1】 Could not determine jupyter lab build status without nodejs 【解决措施】安装nodejs(利用conda进行安装/从官网下载进行安装&#xff09; 1、conda安装 conda install -c anaconda nodejs 安装后出现其他报错&#xff1a;Please install nodejs 5 and npm bef…

Go语言学习Day2:注释与变量

名人说&#xff1a;莫道桑榆晚&#xff0c;为霞尚满天。——刘禹锡&#xff08;刘梦得&#xff0c;诗豪&#xff09; 创作者&#xff1a;Code_流苏(CSDN)&#xff08;一个喜欢古诗词和编程的Coder&#x1f60a;&#xff09; 目录 1、注释①为什么要写注释&#xff1f;②单行注释…

Unity颗粒血条的实现(原创,参考用)

1.创建3个静态物体摆好位置&#xff0c;并将其图层设为UI 2.编写一个脚本 using System.Collections; using System.Collections.Generic; using UnityEngine;public class xt : MonoBehaviour {public GameObject xt1;public GameObject xt2;public GameObject xt3;int x 1;…

Unity | 工具类-UV滚动

一、内置渲染管线Shader Shader"Custom/ImageRoll" {Properties {_MainTex ("Main Tex", 2D) "white" {}_Width ("Width", float) 0.5_Distance ("Distance", float) 0}SubShader {Tags {"Queue""Trans…

JavaEE企业开发新技术4

2.16 模拟Spring IOC容器功能-1 2.17 模拟Spring IOC容器功能-2 什么是IOC&#xff1f; 控制反转&#xff0c;把对象创建和对象之间的调用过程交给Spring框架进行管理使用IOC的目的&#xff1a;为了耦合度降低 解释&#xff1a; 模仿 IOC容器的功能&#xff0c;我们利用 Map…

多线程的学习1

多线程 线程是操作系统能够进入运算调度的最小单位。它被包含在进程之中&#xff0c;是进程中的实际运作单位。 进程&#xff1a;是程序的基本执行实体。 并发&#xff1a;在同一个时刻&#xff0c;有多个指令在单个CPU上交替执行。 并行&#xff1a;在同一时刻&#xff0c…

排序---数组和集合

1、数组排序 Arrays.sort(int[] a)这种形式是对一个数组的所有元素进行排序&#xff0c;并且是按照从小到大的排序。 public static void main(String[] args) {Integer []arr {1,2,3,4,5,6};//升序Arrays.sort(arr);for (int x:arr){System.out.print(x " ");}Sys…

Redis桌面客户端

3.4.Redis桌面客户端 安装完成Redis&#xff0c;我们就可以操作Redis&#xff0c;实现数据的CRUD了。这需要用到Redis客户端&#xff0c;包括&#xff1a; 命令行客户端图形化桌面客户端编程客户端 3.4.1.Redis命令行客户端 Redis安装完成后就自带了命令行客户端&#xff1…

20232831 2023-2024-2 《网络攻防实践》第4次作业

目录 20232831 2023-2024-2 《网络攻防实践》第4次作业1.实验内容2.实验过程&#xff08;1&#xff09;ARP缓存欺骗攻击&#xff08;2&#xff09;ICMP重定向攻击&#xff08;3&#xff09;SYN Flood攻击&#xff08;4&#xff09;TCP RST攻击&#xff08;5&#xff09;TCP会话…

字节算法岗二面,凉凉。。。

节前&#xff0c;我们星球组织了一场算法岗技术&面试讨论会&#xff0c;邀请了一些互联网大厂朋友、参加社招和校招面试的同学&#xff0c;针对算法岗技术趋势、大模型落地项目经验分享、新手如何入门算法岗、该如何准备、面试常考点分享等热门话题进行了深入的讨论。 汇总…

linux + gitee+idea整套配置以及问题详解

目录&#xff1a; 1、安装git 2、git配置 3、git和gitee账户建立安全链接 4、gitee创建仓库 5、idea配置gitee 6、克隆提交代码 1、安装git 使用到github上下载最新版&#xff0c;上传到你的服务器&#xff0c;再进行解压。 这里是我的压缩包。解压命令&#xff1a; cd /usr/g…

Window11系统下,VMware安装Ubuntu 18.04虚拟机

本文主要记录Window11系统&#xff0c;VMware安装Ubuntu 18.04虚拟机&#xff0c;主要包括常见的镜像网站下载、硬盘分区、创建虚拟机和Ubuntu系统安装四部分。 &#x1f3a1;导航小助手&#x1f3a1; 1. Ubuntu镜像下载2.磁盘分区3.创建Ubuntu虚拟机4.Ubuntu系统安装 1. Ubun…

colmap 【Feature matching】特征匹配参数解释

&#xff08;Windows&#xff09;Colmap 具体使用教程可参考我的这篇博文 下面只是matching参数解释 Matching这个阶段很重要&#xff0c;匹配方式不同会对最终结果影响很大&#xff0c;要根据实际情况选择合适的匹配方式。下面是各个参数的详细解释。 1.Exhaustive——官方文…

SQL96 返回顾客名称和相关订单号(表的普通联结、内联结inner join..on..)

方法一&#xff1a;普通联结 select cust_name, order_num from Customers C,Orders O where C.cust_id O.cust_id order by cust_name,order_num;方法二&#xff1a;使用内连接 select cust_name,order_num from Customers C inner join Orders O on C.cust_id O.cust_id …

书生浦语训练营2期-第一节课笔记

笔记总结: 了解大模型的发展方向、本质、以及新一代数据清洗过滤技术、从模型到应用的典型流程、获取数据集的网站、不同微调方式的使用场景和训练数据是什么&#xff0c;以及预训练和微调在训练优势、通信/计算调度、显存管理上的区别。 收获&#xff1a; 理清了预训练和微调…

DICE模型教程

原文练级&#xff1a;DICE模型教程https://mp.weixin.qq.com/s?__bizMzUzNTczMDMxMg&mid2247599474&idx6&snbd716d5719ddd8bd6c565daa0f361b72&chksmfa820495cdf58d83360a402cb2a05042e0f13e6d84d96ee36708e4c5ce90fa124ad9a30b9717&token1105644014&…

系统分析师-软件开发模型总结

前言 软件工程模型也称软件开发模型。它是指软件开发全部过程、活动和任务的结构框架&#xff0c;通过该模型能清晰、直观地表达软件开发全过程&#xff0c;明确地规定要完成的主要活动和任务&#xff0c;它奠定了软件项目工作的基础 一、瀑布模型&#xff08;Waterfall Model…

王道C语言督学营OJ课后习题(课时14)

#include <stdio.h> #include <stdlib.h>typedef char BiElemType; typedef struct BiTNode{BiElemType c;//c 就是书籍上的 datastruct BiTNode *lchild;struct BiTNode *rchild; }BiTNode,*BiTree;//tag 结构体是辅助队列使用的 typedef struct tag{BiTree p;//树…

安卓国内ip代理app,畅游网络

随着移动互联网的普及和快速发展&#xff0c;安卓手机已经成为我们日常生活和工作中不可或缺的一部分。然而&#xff0c;由于地理位置、网络限制或其他因素&#xff0c;我们有时需要改变或隐藏自己的IP地址。这时&#xff0c;安卓国内IP代理App便成为了一个重要的工具。虎观代理…

Android TargetSdkVersion 30 安装失败 resources.arsc 需要对齐且不压缩。

公司项目&#xff0c;之前targetSDKVersion一直是29&#xff0c;近期小米平台上架强制要求升到30&#xff0c;但是这个版本在android12上安装失败&#xff0c;我用adb命令安装&#xff0c;报错如下图 adb: failed to install c: Program Files (x86)(0A_knight\MorkSpace \Home…