当前位置:网站首页>Learn Tai Chi Maker - esp8226 (12) esp8266 multitasking
Learn Tai Chi Maker - esp8226 (12) esp8266 multitasking
2022-06-24 09:24:00 【xuechanba】
The data link :http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-c/esp8266-tips/ticker/
ESP8266 At run time , Tasks can only be executed in one line . But when we are developing the Internet of things project , You may need to ESP8266 In the course of performing a task , Can also handle other tasks . such as , We use ESP8266 To control the operation of the motor , It is also necessary to regularly check whether the connection button on a pin is pressed by the user .
To solve the above problems , We can use Ticker Library to solve this problem .
ESP8266 Multitasking – Ticker Library instructions
Ticker Library is not Arduino Third party library , No installation required .
1、Ticker Library basic operations
Program function : Development board through PWM control LED While the lamp produces the effect of breathing lamp , Send information through serial port .
/********************************************************************** Project name /Project : Zero basic introduction to the Internet of things Program name /Program name : a_basic_tinker The team /Team : Taiji maker team / Taichi-Maker (www.taichi-maker.com) author /Author : CYNO Shuo date /Date(YYYYMMDD) : 20200703 Purpose of procedure /Purpose : The purpose of this program is to demonstrate how to use Ticker Library to perform operations regularly . For a detailed description of this procedure , Please refer to the following functions : http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-c/esp8266-tips/ticker/ ----------------------------------------------------------------------- Other instructions / Other Description: This program is a free video tutorial for Taiji maker team 《 Zero basic introduction to the Internet of things 》 Part of . The tutorial system Tell you ESP8266 Knowledge of software and hardware related to Internet of things applications . The following is the contents page of the tutorial : http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/ ***********************************************************************/
#include <Ticker.h>
Ticker ticker;// establish Ticker Used to realize timing function
int count; // Variable for counting
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
// Call... Every second sayHi Function a ,attach First argument to function
// Is a variable that controls the timing interval . The unit of this parameter is seconds . The second parameter is
// Name of the regularly executed function .
ticker.attach(1, sayHi);
}
void loop() {
// use LED Breathing lamp effect to demonstrate in Tinker Under object control ,ESP8266 It can be timed
// Perform other tasks
for (int fadeValue = 0 ; fadeValue <= 1023; fadeValue += 5) {
analogWrite(LED_BUILTIN, fadeValue);
delay(10);
}
for (int fadeValue = 1023 ; fadeValue >= 0; fadeValue -= 5) {
analogWrite(LED_BUILTIN, fadeValue);
delay(10);
}
delay(3000);
}
// stay Tinker Under object control , This function will execute regularly .
void sayHi(){
count++;
Serial.print("Hi ");
Serial.println(count);
}
Program description :
utilize Ticker library , We can get ESP8266 Call a function regularly .
Through the example program , We can see ,ESP8266 The information will be output through the serial port monitor every second . We are through the statement ticker.attach(1, sayHi) To achieve this .
In this sentence attach Function has two arguments . The first parameter controls the time interval between calls to the function , The unit is seconds . The numbers here 1 explain ESP8266 The function will be called every second . Which function to call ? This function name is qualified by the second parameter . That is, the name is sayHi Function of . This function will make ESP8266 Regularly output information through the serial port monitor . The information content is “Hi” Followed by a numerical value . This value is used to indicate sayHi How many times the function has been called .
2、 Stop the scheduled execution function
hypothesis , We just want sayHi This function executes a finite number of times , How to deal with it ?
When Ticker When a certain function is called regularly and executed a certain number of times , We can use detach Function to stop a scheduled call to a function . In operation , Only need sayHi Add... To this function if Sentence can be used , Examples are as follows .
// stay Tinker Under object control , This function will execute regularly .
void sayHi(){
count++;
Serial.print("Hi ");
Serial.println(count);
if(count >= 10){
ticker.detach();// When the timer calls 10 Next time , Stop calling functions regularly
Serial.print("ticker.detach()");
}
}
The operation results are as follows ,
3、 Pass parameters to the timed call function
We can approach Ticker The library regularly calls functions to pass parameters . But here's the thing , The number of passed parameters can only be one .
Please note that :attach The function can pass only one parameter at most . In addition, the parameter can only be one of the following types :char, short, int, float, void *, char *.
As shown in the following example program , sentence ticker.attach(1, sayHi, 8) Yes 3 Parameters . The third parameter is called to the timer sayHi The arguments passed by the function .
/********************************************************************** Project name /Project : Zero basic introduction to the Internet of things Program name /Program name : a_basic_tinker The team /Team : Taiji maker team / Taichi-Maker (www.taichi-maker.com) author /Author : CYNO Shuo date /Date(YYYYMMDD) : 20200703 Purpose of procedure /Purpose : The purpose of this program is to demonstrate how to use Ticker Library to perform operations regularly . For a detailed description of this procedure , Please refer to the following functions : http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-c/esp8266-tips/ticker/ ----------------------------------------------------------------------- Other instructions / Other Description: This program is a free video tutorial for Taiji maker team 《 Zero basic introduction to the Internet of things 》 Part of . The tutorial system Tell you ESP8266 Knowledge of software and hardware related to Internet of things applications . The following is the contents page of the tutorial : http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/ ***********************************************************************/
#include <Ticker.h>
Ticker ticker;// establish Ticker Used to realize timing function
int count; // Variable for counting
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
analogWriteRange(1023);
// Call... Every second sayHi Function a ,attach First argument to function
// Is a variable that controls the timing interval . The unit of this parameter is seconds . The second parameter is
// Name of the regularly executed function .
ticker.attach(1, sayHi, 10);
}
void loop() {
// use LED Breathing lamp effect to demonstrate in Tinker Under object control ,ESP8266 It can be timed
// Perform other tasks
for (int fadeValue = 0 ; fadeValue <= 1023; fadeValue += 5) {
analogWrite(LED_BUILTIN, fadeValue);
delay(10);
}
for (int fadeValue = 1023 ; fadeValue >= 0; fadeValue -= 5) {
analogWrite(LED_BUILTIN, fadeValue);
delay(10);
}
delay(3000);
}
// stay Tinker Under object control , This function will execute regularly .
void sayHi(int hiTimes){
count++;
Serial.print("Hi ");
Serial.println(count);
if(count >= hiTimes){
ticker.detach();// When the timer calls 10 Next time , Stop calling functions regularly
Serial.print("ticker.detach()");
}
}
The operation results are as follows ,
Example 4. Using multiple Ticker Object let ESP8266 Dealing with multitasking
We can build multiple Ticker object , Let more than one Ticker Object to implement ESP8266 The multitasking of .
The following example program is shown , We pass the sentence Ticker buttonTicker; To create a second Ticker object .
And then use buttonTicker.attach_ms(100, buttonCheck) To achieve the second Ticker Object task processing .
Here we use attach_ms function , The function and attach Functions are similar , The only difference is attach The time unit of the function is seconds , and attach_ms The time unit of the is milliseconds . in other words , This statement will make ESP8266 every other 100 Execute in milliseconds buttonCheck function .
/********************************************************************** Project name /Project : Zero basic introduction to the Internet of things Program name /Program name : a_basic_tinker The team /Team : Taiji maker team / Taichi-Maker (www.taichi-maker.com) author /Author : CYNO Shuo date /Date(YYYYMMDD) : 20200703 Purpose of procedure /Purpose : The purpose of this program is to demonstrate how to use Ticker Library to perform operations regularly . For a detailed description of this procedure , Please refer to the following functions : http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-c/esp8266-tips/ticker/ ----------------------------------------------------------------------- Other instructions / Other Description: This program is a free video tutorial for Taiji maker team 《 Zero basic introduction to the Internet of things 》 Part of . The tutorial system Tell you ESP8266 Knowledge of software and hardware related to Internet of things applications . The following is the contents page of the tutorial : http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/ ***********************************************************************/
#include <Ticker.h>
Ticker ticker;// establish Ticker Used to realize timing function
Ticker buttonTicker;
int count; // Variable for counting
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
analogWriteRange(1023);
pinMode(D3, INPUT_PULLUP);
// Call... Every second sayHi Function a ,attach First argument to function
// Is a variable that controls the timing interval . The unit of this parameter is seconds . The second parameter is
// Name of the regularly executed function .
ticker.attach(1, sayHi, 60);
buttonTicker.attach_ms(100, buttonCheck);
}
void loop() {
// use LED Breathing lamp effect to demonstrate in Tinker Under object control ,ESP8266 It can be timed
// Perform other tasks
for (int fadeValue = 0 ; fadeValue <= 1023; fadeValue += 5) {
analogWrite(LED_BUILTIN, fadeValue);
delay(10);
}
for (int fadeValue = 1023 ; fadeValue >= 0; fadeValue -= 5) {
analogWrite(LED_BUILTIN, fadeValue);
delay(10);
}
delay(3000);
}
// stay Tinker Under object control , This function will execute regularly .
void sayHi(int hiTimes){
count++;
Serial.print("Hi ");
Serial.println(count);
if(count >= hiTimes){
ticker.detach();// When the timer calls 10 Next time , Stop calling functions regularly
Serial.print("ticker.detach()");
}
}
void buttonCheck(){
if (digitalRead(D3) == LOW){
Serial.println("D3 Button Pushed...");
}
}
Example 5. Use ” Counter ” To control ESP8266 Regularly execute more complex functions
Ticker Functions that are called regularly must “ short ”. For example, in the above series of sample programs , We just let Ticker The timing call function performs simple serial port data output , And very basic operations . in fact , In the use of Ticker library , The regular calling function must be executed quickly . Otherwise, unexpected problems will arise .
This raises a question . If we need ESP8266 The operations performed regularly are more complex , What should I do ?
/********************************************************************** Project name /Project : Zero basic introduction to the Internet of things Program name /Program name : e_timer_http The team /Team : Taiji maker team / Taichi-Maker (www.taichi-maker.com) author /Author : CYNO Shuo date /Date(YYYYMMDD) : 20200703 Purpose of procedure /Purpose : The purpose of this program is to demonstrate how to use counters to control ESP8266 Regularly execute more complex functions .Ticker Functions that are called regularly must “ short ”. It should not be a complex and time-consuming function . For more complex functions , We can use the counter method to realize . This program will periodically let ESP8266 towards example The web server sends a request , And the server response information is displayed on the screen . For a detailed description of this procedure , Please refer to the following functions : http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-c/esp8266-tips/tinker/ ----------------------------------------------------------------------- Other instructions / Other Description: This program is a free video tutorial for Taiji maker team 《 Zero basic introduction to the Internet of things 》 Part of . The tutorial system Tell you ESP8266 Knowledge of software and hardware related to Internet of things applications . The following is the contents page of the tutorial : http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/ ***********************************************************************/
#include <Ticker.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define URL "http://www.example.com"
// Set up wifi Access information ( Please according to your WiFi Modify the information )
const char* ssid = "FAST_153C80";
const char* password = "123456798";
Ticker ticker;
int count;
void setup() {
Serial.begin(9600);
// Set up ESP8266 The working mode is wireless terminal mode
WiFi.mode(WIFI_STA);
// Connect WiFi
connectWifi();
ticker.attach(1, tickerCount);
}
void loop() {
if (count >= 5){
httpRequest();
count = 0;
}
}
void tickerCount(){
count++;
Serial.print("count = ");
Serial.println(count);
}
// send out HTTP Request and output the server response through the serial port
void httpRequest(){
WiFiClient client;
HTTPClient httpClient;
httpClient.begin(client, URL);
Serial.print("URL: "); Serial.println(URL);
int httpCode = httpClient.GET();
Serial.print("Send GET request to URL: ");
Serial.println(URL);
if (httpCode == HTTP_CODE_OK) {
// Use getString Function to get the content of the server response body
String responsePayload = httpClient.getString();
Serial.println("Server Response Payload: ");
Serial.println(responsePayload);
} else {
Serial.println("Server Respose Code:");
Serial.println(httpCode);
}
httpClient.end();
}
void connectWifi(){
// Start connecting wifi
WiFi.begin(ssid, password);
// wait for WiFi Connect , Connection successfully printed IP
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi Connected!");
}
There is something wrong with this program , It will always cause an exception and restart automatically .
newspaper Exception (9) ,( Check the relevant manuals and say that there are two reasons , One is a wild pointer , One is reading / Write Cache The address is not aligned ).
It took a long time to find out why .
This program is different from the version of the library used in the video , The version I use here is 3.0.2,
What is used in the video is 2.6.3 edition ,
3.0.0 Version is a watershed . Because there is more code
HTTPClient httpClient;
WiFiClient client;
httpClient.begin(client, URL);
So to make the program work properly , One solution is to reinstall 2.6.3 Version Library , Then don't add WiFiClient client; This object .
later , After trying , Findings will be WiFiClient client; It's defined in HTTPClient httpClient; In front of , The program will run without any problems , So there is no need to reinstall the library ( The above procedure has been corrected ).
边栏推荐
- MySQL - SQL statement
- 解决:jmeter5.5在win11下界面上的字特别小
- 【gdb调试工具】| 如何在多线程、多进程以及正在运行的程序下调试
- Digital cloud released the 2022 white paper on digital operation of global consumers in the beauty industry: global growth solves marketing problems
- Applet cloud data, data request a method to collect data
- Numpy numpy中的np.c_和np.r_详解
- The ambition of JD instant retailing from 618
- Longest public prefix of leetcode
- Go 语言项目开发实战目录
- Target detection series fast r-cnn
猜你喜欢

读CVPR 2022目标检测论文得到的亿点点启发

深入了解 border

CF566E-Restoring Map【bitset】

2022.06.23 (traversal of lc_144,94145\

嵌入式 | 硬件转软件的几条建议
![[e325: attention] VIM editing error](/img/58/1207dec27b3df7dde19d03e9195a53.png)
[e325: attention] VIM editing error

The border problem after the focus of input

深入解析 Apache BookKeeper 系列:第三篇——读取原理

The list of open source summer winners has been publicized, and the field of basic software has become a hot application this year
![[ES6 breakthrough] promise is comparable to native custom encapsulation (10000 words)](/img/b3/b156d75c7b4f03580c449f8499cd74.png)
[ES6 breakthrough] promise is comparable to native custom encapsulation (10000 words)
随机推荐
4274. suffix expression
Transplantation of xuantie e906 -- fanwai 0: Construction of xuantie c906 simulation environment
Zero foundation self-study SQL course | syntax sequence and execution sequence of SQL statements
Numpy NP in numpy c_ And np r_ Explain in detail
I heard that you are still spending money to buy ppt templates from the Internet?
最新Windows下Go语言开发环境搭建+GoLand配置
Niuke.com string deformation
【LeetCode】387. First unique character in string
Get post: do you really know the difference between requests??????
Solution: the word of jmeter5.5 on the win11 lower interface is very small
PhpStrom代码格式化设置
获取带参数的微信小程序二维码-以及修改二维码LOGO源码分享
Cmake命令之target_compile_options
threejs辉光通道01(UnrealBloomPass && layers)
LeetCode之最长公共前缀
The list of open source summer winners has been publicized, and the field of basic software has become a hot application this year
L01_ How is an SQL query executed?
每周推荐短视频:谈论“元宇宙”要有严肃认真的态度
零基础自学SQL课程 | 子查询
Time Series Data Augmentation for Deep Learning: A Survey 之论文阅读