当前位置:网站首页>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 ).
边栏推荐
- leetcode--链表
- The ambition of JD instant retailing from 618
- The list of open source summer winners has been publicized, and the field of basic software has become a hot application this year
- Leetcode-- string
- [redis realize Secondary killing Business ①] Overview of Secondary killing Process | Basic Business Realization
- Every (), map (), forearch () methods. There are objects in the array
- Directly applicable go coding specification
- 每周推薦短視頻:談論“元宇宙”要有嚴肅認真的態度
- Lu Qi: I am most optimistic about these four major technology trends
- Depens:*** but it is not going to be installed
猜你喜欢

Squid proxy application

CF566E-Restoring Map【bitset】

Groovy通过withCredentials获取Jenkins凭据

"I can't understand Sudoku, so I choose to play Sudoku."

Squid代理服务器应用
![[Niuke] convert string to integer](/img/56/3e491b3d0eea0d89a04d0b871501d7.png)
[Niuke] convert string to integer

活动报名|Apache Pulsar x KubeSphere 在线 Meetup 火热报名中

支持向量机(SVC,NuSVC,LinearSVC)

【bug】@JsonFormat 使用时出现日期少一天的问题

The native applet uses canvas to make posters, which are scaled to the same scale. It is similar to the uniapp, but the writing method is a little different
随机推荐
十二、所有功能实现效果演示
嵌入式 | 硬件转软件的几条建议
Squid代理服务器应用
解决:jmeter5.5在win11下界面上的字特别小
Linux MySQL installation
MySQL - SQL statement
[noi simulation] pendulum (linear algebra, Du Jiao sieve)
Netrca: an effective network fault cause localization
[Niuke] convert string to integer
When to use RDD and dataframe/dataset
怎么把mdf和ldf文件导入MySQL workbench中
Inspiration from reading CVPR 2022 target detection paper
From the Huawei weautomate digital robot forum, we can see the "new wisdom of government affairs" in the field of government and enterprises
php单例模式详解
Get post: do you really know the difference between requests??????
Common emoticons
【LeetCode】541. Reverse string II
PhpStrom代码格式化设置
4275. Dijkstra sequence
零基础自学SQL课程 | 相关子查询