当前位置:网站首页>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
边栏推荐
- Advanced transfer learning
- mysql_linux版本的下載及安裝詳解
- Esp01s with Arduino development environment
- One of the reasons why the WebView web page cannot be opened (and some WebView problem records encountered by myself)
- listener. log
- ctfshow-web362(SSTI)
- Actual combat of Nacos as service configuration center
- On iptables
- ctfshow-web362(SSTI)
- 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
猜你喜欢
ctfshow-web362(SSTI)
微搭低代码零基础入门课(第三课)
ESP32 LVGL8. 1 - slider slider (slider 22)
Esp32 (UART receiving and sending) - receiving and sending communication of serial port (4)
Machine learning theory (8): model integration ensemble learning
【历史上的今天】4 月 23 日:YouTube 上传第一个视频;网易云音乐正式上线;数字音频播放器的发明者出生
Esp32 (UART ecoh) - serial port echo worm learning (2)
On iptables
Solutions such as unknown or garbled code or certificate problem prompt in Charles's mobile phone packet capture, actual measurement.
纠结
随机推荐
ctfshow-web361(SSTI)
Resolution: cnpm: unable to load file \cnpm. PS1, because running scripts is prohibited on this system
listener.log
Treatment of incomplete display of listview height
listener. log
Nacos集群搭建和mysql持久化配置
Using bafayun to control the computer
mysql_linux版本的下載及安裝詳解
Eight bit binary multiplier VHDL
12 examples to consolidate promise Foundation
From technical system to business insight, the closing chapter of the practice of small and medium-sized R & D team structure
[today in history] April 23: the first video uploaded on YouTube; Netease cloud music officially launched; The inventor of digital audio player was born
ESP32 LVGL8. 1 - msgbox message box (msgbox 28)
Raspberry pie uses root operation, and the graphical interface uses its own file manager
程序员如何快速开发高质量的代码?
os_authent_prefix
【历史上的今天】4 月 23 日:YouTube 上传第一个视频;网易云音乐正式上线;数字音频播放器的发明者出生
The type initializer for ‘Gdip‘ threw an exception
How about CICC wealth? Is it safe to open an account up there
std::stoi stol stoul stoll stof stod