乐鑫技术交流
直播中

张红

7年用户 1285经验值
私信 关注
[问答]

4个Wemos D1 mini使用DS18B20温度传感器向树莓派上的MYSQL数据库报告的问题求解

我有 4 个 Wemos D1 mini 使用 DS18B20 温度传感器,它们向我的树莓派上的 MYSQL 数据库报告。
自去年 10 月(2017 年)以来,这已经成功地每 15 分钟报告一次,但我想包括 OTA,因为它们很难到达地方和每个传感器的网页。
我现在有 1 个 wemos d1 mini 在处理旧脚本,但我尝试重新配置的 3 个存在以下问题
最初 NTP 时间已经停止,而不是仅在过去的 00、15、30 和 45 分钟报告和上传温度到 MYSQL 数据库。然后,从我更改代码后打开电源开始,它开始每 15 分钟更新一次。这现在已经完全停止工作并报告 ntp 的 ip 地址为 0.0.0.0 并且没有任何更新到 MYSQL 数据库
网络服务器工作并成功报告温度
代码:全选// Including the ESP8266 WiFi library

#include <timeLib.h>

#include
#include

#include

#include

#include

#include
#include

// Replace with your network details
// WiFi
char ssid[] = "Wifi"; // SSID NAME
char password[] = "Wifi-Password"; // SSID PASSWORD


// NTP Servers:
static const char ntpServerName[] = "0.uk.pool.ntp.org";
const int timeZone = 1;
WiFiUDP Udp;
unsigned int localPort = 8888;

time_t getNtpTime();
void sendNTPpacket(IPAddress &address);

WiFiClient client;
MySQL_Connection conn((Client *)&client);

// Data wire is plugged into pin D1 on the ESP8266 12-E - GPIO 5

#define ONE_WIRE_BUS 2

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);


// Pass our oneWire reference to Dallas Temperature.

DallasTemperature DS18B20(&oneWire);

char temperatureCString[7];

char temperatureFString[7];

// MySQL
IPAddress server_addr(192,168,0,15);
char user[] = "sensors";
char pass[] = "SensorsPassword";
char INSERT_DATA[] = "UPDATE sensors.thermostat SET TheTemp = %s, TheUpdated = NOW() WHERE TheLocation = 'Top Bedroom'";
char INSERT_DATA_HISTORY[] = "INSERT INTO sensors.history (HisDate, HisThermostat, HisTemp) VALUES (NOW(),'3',%s)";
char query[128];
char query_HISTORY[128];
char temperature[10];
char temperature_HISTORY[10];


// Web Server on port 80

WiFiServer server(80);



// only runs once on boot

void setup() {

  // Initializing serial port for debugging purposes

  Serial.begin(115200);

  delay(10);

//.30 = Room1 .31 = Room2 .32 = Top Bedroom .33 = Outside
  IPAddress ip(192, 168, 0, 32);
  IPAddress subnet(255, 255, 255, 0);
  IPAddress gt(192, 168, 0, 1);
  WiFi.config(ip, gt, subnet);
  WiFi.hostname("Top-Room-Temp-Sensor");

  DS18B20.begin(); // IC Default 9 bit. If you have troubles consider upping it 12. Ups the delay giving the IC more time to process the temperature measurement



  // Connecting to WiFi network

  Serial.println();

  Serial.print("Connecting to ");

  Serial.println(ssid);



  WiFi.begin(ssid, password);
  Udp.begin(localPort);


  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }

  Serial.println("");

  Serial.println("WiFi connected");



  // Starting the web server

  server.begin();

  Serial.println("Web server running. Waiting for the ESP IP...");

  delay(10000);



  // Printing the ESP IP address

  Serial.println(WiFi.localIP());

  Udp.begin(localPort);
setSyncProvider(getNtpTime);
setSyncInterval(300);

}

void saveTempData() {
if (((minute() == 0) || (minute() ==15) || (minute() ==30) || (minute() ==45)) && (second() == 0)) {
//if (((now.minute() == 0) || (now.minute() ==15) || (now.minute() ==30) || (now.minute() ==45)) && (now.second() == 0)) {
// if ( minute() == 00 && second() == 00 ) {
sensors.requestTemperatures();
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
Serial.print("Temp : ");
Serial.println(sensors.getTemPCByIndex(0));
  Serial.print("Query : ");
dtostrf(sensors.getTempCByIndex(0), 2, 2, temperature);
dtostrf(sensors.getTempCByIndex(0), 2, 2, temperature_HISTORY);
sprintf(query, INSERT_DATA,temperature);
sprintf(query_HISTORY, INSERT_DATA_HISTORY,temperature_HISTORY);
cur_mem->execute(query);
cur_mem->execute(query_HISTORY);
Serial.println(query);
Serial.println(query_HISTORY);
delete cur_mem;
Serial.println("Data stored!");
}
}



void getTemperature() {

  float tempC;

  float tempF;

  do {

    DS18B20.requestTemperatures();

    tempC = DS18B20.getTempCByIndex(0);

    dtostrf(tempC, 2, 2, temperatureCString);

    tempF = DS18B20.getTempFByIndex(0);

    dtostrf(tempF, 3, 2, temperatureFString);

    delay(100);

  } while (tempC == 85.0 || tempC == (-127.0));

}


time_t prevDisplay = 0; // when the digital clock was displayed
// runs over and over again

void loop() {
  saveTempData();

  // Listenning for new clients

  WiFiClient client = server.available();



  if (client) {

    Serial.println("New client");

    // bolean to locate when the http request ends

    boolean blank_line = true;

    while (client.connected()) {

      if (client.available()) {

        char c = client.read();

      

        if (c == 'n' && blank_line) {

            getTemperature();

            client.println("HTTP/1.1 200 OK");

            client.println("Content-Type: text/html");

            client.println("Connection: close");

            client.println();

            // your actual web page that displays temperature

            client.println("");

            client.println("");

            client.println("

Nytram Top Bedroom - Temperature

Temperature in Celsius: ");

            client.println(temperatureCString);

            client.println("*C

Temperature in Fahrenheit: ");

            client.println(temperatureFString);

            client.println("*F

");

            break;

        }

        if (c == 'n') {

          // when starts reading a new line

          blank_line = true;

        }

        else if (c != 'r') {

          // when finds a character on the current line

          blank_line = false;

        }

      }

    }

    // closing the client connection

    delay(1);

    client.stop();

    Serial.println("Client disconnected.");

  }

}  


/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
IPAddress ntpServerIP; // NTP server's ip address

while (Udp.parsePacket() > 0) ; // discard any previously received packets
Serial.println("Transmit NTP Request");
// get a random server from the pool
WiFi.hostByName(ntpServerName, ntpServerIP);
Serial.print(ntpServerName);
Serial.print(": ");
Serial.println(ntpServerIP);
sendNTPpacket(ntpServerIP);
uint32_t beginWait = millis();
while (millis() - beginWait < 1500) {
int size = Udp.parsePacket();
if (size >= NTP_PACKET_SIZE) {
Serial.println("Receive NTP Response");
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
unsigned long secsSince1900;
// convert four bytes starting at location 40 to a long integer
secsSince1900 = (unsigned long)packetBuffer[40] << 24;
secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
secsSince1900 |= (unsigned long)packetBuffer[43];
return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
}
}
Serial.println("No NTP Response :-(");
return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
//Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(packetBuffer, NTP_PACKET_SIZE);
Udp.endPacket();
}
请有人能指出我正确的方向吗?

更多回帖

发帖
×
20
完善资料,
赚取积分