当前位置:网站首页>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
边栏推荐
- Raspberry pie uses root operation, and the graphical interface uses its own file manager
- Loop path
- Advanced transfer learning
- Use Chenxi bookkeeping book to analyze the balance of revenue and expenditure of each account in a certain period of time
- Esp01s with Arduino development environment
- Nacos作为服务注册中心
- 昇腾 AI 开发者创享日全国巡回首站在西安成功举行
- From technical system to business insight, the closing chapter of the practice of small and medium-sized R & D team structure
- 解决:cnpm : 无法加载文件 ...\cnpm.ps1,因为在此系统上禁止运行脚本
- Simplified path (force buckle 71)
猜你喜欢
2022.04.23(LC_763_划分字母区间)
Practice of Druid SQL and security in meituan review
Esp32 drive encoder -- siq-02fvs3 (vscade + IDF)
Teach you to quickly rename folder names in a few simple steps
ESP32 LVGL8. 1 - img picture (IMG 20)
iptables -L执行缓慢
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
12 examples to consolidate promise Foundation
os_ authent_ Prefix
Tangle
随机推荐
Nacos作为服务配置中心实战
Raspberry pie 18b20 temperature
Configure iptables
PyGame tank battle
ESP32 LVGL8. 1 - img picture (IMG 20)
Implementation of TCP UDP communication with golang language
Treatment of incomplete display of listview height
剑指 Offer II 116. 省份数量-空间复杂度O(n),时间复杂度O(n)
std::stoi stol stoul stoll stof stod
ESP32 LVGL8. 1 - roller rolling (roller 24)
STM32: LCD显示
K210串口通信
#yyds干货盘点#stringprep --- 因特网字符串预备
STM32: LCD display
Xlslib use
ctfshow-web362(SSTI)
The type initializer for ‘Gdip‘ threw an exception
Seata handles distributed transactions
Iptables - L executes slowly
Machine learning theory (8): model integration ensemble learning