当前位置:网站首页>8266 obtain 18b20 temperature
8266 obtain 18b20 temperature
2022-04-23 18:55:00 【Brick Porter】
8266 obtain 18B20 temperature , Network synchronization to bafayun . Finally, the real-time temperature can be obtained through mobile phone software or tmall wizard .
I used it here 8266 yes ESP01S. There are too few export interfaces for this board , If you have more operational needs, you'd better buy other models , By the way ,8266 Not a specific board , It's just a chip model . The difference between general boards is the use of flash And exported io The number of mouths is different , Of course, some boards have their own USB To serial chip , In this way, the data cable is directly connected to the computer USB It is more convenient to download the program by mouth , If you are learning, I think this serial chip is more convenient ,flash You'd better choose a bigger one , Lest some examples can't run .
1、 open arduino, Tools -》 Management of the library Enter in the filter onewire The following library I use
2、 Then search in the filter 18b20 Find the following library installation
Be careful library 2 Dependency Library 1, So actually, the library 2 Don't be able to , Call or encapsulate the library by yourself 1 .
3、 Download on bafayun 8266 Routine for Put the address https://cloud.bemfa.com/zip/ap.zip
4、 The installation package above is a ino file , Unzip or directly open and copy to your own project .
5、 stay Put this SSID and PSK Change to yourself wifi Your account number and password
6、 there UID Change to your own bafayun key and device name , I have already created the device name , If not established , Then go to bafayun's console to create a new theme , The last three use 004 Represents the sensor .
7、 Add a get 18B20 Function of , Be careful 18B20 It can be connected in parallel , If you want to read more than one, you need to use the... In the comment while Get multiple , Because I have only one here, I don't need it .
#define DHTPIN 2
DS18B20 ds(DHTPIN);
float GetDS18B02Temperature()
{
// only one , If more than one needs while(ds.selectNext())
return ds.getTempC();
}
8、 Add a function to upload temperature
void upload()
{
String upstr = "";
upstr = "cmd=2&uid=" + UID + "&topic=" + TOPIC + "&msg=on#" + String(GetDS18B02Temperature()) + "\r\n";
sendtoTCPServer(upstr);
Serial.println("upload....");
Serial.println(upstr);
}
9、 Modify upload and receive logic , among bIsOn As a whole bool Variable .
void doTCPClientTick()
{
// Check for disconnection , Disconnected and reconnected
if (WiFi.status() != WL_CONNECTED)
return;
if (!TCPclient.connected())
{ // Disconnect and reconnect
if (preTCPConnected == true)
{
preTCPConnected = false;
preTCPStartTick = millis();
Serial.println();
Serial.println("TCP Client disconnected.");
TCPclient.stop();
}
else if (millis() - preTCPStartTick > 1 * 1000) // Reconnect the
startTCPClient();
}
else
{
if (TCPclient.available())
{ // Receive data
char c = TCPclient.read();
TcpClient_Buff += c;
TcpClient_BuffIndex++;
TcpClient_preTick = millis();
if (TcpClient_BuffIndex >= MAX_PACKETSIZE - 1)
{
TcpClient_BuffIndex = MAX_PACKETSIZE - 2;
TcpClient_preTick = TcpClient_preTick - 200;
}
preHeartTick = millis();
}
if (isOpen && (millis() - preHeartTick >= 10 * 1000))
{
preHeartTick = millis();
upload();
}
else if (millis() - preHeartTick >= KEEPALIVEATIME)
{ // Keep your heart beating
preHeartTick = millis();
Serial.println("--Keep alive:");
sendtoTCPServer("ping\r\n"); // Send a heartbeat , Instruction needs \r\n ending , See the introduction of access document for details
}
}
if ((TcpClient_Buff.length() >= 1) && (millis() - TcpClient_preTick >= 200))
{
TCPclient.flush();
Serial.print("Rev string: ");
TcpClient_Buff.trim(); // Remove first space
Serial.println(TcpClient_Buff); // Print received messages
String getTopic = "";
String getMsg = "";
if (TcpClient_Buff.length() > 15)
{ // Be careful TcpClient_Buff It's just a string , Initialization is done at the beginning of the above String TcpClient_Buff = "";
// At this time, you will receive the push instruction , The instruction is about cmd=2&uid=xxx&topic=light002&msg=off
int topicIndex = TcpClient_Buff.indexOf("&topic=") + 7; // c Language string lookup , lookup &topic= Location , And move 7 position , Don't understand Baidu c Language string lookup
int msgIndex = TcpClient_Buff.indexOf("&msg="); // c Language string lookup , lookup &msg= Location
getTopic = TcpClient_Buff.substring(topicIndex, msgIndex); // c Language string interception , Intercept to topic, Don't understand Baidu c Language string interception
getMsg = TcpClient_Buff.substring(msgIndex + 5); // c Language string interception , Intercepted message
Serial.print("topic:------");
Serial.println(getTopic); // Print the intercepted subject value
Serial.print("msg:--------");
Serial.println(getMsg); // Print the intercepted message value
}
if (String(getMsg).startsWith("on"))
{ // If it's news == open
// upload();
isOpen = true;
}
else if (String(getMsg).startsWith("off"))
{ // If it's news == close
isOpen = false;
}
TcpClient_Buff = "";
TcpClient_BuffIndex = 0;
}
}
10、 Last whole code
/*
This sketch establishes a TCP connection to a "quote of the day" service.
It sends a "hello" message, and then prints received data.
*/
#include <ESP8266WiFi.h>
#include <DS18B20.h>
#ifndef STASSID
#define STASSID " Yours wifi Account number "
#define STAPSK " Yours wifi password "
#endif
#define server_ip "bemfa.com" // The default address of Bafa ECS can be
#define server_port "8344" // Server port ,tcp Maker cloud port 8344
String UID = " Yours UID"; // User private key , Available on the console , Change it to your own UID
String TOPIC = "t004"; // Subject name , You can create a new
const char *ssid = STASSID;
const char *password = STAPSK;
#define DHTPIN 2
DS18B20 ds(DHTPIN);
float GetDS18B02Temperature()
{
// only one , If more than one needs while(ds.selectNext())
return ds.getTempC();
}
// Maximum number of bytes
#define MAX_PACKETSIZE 512
// Set the heartbeat value 30s
#define KEEPALIVEATIME 30 * 1000
// tcp Client related initialization , The default can be
WiFiClient TCPclient;
String TcpClient_Buff = ""; // Initialize string , Used to receive data from the server
unsigned int TcpClient_BuffIndex = 0;
unsigned long TcpClient_preTick = 0;
unsigned long preHeartTick = 0; // heartbeat
unsigned long preTCPStartTick = 0; // Connect
bool preTCPConnected = false;
bool isOpen = false;
// TCP Initialize connection
void doTCPClientTick();
void startTCPClient();
int sendtoTCPServer(String p);
/*
* Send data to TCP The server
*/
int sendtoTCPServer(String p)
{
if (!TCPclient.connected())
{
Serial.println("Client is not readly");
return 0;
}
return TCPclient.print(p);
}
/*
* Initialize and establish a connection with the server
*/
void startTCPClient()
{
if (TCPclient.connect(server_ip, atoi(server_port)))
{
Serial.print("\nConnected to server:");
Serial.printf("%s:%d\r\n", server_ip, atoi(server_port));
String tcpTemp = ""; // Initialize string
tcpTemp = "cmd=1&uid=" + UID + "&topic=" + TOPIC + "\r\n"; // Build subscription instructions
sendtoTCPServer(tcpTemp); // Send subscription instructions
tcpTemp = ""; // Empty
/*
// If you need to subscribe to multiple topics , The subscription instruction can be sent again
tcpTemp = "cmd=1&uid="+UID+"&topic="+ The theme 2+"\r\n"; // Build subscription instructions
sendtoTCPServer(tcpTemp); // Send subscription instructions
tcpTemp="";// Empty
*/
preTCPConnected = true;
preHeartTick = millis();
TCPclient.setNoDelay(true);
}
else
{
Serial.print("Failed connected to server:");
Serial.println(server_ip);
TCPclient.stop();
preTCPConnected = false;
}
preTCPStartTick = millis();
}
void upload()
{
String upstr = "";
upstr = "cmd=2&uid=" + UID + "&topic=" + TOPIC + "&msg=on#" + String(GetDS18B02Temperature()) + "\r\n";
sendtoTCPServer(upstr);
Serial.println("upload....");
Serial.println(upstr);
}
/*
* Check the data , Send a heartbeat
*/
void doTCPClientTick()
{
// Check for disconnection , Disconnected and reconnected
if (WiFi.status() != WL_CONNECTED)
return;
if (!TCPclient.connected())
{ // Disconnect and reconnect
if (preTCPConnected == true)
{
preTCPConnected = false;
preTCPStartTick = millis();
Serial.println();
Serial.println("TCP Client disconnected.");
TCPclient.stop();
}
else if (millis() - preTCPStartTick > 1 * 1000) // Reconnect the
startTCPClient();
}
else
{
if (TCPclient.available())
{ // Receive data
char c = TCPclient.read();
TcpClient_Buff += c;
TcpClient_BuffIndex++;
TcpClient_preTick = millis();
if (TcpClient_BuffIndex >= MAX_PACKETSIZE - 1)
{
TcpClient_BuffIndex = MAX_PACKETSIZE - 2;
TcpClient_preTick = TcpClient_preTick - 200;
}
preHeartTick = millis();
}
if (isOpen && (millis() - preHeartTick >= 10 * 1000))
{
preHeartTick = millis();
upload();
}
else if (millis() - preHeartTick >= KEEPALIVEATIME)
{ // Keep your heart beating
preHeartTick = millis();
Serial.println("--Keep alive:");
sendtoTCPServer("ping\r\n"); // Send a heartbeat , Instruction needs \r\n ending , See the introduction of access document for details
}
}
if ((TcpClient_Buff.length() >= 1) && (millis() - TcpClient_preTick >= 200))
{
TCPclient.flush();
Serial.print("Rev string: ");
TcpClient_Buff.trim(); // Remove first space
Serial.println(TcpClient_Buff); // Print received messages
String getTopic = "";
String getMsg = "";
if (TcpClient_Buff.length() > 15)
{ // Be careful TcpClient_Buff It's just a string , Initialization is done at the beginning of the above String TcpClient_Buff = "";
// At this time, you will receive the push instruction , The instruction is about cmd=2&uid=xxx&topic=light002&msg=off
int topicIndex = TcpClient_Buff.indexOf("&topic=") + 7; // c Language string lookup , lookup &topic= Location , And move 7 position , Don't understand Baidu c Language string lookup
int msgIndex = TcpClient_Buff.indexOf("&msg="); // c Language string lookup , lookup &msg= Location
getTopic = TcpClient_Buff.substring(topicIndex, msgIndex); // c Language string interception , Intercept to topic, Don't understand Baidu c Language string interception
getMsg = TcpClient_Buff.substring(msgIndex + 5); // c Language string interception , Intercepted message
Serial.print("topic:------");
Serial.println(getTopic); // Print the intercepted subject value
Serial.print("msg:--------");
Serial.println(getMsg); // Print the intercepted message value
}
if (String(getMsg).startsWith("on"))
{ // If it's news == open
// upload();
isOpen = true;
}
else if (String(getMsg).startsWith("off"))
{ // If it's news == close
isOpen = false;
}
TcpClient_Buff = "";
TcpClient_BuffIndex = 0;
}
}
void setup()
{
Serial.begin(115200);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
would try to act as both a client and an access-point and could cause
network-issues with your other WiFi-devices on your WiFi-network. */
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println(GetDS18B02Temperature());
startTCPClient();
}
void loop()
{
doTCPClientTick();
}
Pay attention to modifying your information in the code . The temperature cannot be obtained after operation .
11、 In bafayun Console , Pushed a... To the device on The news of , After that, start uploading the temperature regularly . Of course, if you have a tmall elf , Just say to it “ Turn on the temperature sensor ” That's it .
So far, it is basically completed , In addition, bafayun also provides a platform for developing Android AI2Offline file . You can read the development documents by yourself .
Also upload an effect
Of course use TCP Developing one by yourself is also very simple .
版权声明
本文为[Brick Porter]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210603257013.html
边栏推荐
- How about CICC wealth? Is it safe to open an account up there
- 中金财富怎么样?在上边开户安全吗
- The type initializer for ‘Gdip‘ threw an exception
- Resolution: cnpm: unable to load file \cnpm. PS1, because running scripts is prohibited on this system
- K210串口通信
- ESP32 LVGL8. 1 - input devices (input devices 18)
- listener. log
- 2022.04.23(LC_763_划分字母区间)
- Machine learning theory (8): model integration ensemble learning
- Sentinel规则持久化进Nacos
猜你喜欢
How to virtualize the video frame and background is realized in a few simple steps
Teach you to quickly rename folder names in a few simple steps
os_authent_prefix
ESP32 LVGL8. 1 - arc (arc 19)
Esp32 (UART event) - serial port event learning (1)
Use bitnami / PostgreSQL repmgr image to quickly set up PostgreSQL ha
【科普】CRC校验(一)什么是CRC校验?
Esp01s with Arduino development environment
Resolution: cnpm: unable to load file \cnpm. PS1, because running scripts is prohibited on this system
Résolution: cnpm: impossible de charger le fichier... Cnpm. PS1 parce que l'exécution de scripts est désactivée sur ce système
随机推荐
Use of content provider
Resolution: cnpm: unable to load file \cnpm. PS1, because running scripts is prohibited on this system
Simple use of navigation in jetpack
Deeply understand what new and make in golang are and what are the differences?
简化路径(力扣71)
关于unity文件读取的操作(一)
K210 serial communication
From technical system to business insight, the closing chapter of the practice of small and medium-sized R & D team structure
ESP32 LVGL8. 1 - arc (arc 19)
使用晨曦记账本,分析某个时间段每个账户收支结余
Seata handles distributed transactions
Usage of functions decode() and replace() in SQL
Zlib realizes streaming decompression
Sword finger offer II 116 Number of provinces - spatial complexity O (n), time complexity O (n)
Esp32 (UART ecoh) - serial port echo worm learning (2)
Esp32 drive encoder -- siq-02fvs3 (vscade + IDF)
[advanced level 11 of C language -- character and string functions and their simulation implementation (2)]
Introduction to ROS learning notes (I)
ctfshow-web362(SSTI)
Esp32 (UART 485 communication) - 485 communication of serial port (3)