当前位置:网站首页>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 ).
边栏推荐
- Code written by mysql, data addition, deletion, query and modification, etc
- 支持向量机(SVC,NuSVC,LinearSVC)
- Numpy numpy中的np.c_和np.r_详解
- 怎么把mdf和ldf文件导入MySQL workbench中
- Zero foundation self-study SQL course | sub query
- 荐书丨《好奇心的秘密》:一个针尖上可以站多少跳舞的小天使?
- [use picgo+ Tencent cloud object to store cos as a map bed]
- 【Redis實現秒殺業務①】秒殺流程概述|基本業務實現
- 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
- 金仓KFS replicator安装(Oracle-KES)
猜你喜欢

零基础自学SQL课程 | 相关子查询

Yolox backbone -- implementation of cspparknet

Epidemic situation, unemployment, 2022, we shouted to lie down!

Rpiplay implementation of raspberry pie airplay projector
![[e325: attention] VIM editing error](/img/58/1207dec27b3df7dde19d03e9195a53.png)
[e325: attention] VIM editing error

【Redis实现秒杀业务①】秒杀流程概述|基本业务实现
![[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)

Spark - the number of leftouterjoin results is inconsistent with that of the left table

零基础自学SQL课程 | HAVING子句

当程序员被问会不会修电脑时… | 每日趣闻
随机推荐
RISC-V架构下 FPU Context 的动态保存和恢复
tp5 使用post接收数组数据时报variable type error: array错误的解决方法
【Redis實現秒殺業務①】秒殺流程概述|基本業務實現
零基础自学SQL课程 | 子查询
Transplantation of xuantie e906 -- fanwai 0: Construction of xuantie c906 simulation environment
Pytoch read data set (two modes: typical data set and user-defined data set)
The list of open source summer winners has been publicized, and the field of basic software has become a hot application this year
eBanb B1手环刷固件异常中断处理
读CVPR 2022目标检测论文得到的亿点点启发
Rpiplay implementation of raspberry pie airplay projector
When to use RDD and dataframe/dataset
软件系统依赖关系分析
LeetCode之最长公共前缀
牛客网 十进制整数转十六进制字符串
【输入法】迄今为止,居然有这么多汉字输入法!
2022.06.23 (traversal of lc_144,94145\
牛客网 字符串变形
Easyexcel single sheet and multi sheet writing
Leetcode -- wrong set
Go language project development practice directory