• Уважаемые посетители сайта esp8266.ru!
    Мы отказались от размещения рекламы на страницах форума для большего комфорта пользователей.
    Вы можете оказать посильную поддержку администрации форума. Данные средства пойдут на оплату услуг облачных провайдеров для сайта esp8266.ru
  • Система автоматизации с открытым исходным кодом на базе esp8266/esp32 микроконтроллеров и приложения IoT Manager. Наша группа в Telegram

Помогите встроить курс валют, курс биткоина

BPOH

New member
ESP8266
экран SSD1306

Собрал из всяких разных исходников время и погоду, научился переключать экраны помогите пожалуйста встроить курс валют и курс биткоина

JavaScript:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h> // http web access library
#include <ESP8266WebServer.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include "eflogo.h"
#include <ArduinoJson.h>
#include <Fonts/FreeSerifBold18pt7b.h>
#include <Fonts/FreeSansBold12pt7b.h>

#include <Adafruit_SSD1306.h> // include Adafruit SSD1306 OLED display driver
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET LED_BUILTIN
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);



// =======================================================================
// Конфигурация устройства:
// =======================================================================
const char* ssid     = "wifi";                      // SSID
const char* password = "pass";                    // пароль
String weatherKey = "1f7fb68ca5d9a8dd3";  // Чтобы получить API ключь, перейдите по ссылке http://openweathermap.org/api
String weatherLang = "&lang=ru";
String cityID = "706524"; //Kerch

String Location = "Kerch";
String API_Key = "1f7fb68ccbehkd1b2d0a5d9a8dd3";
// =======================================================================

WiFiClient client;
// ======================== Погодные переменные
String weatherMain = "";
String weatherDescription = "";
String weatherLocation = "";
String country;
int humidity;
int pressure;
float temp;
float tempMin, tempMax;
int clouds;
float windSpeed;
String date;
String currencyRates;
String weatherString;


void setup()   {               


//    Serial.begin(115200);                           // Дебаг
    
// ======================== Соединение с WIFI
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);                         // Подключаемся к WIFI
  while (WiFi.status() != WL_CONNECTED) {         // Ждем до посинения
    delay(500);
//    Serial.print(".");
  }

 
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3D (for the 128x64)
  // init done
  Wire.setClock(400000); // set I2C clock to 400kHz
  display.clearDisplay(); // clear the display buffer

  display.setTextColor(WHITE, BLACK);
  display.setTextSize(1);
  display.setCursor(0, 0);
 
  display.drawBitmap(0, 0,  eflogo, 127, 64, WHITE);  // выводим изображение (X, Y, bmp, ширина, высота, цвет)
  display.display();
  delay(3000);     
  display.startscrolldiagright(0x00, 0x07);
  delay(2000);
  display.startscrolldiagleft(0x00, 0x07);
  delay(2000);
  display.stopscroll();
  delay(4000);
  display.clearDisplay();
}

// =========================== Переменные времени
#define MAX_DIGITS 16
byte dig[MAX_DIGITS]={0};
byte digold[MAX_DIGITS]={0};
byte digtrans[MAX_DIGITS]={0};
int updCnt = 0;
int dots = 0;
long dotTime = 0;
long clkTime = 0;
int dx=0;
int dy=0;
byte del=0;
int h,m,s;
// =======================================================================
void loop() {

if(updCnt<=0) { // каждые 10 циклов получаем данные времени
    updCnt = 10;
//    Serial.println("Getting data ...");
    getTime();
//    Serial.println("Data loaded");
    clkTime = millis();
  }

  if(millis()-clkTime > 10000 && !del && dots) { //каждые 15 секунд
    
    pogoda();
    updCnt--;
    clkTime = millis();
  }

 
  vremya();
  if(millis()-dotTime > 500) {
    dotTime = millis();
    dots = !dots;
  }


{
HTTPClient http; //Declare an object of class HTTPClient
// specify request destination
http.begin("http://api.openweathermap.org/data/2.5/weather?q=" + Location + "&APPID=" + API_Key); // !!
int httpCode = http.GET(); // send the request
if (httpCode > 0) // check the returning code
{
String payload = http.getString(); //Get the request response payload
DynamicJsonBuffer jsonBuffer(512);
// Parse JSON object
JsonObject& root = jsonBuffer.parseObject(payload);
if (!root.success()) {
Serial.println(F("Parsing failed!"));
return;
}
float temp = (float)(root["main"]["temp"]) - 273.15; // get temperature in °C
//int temp = root["main"]["temp"]; // get temperature in °C
int humidity = root["main"]["humidity"]; // get humidity in %
float pressure = (float)(root["main"]["pressure"]) / 1000; // get pressure in bar
float wind_speed = root["wind"]["speed"]; // get wind speed in m/s
int wind_degree = root["wind"]["deg"]; // get wind degree in °




}
http.end(); //Close connection
}



// =======================================================================
if (WiFi.status() == WL_CONNECTED) //Check WiFi connection status
{
HTTPClient http; //Declare an object of class HTTPClient
// specify request destination
http.begin("http://api.openweathermap.org/data/2.5/weather?q=" + Location + "&APPID=" + API_Key); // !!
int httpCode = http.GET(); // send the request
if (httpCode > 0) // check the returning code
{
String payload = http.getString(); //Get the request response payload
DynamicJsonBuffer jsonBuffer(512);
// Parse JSON object
JsonObject& root = jsonBuffer.parseObject(payload);
if (!root.success()) {
Serial.println(F("Parsing failed!"));
return;
}
float temp = (float)(root["main"]["temp"]) - 273.15; // get temperature in °C
//int temp = root["main"]["temp"]; // get temperature in °C
int humidity = root["main"]["humidity"]; // get humidity in %
float pressure = (float)(root["main"]["pressure"]) / 1000; // get pressure in bar
float wind_speed = root["wind"]["speed"]; // get wind speed in m/s
int wind_degree = root["wind"]["deg"]; // get wind degree in °
}
http.end(); //Close connection
}
delay(20000); // wait 1 minute
}
//========================================================================
 

BPOH

New member
JavaScript:
void pogoda(void) {

// =======================================================================

// Берем погоду с сайта openweathermap.org

// =======================================================================

{

if (WiFi.status() == WL_CONNECTED) //Check WiFi connection status

{

HTTPClient http; //Declare an object of class HTTPClient

// specify request destination

http.begin("http://api.openweathermap.org/data/2.5/weather?q=" + Location + "&APPID=" + API_Key); // !!

int httpCode = http.GET(); // send the request

if (httpCode > 0) // check the returning code

{

String payload = http.getString(); //Get the request response payload

DynamicJsonBuffer jsonBuffer(512);

// Parse JSON object

JsonObject& root = jsonBuffer.parseObject(payload);

if (!root.success()) {

Serial.println(F("Parsing failed!"));

return;

}

float temp = (float)(root["main"]["temp"]) - 273.15; // get temperature in °C

//int temp = root["main"]["temp"]; // get temperature in °C

int humidity = root["main"]["humidity"]; // get humidity in %

float pressure = (float)(root["main"]["pressure"]) / 1000; // get pressure in bar

float wind_speed = root["wind"]["speed"]; // get wind speed in m/s

int wind_degree = root["wind"]["deg"]; // get wind degree in °

// print data

display.clearDisplay();

display.setTextColor(WHITE, BLACK);

display.setTextSize(1);

display.setCursor(0, 0);



display.println(utf8rus("   [Погода в Керчи]"));

display.print(utf8rus(" Статус - подключено"));

display.display();


Serial.printf("Temperature = %.2f°C\r\n", temp);

Serial.printf("Humidity = %d %%\r\n", humidity);

Serial.printf("Pressure = %.3f bar\r\n", pressure);

Serial.printf("Wind speed = %.1f m/s\r\n", wind_speed);

Serial.printf("Wind degree = %d°\r\n\r\n", wind_degree);

display.setCursor(0, 24);

display.printf("Temperature: %5.2f C\r\n", temp);

//display.printf("Temperature: %d C\r\n", temp);

display.printf("Humidity : %d %%\r\n", humidity);

display.printf("Pressure : %.3fbar\r\n", pressure);

display.printf("Wind speed : %.1f m/s\r\n", wind_speed);

display.printf("Wind degree: %d", wind_degree);

display.drawRect(109, 24, 3, 3, WHITE); // put degree symbol ( ° )

display.drawRect(97, 56, 3, 3, WHITE);

display.display();

}

http.end(); //Close connection

}

delay(15000); // wait 1 minute

}

}


//========================================================================

void vremya(void) {

  updateTime();

  display.clearDisplay();

  display.setTextSize(1);

  display.setTextColor(WHITE);

  display.setCursor(0,0);

  display.println(utf8rus("   МОСКОВСКОЕ  ВРЕМЯ"));

  display.setFont(&FreeSerifBold18pt7b);

  display.setTextSize(1);

  display.setTextColor(WHITE);

  display.setCursor(5,45);

  display.println(String(h/10)+String(h%10)+":"+String(m/10)+String(m%10));

  display.setFont(&FreeSansBold12pt7b);

  display.setTextSize(1);

  display.setTextColor(WHITE);

  display.setCursor(95,45);

  display.println(String(s/10)+String(s%10));

  display.display();

  display.setFont();

}

//========================================================================

void testscrolltext(void) {

  display.setTextSize(2);

  display.setTextColor(WHITE);

  display.setCursor(10,0);

  display.clearDisplay();

  display.println("scroll");

  display.display();

  delay(1);

 

  display.startscrollright(0x00, 0x0F);

  delay(2000);

  display.stopscroll();

  delay(1000);

  display.startscrollleft(0x00, 0x0F);

  delay(2000);

  display.stopscroll();

  delay(1000);   

  display.startscrolldiagright(0x00, 0x07);

  delay(2000);

  display.startscrolldiagleft(0x00, 0x07);

  delay(2000);

  display.stopscroll();

}



// =======================================================================

// Берем время у GOOGLE

// =======================================================================


float utcOffset = 3; //поправка часового пояса

long localEpoc = 0;

long localMillisAtUpdate = 0;


void getTime()

{

  WiFiClient client;

  if (!client.connect("www.google.com", 80)) {

//    Serial.println("connection to google failed");

    return;

  }


  client.print(String("GET / HTTP/1.1\r\n") +

               String("Host: www.google.com\r\n") +

               String("Connection: close\r\n\r\n"));

  int repeatCounter = 0;

  while (!client.available() && repeatCounter < 10) {

    delay(500);

    //Serial.println(".");

    repeatCounter++;

  }


  String line;

  client.setNoDelay(false);

  while(client.connected() && client.available()) {

    line = client.readStringUntil('\n');

    line.toUpperCase();

    if (line.startsWith("DATE: ")) {

      date = "     "+line.substring(6, 22);

      h = line.substring(23, 25).toInt();

      m = line.substring(26, 28).toInt();

      s = line.substring(29, 31).toInt();

      localMillisAtUpdate = millis();

      localEpoc = (h * 60 * 60 + m * 60 + s);

    }

  }

  client.stop();

}


// =======================================================================r


void updateTime()

{

  long curEpoch = localEpoc + ((millis() - localMillisAtUpdate) / 1000);

  long epoch = ((int)round(curEpoch + 3600 * utcOffset + 86400)) % 86400;

  h = ((epoch  % 86400L) / 3600) % 24;

  m = (epoch % 3600) / 60;

  s = epoch % 60;

}


// ================================ Вывод Русских Букв

String utf8rus(String source)

{

  int i,k;

  String target;

  unsigned char n;

  char m[2] = { '0', '\0' };


  k = source.length(); i = 0;


  while (i < k) {

    n = source[i]; i++;


    if (n >= 0xC0) {

      switch (n) {

        case 0xD0: {

          n = source[i]; i++;

          if (n == 0x81) { n = 0xA8; break; }

          if (n >= 0x90 && n <= 0xBF) n = n + 0x30-1;

          break;

        }

        case 0xD1: {

          n = source[i]; i++;

          if (n == 0x91) { n = 0xB8; break; }

          if (n >= 0x80 && n <= 0x8F) n = n + 0x70-1;

          break;

        }

      }

    }

    m[0] = n; target = target + String(m);

  }

return target;

}
 
Сверху Снизу