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

news2024/10/10 6:13:22

一、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 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

  static int state =0;
  state=!state;
  Serial.println(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);

  Serial.begin(115200);
  Serial.println();

  // flip the pin every 0.3s
  flipper.attach(0.3, flip);
}

void loop() {}

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

四、ESP8266硬件定时器

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

/****************************************************************************************************************************
  Argument_None.ino
  For ESP8266 boards
  Written by Khoi Hoang

  Built by Khoi Hoang https://github.com/khoih-prog/ESP8266TimerInterrupt
  Licensed under MIT license

  The 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 timers
  Therefore, 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 assume
   variable 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 disabled
   or 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
#endif

volatile 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 microsecs
  if (ITimer.attachInterruptInterval(TIMER_INTERVAL_MS * 1000, TimerHandler))
  {
    lastMillis = millis();
    Serial.print(F("Starting  ITimer OK, millis() = "));
    Serial.println(lastMillis);
  }
  else
    Serial.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.coloradmin.cn/o/1554374.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

HarmonyOS实战开发-如何构建多种样式弹窗

介绍 本篇Codelab将介绍如何使用弹窗功能&#xff0c;实现四种类型弹窗。分别是&#xff1a;警告弹窗、自定义弹窗、日期滑动选择器弹窗、文本滑动选择器弹窗。需要完成以下功能&#xff1a; 点击左上角返回按钮展示警告弹窗。点击出生日期展示日期滑动选择器弹窗。点击性别展…

electron+VUE Browserwindow与webview通信

仅做记录 前言&#xff1a; electronVUEVITE框架&#xff0c;用的是VUE3.0 主进程定义&#xff1a;用于接收webview发送的消息 ipcMain.on(MyWebviewMessage, (event, message) > {logger.info(收到webmsg message)//转发给渲染进程}) porelaod/webPreload.js定义 cons…

Qt+OpenGL入门教程(二)——OpenGL渲染管线

渲染管线是图形学不可或缺的&#xff0c;在学习它之前&#xff0c;我们先了解一下什么是管线&#xff1f; 管线/流水线 当我们谈到管线时&#xff0c;我们指的是一个由多个阶段组成的过程&#xff0c;每个阶段都完成任务的一部分。在现实世界中&#xff0c;流水线的概念在许多…

vue实现文字一个字一个字的显示(开箱即用)

图示&#xff1a; 核心代码 Vue.prototype.$showHtml function (str, haveCallback null) {let timeFlag let abcStr for (let i 0; i < str.length; i) {(function (i) {timeFlag setTimeout(function () {abcStr str[i]haveCallback(abcStr)if ((i 1) str.length…

C# NumericUpDown 控件正整数输入控制

用到了控件的 KeyPress 和 KeyUp事件。 KeyPress 中控制输入“点、空格&#xff0c;负号”&#xff1b; KeyUp 中防止删空&#xff0c;以及防止输入超过最大值或最小值 。 private void nudStart_KeyPress(object sender, KeyPressEventArgs e){numericUpDownKeyPress(sender…

把组合损失中的权重设置为可学习参数

目前的需求是&#xff1a;有一个模型&#xff0c;准备使用组合损失&#xff0c;其中有2个或者多个损失函数。准备对其进行加权并线性叠加。但想让这些权重进行自我学习&#xff0c;更新迭代成最优加权组合。 目录 1、构建组合损失类 2、调用组合损失类 3、为其构建优化器 …

HiRoPE、MoDiTalker、RecDiffusion、DreamSalon、InterDreamer、BAMM

本文首发于公众号&#xff1a;机器感知 HiRoPE、MoDiTalker、RecDiffusion、DreamSalon、InterDreamer、BAMM Lift3D: Zero-Shot Lifting of Any 2D Vision Model to 3D In recent years, there has been an explosion of 2D vision models for numerous tasks such as seman…

利用lidar生成深度图

前言 目前&#xff0c;深度图像的获取方法有&#xff1a;激光雷达深度成像法、计算机立体视觉成像、坐标测量机法、莫尔条纹法、结构光法等。针对深度图像的研究重点主要集中在以下几个方面&#xff1a;深度图像的分割技术&#xff0c;深度图像的边缘检测技术&#xff0c;基于…

HarmonyOS实战开发-实现自定义弹窗

介绍 本篇Codelab基于ArkTS的声明式开发范式实现了三种不同的弹窗&#xff0c;第一种直接使用公共组件&#xff0c;后两种使用CustomDialogController实现自定义弹窗&#xff0c;效果如图所示 相关概念 AlertDialog&#xff1a;警告弹窗&#xff0c;可设置文本内容和响应回调…

网络七层模型:理解网络通信的架构(〇)

&#x1f90d; 前端开发工程师、技术日更博主、已过CET6 &#x1f368; 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1 &#x1f560; 牛客高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》 &#x1f35a; 蓝桥云课签约作者、上架课程《Vue.js 和 E…

【QT入门】 QListWidget各种常见用法详解之列表模式

往期回顾 【QT入门】 Qt代码创建布局之setLayout使用-CSDN博客 【QT入门】 Qt代码创建布局之多重布局变换与布局删除技巧-CSDN博客 【QT入门】 QTabWidget各种常见用法详解-CSDN博客 【QT入门】 QListWidget各种常见用法详解之列表模式 QListWidget有列表和图标两种显示模式&a…

数据结构刷题篇 之 【力扣二叉树基础OJ】详细讲解(含每道题链接及递归图解)

有没有一起拼用银行卡的&#xff0c;取钱的时候我用&#xff0c;存钱的时候你用 1、相同的树 难度等级&#xff1a;⭐ 直达链接&#xff1a;相同的树 2、单值二叉树 难度等级&#xff1a;⭐ 直达链接&#xff1a;单值二叉树 3、对称二叉树 难度等级&#xff1a;⭐⭐ 直达…

Delphi模式编程

文章目录 Delphi模式编程涉及以下几个关键方面&#xff1a;**设计模式的应用****Delphi特性的利用****实际开发中的实践** Delphi模式编程的实例 Delphi模式编程是指在使用Delphi这一集成开发环境&#xff08;IDE&#xff09;和Object Pascal语言进行软件开发时&#xff0c;采用…

vivado 器件编程

生成器件镜像后 &#xff0c; 下一步是将其下载到目标器件。 Vivado IDE 具有内置原生的系统内器件编程功能用于执行此操作。 Vivado Design Suite 和 Vivado Lab Edition 都包含相应的功能 &#xff0c; 支持您连接到包含 1 个或多个 FPGA 或 ACAP 的硬 件&#xff0c; 以…

9、鸿蒙学习-开发及引用静态共享包(API 9)

HAR&#xff08;Harmony Archive&#xff09;是静态共享包&#xff0c;可以包含代码、C库、资源和配置文件。通过HAR可以实现多个模块或多个工程共享ArkUI组件、资源等相关代码。HAR不同于HAP&#xff0c;不能独立安装运行在设备上&#xff0c;只能作为应用模块的依赖项被引用。…

使用Docker Compose一键部署前后端分离项目(图文保姆级教程)

一、安装Docker和docker Compose 1.Docker安装 //下载containerd.io包 yum install https://download.docker.com/linux/fedora/30/x86_64/stable/Packages/containerd.io-1.2.6-3.3.fc30.x86_64.rpm //安装依赖项 yum install -y yum-utils device-mapper-persistent-data l…

VTK 9.2.6 源码和VTK Examples 编译 Visual Studio 2022

对于编译 VTK 源码和编译详细的说明&#xff1a; VTK 源码编译&#xff1a; 下载源码&#xff1a; 从 VTK 官方网站或者 GitHub 获取源代码。官网目前最近的9.3.0有问题&#xff0c;见VTK 9.3.0 编译问题 Visual Studio 2022去gitlab上选择9.2.6分支进行clone CMake 配置&…

探索数据结构:链式队与循环队列的模拟、实现与应用

✨✨ 欢迎大家来到贝蒂大讲堂✨✨ &#x1f388;&#x1f388;养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; 所属专栏&#xff1a;数据结构与算法 贝蒂的主页&#xff1a;Betty’s blog 1. 队列的定义 队列&#xff08;queue&#xff09;是一种只允许在一端进…

系统分析师-参考模型

前言 网络术语中的参考模型指的是OSI参考模型&#xff0c;由ISO&#xff08;国际标准化组织&#xff09;制定的一套普遍适用的规范集合&#xff0c;以使得全球范围的计算机平台可进行开放式通信。 ISO创建了一个有助于开发和理解计算机的通信模型&#xff0c;即开放系统互联OS…

openwrt 编译mysql数据库固件,并调用

前言 openwrt 编译源码mysql数据库&#xff0c;并编写demo调用 一、整体架构设计 作者要做一个项目&#xff0c;没有后端服务&#xff0c;只有一个电脑&#xff0c;需要在电脑上安装mysql服务端。然后在设备上安装mysql客户端。 二、PC安装mysql 1.官网链接 自行百度安装&a…