1.3寸 SH1106 OLED+ESP8266 NodeMCU+DHT11气象站制作过程(三)

由于代码截图讲解不便,所以代码解释直接在代码注释里。

一、非配网版(先试验成功后再试下面的微信配网版)

/**The MIT License (MIT)

Copyright (c) 2018 by Daniel Eichhorn - ThingPulse

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

See more at https://thingpulse.com
*/
//#include <U8g2lib.h>
#include "DHT.h"
#include <Arduino.h>
#include <ESPWiFi.h>
#include <ESPHTTPClient.h>
#include <JsonListener.h>

// time
#include <time.h>                       // time() ctime()
#include <sys/time.h>                   // struct timeval
#include <coredecls.h>                  // settimeofday_cb()

#include "SH1106Wire.h"
#include "OLEDDisplayUi.h"
#include "Wire.h"
#include "OpenWeatherMapCurrent.h"
#include "OpenWeatherMapForecast.h"
#include "WeatherStationFonts.h"
#include "WeatherStationImages.h"


/***************************
 * Begin Settings
 **************************/
#define DHTTYPE DHT11 
#define DHTPIN D5  //dht11 

// WIFI
const char* WIFI_SSID = "J.Fla";                  //WIFI账号
const char* WIFI_PWD = "j.fla123";                //WIFI密码

#define TZ              7       // (utc+) TZ in hours
#define DST_MN          60      // use 60mn for summer time in some countries

// Setup
const int UPDATE_INTERVAL_SECS = 20 * 60; // Update every 20 minutes

// Display Settings
const int I2C_DISPLAY_ADDRESS = 0x3c;

#if defined(ESP8266)
const int SDA_PIN = D1;
const int SDC_PIN = D2;
#else
const int SDA_PIN = D1; //D3;
const int SDC_PIN = D2; //D4;
#endif

//U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE,D2,D1);

// OpenWeatherMap Settings
// Sign up here to get an API key:
// https://docs.thingpulse.com/how-tos/openweathermap-key/
String OPEN_WEATHER_MAP_APP_ID = "798ef2d2c9d7e1a7ae2c5058e2ce03e0";
/*
Go to https://openweathermap.org/find?q= and search for a location. Go through the
result set and select the entry closest to the actual location you want to display 
data for. It'll be a URL like https://openweathermap.org/city/2657896. The number
at the end is what you assign to the constant below.
 */
String OPEN_WEATHER_MAP_LOCATION_ID = "1804540";

// Pick a language code from this list:
// Arabic - ar, Bulgarian - bg, Catalan - ca, Czech - cz, German - de, Greek - el,
// English - en, Persian (Farsi) - fa, Finnish - fi, French - fr, Galician - gl,
// Croatian - hr, Hungarian - hu, Italian - it, Japanese - ja, Korean - kr,
// Latvian - la, Lithuanian - lt, Macedonian - mk, Dutch - nl, Polish - pl,
// Portuguese - pt, Romanian - ro, Russian - ru, Swedish - se, Slovak - sk,
// Slovenian - sl, Spanish - es, Turkish - tr, Ukrainian - ua, Vietnamese - vi,
// Chinese Simplified - zh_cn, Chinese Traditional - zh_tw.
String OPEN_WEATHER_MAP_LANGUAGE = "en";
const uint8_t MAX_FORECASTS = 4;

const boolean IS_METRIC = true;

// Adjust according to your language
const String WDAY_NAMES[] = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
const String MONTH_NAMES[] = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};

/***************************
 * End Settings
 **************************/
 // Initialize the oled display for address 0x3c
 // sda-pin=14 and sdc-pin=12
 SH1106Wire     display(I2C_DISPLAY_ADDRESS, SDA_PIN, SDC_PIN);
 OLEDDisplayUi   ui( &display );

OpenWeatherMapCurrentData currentWeather;
OpenWeatherMapCurrent currentWeatherClient;

OpenWeatherMapForecastData forecasts[MAX_FORECASTS];
OpenWeatherMapForecast forecastClient;

#define TZ_MN           ((TZ)*60)
#define TZ_SEC          ((TZ)*3600)
#define DST_SEC         ((DST_MN)*60)
time_t now;

// flag changed in the ticker function every 10 minutes
bool readyForWeatherUpdate = false;

String lastUpdate = "--";

long timeSinceLastWUpdate = 0;

//declaring prototypes
void drawProgress(OLEDDisplay *display, int percentage, String label);
void updateData(OLEDDisplay *display);
void drawDateTime(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y);
void drawCurrentWeather(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y);
void drawForecast(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y);
void drawForecastDetails(OLEDDisplay *display, int x, int y, int dayIndex);
void drawHeaderOverlay(OLEDDisplay *display, OLEDDisplayUiState* state);
void setReadyForWeatherUpdate();
void drawCurrentHT(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y);


// Add frames
// this array keeps function pointers to all frames
// frames are the single views that slide from right to left
FrameCallback frames[] = { drawDateTime, drawCurrentWeather, drawForecast,drawCurrentHT };
int numberOfFrames = 4;

OverlayCallback overlays[] = { drawHeaderOverlay };
int numberOfOverlays = 1;

DHT dht(DHTPIN, DHTTYPE);

  float old_h  ;
  float old_t  ;

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  
  //initialize dht11
  dht.begin(); 
  //u8g2.begin();
  //u8g2.enableUTF8Print();
  // initialize dispaly
  display.init();
  display.clear();
  display.display();

  //display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setContrast(255);

  WiFi.begin(WIFI_SSID, WIFI_PWD);

  int counter = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    display.clear();
    display.drawString(64, 10, "Connecting to WiFi");
    display.drawXbm(46, 30, 8, 8, counter % 3 == 0 ? activeSymbole : inactiveSymbole);
    display.drawXbm(60, 30, 8, 8, counter % 3 == 1 ? activeSymbole : inactiveSymbole);
    display.drawXbm(74, 30, 8, 8, counter % 3 == 2 ? activeSymbole : inactiveSymbole);
    display.display();

    counter++;
  }
  // Get time from network time service
  configTime(TZ_SEC, DST_SEC, "pool.ntp.org");

  ui.setTargetFPS(30);

  ui.setActiveSymbol(activeSymbole);
  ui.setInactiveSymbol(inactiveSymbole);

  // You can change this to
  // TOP, LEFT, BOTTOM, RIGHT
  //ui.setIndicatorPosition(TOP);
  ui.setIndicatorPosition(BOTTOM);

  // Defines where the first frame is located in the bar.
  ui.setIndicatorDirection(LEFT_RIGHT);

  // You can change the transition that is used
  // SLIDE_LEFT, SLIDE_RIGHT, SLIDE_TOP, SLIDE_DOWN
  ui.setFrameAnimation(SLIDE_LEFT);

  ui.setFrames(frames, numberOfFrames);

  ui.setOverlays(overlays, numberOfOverlays);

  // Inital UI takes care of initalising the display too.
  ui.init();

  Serial.println("");

  updateData(&display);

}

void loop() {
  

  if (millis() - timeSinceLastWUpdate > (1000L*UPDATE_INTERVAL_SECS)) {
    setReadyForWeatherUpdate();
    timeSinceLastWUpdate = millis();
  }

  if (readyForWeatherUpdate && ui.getUiState()->frameState == FIXED) {
    updateData(&display);
    
  }

  int remainingTimeBudget = ui.update();

  if (remainingTimeBudget > 0) {
    // You can do some work here
    // Don't do stuff if you are below your
    // time budget.
    
    delay(remainingTimeBudget);
  }
    

}

void drawProgress(OLEDDisplay *display, int percentage, String label) {
  display->clear();
  display->setTextAlignment(TEXT_ALIGN_CENTER);
  display->setFont(ArialMT_Plain_10);
  display->drawString(64, 10, label);
  display->drawProgressBar(2, 28, 124, 10, percentage);
  display->display();
}

void updateData(OLEDDisplay *display) {
  drawProgress(display, 10, "Updating time...");
  drawProgress(display, 30, "Updating weather...");
  currentWeatherClient.setMetric(IS_METRIC);
  currentWeatherClient.setLanguage(OPEN_WEATHER_MAP_LANGUAGE);
  currentWeatherClient.updateCurrentById(&currentWeather, OPEN_WEATHER_MAP_APP_ID, OPEN_WEATHER_MAP_LOCATION_ID);
  drawProgress(display, 50, "Updating forecasts...");
  forecastClient.setMetric(IS_METRIC);
  forecastClient.setLanguage(OPEN_WEATHER_MAP_LANGUAGE);
  uint8_t allowedHours[] = {12};
  forecastClient.setAllowedHours(allowedHours, sizeof(allowedHours));
  forecastClient.updateForecastsById(forecasts, OPEN_WEATHER_MAP_APP_ID, OPEN_WEATHER_MAP_LOCATION_ID, MAX_FORECASTS);

  readyForWeatherUpdate = false;
  drawProgress(display, 100, "Done...");
  delay(1000);
}



void drawDateTime(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
  now = time(nullptr);
  struct tm* timeInfo;
  timeInfo = localtime(&now);
  char buff[16];


  display->setTextAlignment(TEXT_ALIGN_CENTER);
  display->setFont(ArialMT_Plain_10);
  String date = WDAY_NAMES[timeInfo->tm_wday];

  sprintf_P(buff, PSTR("%s, %04d/%02d/%02d"), WDAY_NAMES[timeInfo->tm_wday].c_str(),  timeInfo->tm_year + 1900, timeInfo->tm_mon+1,timeInfo->tm_mday);   // year /mouth /day
  display->drawString(64 + x, 5 + y, String(buff));
  display->setFont(ArialMT_Plain_24);

  sprintf_P(buff, PSTR("%02d:%02d:%02d"), timeInfo->tm_hour, timeInfo->tm_min, timeInfo->tm_sec);
  display->drawString(64 + x, 13 + y, String(buff));
  display->setTextAlignment(TEXT_ALIGN_LEFT);
}

void drawCurrentWeather(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
  display->setFont(ArialMT_Plain_10);
  display->setTextAlignment(TEXT_ALIGN_CENTER);
  display->drawString(64 + x, 36 + y, currentWeather.description);                                             //weather description up 2

  display->setFont(ArialMT_Plain_24);
  display->setTextAlignment(TEXT_ALIGN_LEFT);
  String temp = String(currentWeather.temp, 1) + (IS_METRIC ? "°C" : "°F");
  display->drawString(60 + x, 5 + y, temp);

  display->setFont(Meteocons_Plain_36);
  display->setTextAlignment(TEXT_ALIGN_CENTER);
  display->drawString(33 + x, 0 + y, currentWeather.iconMeteoCon);
}


void drawForecast(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
  drawForecastDetails(display, x, y, 0);
  drawForecastDetails(display, x + 44, y, 1);
  drawForecastDetails(display, x + 88, y, 2);
}

void drawForecastDetails(OLEDDisplay *display, int x, int y, int dayIndex) {
  time_t observationTimestamp = forecasts[dayIndex].observationTime;
  struct tm* timeInfo;
  timeInfo = localtime(&observationTimestamp);
  display->setTextAlignment(TEXT_ALIGN_CENTER);
  display->setFont(ArialMT_Plain_10);
  display->drawString(x + 20, y, WDAY_NAMES[timeInfo->tm_wday]);

  display->setFont(Meteocons_Plain_21);
  display->drawString(x + 20, y + 12, forecasts[dayIndex].iconMeteoCon);
  String temp = String(forecasts[dayIndex].temp, 0) + (IS_METRIC ? "°C" : "°F");
  display->setFont(ArialMT_Plain_10);
  display->drawString(x + 20, y + 34, temp);
  display->setTextAlignment(TEXT_ALIGN_LEFT);
  
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t) ) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  else
  {
    Serial.println(h);
    Serial.println(t);
    old_h=h;
    old_t=t;
    }
}

void drawHeaderOverlay(OLEDDisplay *display, OLEDDisplayUiState* state) {
  now = time(nullptr);
  struct tm* timeInfo;
  timeInfo = localtime(&now);
  char buff[14];
  sprintf_P(buff, PSTR("%02d:%02d"), timeInfo->tm_hour, timeInfo->tm_min);

  display->setColor(WHITE);
  display->setFont(ArialMT_Plain_10);
  display->setTextAlignment(TEXT_ALIGN_LEFT);
  display->drawString(0, 52, String(buff));
  display->setTextAlignment(TEXT_ALIGN_RIGHT);
  String temp = String(currentWeather.temp, 1) + (IS_METRIC ? "°C" : "°F");
  display->drawString(128, 52, temp);                                                  //right down time UP 2
  display->drawHorizontalLine(0, 50, 128);                                            //line up 2
}
void drawCurrentHT (OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y)
{
  
 //float old_h=0,old_t=0;
 //float h = dht.readHumidity();
 //float t = dht.readTemperature();
 
 /*if(old_h==h)
 {return;} 
 else
 {
 float h = dht.readHumidity();
 old_h=h;
 }
 
 if(old_t==t)
 {return;} 
 else
 {
 float t = dht.readTemperature();
 old_t=t;
 }
 */
 


  /*if((h!=0)||(t!=0))
  {
    Serial.println(h);
    Serial.println(t);
    }*/
  
  display->setFont(ArialMT_Plain_16);
  display->setTextAlignment(TEXT_ALIGN_LEFT);
  display->drawString(10 + x, 0 + y,"Humt :");
  display->drawString(60 + x, 0 + y,String(old_h));
  display->drawString(100 + x, 0 + y, "%");
  
  display->drawString(10 + x, 25 + y,"Temp :");
  display->drawString(60 + x, 25 + y,String(old_t));
  display->drawString(100 + x, 25 + y, "°C");
  
  
  
  
  /*u8g2.clearBuffer();
  u8g2.setFontMode(1);
  u8g2.setFont(u8g2_font_ncenB10_tf);
  u8g2.setFontDirection(0);
  u8g2.setCursor(5, 15);
  u8g2.print("Humt:");
  u8g2.setCursor(60, 15);
  u8g2.print(h);
  u8g2.setCursor(103, 15);
  u8g2.print("%");
  

  u8g2.setCursor(5, 35);
  u8g2.print("Temp:");
  u8g2.setCursor(60, 35);
  u8g2.print(t);
  u8g2.setCursor(100, 35);
  u8g2.print("°C");
  u8g2.sendBuffer();
  */
  }
  

void setReadyForWeatherUpdate() {
  Serial.println("Setting readyForUpdate to true");
  readyForWeatherUpdate = true;
}

二、微信配网版

/**The MIT License (MIT)



Copyright (c) 2018 by Daniel Eichhorn - ThingPulse



Permission is hereby granted, free of charge, to any person obtaining a copy

of this software and associated documentation files (the "Software"), to deal

in the Software without restriction, including without limitation the rights

to use, copy, modify, merge, publish, distribute, sublicense, and/or sell

copies of the Software, and to permit persons to whom the Software is

furnished to do so, subject to the following conditions:



The above copyright notice and this permission notice shall be included in all

copies or substantial portions of the Software.



THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR

IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER

LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,

OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE

SOFTWARE.



See more at https://thingpulse.com

*/



//dht11温湿度传感器头文件

#include "DHTesp.h"

#ifdef ESP32

#pragma message(THIS EXAMPLE IS FOR ESP8266 ONLY!)

#error Select ESP8266 board.

#endif

DHTesp dht;



#include <ESPWiFi.h>

#include <ESPHTTPClient.h>

#include <JsonListener.h>



// time

#include <time.h>                       // time() ctime()

#include <sys/time.h>                   // struct timeval

#include <coredecls.h>                  // settimeofday_cb()



#include "SH1106Wire.h"     //sh1106驱动芯片,头文件

#include "OLEDDisplayUi.h"

#include "Wire.h"

#include "OpenWeatherMapCurrent.h"

#include "OpenWeatherMapForecast.h"

#include "WeatherStationFonts.h"

#include "WeatherStationImages.h"





/***************************

 * Begin Settings

 **************************/



//时区设置

#define TZ              7       // (utc+) TZ in hours

#define DST_MN          60      // use 60mn for summer time in some countries



// Setup

const int UPDATE_INTERVAL_SECS = 20 * 60; // Update every 20 minutes



// Display Settings

const int I2C_DISPLAY_ADDRESS = 0x3c;



//OLED引脚定义

#if defined(ESP8266)

const int SDA_PIN = D1;

const int SDC_PIN = D2;

#else

const int SDA_PIN = D1; //D3;

const int SDC_PIN = D2; //D4;

#endif



// OpenWeatherMap Settings

// Sign up here to get an API key:

// https://docs.thingpulse.com/how-tos/openweathermap-key/

//建议大家自己申请一个API接口,如果都用我下面这个肯定会出现显示不正常的现象,因为免费的有读取频率限制

String OPEN_WEATHER_MAP_APP_ID = "798ef2d2c9d7e1a7ae2c5058e2ce03e0";

/*

Go to https://openweathermap.org/find?q= and search for a location. Go through the

result set and select the entry closest to the actual location you want to display 

data for. It'll be a URL like https://openweathermap.org/city/2657896. The number

at the end is what you assign to the constant below.

 */

 //城市编号

String OPEN_WEATHER_MAP_LOCATION_ID = "1804540";



// Pick a language code from this list:

// Arabic - ar, Bulgarian - bg, Catalan - ca, Czech - cz, German - de, Greek - el,

// English - en, Persian (Farsi) - fa, Finnish - fi, French - fr, Galician - gl,

// Croatian - hr, Hungarian - hu, Italian - it, Japanese - ja, Korean - kr,

// Latvian - la, Lithuanian - lt, Macedonian - mk, Dutch - nl, Polish - pl,

// Portuguese - pt, Romanian - ro, Russian - ru, Swedish - se, Slovak - sk,

// Slovenian - sl, Spanish - es, Turkish - tr, Ukrainian - ua, Vietnamese - vi,

// Chinese Simplified - zh_cn, Chinese Traditional - zh_tw.

String OPEN_WEATHER_MAP_LANGUAGE = "en";

const uint8_t MAX_FORECASTS = 4;



const boolean IS_METRIC = true;



// Adjust according to your language

const String WDAY_NAMES[] = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};

const String MONTH_NAMES[] = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};



/***************************

 * End Settings

 **************************/

 // Initialize the oled display for address 0x3c

 // sda-pin=14 and sdc-pin=12

 SH1106Wire     display(I2C_DISPLAY_ADDRESS, SDA_PIN, SDC_PIN);

 OLEDDisplayUi   ui( &display );



OpenWeatherMapCurrentData currentWeather;

OpenWeatherMapCurrent currentWeatherClient;



OpenWeatherMapForecastData forecasts[MAX_FORECASTS];

OpenWeatherMapForecast forecastClient;



#define TZ_MN           ((TZ)*60)

#define TZ_SEC          ((TZ)*3600)

#define DST_SEC         ((DST_MN)*60)

time_t now;



// flag changed in the ticker function every 10 minutes

bool readyForWeatherUpdate = false;



String lastUpdate = "--";



long timeSinceLastWUpdate = 0;



//declaring prototypes

void drawProgress(OLEDDisplay *display, int percentage, String label);

void updateData(OLEDDisplay *display);

void drawDateTime(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y); //界面1

void drawCurrentWeather(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y); //界面2

void drawForecast(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y); //界面3

void drawForecastDetails(OLEDDisplay *display, int x, int y, int dayIndex); //界面3

void drawHeaderOverlay(OLEDDisplay *display, OLEDDisplayUiState* state); //底部公共UI界面

void setReadyForWeatherUpdate(); //界面3

void drawCurrentHT(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y); //界面4

//微信配网

void configwifi( );

void smartConfig();



// Add frames

// this array keeps function pointers to all frames

// frames are the single views that slide from right to left

FrameCallback frames[] = { drawDateTime, drawCurrentWeather, drawForecast,drawCurrentHT };

int numberOfFrames = 4;  //ui界面个数



OverlayCallback overlays[] = { drawHeaderOverlay };

int numberOfOverlays = 1;





  float old_h  ;  //湿度中间变量

  float old_t  ;  //温度度中间变量

  int counter = 0;  //加载点计数



void setup() {

  Serial.begin(115200);

  Serial.println();

  Serial.println();

  pinMode(LED_BUILTIN, OUTPUT);

  //initialize dht11

  dht.setup(D5, DHTesp::DHT11);   //dht11引脚定义

  // initialize dispaly

  display.init();

  display.clear();

  display.display();



  //display.flipScreenVertically();

  display.setFont(ArialMT_Plain_10);      //设置字体大小

  display.setTextAlignment(TEXT_ALIGN_CENTER);    //设置字体中心点为标记点

  display.setContrast(255); 

  



//connect to wifi network

  smartConfig();    //微信配网

  delay(500);

  Serial.println("");

  Serial.println("WiFi connected");

//WIFI连接中显示界面

  int counter = 0;

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

    delay(500);

    Serial.print(".");

    display.clear();

    display.drawString(64, 10, "Connecting to WiFi");

    display.drawXbm(46, 30, 8, 8, counter % 3 == 0 ? activeSymbole : inactiveSymbole);

    display.drawXbm(60, 30, 8, 8, counter % 3 == 1 ? activeSymbole : inactiveSymbole);

    display.drawXbm(74, 30, 8, 8, counter % 3 == 2 ? activeSymbole : inactiveSymbole);

    display.display();



    counter++;

  }

  // Get time from network time service

  configTime(TZ_SEC, DST_SEC, "pool.ntp.org");



  ui.setTargetFPS(30);



  ui.setActiveSymbol(activeSymbole);

  ui.setInactiveSymbol(inactiveSymbole);



  // You can change this to

  // TOP, LEFT, BOTTOM, RIGHT

  //ui.setIndicatorPosition(TOP);

  ui.setIndicatorPosition(BOTTOM);       



  // Defines where the first frame is located in the bar.

  ui.setIndicatorDirection(LEFT_RIGHT);



  // You can change the transition that is used

  // SLIDE_LEFT, SLIDE_RIGHT, SLIDE_TOP, SLIDE_DOWN

  ui.setFrameAnimation(SLIDE_LEFT);    //界面滑动方向



  ui.setFrames(frames, numberOfFrames);



  ui.setOverlays(overlays, numberOfOverlays);



  // Inital UI takes care of initalising the display too.

  ui.init();



  Serial.println("");



  updateData(&display);



}



void loop() {

  



  if (millis() - timeSinceLastWUpdate > (1000L*UPDATE_INTERVAL_SECS)) {

    setReadyForWeatherUpdate();

    timeSinceLastWUpdate = millis();

  }



  if (readyForWeatherUpdate && ui.getUiState()->frameState == FIXED) {

    updateData(&display);

    

  }



  int remainingTimeBudget = ui.update();



  if (remainingTimeBudget > 0) {

    // You can do some work here

    // Don't do stuff if you are below your

    // time budget.

    

    delay(remainingTimeBudget);

  }

    



}



void drawProgress(OLEDDisplay *display, int percentage, String label) {

  display->clear();

  display->setTextAlignment(TEXT_ALIGN_CENTER);

  display->setFont(ArialMT_Plain_10);

  display->drawString(64, 10, label);

  display->drawProgressBar(2, 28, 124, 10, percentage);

  display->display();

}



void updateData(OLEDDisplay *display) {

  drawProgress(display, 10, "Updating time...");

  drawProgress(display, 30, "Updating weather...");

  currentWeatherClient.setMetric(IS_METRIC);

  currentWeatherClient.setLanguage(OPEN_WEATHER_MAP_LANGUAGE);

  currentWeatherClient.updateCurrentById(&currentWeather, OPEN_WEATHER_MAP_APP_ID, OPEN_WEATHER_MAP_LOCATION_ID);

  drawProgress(display, 50, "Updating forecasts...");

  forecastClient.setMetric(IS_METRIC);

  forecastClient.setLanguage(OPEN_WEATHER_MAP_LANGUAGE);

  uint8_t allowedHours[] = {12};

  forecastClient.setAllowedHours(allowedHours, sizeof(allowedHours));

  forecastClient.updateForecastsById(forecasts, OPEN_WEATHER_MAP_APP_ID, OPEN_WEATHER_MAP_LOCATION_ID, MAX_FORECASTS);



  readyForWeatherUpdate = false;

  drawProgress(display, 100, "Done...");

  delay(1000);

}







void drawDateTime(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {

  now = time(nullptr);

  struct tm* timeInfo;

  timeInfo = localtime(&now);

  char buff[16];





  display->setTextAlignment(TEXT_ALIGN_CENTER);

  display->setFont(ArialMT_Plain_10);

  String date = WDAY_NAMES[timeInfo->tm_wday];



  sprintf_P(buff, PSTR("%s, %04d/%02d/%02d"), WDAY_NAMES[timeInfo->tm_wday].c_str(),  timeInfo->tm_year + 1900, timeInfo->tm_mon+1,timeInfo->tm_mday);   // year /mouth /day

  display->drawString(64 + x, 5 + y, String(buff));

  display->setFont(ArialMT_Plain_24);



  sprintf_P(buff, PSTR("%02d:%02d:%02d"), timeInfo->tm_hour, timeInfo->tm_min, timeInfo->tm_sec);

  display->drawString(64 + x, 13 + y, String(buff));

  display->setTextAlignment(TEXT_ALIGN_LEFT);

}



void drawCurrentWeather(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {

  display->setFont(ArialMT_Plain_10);

  display->setTextAlignment(TEXT_ALIGN_CENTER);

  display->drawString(64 + x, 36 + y, currentWeather.description);                                             //weather description up 2



  display->setFont(ArialMT_Plain_24);

  display->setTextAlignment(TEXT_ALIGN_LEFT);

  String temp = String(currentWeather.temp, 1) + (IS_METRIC ? "°C" : "°F");

  display->drawString(55 + x, 5 + y, temp);



  display->setFont(Meteocons_Plain_36);

  display->setTextAlignment(TEXT_ALIGN_CENTER);

  display->drawString(33 + x, 0 + y, currentWeather.iconMeteoCon);

}





void drawForecast(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {

  drawForecastDetails(display, x, y, 0);

  drawForecastDetails(display, x + 44, y, 1);

  drawForecastDetails(display, x + 88, y, 2);

}



void drawForecastDetails(OLEDDisplay *display, int x, int y, int dayIndex) {

  time_t observationTimestamp = forecasts[dayIndex].observationTime;

  struct tm* timeInfo;

  timeInfo = localtime(&observationTimestamp);

  display->setTextAlignment(TEXT_ALIGN_CENTER);

  display->setFont(ArialMT_Plain_10);

  display->drawString(x + 20, y, WDAY_NAMES[timeInfo->tm_wday]);



  display->setFont(Meteocons_Plain_21);

  display->drawString(x + 20, y + 12, forecasts[dayIndex].iconMeteoCon);

  String temp = String(forecasts[dayIndex].temp, 0) + (IS_METRIC ? "°C" : "°F");

  display->setFont(ArialMT_Plain_10);

  display->drawString(x + 20, y + 34, temp);

  display->setTextAlignment(TEXT_ALIGN_LEFT);

  

 // delay(dht.getMinimumSamplingPeriod());

  float h = dht.getHumidity();

  float t = dht.getTemperature();;

  if (isnan(h) || isnan(t) ) {

    Serial.println("Failed to read from DHT sensor!");

    return;

  }

  else

  {

    Serial.println(h);

    Serial.println(t);

    old_h=h;

    old_t=t;

    }

}



void drawHeaderOverlay(OLEDDisplay *display, OLEDDisplayUiState* state) {

  now = time(nullptr);

  struct tm* timeInfo;

  timeInfo = localtime(&now);

  char buff[14];

  sprintf_P(buff, PSTR("%02d:%02d"), timeInfo->tm_hour, timeInfo->tm_min);



  display->setColor(WHITE);

  display->setFont(ArialMT_Plain_10);

  display->setTextAlignment(TEXT_ALIGN_LEFT);

  display->drawString(0, 52, String(buff));

  display->setTextAlignment(TEXT_ALIGN_RIGHT);

  String temp = String(currentWeather.temp, 1) + (IS_METRIC ? "°C" : "°F");

  display->drawString(128, 52, temp);                                                  //right down time UP 2

  display->drawHorizontalLine(0, 50, 128);                                            //line up 2

}



void setReadyForWeatherUpdate() {

  Serial.println("Setting readyForUpdate to true");

  readyForWeatherUpdate = true;

}

//由于在界面4获取DHT11的数据会产生显示不稳定的现象,所以DHT11数据收集放在界面3,提前收集好数据,界面4做显示的工作。也就是说,这个方案会有些缺陷,界面4无法实时显示温湿度变化。如果需要实时显示,按重置键到未配网界面。

void drawCurrentHT (OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y)

{

    

  display->setFont(ArialMT_Plain_16);

  display->setTextAlignment(TEXT_ALIGN_LEFT);

  display->drawString(10 + x, 0 + y,"Humt :");

  display->drawString(60 + x, 0 + y,String(old_h));

  display->drawString(100 + x, 0 + y, "%");

  

  display->drawString(10 + x, 25 + y,"Temp :");

  display->drawString(60 + x, 25 + y,String(old_t));

  display->drawString(100 + x, 25 + y, "°C");

  

  }

  void configwifi( )     //未联网显示界面

{

  

    display.clear();

    display.drawString(30, 50, "WiFi  Waiting");

    display.drawXbm(65,  53, 8, 8, counter % 6 == 0 ? activeSymbole : inactiveSymbole);

    display.drawXbm(75,  53, 8, 8, counter % 6 == 1 ? activeSymbole : inactiveSymbole);

    display.drawXbm(85,  53, 8, 8, counter % 6 == 2 ? activeSymbole : inactiveSymbole);

    display.drawXbm(95,  53, 8, 8, counter % 6 == 3 ? activeSymbole : inactiveSymbole);

    display.drawXbm(105, 53, 8, 8, counter % 6 == 4 ? activeSymbole : inactiveSymbole);

    display.drawXbm(115, 53, 8, 8, counter % 6 == 5 ? activeSymbole : inactiveSymbole);

    display.drawHorizontalLine(0, 50, 128);                               //画一条水平直线



    display.setFont(ArialMT_Plain_16);                                     //设置字体的大小

    display.setTextAlignment(TEXT_ALIGN_LEFT);                 //以字符的左上角为标记点

    display.drawString(10 , 0 ,"Humt :");

    display.drawString(60 , 0 ,String(old_h));

    display.drawString(100 , 0 , "%");

  

    display.drawString(10 , 25  ,"Temp :");                                 //前面的数字是x,y坐标,也就是上面标记点的坐标,后面的字符是显示的内容

    display.drawString(60 , 25  ,String(old_t));                          //将中间变量float转成字符型,并显示

    display.drawString(100 , 25 , "°C");



    display.setFont(ArialMT_Plain_10);

    display.setTextAlignment(TEXT_ALIGN_CENTER);

        

    display.display();      

    counter++;

   }

   

   void smartConfig()

{

  WiFi.mode(WIFI_STA);

  Serial.println("\r\nWait for Smartconfig...");

  WiFi.beginSmartConfig();

  while (1)

  {

    Serial.print(".");

    digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)

    delay(350);                                    // wait for a second

    digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW

    delay(350);     

  //    dht11 get data

    

    float h = dht.getHumidity();

    float t = dht.getTemperature();

    if (isnan(h) || isnan(t) ) {

    Serial.println("Failed to read from DHT sensor!");

    return;

  }

  else

  {

    Serial.println(h);

    Serial.println(t);

    old_h=h;

    old_t=t;

    }

       

    if (WiFi.smartConfigDone())

    { 

      Serial.println("SmartConfig Success");

      Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());

      Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());   

      break;

    }

    configwifi( );

  }

}
/*
作者:Jawa_D
https://www.bilibili.com/read/cv1773561
出处: bilibili
*/

这个项目到此就告一段落了,如果后续有时间会设计一个外壳,并用3D打印机打出来。

祝君成功!

紧急补充一下,我上传的资源中的源代码中DHT11使用的是下图中的库文件,没有解释清楚,非常抱歉!

在这里插入图片描述

  • 7
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 20
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值