当前位置:网站首页>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 ).
边栏推荐
- Redis implements a globally unique ID
- Longest public prefix of leetcode
- Niuke network decimal integer to hexadecimal string
- 【LeetCode】541. Reverse string II
- Essay - Reflection
- Code written by mysql, data addition, deletion, query and modification, etc
- 2022.06.23 (traversal of lc_144,94145\
- Linux (centos7.9) installation and deployment of MySQL Cluster 7.6
- 十二、所有功能实现效果演示
- Niuke.com string deformation
猜你喜欢

浮点数表示法(总结自CS61C和CMU CSAPP)

目标检测系列——Fast R-CNN

linux(centos7.9)安装部署mysql-cluster 7.6

陆奇:我现在最看好这四大技术趋势

CF566E-Restoring Map【bitset】

【ES6闯关】Promise堪比原生的自定义封装(万字)

学习太极创客 — ESP8226 (十二)ESP8266 多任务处理

当程序员被问会不会修电脑时… | 每日趣闻

Netrca: an effective network fault cause localization

Zero foundation self-study SQL course | related sub query
随机推荐
Redis implements a globally unique ID
Data midrange: analysis of full stack technical architecture of data midrange, with industry solutions
NETRCA: AN EFFECTIVE NETWORK FAULT CAUSE LOCALIZATION之论文阅读
Niuke network decimal integer to hexadecimal string
MySQL data (Linux Environment) scheduled backup
Pytorch读入据集(典型数据集及自定义数据集两种模式)
[Niuke] length of the last word of HJ1 string
Leetcode-- string
支持向量机(SVC,NuSVC,LinearSVC)
Software system dependency analysis
[redis realize Secondary killing Business ①] Overview of Secondary killing Process | Basic Business Realization
十二、所有功能实现效果演示
When programmers are asked if they can repair computers... | daily anecdotes
牛客网 字符串变形
【bug】@JsonFormat 使用时出现日期少一天的问题
4275. Dijkstra sequence
怎么把mdf和ldf文件导入MySQL workbench中
2021-05-20computed and watch applications and differences
荐书丨《好奇心的秘密》:一个针尖上可以站多少跳舞的小天使?
Pytoch read data set (two modes: typical data set and user-defined data set)