Помощь со скетчем

tastek
Offline
Зарегистрирован: 20.12.2017

Добрый день, есть скетч с 2мя датчиками воды, хочу через mqtt отправить команду на  добавление запись в ROM, что бы датчик потока воды отложенно исполнял команду на выключение, команда отправляется, время меняется, но при перезагрузки, не сохраняет данные.

/*
  Liquid flow rate sensor -DIYhacking.com Arvind Sanjeev

  Measure the liquid/water flow rate using this code.
  Connect Vcc and Gnd of sensor to arduino, and the
  signal line to arduino digital pin 2.

*/
#include <EEPROM.h>
#include <ESP.h>


byte statusLed    = 13;
byte sensorInterrupt = D2;  // 0 = digital pin 2
byte sensorPin       = D2;
byte sensorPin1 = A0;
// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 4.5;
volatile byte pulseCount;
float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;
unsigned long oldTime;

int seconds_wait_for_water_from_start;
byte value;
boolean first_time_wait_for_water;

void setup()
{

  // Initialize a serial connection for reporting values to the host
  Serial.begin(38400);

  // Set up the status LED line as an output
  pinMode(statusLed, OUTPUT);
  digitalWrite(statusLed, HIGH);  // We have an active-low LED attached

  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;

  // The Hall-effect sensor is connected to pin 2 which uses interrupt 0.
  // Configured to trigger on a FALLING state change (transition from HIGH
  // state to LOW state)
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  Serial.println("Setup WiFi...");
  setupWifi();

  EEPROM.begin(0);

  value = EEPROM.read(seconds_wait_for_water_from_start);
  if (seconds_wait_for_water_from_start == 0)
    seconds_wait_for_water_from_start = 120;

  Serial.println();
  Serial.print("Parameter waiting for water: ");
  Serial.print(seconds_wait_for_water_from_start);
  Serial.println();

  first_time_wait_for_water = true;


}

#include <PubSubClient.h>
#include <ESP8266WiFi.h>

#define WIFI_SSID        "*"
#define WIFI_PASSWORD    "*"

//#define WIFI_SSID        "high"
//#define WIFI_PASSWORD    "Version5.0"

#define MQTT_SERVER      "192.168.124.33"
#define MQTT_USER        "*"
#define MQTT_PASSWORD    "*"



WiFiClient wifiClient;

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);

  if (strcmp(topic,"my_theme") == 0)
  {
    int new_parameter = 60;

    seconds_wait_for_water_from_start = new_parameter;
    
    EEPROM.write(seconds_wait_for_water_from_start, 1);
    EEPROM.commit();

    Serial.println();
    Serial.print("NEW parameter waiting for water: ");
    Serial.print(seconds_wait_for_water_from_start);
    Serial.println();
  }

  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

PubSubClient mqtt_client(MQTT_SERVER, 1883, callback, wifiClient);


void setupWifi()

{

  Serial.println("Connecting to WiFi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  unsigned long wifi_conn_started;
  wifi_conn_started = millis();
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");

    if ((millis() - wifi_conn_started) / 1000 > 60)
    {
      Serial.println(" !!!");
      Serial.println("Was waiting for WiFi for too long. Rebooting...");
      delay(5000);

      ESP.restart();
    }
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());



  delay(5000);

  char client_id[20];
  char lwt_topic[20];
  char sub_topic[20];
  sprintf(client_id, "watet_flow");
  sprintf(lwt_topic, "/watet_flow");
  sprintf(client_id, "watet_meter");
  sprintf(lwt_topic, "/watet_meter");
  sprintf(sub_topic, "/test_theme");

  if (mqtt_client.connect(client_id, MQTT_USER, MQTT_PASSWORD, lwt_topic, 0, true, "Offline"))
  {
    Serial.println("Connected to MQTT broker");

    mqtt_client.publish(lwt_topic, "Online");

    if (mqtt_client.subscribe(sub_topic))
      Serial.println("Subscribed successfully");

    if (mqtt_client.subscribe("#"))
      Serial.println("Subscribed successfully 2");

  }
  else
  {
    Serial.println("MQTT connect failed");
    Serial.println("Will reset and try again...");
    ESP.restart();
  }
}


/**
   Main program loop
*/
void loop() {

  mqtt_client.loop();

  if ((millis() - oldTime) > 1000)   // Only process counters once per second
  {
    char lwt_topic1[128];
    char lwt_topic2[128];
    char data[20];
    sprintf(lwt_topic1, "/water_flow");
    sprintf(data, "%i", flowMilliLitres);


    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();

    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;

    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(int(flowRate));  // Print the integer part of the variable
    Serial.print(".");             // Print the decimal point
    // Determine the fractional part. The 10 multiplier gives us 1 decimal place.
    frac = (flowRate - int(flowRate)) * 10;
    Serial.print(frac, DEC) ;      // Print the fractional part of the variable
    Serial.print("L/min");
    // Print the number of litres flowed in this second
    Serial.print("  Current Liquid Flowing: ");             // Output separator
    Serial.print(flowMilliLitres);
    flowMilliLitres = char(flowMilliLitres);
    Serial.print("mL/Sec");

    // Print the cumulative total of litres flowed since starting
    Serial.print("  Output Liquid Quantity: ");             // Output separator
    Serial.print(totalMilliLitres);
    Serial.println("mL");
    Serial.print("$$$$$$$$$ Want to publish:");
    Serial.print(lwt_topic1);
    Serial.print(", data:");
    Serial.println(data);
    mqtt_client.publish(lwt_topic1, data);
    // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

    int val = analogRead(sensorPin1);
    Serial.println (val);

    //delay(1000);
    delayWithLoop(1000);

    sprintf(lwt_topic2, "/water_meter");
    sprintf(data, "%i", val);
    mqtt_client.publish(lwt_topic2, data);

    //delay(5000);
    delayWithLoop(5000);

    if ((flowMilliLitres <= 0) && (millis() > seconds_wait_for_water_from_start * 1000 || !first_time_wait_for_water))
    {
      char offline[128];
      sprintf(offline, "cmnd/Sk2/POWER");
      Serial.println("No Water");
      Serial.println("Go offline");
      mqtt_client.publish(offline, "OFF");

      first_time_wait_for_water = false;

    }
  }

}


void delayWithLoop(unsigned long delay_time)
{

  unsigned long start_time;
  start_time = millis();

  while (millis() - start_time < delay_time)
  {
    mqtt_client.loop();
  }

}


/*
  Insterrupt Service Routine
*/
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

 

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

Ваша строка 58

value = EEPROM.read(seconds_wait_for_water_from_start);

здесь у Вас написано: прочитать значение, хранящееся по адресу seconds_wait_for_water_from_start и поместить его в value.

Судя по дальнейшим манипуляциям, Вы перепутали адрес и результат, т.к. Вы после этой строки явно пытаетесь seconds_wait_for_water_from_start как результат использовать.

А в строке 99

EEPROM.write(seconds_wait_for_water_from_start, 1);

Вы, похоже, опять перепутали адрес и значение. У Вас написано: "поместить единицу по адресу, хранящемуся в переменной seconds_wait_for_water_from_start. Уверен, что Вы имели в виду наоборот.

tastek
Offline
Зарегистрирован: 20.12.2017

Писали с 1 человеком, я в С++ очень плохо понимаю, если я правильно понял то должно получится так?Но все равно не хочет сохранять

/*
  Liquid flow rate sensor -DIYhacking.com Arvind Sanjeev

  Measure the liquid/water flow rate using this code.
  Connect Vcc and Gnd of sensor to arduino, and the
  signal line to arduino digital pin 2.

*/
#include <EEPROM.h>
#include <ESP.h>


byte statusLed    = 13;
byte sensorInterrupt = D2;  // 0 = digital pin 2
byte sensorPin       = D2;
byte sensorPin1 = A0;
// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 4.5;
volatile byte pulseCount;
float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;
unsigned long oldTime;

int seconds_wait_for_water_from_start;
byte value;
boolean first_time_wait_for_water;

void setup()
{

  // Initialize a serial connection for reporting values to the host
  Serial.begin(38400);

  // Set up the status LED line as an output
  pinMode(statusLed, OUTPUT);
  digitalWrite(statusLed, HIGH);  // We have an active-low LED attached

  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;

  // The Hall-effect sensor is connected to pin 2 which uses interrupt 0.
  // Configured to trigger on a FALLING state change (transition from HIGH
  // state to LOW state)
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  Serial.println("Setup WiFi...");
  setupWifi();

  EEPROM.begin(0);

  EEPROM.read(seconds_wait_for_water_from_start);
  if (seconds_wait_for_water_from_start == 0)
    seconds_wait_for_water_from_start = 120;

  Serial.println();
  Serial.print("Parameter waiting for water: ");
  Serial.print(seconds_wait_for_water_from_start);
  Serial.println();

  first_time_wait_for_water = true;


}

#include <PubSubClient.h>
#include <ESP8266WiFi.h>

#define WIFI_SSID        "BP"
#define WIFI_PASSWORD    "blend21h"

//#define WIFI_SSID        "high"
//#define WIFI_PASSWORD    "Version5.0"

#define MQTT_SERVER      "192.168.124.33"
#define MQTT_USER        "mqtt"
#define MQTT_PASSWORD    "mqtt21h"



WiFiClient wifiClient;

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);

  if (strcmp(topic,"my_theme") == 0)
  {
    int new_parameter = 60;

    seconds_wait_for_water_from_start = new_parameter;
    
    EEPROM.write(0, seconds_wait_for_water_from_start);
    EEPROM.commit();

    Serial.println();
    Serial.print("NEW parameter waiting for water: ");
    Serial.print(seconds_wait_for_water_from_start);
    Serial.println();
  }

  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

PubSubClient mqtt_client(MQTT_SERVER, 1883, callback, wifiClient);


void setupWifi()

{

  Serial.println("Connecting to WiFi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  unsigned long wifi_conn_started;
  wifi_conn_started = millis();
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");

    if ((millis() - wifi_conn_started) / 1000 > 60)
    {
      Serial.println(" !!!");
      Serial.println("Was waiting for WiFi for too long. Rebooting...");
      delay(5000);

      ESP.restart();
    }
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());



  delay(5000);

  char client_id[20];
  char lwt_topic[20];
  char sub_topic[20];
  sprintf(client_id, "watet_flow");
  sprintf(lwt_topic, "/watet_flow");
  sprintf(client_id, "watet_meter");
  sprintf(lwt_topic, "/watet_meter");
  sprintf(sub_topic, "/test_theme");

  if (mqtt_client.connect(client_id, MQTT_USER, MQTT_PASSWORD, lwt_topic, 0, true, "Offline"))
  {
    Serial.println("Connected to MQTT broker");

    mqtt_client.publish(lwt_topic, "Online");

    if (mqtt_client.subscribe(sub_topic))
      Serial.println("Subscribed successfully");

    if (mqtt_client.subscribe("#"))
      Serial.println("Subscribed successfully 2");

  }
  else
  {
    Serial.println("MQTT connect failed");
    Serial.println("Will reset and try again...");
    ESP.restart();
  }
}


/**
   Main program loop
*/
void loop() {

  mqtt_client.loop();

  if ((millis() - oldTime) > 1000)   // Only process counters once per second
  {
    char lwt_topic1[128];
    char lwt_topic2[128];
    char data[20];
    sprintf(lwt_topic1, "/water_flow");
    sprintf(data, "%i", flowMilliLitres);


    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();

    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;

    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(int(flowRate));  // Print the integer part of the variable
    Serial.print(".");             // Print the decimal point
    // Determine the fractional part. The 10 multiplier gives us 1 decimal place.
    frac = (flowRate - int(flowRate)) * 10;
    Serial.print(frac, DEC) ;      // Print the fractional part of the variable
    Serial.print("L/min");
    // Print the number of litres flowed in this second
    Serial.print("  Current Liquid Flowing: ");             // Output separator
    Serial.print(flowMilliLitres);
    flowMilliLitres = char(flowMilliLitres);
    Serial.print("mL/Sec");

    // Print the cumulative total of litres flowed since starting
    Serial.print("  Output Liquid Quantity: ");             // Output separator
    Serial.print(totalMilliLitres);
    Serial.println("mL");
    Serial.print("$$$$$$$$$ Want to publish:");
    Serial.print(lwt_topic1);
    Serial.print(", data:");
    Serial.println(data);
    mqtt_client.publish(lwt_topic1, data);
    // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

    int val = analogRead(sensorPin1);
    Serial.println (val);

    //delay(1000);
    delayWithLoop(1000);

    sprintf(lwt_topic2, "/water_meter");
    sprintf(data, "%i", val);
    mqtt_client.publish(lwt_topic2, data);

    //delay(5000);
    delayWithLoop(5000);

    if ((flowMilliLitres <= 0) && (millis() > seconds_wait_for_water_from_start * 1000 || !first_time_wait_for_water))
    {
      char offline[128];
      sprintf(offline, "cmnd/Sk2/POWER");
      Serial.println("No Water");
      Serial.println("Go offline");
      mqtt_client.publish(offline, "OFF");

      first_time_wait_for_water = false;

    }
  }

}


void delayWithLoop(unsigned long delay_time)
{

  unsigned long start_time;
  start_time = millis();

  while (millis() - start_time < delay_time)
  {
    mqtt_client.loop();
  }

}


/*
  Insterrupt Service Routine
*/
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

 

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

tastek пишет:

я в С++ очень плохо понимаю

Да, Вы и читать не умеете! Читайте ещё раз то, что я написал про Вашу строку 99

ЕвгенийП пишет:

Ваша строка 58

value = EEPROM.read(seconds_wait_for_water_from_start);

здесь у Вас написано: прочитать значение, хранящееся по адресу seconds_wait_for_water_from_start и поместить его в value.

Читайте до тех пор, пока не поймёте, что написано - где должен быть адрес и куда помещается значение. А потом посмотрите на свою новую строку и исправьте как следует.

b707
Offline
Зарегистрирован: 26.05.2017

tastek пишет:

Писали с 1 человеком, я в С++ очень плохо понимаю, если я правильно понял то должно получится так?

нет, опять не так. Переставлять параметры наугад - это не слишком продуктивно. Почему бы вам для начала не пояитать синтаксис методов библиотеки EEPROM ?

и если вы "в С++ очень плохо понимаете" -не ясно, зачем вы вообще пришли на форум. Это не форум изучения языка.

tastek
Offline
Зарегистрирован: 20.12.2017

синтаксис читал

b707
Offline
Зарегистрирован: 26.05.2017

tastek пишет:

синтаксис читал

или вранье, или "ниче не понял" - тогда случай безнадежный.

tastek
Offline
Зарегистрирован: 20.12.2017

b707 пишет:

tastek пишет:

синтаксис читал

или вранье, или "ниче не понял" - тогда случай безнадежный.

 

у меня другие сильные стороны, програмирование не мой конек, но мне сказали делай :(

tastek
Offline
Зарегистрирован: 20.12.2017

b707 пишет:

tastek пишет:

синтаксис читал

или вранье, или "ниче не понял" - тогда случай безнадежный.

 

у меня другие сильные стороны, програмирование не мой конек, но мне сказали делай :(

sadman41
Offline
Зарегистрирован: 19.10.2016

Ежели человек сильный - ему никто не может сказать "делай" ;)

tastek
Offline
Зарегистрирован: 20.12.2017

добрый день, получилось сделать что хотел, не подскажите что можно прочесть или какой скетч посмотреть, что бы я через функцию колбек забирал значения, а не только статичные цифры, понимаю что там должен быть какой-то параметр. спасибо

/*
  Liquid flow rate sensor -DIYhacking.com Arvind Sanjeev

  Measure the liquid/water flow rate using this code.
  Connect Vcc and Gnd of sensor to arduino, and the
  signal line to arduino digital pin 2.

*/
#include <EEPROM.h>
#include <ESP.h>


byte statusLed    = 13;
byte sensorInterrupt = D2;  // 0 = digital pin 2
byte sensorPin       = D2;
byte sensorPin1 = A0;
// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 4.5;
volatile byte pulseCount;
float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;
unsigned long oldTime;

int seconds_wait_for_water_from_start = 0;
byte value;
boolean first_time_wait_for_water;

void setup()
{

  // Initialize a serial connection for reporting values to the host
  Serial.begin(38400);

  // Set up the status LED line as an output
  pinMode(statusLed, OUTPUT);
  digitalWrite(statusLed, HIGH);  // We have an active-low LED attached

  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;

  // The Hall-effect sensor is connected to pin 2 which uses interrupt 0.
  // Configured to trigger on a FALLING state change (transition from HIGH
  // state to LOW state)
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  Serial.println("Setup WiFi...");
  setupWifi();

  EEPROM.begin(512);

  value = EEPROM.read(seconds_wait_for_water_from_start);
  if (value == 0)
    value = 120;

  Serial.println();
  Serial.print("Parameter waiting for water: ");
  Serial.print(seconds_wait_for_water_from_start);
    Serial.print("\t");
  Serial.print(value, DEC);
  Serial.println();

  first_time_wait_for_water = true;


}

#include <PubSubClient.h>
#include <ESP8266WiFi.h>

#define WIFI_SSID        "*"
#define WIFI_PASSWORD    "*"

//#define WIFI_SSID        "high"
//#define WIFI_PASSWORD    "Version5.0"

#define MQTT_SERVER      "*"
#define MQTT_USER        "*"
#define MQTT_PASSWORD    "*"



WiFiClient wifiClient;

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);

  if (strcmp(topic,"my_theme") == 0)
  {
    int new_parameter = 0;
    EEPROM.write(0, new_parameter);
    EEPROM.commit();

    Serial.println();
    Serial.print("NEW parameter waiting for water: ");
    Serial.print(seconds_wait_for_water_from_start);
    Serial.print("\t");
    Serial.print(new_parameter, DEC);
    Serial.println();
  }

  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

PubSubClient mqtt_client(MQTT_SERVER, 1883, callback, wifiClient);


void setupWifi()

{

  Serial.println("Connecting to WiFi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  unsigned long wifi_conn_started;
  wifi_conn_started = millis();
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");

    if ((millis() - wifi_conn_started) / 1000 > 60)
    {
      Serial.println(" !!!");
      Serial.println("Was waiting for WiFi for too long. Rebooting...");
      delay(5000);

      ESP.restart();
    }
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());



  delay(5000);

  char client_id[20];
  char lwt_topic[20];
  char sub_topic[20];
  sprintf(client_id, "watet_flow");
  sprintf(lwt_topic, "/watet_flow");
  sprintf(client_id, "watet_meter");
  sprintf(lwt_topic, "/watet_meter");
  sprintf(sub_topic, "/test_theme");

  if (mqtt_client.connect(client_id, MQTT_USER, MQTT_PASSWORD, lwt_topic, 0, true, "Offline"))
  {
    Serial.println("Connected to MQTT broker");

    mqtt_client.publish(lwt_topic, "Online");

    if (mqtt_client.subscribe(sub_topic))
      Serial.println("Subscribed successfully");

    if (mqtt_client.subscribe("#"))
      Serial.println("Subscribed successfully 2");

  }
  else
  {
    Serial.println("MQTT connect failed");
    Serial.println("Will reset and try again...");
    ESP.restart();
  }
}


/**
   Main program loop
*/
void loop() {

  mqtt_client.loop();

  if ((millis() - oldTime) > 1000)   // Only process counters once per second
  {
    char lwt_topic1[128];
    char lwt_topic2[128];
    char data[20];
    sprintf(lwt_topic1, "/water_flow");
    sprintf(data, "%i", flowMilliLitres);


    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();

    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;

    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(int(flowRate));  // Print the integer part of the variable
    Serial.print(".");             // Print the decimal point
    // Determine the fractional part. The 10 multiplier gives us 1 decimal place.
    frac = (flowRate - int(flowRate)) * 10;
    Serial.print(frac, DEC) ;      // Print the fractional part of the variable
    Serial.print("L/min");
    // Print the number of litres flowed in this second
    Serial.print("  Current Liquid Flowing: ");             // Output separator
    Serial.print(flowMilliLitres);
    flowMilliLitres = char(flowMilliLitres);
    Serial.print("mL/Sec");

    // Print the cumulative total of litres flowed since starting
    Serial.print("  Output Liquid Quantity: ");             // Output separator
    Serial.print(totalMilliLitres);
    Serial.println("mL");
    Serial.print("$$$$$$$$$ Want to publish:");
    Serial.print(lwt_topic1);
    Serial.print(", data:");
    Serial.println(data);
    mqtt_client.publish(lwt_topic1, data);
    // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

    int val = analogRead(sensorPin1);
    Serial.println (val);

    //delay(1000);
    delayWithLoop(1000);

    sprintf(lwt_topic2, "/water_meter");
    sprintf(data, "%i", val);
    mqtt_client.publish(lwt_topic2, data);

    //delay(5000);
    delayWithLoop(5000);

    if ((flowMilliLitres <= 0) && (millis() > value * 1000 || !first_time_wait_for_water))
    {
      char offline[128];
      sprintf(offline, "cmnd/Sk2/POWER");
      Serial.println("No Water");
      Serial.println("Go offline");
      mqtt_client.publish(offline, "OFF");

      first_time_wait_for_water = false;

    }
  }

}


void delayWithLoop(unsigned long delay_time)
{

  unsigned long start_time;
  start_time = millis();

  while (millis() - start_time < delay_time)
  {
    mqtt_client.loop();
  }

}


/*
  Insterrupt Service Routine
*/
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

 

tastek
Offline
Зарегистрирован: 20.12.2017

sadman41 пишет:

Ежели человек сильный - ему никто не может сказать "делай" ;)

 

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