Как поместить время с ntp сервера в отдельные переменные (часы и минуты)?

Тема в разделе "ESP8266, ESP32", создана пользователем Alex20280, 20 фев 2022.

Метки:
  1. Alex20280

    Alex20280 Нерд

    Всем привет! Помогите плиз. Я пытаюсь получить время с NTP сервера и поместить часы и минуты в отдельные переменные(current_hour и current_min), но у меня ничего не получается. Выходит только печатать время с помощью Serial.println(&timeinfo, "%H:%M:%S");. Как мне отсюда достать часы и минуты?
    Я хочу по достижению определенного времени запускать сервопривод.

    Код (C++):

    //https://randomnerdtutorials.com/esp32-date-time-ntp-client-server-arduino/
    #include <NTPClient.h>
    #include <time.h>                       // time() ctime()
    #include <sys/time.h>                   // struct timeval
    #include <sntp.h>                       // sntp_servermode_dhcp()
    #include <Wire.h>
    #include "PubSubClient.h"
    #include "WiFi.h"
    #include <Ticker.h>  //Ticker Library
    #include <ESP32Servo.h>
    #define PIN_SERVO 5
    #define ctsPin 3   // button

    Ticker blinker;

    const char* ssid          = "***********";
    const char* password      = "***********";
    const char*   mqtt_server = "192.168.1.151";
    const int     mqtt_port   = 1883;
    const char*   mqtt_topic  = "***********";
    const char*   mqtt_topic2  = "***********";
    const char*   mqtt_user   = "***********";
    const char*   mqtt_psw    = "***********";
     
    const char* ntpServer = "pool.ntp.org";
    const long  gmtOffset_sec = 7200;
    const long   daylightOffset_sec = 3600;
    WiFiUDP ntpUDP;
    NTPClient timeClient(ntpUDP, ntpServer, daylightOffset_sec);

    WiFiClient wifi_client;
    PubSubClient mqtt_client(mqtt_server, mqtt_port, wifi_client);

    WiFiClient espClient;
    PubSubClient client(espClient);

    Servo feedServo;

    char buff[50];

    //times
    unsigned long last_wifi_connection_time = 0;
    unsigned long last_data_time = 0, last_pub_time = 0; // last get data & publish  time stamps
    uint32_t myTimer1;

    int counterPause = 0;

    int feed1hour = 20;
    int feed1minute = 02;
    int feed2hour = 20;
    int feed2minute = 03;

    int feedQty = 4;
    int feedRate = 800;   //a pwm rate the triggers forward on the servo 75
    int feedReversal = 300;

    bool feed_0 = false;
    bool feed_1 = false;

    byte decToBcd(byte val) // Convert normal decimal numbers to binary coded decimal
    {
      return( (val/10*16) + (val%10) );
    }

    byte bcdToDec(byte val) // Convert binary coded decimal to normal decimal numbers
    {
      return( (val/16*10) + (val%16) );
    }

    void setup() {

    Serial.begin(115200);

        //wifi
      WiFi.setAutoConnect(false);
      WiFi.setAutoReconnect(false);
      connect_to_wifi();
      Serial.println("Setup WIFI");
     
      // Init time
      timeClient.begin();
      configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
      Serial.println("Setup Time");
     
      pinMode(ctsPin, INPUT);

    }

    void loop() {


      if (current_hour == feed1hour && current_min >= feed1minute &&  !feed_0)  {
      feed();  
      mqtt_pub_data();
      timeClient.forceUpdate();
      Serial.println(current_hour + current_min);
      feed_0 = 1;}
      else if (current_hour == feed2hour && current_min >= feed2minute && !feed_1)   {
        feed();
        mqtt_pub_data();
        timeClient.forceUpdate();
        Serial.println(current_hour + current_min);
        feed_1 = 1;
        }
    else if ((feed_0 | feed_1) & current_hour == feed1hour - 1)  {
      feed_0 = 0;
      feed_1 = 0;
      }


    //Manual feed button
    bool ctsValue = digitalRead(ctsPin);
    static bool ctsValueOld = 0;
    static bool ctsValueTik = 0;
      ctsValueTik = ctsValue & !ctsValueOld;
      ctsValueOld = ctsValue;
      if (ctsValueTik) {
        feed();
        mqtt_pub_data();
      }

    }


    void feed() {
       feedServo.attach(13); //   feedServo.attach(PIN_SERVO);
       for(int i = 0; i<7; i++) {
        feedServo.write(0);
          delay(1600);  
          feedServo.write(360);
          delay(1600);
       }
         feedServo.write (300);
         feedServo.detach();
    }


    void connect_to_wifi() {

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);

      int wifi_connect_counter = 0;
      while ((WiFi.status() != WL_CONNECTED) && (wifi_connect_counter < 10)) {
        delay(500);
        wifi_connect_counter++;
      }

      if (WiFi.status() == WL_CONNECTED) {
         //RTC time
        if ((millis() - last_wifi_connection_time) >= 360000UL) configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

        //time stamp
        last_wifi_connection_time = millis();
      }


    }

    void callback(char* topic, byte* payload, unsigned int length) {

    }

    void mqtt_pub_data ()
    {
      client.setServer(mqtt_server, mqtt_port);
      client.setCallback(callback);

      while (!client.connected()) {
        if (client.connect("ESP8266Client", mqtt_user, mqtt_psw )) {
         
          String feed = "Feeded";
          String payload = feed;
         
          client.publish(mqtt_topic, payload.c_str());
        } else {
            Serial.println("Data not published");
            return;
        }
      }
    }

    void printLocalTime()
    {
      struct tm timeinfo;
      if(!getLocalTime(&timeinfo)){
        Serial.println("Failed to obtain time");
        return;
      }
        Serial.println(&timeinfo, "%H:%M:%S");
    }


     
     
  2. parovoZZ

    parovoZZ Гуру