Skocz do zawartości

Stacja pogodowa NodeMCU i Fujitsu VF60- pomóżcie znaleźć błąd


Kuba83

Pomocna odpowiedź

Witam!

Jestem 19 lat użytkownikiem Forum Elektrody i miałem kontakt z pewnym użytkownikiem, który zamieścił projekt stacji pogodowej online na ESP8266 i wyświetlaczu VFD Fujitsu VF60.

Chciałem to zrobić, ów kolega pomagał....niestety wtedy nie było gdzie kupić tych wyświetlaczy.

W tym roku kupiłem dwie sztuki po 40zł, chciałem nawiązać z nim kontakt ale mu się zmarło w lutym choć był dwa lata młodszy ode mnie.

Jako, że człowiek ten nie żyje a był to projekt amatorski, pozwolę sobie zapytać, co robię źle.

To jest kod programu


#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <JsonListener.h>
#include <TimeLib.h>
#include <Timezone.h>
#include <WiFiUdp.h>>
#include "OpenWeatherMapForecast.h"
#include "OpenWeatherMapCurrent.h"
#include <WiFiManager.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>



int menu = 0;

// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
    
// initiate the client
OpenWeatherMapCurrent clientCurrent;
OpenWeatherMapForecast clientForecast;

// See https://docs.thingpulse.com/how-tos/openweathermap-key/
char owm_token[34] = "twoj kod owm";
String OPEN_WEATHER_MAP_APP_ID = "twoj kod owm";
//
char owm_location_id[34] = "3097405";  //twoja lokalizacja
String OPEN_WEATHER_MAP_LOCATION_ID = "3097405"; //"3083829"; - for Szczecin
//String OPEN_WEATHER_MAP_LOCATION = "";

String OPEN_WEATHER_MAP_LANGUAGE = "pl";
boolean IS_METRIC = true;
uint8_t MAX_FORECASTS = 14;

// Auxiliar variables to store the current output state
String output5State = "off";
String output4State = "off";

// Assign output variables to GPIO pins
const int output5 = 5;
const int output4 = 4;

// WiFi Settings
const char* ESP_HOST_NAME = "esp-" + ESP.getFlashChipId();
const char* WIFI_SSID     = "twoja siec";
const char* WIFI_PASSWORD = "hasło sieci";

// initiate the WifiClient
WiFiClient wifiClient;
WiFiManager wifiManager;

// TIME:
static const char ntpServerName[] = "time.nist.gov";
const int timeZone = 0;     // Central European Time //=0 because use TimeZone lib
WiFiUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets
time_t getNtpTime();
void digitalClockDisplay();
void printDigits(int digits);
void sendNTPpacket(IPAddress &address);
TimeChangeRule myDST = {"EDT", Last, Sun, Mar, 2, 120};    // Daylight time = UTC - 4 hours
TimeChangeRule mySTD = {"EST", Last, Sun, Nov, 2, 60};     // Standard time = UTC - 5 hours
Timezone myTZ(myDST, mySTD);
TimeChangeRule *tcr;
time_t prevDisplay = 0; // when the digital clock was displayed
time_t utc;
time_t local;

String stringHour, stringMinute, stringSecond, stringTime = "10:10", stringDate = "2020-05-05", stringWeek = "00";
String info_1 = "Information line 1",info_11 = "Information line 1", info_2 = "Information line 2";
String info_3 = "Information line 3", info_4 = "Information line 4", info_5 = "Information line 5";
short DN;   //Returns the number of day in the year
short WN;   //Returns the number of the week in the year

float CurrentTemp = 0;
unsigned int last_minute;
bool CheckedWeatherData = true;

int myInfo = 0;
const int max_FORECASTS=16;
String forecastCharPic[max_FORECASTS];
float  forecastTemp[max_FORECASTS];
float  forecastFeelsLike[max_FORECASTS];
String forecastHour[max_FORECASTS];
String forecastPic[max_FORECASTS];
String forecastTime[max_FORECASTS];
float  forecastMaxTemp[max_FORECASTS];
float  forecastMinTemp[max_FORECASTS];
float  forecastPressure[max_FORECASTS];
int  forecastPressureSeaLevel[max_FORECASTS];
int  forecastPressureGroundLevel[max_FORECASTS];
int  forecastHumidity[max_FORECASTS];
double  forecastWeatherId[max_FORECASTS];
String  forecastMain[max_FORECASTS];
String  forecastDescription[max_FORECASTS];
String  forecastIcon[max_FORECASTS];
String  forecastIconMeteoCon[max_FORECASTS];
int  forecastClouds[max_FORECASTS];
float  forecastWindSpeed[max_FORECASTS];
float  forecastWindDeg[max_FORECASTS];
float  forecastRain[max_FORECASTS];
String  forecastObservationTimeText[max_FORECASTS];

long Timer1 = 0, Timer2 = 0;

// ########## SETUP ########

void setup() {
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(200);
  
  // Initialize the output variables as outputs
  pinMode(output5, OUTPUT);
  pinMode(output4, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output5, LOW);
  digitalWrite(output4, LOW);
  
  Serial.begin(9600);

  WiFiManagerParameter owm_key("key", "TOKEN", owm_token, 32);
  WiFiManagerParameter owm_id("id", "LOCATION ID", owm_location_id, 32);
  WiFiManagerParameter custom_text1("<p>Please provide data:</p>");
  wifiManager.addParameter(&custom_text1);

  wifiManager.addParameter(&owm_key);
  wifiManager.addParameter(&owm_id);

  //reset saved settings
  //
  
  
  wifiManager.resetSettings();
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.println("Proba polaczenia");
  delay(6000);
  
  if (WiFi.status() != WL_CONNECTED) {    
    Serial.println("AP: Stacja pogody");    
    delay(500);     
    wifiManager.autoConnect("Stacja pogody");       
  }  
  VFDclear();
  VFDsetCursor(1);
  Serial.println("Polaczono");
  VFDsetCursor(21);
  Serial.print(WiFi.localIP());
  delay(3000);     
  OPEN_WEATHER_MAP_APP_ID = (String)owm_key.getValue();
  OPEN_WEATHER_MAP_LOCATION_ID = (String)owm_id.getValue(); 
  server.begin();   
  //time:
  Udp.begin(localPort);
  setSyncProvider(getNtpTime);
  setSyncInterval(30);
  utc = now();
  local = myTZ.toLocal(utc, &tcr);
  DayWeekNumber(year(local), month(local), day(local), weekday(local));
  // get first weather and forecast:
  getWeather();
  drawScreen();
}

// ########## MAIN LOOP  ########

void loop() {
  if (millis() - Timer1 > 3000 ) { //10minutes
    Timer1 = millis();

    drawScreen();
    menu=menu+1;
    if(menu>((MAX_FORECASTS/2)+2)){
      getWeather();
      CheckedWeatherData = true;
      DayWeekNumber(year(local), month(local), day(local), weekday(local));
      menu = 0;
    }    
  }

  if (last_minute != minute() || CheckedWeatherData) {
    local = myTZ.toLocal(now(), &tcr);
    date_to_string();
    time_to_string();
    last_minute = minute();    
    CheckedWeatherData = false;
  }
  
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    //Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        //Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // turns the GPIOs on and off
            if (header.indexOf("GET /5/on") >= 0) {
              //Serial.println("GPIO 5 on");
              output5State = "on";
              digitalWrite(output5, HIGH);
            } else if (header.indexOf("GET /5/off") >= 0) {
              //Serial.println("GPIO 5 off");
              output5State = "off";
              digitalWrite(output5, LOW);
            } else if (header.indexOf("GET /4/on") >= 0) {
              //Serial.println("GPIO 4 on");
              output4State = "on";
              digitalWrite(output4, HIGH);
            } else if (header.indexOf("GET /4/off") >= 0) {
              //Serial.println("GPIO 4 off");
              output4State = "off";
              digitalWrite(output4, LOW);
            }
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");
            
            // Web Page Heading
            client.println("<head>");
            client.println("<title>STACJA POGODY</title>");
            client.println("</head>");
            client.println("<body><h1>STACJA POGODY - ESP8266</h1>");
            client.println("<body><h1>                  </h1>");
            client.println("<body><h2>   " + stringTime + " Dzień: " + DayOfWeek()+ "  " + stringDate + " Tydzień: " + stringWeek + "</h2>");
            client.println("<body><h2> " + info_11 + "  " + info_2 + " </h2>");
            client.println("<body><h2> " + info_3 + "  " + info_4 + "  " + info_5 + " </h2>");
            client.println("<body><h1>                  </h1>");


            client.println("<style> td { border: 1px solid black; } </style>");
            client.println("<table>");
            client.println("<tr>");
            client.println("<td><b>Godz.</b></td> <td><b> Temp. [°C] </b></td>   <td><b> Temp. odczuwalna [°C] </b></td>  <td><b> Temp. min [°C] </b></td>   <td><b> Temp. max [°C]</b></td>   <td><b>  Pogoda  </b></td><td><b>Ciśnienie wzgl. [hPa]</b></td>  <td><b>Ciśnienie bezwzgl. [hPa]</b></td>   <td><b>Wilgotność  [%]</b></td>   <td><b>Zachmu rzenie [%]</b></td>  <td><b>Prędkość wiatru  [m/s]</b></td> <td><b>Kierunek wiatru  [m/s]</b></td> <td><b>Opady [mm/h]</b></td> <td><b>Opis</b></td> <td><b>Char Pic</b></td>   <td><b>Czas</b></td>   <td><b>weather Id</b></td>   <td><b>main</b></td>  <td><b>icon</b></td>  <td><b>icon Meteo Con</b></td>  ");
            client.println("</tr>");
            for (int i = 0; i < MAX_FORECASTS; i++) { 
              client.println("<tr>");
              client.println("<td><i>" + forecastHour[i] + "</i></td> <td><i>" + roundAndString(forecastTemp[i]) + "</i></td> <td><i>" + roundAndString(forecastFeelsLike[i]) + "</i></td> <td><i>" + roundAndString(forecastMinTemp[i]) + "</i></td>  <td><i>" + roundAndString(forecastMaxTemp[i]) + "</i></td>  <td><i>" + forecastPic[i] + "</i></td><td><i>"+forecastPressureSeaLevel[i]+"</i></td>  <td><i>"+forecastPressureGroundLevel[i]+"</i></td>  <td><i>"+forecastHumidity[i]+"</i></td>  <td><i>"+forecastClouds[i]+"</i></td>  <td><i>"+forecastWindSpeed[i]+"</i></td> <td><i>"+forecastWindDeg[i]+"</i></td> <td><i>"+forecastRain[i]+"</i></td>  <td><i>"+forecastDescription[i]+"</i></td>  <td><i>"+forecastCharPic[i]+"</i></td> <td><i>"+forecastObservationTimeText[i]+"</i></td> <td><i>"+forecastWeatherId[i]+"</i></td>  <td><i>"+forecastMain[i]+"</i></td>  <td><i>"+forecastIcon[i]+"</i></td>  <td><i>"+forecastIconMeteoCon[i]+"</i></td>");
              client.println("</tr>");
            }
            client.println("</table>");
            //<td><b>pressureSeaLevel</b></td>  <td><b>pressureGroundLevel</b></td>   <td><b>humidity</b></td>  <td><b>weatherId</b></td>   <td><b>main</b></td>  <td><b>description</b></td>   <td><b>icon</b></td>  <td><b>iconMeteoCon</b></td>  <td><b>clouds</b></td>  <td><b>windSpeed</b></td>  <td><b>rain</b></td>  <td><b>observationTimeText</b></td>       
            //<td><i>"+forecastPressureSeaLevel[i]+"</i></td>  <td><i>"+forecastPressureGroundLevel[i]+"</i></td>  <td><i>"+forecastHumidity[i]+"</i></td>  <td><i>"+forecastWeatherId[i]+"</i></td>  <td><i>"+forecastMain[i]+"</i></td>  <td><i>"+forecastDescription[i]+"</i></td>  <td><i>"+forecastIcon[i]+"</i></td>  <td><i>"+forecastIconMeteoCon[i]+"</i></td>  <td><i>"+forecastClouds[i]+"</i></td>  <td><i>"+forecastWindSpeed[i]+"</i></td>  <td><i>"+forecastRain[i]+"</i></td>  <td><i>"+forecastObservationTimeText[i]+"</i></td>
  
            // Display current state, and ON/OFF buttons for GPIO 5  
            client.println("<p>GPIO 5 - State " + output5State + "</p>");
            // If the output5State is off, it displays the ON button       
            if (output5State=="off") {
              client.println("<p><a href=\"/5/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/5/off\"><button class=\"button button2\">OFF</button></a></p>");
            } 
               
            // Display current state, and ON/OFF buttons for GPIO 4  
            client.println("<p>GPIO 4 - State " + output4State + "</p>");
            // If the output4State is off, it displays the ON button       
            if (output4State=="off") {
              client.println("<p><a href=\"/4/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    //Serial.println("Client disconnected.");
    //Serial.println("");
  }
}
// #### END OF MAIN LOOP  ########

void drawScreen(void) {
 
  switch (menu)
  {    
    case 0:
      VFDclear();
      VFDsetCursor(1); // 1st line
      Serial.print(("  " + stringTime + "  " + DayOfWeek()).c_str());
      VFDsetCursor(21); // date
      Serial.print((" " + stringDate + " tydz:" + stringWeek).c_str());
      break;
    case 1:    
      break;
    case 2:
      VFDclear();
      VFDsetCursor(1);  // pierwsza ramka informacyjna
      Serial.print(info_1.c_str() );
      VFDsetCursor(21);
      Serial.print(info_2.c_str() ); 
      break;
    case 3:
      VFDclear();
      VFDsetCursor(1);
      Serial.print(info_3.c_str() );
      VFDsetCursor(21);
      Serial.print((forecastHour[0] + "  " + roundAndString(forecastTemp[0]) + char(176) + "C  " + forecastPic[0]).c_str());      
      break;
    default:
      VFDclear();
      VFDsetCursor(1);
      Serial.print((forecastHour[(menu-3)*2-1] ).c_str());
      VFDsetCursor(5);
      Serial.print((roundAndString(forecastTemp[(menu-3)*2-1]) + char(176) + "C  " + forecastPic[(menu-3)*2-1] ).c_str());
      VFDsetCursor(21);
      Serial.print((forecastHour[(menu-3)*2]).c_str());
      VFDsetCursor(25);
      Serial.print((roundAndString(forecastTemp[(menu-3)*2]) + char(176) + "C  " + forecastPic[(menu-3)*2]).c_str());
      break;    
   }
}

void getWeather(void) {
  time_t time;
  // GET CURRENT WEATHER
  OpenWeatherMapCurrentData data;
  clientCurrent.setLanguage(OPEN_WEATHER_MAP_LANGUAGE);
  clientCurrent.setMetric(IS_METRIC);
  clientCurrent.updateCurrentById(&data, OPEN_WEATHER_MAP_APP_ID, OPEN_WEATHER_MAP_LOCATION_ID);

  CurrentTemp = data.temp;
  info_1 = "  " + roundAndString(data.temp) + char(176) + "C   " + roundAndString(data.windSpeed) + "m/s" ;
  info_11 = roundAndString(data.temp) +  "°C   " + roundAndString(data.windSpeed) + "m/s" ;
  info_2 = "H:" + (String)data.humidity + "%   P:" + (String)data.pressure + "hPa";
  info_3 = data.description;
  info_4 = data.cityName;
  info_5 = "Widoczność:" + (String)(data.visibility/1000) + "km   Kier. wiatru:" + (String)data.windDeg + "st  ";
  
    // GET FORECAST
  OpenWeatherMapForecastData dataForecast[MAX_FORECASTS];
  clientForecast.setMetric(IS_METRIC);
  clientForecast.setLanguage(OPEN_WEATHER_MAP_LANGUAGE);
  //uint8_t allowedHours[] = {0,12};                     // If You want use only specifig hours in forecast
  //clientForecast.setAllowedHours(allowedHours, 2);
  uint8_t foundForecasts = clientForecast.updateForecastsById(dataForecast, OPEN_WEATHER_MAP_APP_ID, OPEN_WEATHER_MAP_LOCATION_ID, MAX_FORECASTS);

  for (uint8_t i = 0; i < foundForecasts; i++) {                  // start FOR
    //    Forecast number:  i;
    time = dataForecast[i].observationTime;
    forecastHour[i] = hour( myTZ.toLocal(time, &tcr) ); //konwersja do czasu lokalnego
    //    Serial.printf("observationTime: %d, full date: %s", dataForecast[i].observationTime, ctime(&time));
    //    Serial.printf("temp: %f\n", dataForecast[i].temp);
    forecastTemp[i] = dataForecast[i].temp;
    forecastMaxTemp[i] = dataForecast[i].tempMax;
    forecastMinTemp[i] = dataForecast[i].tempMin;
    forecastPressure[i] = dataForecast[i].pressure;
    forecastPressureSeaLevel[i] = dataForecast[i].pressureSeaLevel;
    forecastPressureGroundLevel[i] = dataForecast[i].pressureGroundLevel;
    forecastHumidity[i] = dataForecast[i].humidity;
    forecastWeatherId[i] = dataForecast[i].weatherId;
    forecastMain[i] = dataForecast[i].main;
    forecastDescription[i] = dataForecast[i].description;
    forecastIcon[i] = dataForecast[i].icon;
    forecastIconMeteoCon[i] = dataForecast[i].iconMeteoCon;
    forecastClouds[i] = dataForecast[i].clouds;
    forecastWindSpeed[i] = dataForecast[i].windSpeed;
    forecastRain[i] = dataForecast[i].rain;
    forecastObservationTimeText[i] = dataForecast[i].observationTimeText;
    forecastFeelsLike[i] = dataForecast[i].feelsLike;
    forecastWindDeg[i] = dataForecast[i].windDeg;
    
    //    Serial.printf("tempMin: %f\n", dataForecast[i].tempMin);
    //    Serial.printf("tempMax: %f\n", dataForecast[i].tempMax);
    //    Serial.printf("pressure: %f\n", dataForecast[i].pressure);
    //    Serial.printf("pressureSeaLevel: %f\n", dataForecast[i].pressureSeaLevel);
    //    Serial.printf("pressureGroundLevel: %f\n", dataForecast[i].pressureGroundLevel);
    //    Serial.printf("humidity: %d\n", dataForecast[i].humidity);
    //    Serial.printf("weatherId: %d\n", dataForecast[i].weatherId);
    //    Serial.printf("main: %s\n", dataForecast[i].main.c_str());
    //    Serial.printf("description: %s\n", dataForecast[i].description.c_str());
    //forecastPic[i] = dataForecast[i].main;
    if( dataForecast[i].main == "Clear" ) forecastPic[i] = "slonce";   //"☀☁☂❄"
    else if( dataForecast[i].main == "Clouds" ) forecastPic[i] = "chmury";
    else if( dataForecast[i].main == "Rain" ) forecastPic[i] = "deszcz";
    else if( dataForecast[i].main == "Snow" ) forecastPic[i] = "snieg";
    else forecastPic[i] = "brak info";
    
    if( dataForecast[i].main == "Clear" ) forecastCharPic[i] = "☀";   //"☀☁☂❄"
    else if( dataForecast[i].main == "Clouds" ) forecastCharPic[i] = "☁";
    else if( dataForecast[i].main == "Rain" ) forecastCharPic[i] = "";
    else if( dataForecast[i].main == "Snow" ) forecastCharPic[i] = "❄";
    else forecastCharPic[i] = "☍";
    

    

    //    Serial.printf("icon: %s\n", dataForecast[i].icon.c_str());
    //    Serial.printf("iconMeteoCon: %s\n", dataForecast[i].iconMeteoCon.c_str());
    //    Serial.printf("clouds: %d\n", dataForecast[i].clouds);
    //    Serial.printf("windSpeed: %f\n", dataForecast[i].windSpeed);
    //    Serial.printf("rain: %f\n", dataForecast[i].rain);
    //    Serial.printf("observationTimeText: %s\n", dataForecast[i].observationTimeText.c_str());
  }
}

String roundAndString(float input) {
  input = round(input * 10) / 10;
  String output = (String)(input);
  output.remove(output.length() - 1, 1);
  return output;
}

String roundAndString2(float input) {
  input = round(input * 10) / 10;
  input = round(input);
  String output = (String)(input);
  output.remove(output.length() - 3, 3);
  return output;
}

/*-------- 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()
{
  myInfo++;
  IPAddress ntpServerIP; // NTP server's ip address
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  // get a random server from the pool
  WiFi.hostByName(ntpServerName, 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;
    }
  }
  return 0; // return 0 if unable to get the time //Serial.println("No NTP Response :-(");
}

// 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();
}

void time_to_string()
{
  stringHour   = "";  stringMinute = "";  stringSecond = "";  stringTime   = "";
  // adding 0 if number if less than 0
  if (hour(local) < 10) {
    stringHour =  stringHour + "0" + hour(local);
  }
  else stringHour =  stringHour + hour(local);

  if (minute(local) < 10) {
    stringMinute =  stringMinute + "0" + minute(local);
  }
  else stringMinute =  stringMinute + minute(local);

  /*
    if (second(local) < 10) {
    stringSecond =  stringSecond + "0" + second(local);
    }
    else stringSecond =  stringSecond + second(local);
  */
  // time as a one string
  stringTime = stringHour + ":" + stringMinute;// + ":" + stringSecond;
}

void date_to_string()
{
  String stringYear = "", stringMonth = "", stringDay = "";  stringYear = year(local);

  if (month(local) < 10) {
    stringMonth =  stringMonth + "0" + month(local);
  }
  else stringMonth = month(local);

  if (day(local) < 10) {
    stringDay =  stringDay + "0" + day(local);
  }
  else stringDay = day(local);

  // date as a one string
  stringDate = stringDay + "-" + stringMonth + "-" + stringYear;
}

String DayOfWeek(void) {
  switch ( weekday(local) ) { // day of the week (1-7), Sunday is day 1
    case 2:
      return "Poniedz.";
    case 3:
      return "Wtorek";
    case 4:
      return "Sroda";
    case 5:
      return "Czwartek";
    case 6:
      return "Piatek";
    case 7:
      return "Sobota";
    case 1:
      return "Niedziela";
  }
}

void DayWeekNumber(unsigned int y, unsigned int m, unsigned int d, unsigned int w) {
  int days[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; // Number of days at the beginning of the month in a not leap year.
  stringWeek = "";
  //Start to calculate the number of day
  if (m == 1 || m == 2) {
    DN = days[(m - 1)] + d;                 //for any type of year, it calculate the number of days for January or february
  }                        // Now, try to calculate for the other months
  else if ((y % 4 == 0 && y % 100 != 0) ||  y % 400 == 0) { //those are the conditions to have a leap year
    DN = days[(m - 1)] + d + 1; // if leap year, calculate in the same way but increasing one day
  }
  else {                                //if not a leap year, calculate in the normal way, such as January or February
    DN = days[(m - 1)] + d;
  }
  // Now start to calculate Week number
  if (w == 0) {
    WN = (DN - 7 + 10) / 7;       //if it is sunday (time library returns 0)
  }
  else {
    WN = (DN - w + 10) / 7;  // for the other days of week
  }
  stringWeek = WN;
}

void VFDreset()
{
  Serial.write(0x1B);
  Serial.write(0x5B);
  Serial.write(0x30);
  Serial.write(0x6D);
  VFDcountry();
}

void VFDclear()
{
  Serial.println("");
  Serial.write(0x1B);
  Serial.write(0x5B);
  Serial.write(0x32);
  Serial.write(0x4A);
  Serial.write(0x0D);
}

void VFDdel2end()
{
  Serial.write(0x1B);
  Serial.write(0x5B);
  Serial.write(0x30);
  Serial.write(0x4B);
}

void VFDcountry()
{
  Serial.write(0x1B);
  Serial.write(0x52);
  Serial.write(0x0D);
}

void VFDdimmer(int amount)
{
  Serial.write(0x1B);
  Serial.write(0x5C);
  Serial.write(0x3F);
  Serial.write(0x4C);
  Serial.write(0x44);
  switch (amount)
  {
    case 0:
      Serial.write(0x30); // 0% Dimmer
      break;
    case 20:
      Serial.write(0x31); // 20% Dimmer
      break;
    case 40:
      Serial.write(0x32); // 40% Dimmer
      break;
    case 60:
      Serial.write(0x33); // 60% Dimmer
      break;
    case 80:
      Serial.write(0x34); // 80% Dimmer
      break;
    case 100:
      Serial.write(0x35); // 100% Dimmer
  }
}

void VFDchars()
{
  for (int i = 21; i < 256; i++)
  {
    Serial.write(i);
    delay(30);
  }
}



void VFDbackspace()
{
  Serial.write(0x08);
}

void VFDhorizontaltab()
{
  Serial.write(0x09);
}

void VFDcursormode(int amount)
{
  Serial.write(0x1B);
  Serial.write(0x5C);
  Serial.write(0x3F);
  Serial.write(0x4C);
  Serial.write(0x43);
  switch (amount)
  {
    case 0:
      Serial.write(0x30); // cursor off
      break;
    case 1:
      Serial.write(0x31); // cursor blink
      break;
    case 2:
      Serial.write(0x32); // cursor on
  }
}

void VFDdisplayattribte(int amount)
{
  Serial.write(0x1B);
  switch (amount)
  {
    case 0:
      Serial.write(0x5B); // blink
      Serial.write(0x35);
      Serial.write(0x6D);
      break;
    case 1:
      Serial.write(0x5B); // reverse
      Serial.write(0x37);
      Serial.write(0x6D);
      break;
    case 2:
      Serial.write(0x5B); // blink/reverse reset
      Serial.write(0x30);
      Serial.write(0x6D);
      break;
    case 3:
      Serial.write(0x23); // Horizontal Double Set
      Serial.write(0x36);
      break;
    case 4:
      Serial.write(0x23); // Horizontal Double ReSet
      Serial.write(0x35);
  }
}

void VFDsetCursor(byte position)
{
  Serial.write(0x1B);
  Serial.write(0x5B);
  if (position < 21) {
    Serial.write(0x31);
  }
  else {
    Serial.write(0x32);
  }
  Serial.write(0x3B);
  if (position < 21) {
    Serial.write(0x30 + position);
  }
  else {
    Serial.write(0x30 + position - 20);
  }
  Serial.write(0x48);
}

void VFDscroll(int amount)
{
  /*Serial.write(0x1B);
    Serial.write(0x5C);
    Serial.write(0x3F);
    Serial.write(0x4C);
    Serial.write(0x48);
    Serial.write(0x36);  //Pm   6
    Serial.write(0x3B);
    Serial.write(0x31);  // Pl  1
    Serial.write(0x3B);
    Serial.write(0x32);  //Pt scrolll speed  31h / 32H 10/20ms
    Serial.write(0x3B);
    Serial.write(0x31);   ///Pn
    Serial.write(0x3B);
    Serial.write(0x31); //Pd  1
  */
  Serial.write(0x1B);
  Serial.write(0x5C);
  Serial.write(0x3F);
  Serial.write(0x4C);
  Serial.write(0x4D);
  Serial.write(0x53);
}

void VFDall()
{
  Serial.write(0x0F);
}

Oczywiście konto OpenWeather założyłem dla Grudziądza, choć u mnie  za Wisłą klimat raczej do Tczewa podobny ale pal licho lokalizację....

// TIME:
static const char ntpServerName[] = "time.nist.gov";
const int timeZone = 0;     // Central European Time //=0 because use TimeZone lib
WiFiUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets
time_t getNtpTime();
void digitalClockDisplay();
void printDigits(int digits);
void sendNTPpacket(IPAddress &address);
TimeChangeRule myDST = {"EDT", Last, Sun, Mar, 2, 120};    // Daylight time = UTC - 4 hours
TimeChangeRule mySTD = {"EST", Last, Sun, Nov, 2, 60};     // Standard time = UTC - 5 hours
Timezone myTZ(myDST, mySTD);
TimeChangeRule *tcr;
time_t prevDisplay = 0; // when the digital clock was displayed
time_t utc;
time_t local;

String stringHour, stringMinute, stringSecond, stringTime = "10:10", stringDate = "2020-05-05", stringWeek = "00";
String info_1 = "Information line 1",info_11 = "Information line 1", info_2 = "Information line 2";
String info_3 = "Information line 3", info_4 = "Information line 4", info_5 = "Information line 5";
short DN;   //Returns the number of day in the year
short WN;   //Returns the number of the week in the year

float CurrentTemp = 0;
unsigned int last_minute;
bool CheckedWeatherData = true;

int myInfo = 0;
const int max_FORECASTS=16;
String forecastCharPic[max_FORECASTS];
float  forecastTemp[max_FORECASTS];
float  forecastFeelsLike[max_FORECASTS];
String forecastHour[max_FORECASTS];
String forecastPic[max_FORECASTS];
String forecastTime[max_FORECASTS];
float  forecastMaxTemp[max_FORECASTS];
float  forecastMinTemp[max_FORECASTS];
float  forecastPressure[max_FORECASTS];
int  forecastPressureSeaLevel[max_FORECASTS];
int  forecastPressureGroundLevel[max_FORECASTS];
int  forecastHumidity[max_FORECASTS];
double  forecastWeatherId[max_FORECASTS];
String  forecastMain[max_FORECASTS];
String  forecastDescription[max_FORECASTS];
String  forecastIcon[max_FORECASTS];
String  forecastIconMeteoCon[max_FORECASTS];
int  forecastClouds[max_FORECASTS];
float  forecastWindSpeed[max_FORECASTS];
float  forecastWindDeg[max_FORECASTS];
float  forecastRain[max_FORECASTS];
String  forecastObservationTimeText[max_FORECASTS];

long Timer1 = 0, Timer2 = 0;

Układ po kombinowaniu z bibliotekami i podaniu "swoich" danych, w tym Wi-Fi, ruszył, pokazuje pogodę, wyświetla adres IP ale nie mam synchronizacji czasu, jest cały czas 2020-05-05, nie mam synchronizacji z serwerem NTP.

Nie mogę znaleźć wszystkich bibliotek, ostatnio pogoda mi tak dowaliła, że do niczego się nie nadaję, nawet za swoje lampowe złomy się nie mogę zabrać.

Jakby mi ktoś z tym kodem pomógł....nie wychowałem się w epoce komputerów jak większość użytkowników Forum Forbot, komputer posiadam dopiero 19 lat a MCU bawię się dopiero 2 lata i raczej poprawiam czyjeś spaprane projekty niż własne piszę.

Niestety tu ugrzązłem niczym ruski czołg w błocie....nie mogę znaleźć bibliotek dla ESP8266, które odpowiadają za NTP, do "zwykłego" Arduino są i Arduino IDE mnie o tym informuje, że nie są zgodne biblioteki

Chciałbym ten układ uruchomić, bo jest fajny a moje wyświetlacze są jak nowe, świecą piękną zielenią.

Lubię bardzo VFD, to lata 90-te czyli moje dzieciństwo, wówczas każdy sprzęt RTV miał taki wyświetlacz a nawet miały go zegary w kuchenkach i mikrofalówkach.

Czy mógłby ktoś pomóc?

Link do komentarza
Share on other sites

- tez robię stację pogodową ale na ePapierze, 4.2" oraz 2.9", robiłem na esp8266 ale znalazłem esp32 Lolin32 z ładowarką do LiPo i się przesiadłem na Lolin32.

- poniżej urywki z mego programu dla podprogramu Time, tez trochę z tym walczyłem.


const char server[] = "api.openweathermap.org";
	//http://api.openweathermap.org/data/2.5/weather?q=Melksham,UK&APPID=your_OWM_API_key&mode=json&units=metric&cnt=1
	//Set your location according to OWM locations
String City             = "WROCLAW";                      // Your home city See: http://bulk.openweathermap.org/sample/
String Country          = "PL";                            // Your _ISO-3166-1_two-letter_country_code country code
                                                           // https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes
String Language         = "PL";                            // NOTE: Only the weather description is translated by OWM
                                                           // Examples: Arabic (AR) Czech (CZ) English (EN) Greek (EL) 
                                                           // Korean (KR) Latvian (LA) Lithuanian (LT) Macedonian (MK)
String Hemisphere       = "north";                         // or "south"  
String Units            = "M";                             // Use 'M' for Metric or I for Imperial 
const char* Timezone    = "CET-1CEST,M3.5.0/02,M10.5.0/3"; // Warsaw PL
								// https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv 
                                                           // See below for examples
const char* ntpServer   = "pl.pool.ntp.org";               // Or, choose a time server close to you, available servers
const char* ntpServer1  = "pool.ntp.org";

// ----------------- setup -----------------------------
	// Time
#include <sys/time.h>
//	RTC_DATA_ATTR time_t now;
//	RTC_DATA_ATTR struct tm * timeinfo;
// ------------------------- Globals -----------------------------
time_t now;    											// this is the epoch
tm tm;         											// the structure tm holds time information in a more convient way		
			
			
	// ----------------------------
void SetupTime() {
				
	#ifdef ARDUINO_ARCH_ESP32
			// ESP32 seems to be a little more complex:
		configTime(0, 0, ntpServer, ntpServer1);					// 0, 0 because we will use TZ in the next line
		delay(500);
		setenv("TZ", Timezone, 1); 												// Set environment variable with your time zone
		tzset();
		#else
			// ESP8266
		configTime(Timezone, ntpServer); 									// --> for the ESP8266 only
		#endif
					
  printLocalTime();  
}		
		
	// ----------------------	
void printLocalTime()
{
		
  time(&now); 																				// read the current time
	localtime_r(&now, &tm); 														// update the structure tm with the current time
	Serial.print("_52_");
  Serial.println(&tm, "%A, %B %d %Y %H:%M:%S");
			
		//Serial.print(timeinfo.tm_wday);									// 0 ..6
		//Serial.print(timeinfo.tm_mday);									// 1 .. 31
		//Serial.println(timeinfo.tm_mon);									// 0 ..11
}    
		
	// ----------------------------
void UpdateLocalTime() {
			
	time(&now); 																				// read the current time
	localtime_r(&now, &tm); 														// update the structure tm with the current time	
	Serial.print("_65_ update time ");
					
  char time_output[30], day_output[30], update_time[30];
	char * month_Name[] = {"Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec",
                        "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzien"
                       };
  char * weekday_Name[] = {"Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", };
	       
  CurrentHour = tm.tm_hour;  
  CurrentMin  = tm.tm_min;
  CurrentSec  = tm.tm_sec;
			
			//See http://www.cplusplus.com/reference/ctime/strftime/
  Serial.println(&tm, "%a %b %d %Y   %H:%M:%S");      						// Displays: Saturday, June 24 2017 14:05:49
						
	if (Units == "M") {
    if ((Language == "CZ") || (Language == "DE") || (Language == "NL") || (Language == "PL")) {
      sprintf(day_output, "%s %02u %s %04u", weekday_Name[tm.tm_wday], tm.tm_mday, month_Name[tm.tm_mon], (tm.tm_year) + 1900);	
							// Creates: Sobota., 23. Lipca 2022 <<
						
    }else{
      sprintf(day_output, "%s  %02u-%s-%04u", weekday_Name[tm.tm_wday], tm.tm_mday, month_Name[tm.tm_mon], (tm.tm_year) + 1900);
    }
				
    strftime(update_time, sizeof(update_time), "%H:%M:%S", &tm);  // Creates: '@ 14:05:49'   
    sprintf(time_output, "%s", update_time);
    
  }else{
    strftime(day_output, sizeof(day_output), "%a %b-%d-%Y", &tm); // Creates  'Sat May-31-2019'
    strftime(update_time, sizeof(update_time), "%r", &tm);        // Creates: '02:05:49pm'
    sprintf(time_output, "%s", update_time);
  }
					
	date_str = day_output;
  time_str = time_output;
	if (!bootCount )	locktime = time_output;
	/*		
  Serial.printf("_262_ %s\n", day_output);
	Serial.printf("_263_ %s\n", time_output);	
	Serial.println(date_str.c_str());
	Serial.printf("_265_ %s\n", time_str);
	*/
}		
					

- nie analizuje innych programów, to zabiera dużo czasu.

Link do komentarza
Share on other sites

- kolego programisto a ten błąd z biblioteka Timezone chyba nie pasuje do esp8266, no chyba że mam inna biblitekę.

- library properties daje:

name=Timezone
version=1.2.4
author=Jack Christensen <jack.christensen@outlook.com>

- można bibliotekę z AVR przeportować na esp8266, tylko kto to zrobi.

UWAGA: biblioteka Timezone działa na architekturze(/architekturach) avr i może nie być kompatybilna z obecną płytką która działa na architekturze(/architekturach) esp8266.

 

2.4cala.jpg

Edytowano przez 99teki
Link do komentarza
Share on other sites

Zarejestruj się lub zaloguj, aby ukryć tę reklamę.
Zarejestruj się lub zaloguj, aby ukryć tę reklamę.

jlcpcb.jpg

jlcpcb.jpg

Produkcja i montaż PCB - wybierz sprawdzone PCBWay!
   • Darmowe płytki dla studentów i projektów non-profit
   • Tylko 5$ za 10 prototypów PCB w 24 godziny
   • Usługa projektowania PCB na zlecenie
   • Montaż PCB od 30$ + bezpłatna dostawa i szablony
   • Darmowe narzędzie do podglądu plików Gerber
Zobacz również » Film z fabryki PCBWay

Dnia 10.04.2022 o 11:44, 99teki napisał:

- kolego programisto a ten błąd z biblioteka Timezone chyba nie pasuje do esp8266, no chyba że mam inna biblitekę.

- library properties daje:

name=Timezone
version=1.2.4
author=Jack Christensen <jack.christensen@outlook.com>

- można bibliotekę z AVR przeportować na esp8266, tylko kto to zrobi.


UWAGA: biblioteka Timezone działa na architekturze(/architekturach) avr i może nie być kompatybilna z obecną płytką która działa na architekturze(/architekturach) esp8266.

 

2.4cala.jpg

Witam!

Właśnie ten błąd mi wywalało....teraz lipa, autor nie żyje a ja go z zaświatów nie wywołam.....trudno, są wyświetlacze i się pomyśli

Link do komentarza
Share on other sites

Bądź aktywny - zaloguj się lub utwórz konto!

Tylko zarejestrowani użytkownicy mogą komentować zawartość tej strony

Utwórz konto w ~20 sekund!

Zarejestruj nowe konto, to proste!

Zarejestruj się »

Zaloguj się

Posiadasz własne konto? Użyj go!

Zaloguj się »
×
×
  • Utwórz nowe...

Ważne informacje

Ta strona używa ciasteczek (cookies), dzięki którym może działać lepiej. Więcej na ten temat znajdziesz w Polityce Prywatności.