Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Русский
    3. ioBroker
    4. Скрипты
    5. ioBroker скрипты
    6. Скрипт для счётчика

    NEWS

    • Neuer Blog: Fotos und Eindrücke aus Solingen

    • ioBroker@Smart Living Forum Solingen, 14.06. - Agenda added

    • ioBroker goes Matter ... Matter Adapter in Stable

    Скрипт для счётчика

    This topic has been deleted. Only users with topic management privileges can see it.
    • I
      instalator last edited by

      @smoker_vvo:

      Что то не прет компиляция….Electro_Counter2, код взят с Githuba

      ! Arduino: 1.8.2 (Windows 7), Плата:"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\count.ino:6:0: warning: "PWR_CTRL" redefined
      ! #define PWR_CTRL A0
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:7:0: note: this is the location of the previous definition
      ! #define PWR_CTRL A2 //Контроль напряжения
      ! ^
      ! count:14: error: conflicting declaration 'volatile long unsigned int cnt'
      ! volatile unsigned long cnt = 1 ;
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:34:15: note: previous declaration as 'long unsigned int cnt'
      ! unsigned long cnt = 0;
      ! ^
      ! count:15: error: conflicting declaration 'volatile long unsigned int prev_cnt'
      ! volatile unsigned long prev_cnt = 0;
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:35:15: note: previous declaration as 'long unsigned int prev_cnt'
      ! unsigned long prev_cnt = 2;
      ! ^
      ! count:16: error: conflicting declaration 'volatile long unsigned int pwr'
      ! volatile unsigned long pwr = 0;
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:36:15: note: previous declaration as 'long unsigned int pwr'
      ! unsigned long pwr = 0;
      ! ^
      ! count:17: error: conflicting declaration 'volatile long unsigned int prev_pwr'
      ! volatile unsigned long prev_pwr = 1;
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:37:15: note: previous declaration as 'long unsigned int prev_pwr'
      ! unsigned long prev_pwr = 2;
      ! ^
      ! count:18: error: conflicting declaration 'long unsigned int chk'
      ! unsigned long chk = 0;
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:44:5: note: previous declaration as 'int chk'
      ! int chk = 0;
      ! ^
      ! count:19: error: redefinition of 'int num'
      ! int num = 3200;
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:40:5: note: 'int num' previously defined here
      ! int num = 0;
      ! ^
      ! count:21: error: redefinition of 'int amp'
      ! int amp = 0;
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:38:5: note: 'int amp' previously defined here
      ! int amp = 0;
      ! ^
      ! count:22: error: redefinition of 'int prev_amp'
      ! int prev_amp = 0;
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:39:5: note: 'int prev_amp' previously defined here
      ! int prev_amp = 2;
      ! ^
      ! count:23: error: redefinition of 'int bounce'
      ! int bounce = 1;
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:42:5: note: 'int bounce' previously defined here
      ! int bounce = 10;
      ! ^
      ! count:31: error: redefinition of 'String cmd'
      ! String cmd = "";
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:50:8: note: 'String cmd' previously declared here
      ! String cmd = "";
      ! ^
      ! count:32: error: redefinition of 'bool strComplete'
      ! bool strComplete = false;
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:51:6: note: 'bool strComplete' previously defined here
      ! bool strComplete = false;
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\count.ino: In function 'void setup()':
      ! count:35: error: redefinition of 'void setup()'
      ! void setup() {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:67:6: note: 'void setup()' previously defined here
      ! void setup() {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\count.ino: In function 'void loop()':
      ! count:60: error: redefinition of 'void loop()'
      ! void loop() {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:265:6: note: 'void loop()' previously defined here
      ! void loop() {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\count.ino: In function 'void serialEvent()':
      ! count:129: error: redefinition of 'void serialEvent()'
      ! void serialEvent() {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:111:6: note: 'void serialEvent()' previously defined here
      ! void serialEvent() {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\count.ino: In function 'void save()':
      ! count:139: error: redefinition of 'void save()'
      ! void save() {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:175:6: note: 'void save()' previously defined here
      ! void save() {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\count.ino: In function 'void EEPROMWriteLong(int, long unsigned int)':
      ! count:150: error: redefinition of 'void EEPROMWriteLong(int, long unsigned int)'
      ! void EEPROMWriteLong(int p_address, unsigned long p_value) {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:195:6: note: 'void EEPROMWriteLong(int, long unsigned int)' previously defined here
      ! void EEPROMWriteLong(int p_address, unsigned long p_value) {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\count.ino: In function 'long unsigned int EEPROMReadLong(int)':
      ! count:161: error: redefinition of 'long unsigned int EEPROMReadLong(int)'
      ! unsigned long EEPROMReadLong(int p_address) {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:206:15: note: 'long unsigned int EEPROMReadLong(int)' previously defined here
      ! unsigned long EEPROMReadLong(int p_address) {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\count.ino: In function 'void EEPROMWriteInt(int, int)':
      ! count:169: error: redefinition of 'void EEPROMWriteInt(int, int)'
      ! void EEPROMWriteInt(int p_address, int p_value) {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:214:6: note: 'void EEPROMWriteInt(int, int)' previously defined here
      ! void EEPROMWriteInt(int p_address, int p_value) {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\count.ino: In function 'unsigned int EEPROMReadInt(int)':
      ! count:175: error: redefinition of 'unsigned int EEPROMReadInt(int)'
      ! unsigned int EEPROMReadInt(int p_address) {
      ! ^
      ! F:\Arduino MDM\Electro_Counter2-master\mqtt\mqtt.ino:220:14: note: 'unsigned int EEPROMReadInt(int)' previously defined here
      ! unsigned int EEPROMReadInt(int p_address) {
      ! ^
      ! Несколько библиотек найдено для "SPI.h"
      ! Используется: C:\Users\5\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.19\libraries\SPI
      ! Не используется: C:\Program Files (x86)\Arduino\libraries\SPI
      ! Несколько библиотек найдено для "PubSubClient.h"
      ! Используется: C:\Users\5\Documents\Arduino\libraries\PubSubClient
      ! Не используется: C:\Program Files (x86)\Arduino\libraries\PubSubClient
      ! Несколько библиотек найдено для "EEPROM.h"
      ! Используется: C:\Users\5\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.19\libraries\EEPROM
      ! Не используется: C:\Program Files (x86)\Arduino\libraries\EEPROM
      ! exit status 1
      ! conflicting declaration 'volatile long unsigned int cnt'
      ! Этот отчёт будет иметь больше информации с
      ! включенной опцией Файл -> Настройки ->
      ! "Показать подробный вывод во время компиляции" `
      Потому что там два разных скетча.

      Один непосредственно для счетчика, второй для второго мк который для связи

      1 Reply Last reply Reply Quote 0
      • S
        smoker_vvo last edited by

        Таааак…. А вот с этого места поподробнее... Если я правильно понимаю, одна сборка снимает показания и передает их другой сборке, которая по MQTT их публикует.... Эт получается надо пару ардуин вешать?? А как обмен между ними организован??

        Сечас я использую одну 2560 для обработки температуры, датчиков освещения и контроля за насосом и промсетью, а на второй 2560 пытаюсь сделать счетчик КВт.....

        и возможно на нее же посажу управление вентиляцией и освещением...

        1 Reply Last reply Reply Quote 0
        • S
          smoker_vvo last edited by

          И еще, хотелось бы схемку, подключения счетчика…..

          Да, по отдельности оба скетча скомпилились без проблем...

          1 Reply Last reply Reply Quote 0
          • S
            smoker_vvo last edited by

            Обновил информацию по статье на твоем Блоге, но не дружу с UART, как это выглядит для домохозяек….

            1 Reply Last reply Reply Quote 0
            • I
              instalator last edited by

              @smoker_vvo:

              Таааак…. А вот с этого места поподробнее... Если я правильно понимаю, одна сборка снимает показания и передает их другой сборке, которая по MQTT их публикует.... Эт получается надо пару ардуин вешать?? А как обмен между ними организован??

              Сечас я использую одну 2560 для обработки температуры, датчиков освещения и контроля за насосом и промсетью, а на второй 2560 пытаюсь сделать счетчик КВт.....

              и возможно на нее же посажу управление вентиляцией и освещением... `
              Импульсы считает отдельный МК, сделано для того чтобы не пропускались импульсы и ни на что другое не влияло. Выдает данные на уарт, второй МК принимает эти данные и шлёт уже по mqtt.

              Возьми для счётчика например ардуиной про мини и ей считай только импульсы. А вся остальная логика - mqtt, датчики и ТД и тп

              1 Reply Last reply Reply Quote 0
              • S
                smoker_vvo last edited by

                Попробовал залить скетч Count в 2560…. Результат отрицательный, в сериал ни чего не летит.... ПРверял Монитором порта от IDE Arduino 1.6.13.

                Я правильно понимаю что один выход счетчика подключаем к А0, второй к GND или я не прав.

                Вот типовая схема счетчика
                1308_watermarked-shema-se101.png.jpg

                1 Reply Last reply Reply Quote 0
                • I
                  instalator last edited by

                  @smoker_vvo:

                  Попробовал залить скетч Count в 2560…. Результат отрицательный, в сериал ни чего не летит.... ПРверял Монитором порта от IDE Arduino 1.6.13.

                  Я правильно понимаю что один выход счетчика подключаем к А0, второй к GND или я не прав.

                  Вот типовая схема счетчика `
                  Нет, вход идет на вход прерывания INT0.

                  1 Reply Last reply Reply Quote 0
                  • S
                    smoker_vvo last edited by

                    Все, сдаюсь. Ткните носом - куда подключать выводы от счетчика…. INT0- это какая нога(pin) на 2560, 21? или я уже ни чего не понимаю

                    И где в скетче это прописано....

                    Считывание идет, как я вижу со 2 pin.....

                    ! ````
                    #include <eeprom.h>
                    #include <avr wdt.h="">
                    #include <avr io.h="">
                    #include <avr interrupt.h="">
                    ! #define PWR_CTRL A0
                    #define CNT_ADR 10
                    #define PWR_ADR 20
                    #define IMP_ADR 30
                    #define BNC_ADR 40
                    #define NUM_ADR 50
                    #define CHK_ADR 100
                    ! volatile unsigned long cnt = 1 ;
                    volatile unsigned long prev_cnt = 0;
                    volatile unsigned long pwr = 0;
                    volatile unsigned long prev_pwr = 1;
                    unsigned long chk = 0;
                    int num = 3200;
                    int imp = 0;
                    int amp = 0;
                    int prev_amp = 0;
                    int bounce = 1;
                    unsigned long prev;
                    volatile unsigned long prev_millis;
                    volatile unsigned long cur_tmS = millis();
                    volatile unsigned long pre_tmS = cur_tmS;
                    volatile float diffS = 0;
                    volatile unsigned long tm_diffS = 0;
                    bool err = false;
                    String cmd = "";
                    bool strComplete = false;
                    ! //////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    void setup() {
                    MCUSR = 0;
                    wdt_disable();
                    Serial.begin(115200);
                    cmd.reserve(200);
                    Serial.print("Start");
                    pinMode(2, INPUT);
                    digitalWrite(2, HIGH);
                    delay(200);
                    if (EEPROM.read(1) != 88) { //Если первый запуск
                    EEPROM.write(1, 88);
                    } else {
                    chk = EEPROMReadLong(CHK_ADR);
                    cnt = EEPROMReadLong(CNT_ADR);
                    pwr = EEPROMReadLong(PWR_ADR);
                    imp = EEPROMReadInt(IMP_ADR);
                    num = EEPROMReadInt(NUM_ADR);
                    bounce = EEPROMReadInt(BNC_ADR);
                    if (chk != cnt + imp + bounce) {
                    err = true;
                    }
                    }
                    wdt_enable(WDTO_8S);
                    attachInterrupt(0, count, FALLING);
                    }
                    ! void loop() {
                    wdt_reset();
                    if (analogRead(PWR_CTRL) < 1000) {
                    save();
                    }
                    ! if (strComplete) {
                    // Serial.println(inputString);
                    if (cmd.substring(0, 1) == "S") {
                    if (cmd.substring(1, 2) == "N") {
                    num = cmd.substring(cmd.lastIndexOf('N') + 1).toInt();
                    }
                    else if (cmd.substring(1, 2) == "S") {
                    save();
                    }
                    else if (cmd.substring(1, 2) == "C") {
                    cnt = atol(cmd.substring(cmd.lastIndexOf('C') + 1).c_str());
                    }
                    else if (cmd.substring(1, 2) == "B") {
                    bounce = cmd.substring(cmd.lastIndexOf('B') + 1).toInt();
                    }
                    save();
                    }
                    cmd = "";
                    strComplete = false;
                    }
                    ! tm_diffS = cur_tmS - pre_tmS;
                    diffS = (float(tm_diffS) / 1000);
                    pwr = 3600000 / (num * diffS);
                    if ((cnt != prev_cnt || amp != prev_amp || pwr >= (prev_pwr + 10) || pwr <= (prev_pwr - 10)) && pwr > 0 && millis() - 2000 > prev) {
                    prev = millis();
                    Serial.print(cnt);
                    Serial.print(";");
                    if (pwr > (prev_pwr + 4000)) {
                    Serial.print(prev_pwr);
                    } else {
                    Serial.print(pwr);
                    }
                    Serial.print(";");
                    Serial.print(amp);
                    Serial.print(";");
                    Serial.print(bounce);
                    Serial.print(";");
                    Serial.print(num);
                    Serial.print(";");
                    Serial.print(err);
                    Serial.print('\n');
                    }
                    prev_cnt = cnt;
                    prev_amp = amp;
                    prev_pwr = pwr;
                    }
                    ! void count() {
                    detachInterrupt(0);
                    if (millis() - bounce > prev_millis) {
                    prev_millis = millis();
                    pre_tmS = cur_tmS;
                    cur_tmS = millis();
                    imp++;
                    if (imp >= num) {
                    imp = 0;
                    cnt++;
                    }
                    }
                    attachInterrupt(0, count, FALLING);
                    }
                    ! void serialEvent() {
                    while (Serial.available() > 0) {
                    char inChar = (char)Serial.read();
                    cmd += inChar;
                    if (inChar == '\n') {
                    strComplete = true;
                    }
                    }
                    }
                    ! void save() {
                    chk = cnt + imp + bounce;
                    EEPROMWriteLong(CNT_ADR, cnt);
                    EEPROMWriteLong(PWR_ADR, pwr);
                    EEPROMWriteInt(IMP_ADR, imp);
                    EEPROMWriteInt(NUM_ADR, num);
                    EEPROMWriteInt(BNC_ADR, bounce);
                    EEPROMWriteLong(CHK_ADR, chk);
                    }
                    ! void EEPROMWriteLong(int p_address, unsigned long p_value) {
                    byte four = (p_value & 0xFF);
                    byte three = ((p_value >> 😎 & 0xFF);
                    byte two = ((p_value >> 16) & 0xFF);
                    byte one = ((p_value >> 24) & 0xFF);
                    EEPROM.write(p_address, four);
                    EEPROM.write(p_address + 1, three);
                    EEPROM.write(p_address + 2, two);
                    EEPROM.write(p_address + 3, one);
                    }
                    ! unsigned long EEPROMReadLong(int p_address) {
                    long four = EEPROM.read(p_address);
                    long three = EEPROM.read(p_address + 1);
                    long two = EEPROM.read(p_address + 2);
                    long one = EEPROM.read(p_address + 3);
                    return ((four << 0) & 0xFF) + ((three << 😎 & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF);
                    }
                    ! void EEPROMWriteInt(int p_address, int p_value) {
                    byte lowByte = ((p_value >> 0) & 0xFF);
                    byte highByte = ((p_value >> 😎 & 0xFF);
                    EEPROM.write(p_address, lowByte);
                    EEPROM.write(p_address + 1, highByte);
                    }
                    unsigned int EEPROMReadInt(int p_address) {
                    byte lowByte = EEPROM.read(p_address);
                    byte highByte = EEPROM.read(p_address + 1);
                    return ((lowByte << 0) & 0xFF) + ((highByte << 😎 & 0xFF00);
                    }</avr></avr></avr></eeprom.h>

                    1 Reply Last reply Reply Quote 0
                    • S
                      smoker_vvo last edited by

                      Хотя…. отключив логику и перелистав ДатаШИТ на 2560, понимаю что INT0 - это pin2 (RX0)

                      и тогда, о чудо.... я увидел вот это....

                      ! ````
                      4278188031;4294427971;0;-5;-5;1
                      4278188031;4294427161;0;-5;-5;1
                      4278188031;4294414725;0;-5;-5;1
                      4278188031;4294429983;0;-5;-5;1
                      4278188031;4294433568;0;-5;-5;1
                      4278188031;4294428374;0;-5;-5;1
                      4278188031;4294415995;0;-5;-5;1
                      4278188031;4294427971;0;-5;-5;1
                      4278188031;4294428777;0;-5;-5;1
                      4278188031;4294427161;0;-5;-5;1
                      4278188031;4294413876;0;-5;-5;1
                      4278188031;4294422667;0;-5;-5;1
                      4278188031;4294426350;0;-5;-5;1
                      4278188031;4294425128;0;-5;-5;1
                      4278188031;4294426350;0;-5;-5;1

                      
                      Это то что я ищу???
                      1 Reply Last reply Reply Quote 0
                      • I
                        instalator last edited by

                        @smoker_vvo:

                        Хотя…. отключив логику и перелистав ДатаШИТ на 2560, понимаю что INT0 - это pin2 (RX0)

                        и тогда, о чудо.... я увидел вот это....

                        ! ````
                        4278188031;4294427971;0;-5;-5;1
                        4278188031;4294427161;0;-5;-5;1
                        4278188031;4294414725;0;-5;-5;1
                        4278188031;4294429983;0;-5;-5;1
                        4278188031;4294433568;0;-5;-5;1
                        4278188031;4294428374;0;-5;-5;1
                        4278188031;4294415995;0;-5;-5;1
                        4278188031;4294427971;0;-5;-5;1
                        4278188031;4294428777;0;-5;-5;1
                        4278188031;4294427161;0;-5;-5;1
                        4278188031;4294413876;0;-5;-5;1
                        4278188031;4294422667;0;-5;-5;1
                        4278188031;4294426350;0;-5;-5;1
                        4278188031;4294425128;0;-5;-5;1
                        4278188031;4294426350;0;-5;-5;1

                        
                        Это то что я ищу??? `  да, только надо конфиг задать через уарт
                        1 Reply Last reply Reply Quote 0
                        • S
                          smoker_vvo last edited by

                          как? И еще вопрос, просто хочется оперативно посмотреть результаты….

                          Как объединить этот код

                          ! ```
                          `#include <spi.h> // Ethernet shield
                          #include <ethernet.h> // Ethernet shield
                          #include <pubsubclient.h> // MQTT
                          #include <servo.h>
                          #include <dht.h>
                          #include <onewire.h>
                          #include <dallastemperature.h>
                          Servo servo;
                          ! byte mac[] = { 0xC1, 0x7C, 0x38, 0x41, 0x89, 0x15 };
                          byte server[] = { 192, 168, 10, 15 }; //IP Брокера
                          byte ip[] = { 192, 168, 10, 88 }; //IP Клиента (Arduino)
                          ! ////////////////////////////////////////////////////////////////////////////
                          void callback(char* topic, byte* payload, unsigned int length) {
                          payload[length] = '\0';
                          // Serial.print(topic);
                          // Serial.print("=");
                          String strTopic = String(topic);
                          String strPayload = String((char*)payload);
                          // Serial.println(strPayload);
                          callback_iobroker(strTopic, strPayload);
                          }
                          ! EthernetClient ethClient;
                          PubSubClient client(server, 1883, callback, ethClient);
                          #define id_connect "myhome-temp"
                          #define id_connect "myhome-status"
                          #define Prefix_subscribe "myhome/Temp/"
                          #define Prefix_subscribe "myhome/Status/"
                          ! ///////////////Объявляем порты ввода-вывода
                          #define ServoPin 3 //Порт к которому подключен сервопривод
                          ! const int start_DI_pin []= {2, 4, 5}; // Порты Ввода
                          int n_DI_pin = sizeof(start_DI_pin) / sizeof(start_DI_pin[0])-1; //Вычисляем длинну массива
                          ! const int start_DO_pin []= {6, 7}; //Порты Вывода
                          int n_DO_pin = sizeof(start_DO_pin) / sizeof(start_DO_pin[0])-1; //Вычисляем длинну массива
                          ! int DI[] = {0, 0, 0};
                          int old_DI[] = {0, 0, 0};
                          ! ///////////////////////////Переменные для работы с освещением//////////////////////////////////////
                          int ServoAngle = 100; //Угол сервопривода при включении
                          int flag = 0;
                          int flag2 = 0;
                          int pause = 0;
                          ! //------------------------------------------- Sensors -------------------------------------------//
                          const int MQ7_Pin = A0; // Куда подключили MQ7
                          //int MQ7Value = 0;
                          int MQ7Value = analogRead(MQ7_Pin);

                          const int foto_Pin = A1; // устанавливаем входную ногу для Фоторезистора
                          //unsigned int fotoValue = 0; // цифровое значение фоторезистора
                          unsigned int fotoValue = analogRead(foto_Pin);

                          ! #define ONE_WIRE_BUS 8
                          //#define TEMPERATURE_PRECISION 9
                          OneWire oneWire(ONE_WIRE_BUS);
                          DallasTemperature DS_sensors(&oneWire);
                          // 28 80 E9 3A 04 00 00 10
                          //T0:28 88 AD D7 02 00 00 42
                          //T1:28 14 A5 D7 02 00 00 B0
                          //T2:28 72 26 7B 04 00 00 2E
                          //T3:28 CA 1A 3B 04 00 00 CD
                          //T4:28 E6 D5 D7 02 00 00 C1
                          //T5:28 16 B4 7A 04 00 00 8A
                          //T6:28 2B 86 D7 02 00 00 CF
                          //T7:28 AB 9D D7 02 00 00 29
                          DeviceAddress addr_T1 = { 0x28, 0x80, 0xE9, 0x3A, 0x4, 0x0, 0x0, 0x10 };//кладовка
                          DeviceAddress addr_T2 = { 0x28, 0x88, 0xAD, 0xD7, 0x2, 0x0, 0x0, 0x42 };//кухня
                          DeviceAddress addr_T3 = { 0x28, 0x14, 0xA5, 0xD7, 0x2, 0x0, 0x0, 0xB0 };//детская
                          DeviceAddress addr_T4 = { 0x28, 0x72, 0x26, 0x7B, 0x4, 0x0, 0x0, 0x2E };//гараж
                          DeviceAddress addr_T5 = { 0x28, 0xCA, 0x1A, 0x3B, 0x4, 0x0, 0x0, 0xCD };//ванная
                          DeviceAddress addr_T6 = { 0x28, 0xE6, 0xD5, 0xD7, 0x2, 0x0, 0x0, 0xC1 };//улица
                          DeviceAddress addr_T7 = { 0x28, 0x16, 0xB4, 0x7A, 0x4, 0x0, 0x0, 0x8A };//спальня2
                          DeviceAddress addr_T8 = { 0x28, 0x2B, 0x86, 0xD7, 0x2, 0x0, 0x0, 0xCF };//зал
                          DeviceAddress addr_T9 = { 0x28, 0xAB, 0x9D, 0xD7, 0x2, 0x0, 0x0, 0x29 };//мансарда
                          ! float T1=0;
                          float T2=0;
                          float T3=0;
                          float T4=0;
                          float T5=0;
                          float T6=0;
                          float T7=0;
                          float T8=0;
                          float T9=0;
                          ! //dht DHT;
                          //#define DHT22_PIN 9
                          //float Hout = 0;
                          //float Tout = 0;
                          ! ////////////////////////////////////////////////////////////////////////////
                          //void callback(char* topic, byte* payload, unsigned int length) {
                          // payload[length] = '\0';
                          // Serial.print(topic);
                          // Serial.print("=");
                          // String strTopic = String(topic);
                          // String strPayload = String((char*)payload);
                          // Serial.println(strPayload);
                          // callback_iobroker(strTopic, strPayload);
                          //}
                          ////////////////////////////////////////////////////////////////////////////
                          void setup() {
                          Serial.begin(57600);
                          Serial.println("start");

                          Serial.print("Locating devices...");
                          DS_sensors.begin();
                          Serial.print("Found ");
                          Serial.print(DS_sensors.getDeviceCount(), DEC);
                          Serial.println(" devices.");

                          ! // report parasite power requirements
                          Serial.print("Parasite power is: ");
                          if (DS_sensors.isParasitePowerMode()) Serial.println("ON");
                          else Serial.println("OFF");

                          //Объявляем порты Digital inputs/outputs
                          

                          for(int i=0 ;i<=n_DI_pin; i++) { pinMode (start_DI_pin [i], INPUT); }
                          digitalWrite(5, HIGH); //Насос скважины
                          digitalWrite(4, HIGH); //Электрика
                          for(int i=0 ;i<=n_DO_pin; i++) { pinMode (start_DO_pin [i], OUTPUT); }

                          ! Ethernet.begin(mac, ip);
                          if (client.connect(id_connect)) {
                          getSensors();
                          control();
                          //client.publish("myhome/Kitchen/Change_Counter", "0");
                          //client.publish("myhome/Kitchen/Temp_room", "0");
                          //client.publish("myhome/Kitchen/Humidity_room", "0");
                          client.publish("myhome/Temp/Kladovka", "0");
                          client.publish("myhome/Temp/Kitchen", "0");
                          client.publish("myhome/Temp/Detskaya", "0");
                          client.publish("myhome/Temp/Garage", "0");
                          client.publish("myhome/Temp/Street", "0");
                          client.publish("myhome/Temp/Spalnya2", "0");
                          client.publish("myhome/Temp/Zal", "0");
                          client.publish("myhome/Temp/Mansarda", "0");
                          client.publish("myhome/Temp/Vannaya", "0");

                          //client.publish("myhome/Kitchen/Lux", "0");
                          //client.publish("myhome/Kitchen/Servo", "0");
                          client.publish("myhome/Temp/MQ7", "0");
                          
                          client.publish("myhome/Status/Power", "0");
                          client.publish("myhome/Status/Pompe", "0");
                          
                          client.subscribe("myhome/Temp/#");
                          client.subscribe("myhome/Status/#");
                          

                          }
                          }
                          /////////////////////////////////////////////////////////////////////////
                          void loop() {
                          client.loop();
                          control();
                          getSensors();
                          if (!client.connected()) {
                          if (client.connect(id_connect)) {
                          control();
                          getSensors();
                          client.subscribe("myhome/Temp/#");
                          }
                          }
                          }</dallastemperature.h></onewire.h></dht.h></servo.h></pubsubclient.h></ethernet.h></spi.h>`

                          ! function.ino
                          `[code]//--------------------------------- Functions ---------------------------------//
                          /////////////////////////////////От Брокера//////////////////////////////////////////////
                          void callback_iobroker(String strTopic, String strPayload){
                          if (strTopic == "myhome/Kitchen/Servo"){
                          ServoAngle=strPayload.toInt();
                          if (ServoAngle >= 0 && ServoAngle <= 255){
                          servo.attach(ServoPin);
                          //delay(200); //ждем 2 секунды
                          servo.write(ServoAngle); //ставим вал под 0
                          delay(1000); //ждем 2 секунды
                          //client.publish("myhome/Kitchen/Servo", b);
                          servo.detach();
                          }
                          }
                          }
                          ! ////////////////////////////////////Брокеру/////////////////////////////////////
                          void control(){

                             if(digitalRead(5)==HIGH && flag==0) { //если насос включен
                                client.publish("myhome/Status/Pompe", "1");
                                flag=1; 
                          
                             } 
                             if(digitalRead(5)==LOW && flag==1){//если насос выключен  
                              client.publish("myhome/Status/Pompe", "0");       
                              flag=0;//обнуляем переменную flag 
                             }   
                          
                             if(digitalRead(4)==HIGH && flag2==0) { // Если электрика есть
                                client.publish("myhome/Status/Power", "1");
                                flag2=1; 
                             } 
                             if(digitalRead(4)==LOW && flag2==1){// Если эректрики нет
                              client.publish("myhome/Status/Power", "0");       
                              flag2=0;//обнуляем переменную flag 
                             }          
                          

                          }
                          ///////////////////////////////Данные сенсоров////////////////////////////////////

                          ! void getSensors () {
                          ! MQ7Value = analogRead(MQ7_Pin);
                          fotoValue = analogRead(foto_Pin); // считываем значение с фоторезистора
                          // ServoAngle = analogRead(2);
                          ! //Обработка данных датчика DHT22. Подключение к порту цифровому P9 Arduino
                          //Глобальные переменные Hout и Tout типа флоат - влажность (%) и температура (град. С)
                          // if (DHT.read22(DHT22_PIN)== DHTLIB_OK) {
                          // Hout = DHT.humidity;
                          // Tout = DHT.temperature;
                          // }
                          // if (Hout == 0 || Tout == 0){
                          // delay (1000);
                          // if (DHT.read22(DHT22_PIN)== DHTLIB_OK) {
                          // Hout = DHT.humidity;
                          // Tout = DHT.temperature;
                          // }
                          // }
                          //Обработка данных цифровых датчиков температуры типа DS18B20.
                          //Шина 1-Wire на цифровой пин P8 Arduino.
                          //Подключено 2 датчика температуры, адреса задаются в секции глобальных констант "Sensors"
                          //Три значение температуры T1, T2, типа float (град. С).
                          DS_sensors.setResolution(addr_T1, 9);
                          DS_sensors.setResolution(addr_T2, 9);
                          DS_sensors.setResolution(addr_T3, 9);
                          DS_sensors.setResolution(addr_T4, 9);
                          DS_sensors.setResolution(addr_T5, 9);
                          DS_sensors.setResolution(addr_T6, 9);
                          DS_sensors.setResolution(addr_T7, 9);
                          DS_sensors.setResolution(addr_T8, 9);
                          DS_sensors.setResolution(addr_T9, 9);

                          float T1 = DS_sensors.getTempC(addr_T1);
                          float T2 = DS_sensors.getTempC(addr_T2);
                          float T3 = DS_sensors.getTempC(addr_T3);
                          float T4 = DS_sensors.getTempC(addr_T4);
                          float T5 = DS_sensors.getTempC(addr_T5);
                          float T6 = DS_sensors.getTempC(addr_T6);
                          float T7 = DS_sensors.getTempC(addr_T7);
                          float T8 = DS_sensors.getTempC(addr_T8);
                          float T9 = DS_sensors.getTempC(addr_T9);

                          DS_sensors.requestTemperatures();
                          //Serial.print(DS_sensors.getResolution(addr_T1), DEC);
                          Serial.println();
                          Serial.print("Temp T1 😄 ");
                          Serial.print(T1);
                          Serial.println();

                          ! Serial.println();
                          Serial.print("Temp T2 😄 ");
                          Serial.print(T2);
                          Serial.println();
                          //
                          Serial.println();
                          Serial.print("Temp T3 😄 ");
                          Serial.print(T3);
                          Serial.println();
                          //
                          Serial.println();
                          Serial.print("Temp T4 😄 ");
                          Serial.print(T4);
                          Serial.println();
                          //
                          Serial.println();
                          Serial.print("Temp T5 😄 ");
                          Serial.print(T5);
                          Serial.println();
                          //
                          Serial.println();
                          Serial.print("Temp T6 😄 ");
                          Serial.print(T6);
                          Serial.println();
                          //
                          Serial.println();
                          Serial.print("Temp T7 😄 ");
                          Serial.print(T7);
                          Serial.println();
                          //
                          Serial.println();
                          Serial.print("Temp T8 😄 ");
                          Serial.print(T8);
                          Serial.println();
                          //
                          Serial.println();
                          Serial.print("Temp T9 😄 ");
                          Serial.print(T9);
                          Serial.println();
                          //
                          ///////////////////////Паблик данных сенсоров////////////////////////
                          if (pause == 50 || pause == 0){

                          char b[5];
                          // String char_Hout = String(Hout);
                          // char_Hout.toCharArray(b,5);
                          // client.publish("myhome/Kitchen/Humidity_room", b);

                          // String char_Tout = String(Tout);
                          // char_Tout.toCharArray(b,5);
                          // client.publish("myhome/Kitchen/Temp_room", b);

                          String char_T1 = String(T1);
                          char_T1.toCharArray(b,5);
                          client.publish("myhome/Temp/Kladovka", b);
                          String char_T2 = String(T2);
                          char_T2.toCharArray(b,5);
                          client.publish("myhome/Temp/Kitchen", b);
                          String char_T3 = String(T3);
                          char_T3.toCharArray(b,5);
                          client.publish("myhome/Temp/Detskaya", b);
                          String char_T4 = String(T4);
                          char_T4.toCharArray(b,5);
                          client.publish("myhome/Temp/Garage", b);
                          String char_T5 = String(T5);
                          char_T5.toCharArray(b,5);
                          client.publish("myhome/Temp/Vannaya", b);
                          String char_T6 = String(T6);
                          char_T6.toCharArray(b,5);
                          client.publish("myhome/Temp/Street", b);
                          String char_T7 = String(T7);
                          char_T7.toCharArray(b,5);
                          client.publish("myhome/Temp/Spalnya2", b);
                          String char_T8 = String(T8);
                          char_T8.toCharArray(b,5);
                          client.publish("myhome/Temp/Zal", b);
                          String char_T9 = String(T9);
                          char_T9.toCharArray(b,5);
                          client.publish("myhome/Temp/Mansarda", b);
                          //Serial.println(T1);
                          String char_fotoValue = String(fotoValue);
                          char_fotoValue.toCharArray(b,4);
                          client.publish("myhome/Kitchen/Lux", b);
                          

                          String char_ServoAngle = String(ServoAngle);
                          char_ServoAngle.toCharArray(b,4);
                          client.publish("myhome/Kitchen/Servo", b);

                          String char_MQ7Value = String(MQ7Value);
                          char_MQ7Value.toCharArray(b,4);
                          client.publish("myhome/Temp/MQ7", b);
                          
                          pause = 1;
                          

                          }
                          else pause++;
                          }

                          ! [/code] и код вот этот... ! >! ~~[spoiler]~~[code]#include <spi.h>#include <ethernet.h>#include <pubsubclient.h>#include <eeprom.h>#include <avr wdt.h="">#define PWR_CTRL A2 //Контроль напряжения
                          #define LED 9 //Светодиод
                          #define CHK_ADR 100
                          #define CNT_ADR 10
                          #define PWR_ADR 20
                          #define POLL_ADR 30
                          #define RATIO_ADR 40
                          ! const char* topic_err = "myhome/elcounter/error";
                          const char* topic_cnt = "myhome/elcounter/count";
                          const char* topic_pwr = "myhome/elcounter/power";
                          const char* topic_amp = "myhome/elcounter/amp";
                          const char* topic_save = "myhome/elcounter/save";
                          const char* topic_correction = "myhome/elcounter/correction";
                          const char* topic_connection = "myhome/elcounter/connection";
                          const char* topic_ip = "myhome/elcounter/config/ip";
                          const char* topic_polling = "myhome/elcounter/config/polling";
                          const char* topic_bounce = "myhome/elcounter/config/bounce";
                          const char* topic_num = "myhome/elcounter/config/num";
                          const char* topic_reset = "myhome/elcounter/config/reset";
                          const char* topic_raw = "myhome/elcounter/RAW";
                          const char* subscr = "myhome/elcounter/#";
                          ! byte mac[6] = {0xC4, 0xE7, 0xC4, 0x9E, 0x83, 0x12};
                          byte ip[4] = {192, 168, 1, 52};
                          byte server[4] = {192, 168, 1, 190};
                          ! unsigned long cnt = 0;
                          unsigned long prev_cnt = 2;
                          unsigned long pwr = 0;
                          unsigned long prev_pwr = 2;
                          int amp = 0;
                          int prev_amp = 2;
                          int num = 0;
                          int prev_num;
                          int bounce = 10;
                          int prev_bounce;
                          int chk = 0;
                          int chk_S = 0;
                          unsigned long prevMillis = 0;
                          unsigned long prevMillis_cnt = 0;
                          int poll = 5000;
                          bool error = 0;
                          String cmd = "";
                          bool strComplete = false;
                          char buf [50];
                          char buffer[100];
                          char s[16];
                          ! ////////////////////////////////////////////////////////////////////////////
                          void callback(char* topic, byte* payload, unsigned int length) {
                          payload[length] = '\0';
                          String strTopic = String(topic);
                          String strPayload = String((char*)payload);
                          callback_iobroker(strTopic, strPayload);
                          }
                          ! EthernetClient ethClient;
                          PubSubClient client(ethClient);
                          ! void setup() {
                          MCUSR = 0;
                          wdt_disable();
                          cmd.reserve(100);
                          delay(10000);
                          Serial.begin(115200);

                          if (EEPROM.read(1) != 99) { //Если первый запуск
                          EEPROM.write(1, 99);
                          for (int i = 0 ; i < 4; i++) {
                          EEPROM.write(110 + i, ip[i]);
                          }
                          for (int i = 0 ; i < 4; i++) {
                          EEPROM.write(120 + i, server[i]);
                          }
                          } else {
                          chk = EEPROMReadInt(CHK_ADR);
                          cnt = EEPROMReadLong(CNT_ADR);
                          poll = EEPROMReadInt(POLL_ADR);
                          chk_S = poll - 500;
                          if (chk != chk_S) {
                          error = 2;
                          }
                          for (int i = 0; i < 4; i++) {
                          ip[i] = EEPROM.read(110 + i);
                          }
                          for (int i = 0; i < 4; i++) {
                          server[i] = EEPROM.read(120 + i);
                          }
                          }

                          ! pinMode(LED, OUTPUT);

                          client.setServer(server, 1883);
                          client.setCallback(callback);
                          Ethernet.begin(mac, ip);
                          delay(200);
                          wdt_enable(WDTO_8S);
                          if (client.connect("elcounter")) {
                          digitalWrite(LED, LOW);
                          Public();
                          }
                          }

                          ! void serialEvent() {
                          while (Serial.available() > 0) {
                          char inChar = (char)Serial.read();
                          cmd += inChar;
                          if (inChar == '\n') {
                          strComplete = true;
                          }
                          }
                          }
                          ! void callback_iobroker(String strTopic, String strPayload) {
                          if (strTopic == topic_correction) {
                          cnt = atol((strPayload).c_str());
                          Serial.print("SC");
                          Serial.println(cnt);
                          client.publish(topic_correction, "0");
                          }
                          else if (strTopic == topic_save) {
                          if (strPayload == "true") {
                          Serial.println("SS");
                          save();
                          client.publish(topic_save, "false");
                          }
                          }
                          else if (strTopic == topic_polling) {
                          poll = strPayload.toInt();
                          if (poll < 1000) {
                          poll = 1000;
                          } else if (poll > 32767) {
                          poll = 32767;
                          }
                          EEPROMWriteInt(POLL_ADR, poll); //Интервал публикации
                          client.publish(topic_polling, IntToChar(poll));
                          }
                          else if (strTopic == topic_reset) {
                          if (strPayload == "true") {
                          client.publish(topic_reset, "false");
                          reboot();
                          }
                          }
                          else if (strTopic == topic_bounce) {
                          bounce = strPayload.toInt();
                          if (bounce < 0) {
                          bounce = 0;
                          } else if (bounce > 10000) {
                          bounce = 10000;
                          }
                          Serial.print("SB");
                          Serial.println(bounce);
                          client.publish(topic_bounce, IntToChar(bounce));
                          }
                          else if (strTopic == topic_num) {
                          num = strPayload.toInt();
                          if (num < 0) {
                          num = 0;
                          } else if (num > 32767) {
                          num = 32767;
                          }
                          Serial.print("SN");
                          Serial.println(num);
                          client.publish(topic_num, IntToChar(num));
                          }
                          }
                          ! void save() {
                          chk = poll - 500;
                          EEPROMWriteLong(CNT_ADR, cnt); //Пишем показания счетчика в eeprom из переменной
                          EEPROMWriteInt(POLL_ADR, poll); //Интервал публикации
                          EEPROMWriteInt(CHK_ADR, chk); //чек
                          }
                          ! void reboot() {
                          save();
                          delay(500);
                          wdt_enable(WDTO_1S);
                          for (;;) {}
                          }
                          ! char* StrToChar (String str) {
                          int length = str.length();
                          str.toCharArray(buf, length + 1);
                          return buf;
                          }
                          ! void EEPROMWriteLong(int p_address, unsigned long p_value) {
                          byte four = (p_value & 0xFF);
                          byte three = ((p_value >> 😎 & 0xFF);
                          byte two = ((p_value >> 16) & 0xFF);
                          byte one = ((p_value >> 24) & 0xFF);
                          EEPROM.write(p_address, four);
                          EEPROM.write(p_address + 1, three);
                          EEPROM.write(p_address + 2, two);
                          EEPROM.write(p_address + 3, one);
                          }
                          ! unsigned long EEPROMReadLong(int p_address) {
                          long four = EEPROM.read(p_address);
                          long three = EEPROM.read(p_address + 1);
                          long two = EEPROM.read(p_address + 2);
                          long one = EEPROM.read(p_address + 3);
                          return ((four << 0) & 0xFF) + ((three << 😎 & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF);
                          }
                          ! void EEPROMWriteInt(int p_address, int p_value) {
                          byte lowByte = ((p_value >> 0) & 0xFF);
                          byte highByte = ((p_value >> 😎 & 0xFF);
                          EEPROM.write(p_address, lowByte);
                          EEPROM.write(p_address + 1, highByte);
                          }
                          unsigned int EEPROMReadInt(int p_address) {
                          byte lowByte = EEPROM.read(p_address);
                          byte highByte = EEPROM.read(p_address + 1);
                          return ((lowByte << 0) & 0xFF) + ((highByte << 😎 & 0xFF00);
                          }
                          ! char* IntToChar (unsigned long a) {
                          sprintf(buf, "%lu", a);
                          return buf;
                          }
                          ! void Public(){
                          sprintf(s, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
                          client.publish(topic_err, " ");
                          client.publish(topic_cnt, IntToChar(cnt));
                          client.publish(topic_pwr, IntToChar(pwr));
                          client.publish(topic_amp, IntToChar(amp));
                          client.publish(topic_save, "false");
                          client.publish(topic_correction, "0");
                          client.publish(topic_connection, "true");
                          client.publish(topic_ip, s);
                          client.publish(topic_polling, IntToChar(poll));
                          client.publish(topic_bounce, IntToChar(bounce));
                          client.publish(topic_num, IntToChar(num));
                          client.publish(topic_reset, "false");
                          client.subscribe(subscr);
                          }
                          void reconnect() {
                          int a = 0;
                          while (!client.connected()) {
                          a++;
                          digitalWrite(LED, !digitalRead(LED));
                          wdt_reset();
                          if (client.connect("elcounter")) {
                          digitalWrite(LED, LOW);
                          Public();
                          } else {
                          delay(10000);
                          }
                          if (a >= 10) {
                          wdt_enable(WDTO_1S);
                          }
                          }
                          }
                          ! void loop() {
                          wdt_reset();
                          client.loop();
                          if (!client.connected()) {
                          reconnect();
                          }
                          ! if (analogRead(PWR_CTRL) < 1000) {
                          digitalWrite(LED, LOW);
                          save();
                          delay(10000);
                          }
                          ! if (strComplete) {
                          digitalWrite(LED, !digitalRead(LED));
                          cmd.toCharArray(buffer, 100);
                          cnt = atoi(strtok(buffer, ";"));
                          pwr = atoi(strtok(NULL, ";"));
                          amp = atoi(strtok(NULL, ";"));
                          bounce = atoi(strtok(NULL, ";"));
                          num = atoi(strtok(NULL, ";"));
                          error = atoi(strtok(NULL, ";"));
                          client.publish(topic_raw, StrToChar(cmd));
                          cmd = "";
                          strComplete = false;
                          }
                          ! if (millis() - prevMillis >= poll) {
                          wdt_reset();
                          prevMillis = millis();
                          if (cnt != prev_cnt || pwr != prev_pwr || amp != prev_amp) {
                          prev_cnt = cnt;
                          prev_pwr = pwr;
                          prev_amp = amp;
                          client.publish(topic_cnt, IntToChar(cnt));
                          client.publish(topic_pwr, IntToChar(pwr));
                          client.publish(topic_amp, IntToChar(amp));
                          }
                          if (num != prev_num || bounce != prev_bounce) {
                          prev_num = num;
                          prev_bounce = bounce;
                          client.publish(topic_num, IntToChar(num));
                          client.publish(topic_bounce, IntToChar(bounce));
                          }
                          if (error > 0) {
                          client.publish(topic_err, "err");
                          } else {
                          client.publish(topic_err, " ");
                          }
                          }</avr></eeprom.h></pubsubclient.h></ethernet.h></spi.h>`
                          причина проста, есть две 2560 одна считает энергию и отдает другой 2560 которая, отвечает за температуру и все это публикует. И как правильно настроить UART между двумя 2560[/i][/i][/i][/i][/code][/spoiler][/i][/i]

                          1 Reply Last reply Reply Quote 0
                          • I
                            instalator last edited by

                            @smoker_vvo:

                            как? `

                            ! ````
                            if (cmd.substring(0, 1) == "S") {
                            if (cmd.substring(1, 2) == "N") {
                            num = cmd.substring(cmd.lastIndexOf('N') + 1).toInt();
                            }
                            else if (cmd.substring(1, 2) == "S") {
                            save();
                            }
                            else if (cmd.substring(1, 2) == "C") {
                            cnt = atol(cmd.substring(cmd.lastIndexOf('C') + 1).c_str());
                            }
                            else if (cmd.substring(1, 2) == "B") {
                            bounce = cmd.substring(cmd.lastIndexOf('B') + 1).toInt();
                            }
                            save();
                            }
                            cmd = "";
                            strComplete = false;
                            }

                            т.о. чтобы задать bounce надо в уарт послать B1000 например.
                            
                            или чтобы задать данные счетчика то - C51423
                            
                            Как объединить этот код
                            
                            ….........
                            
                            и код вот этот...
                            
                            >! ````
                            >! void serialEvent() {
                              while (Serial.available() > 0) {
                                char inChar = (char)Serial.read();
                                cmd += inChar;
                                if (inChar == '\n') {
                                  strComplete = true;
                                }
                              }
                            }
                            if (strComplete) {
                                digitalWrite(LED, !digitalRead(LED));
                                cmd.toCharArray(buffer, 100);
                                cnt = atoi(strtok(buffer, ";"));
                                pwr = atoi(strtok(NULL, ";"));
                                amp = atoi(strtok(NULL, ";"));
                                bounce = atoi(strtok(NULL, ";"));
                                num = atoi(strtok(NULL, ";"));
                                error = atoi(strtok(NULL, ";"));
                                client.publish(topic_raw, StrToChar(cmd));
                                cmd = "";
                                strComplete = false;
                              }
                            >! ````
                            
                            Тут мы как раз получаем данные из уарт и парсим их, а дальше делай что хочешь
                            1 Reply Last reply Reply Quote 0
                            • S
                              smoker_vvo last edited by

                              ой мамочки…. У меня есть немного вопросов касаемо счетчика:

                              1. тип оборудования Arduino Uno + Mega 2560

                              2. Скетч Count - на УНО завелся без проблем, показания получаю.

                              3. Как правильно состыковать УНО и МЕГА, сделано так TX & RX Uno соединены с RX(0) & TX(1) Mega, ни чего нет на Меге.

                              4. Самое противное, при заливке скетча MQTT на 2560 получаю странную картину - постоянно мигает светодиод L и Мега ни как не реагирует на поступающие данные, и не пингуется по своему адресу. в кодах ни чего не менял кроме ip адресов

                              Куда рыть далее???

                              1 Reply Last reply Reply Quote 0
                              • S
                                smoker_vvo last edited by

                                по умолчанию считаю что в обоих скетчах - UART уже прописан. или я не прав?

                                1 Reply Last reply Reply Quote 0
                                • S
                                  smoker_vvo last edited by

                                  Пардон, не UNO а NANO

                                  1 Reply Last reply Reply Quote 0
                                  • S
                                    smoker_vvo last edited by

                                    и еще в Count и MQTT есть такие строки

                                    Count

                                    #define PWR_CTRL A0

                                    MQTT

                                    #define PWR_CTRL A2 //Контроль напряжения

                                    прошу пояснить их назначение и схемку подключения

                                    1 Reply Last reply Reply Quote 0
                                    • I
                                      instalator last edited by

                                      @smoker_vvo:

                                      ой мамочки…. У меня есть немного вопросов касаемо счетчика:

                                      1. тип оборудования Arduino Uno + Mega 2560

                                      2. Скетч Count - на УНО завелся без проблем, показания получаю.

                                      3. Как правильно состыковать УНО и МЕГА, сделано так TX & RX Uno соединены с RX(0) & TX(1) Mega, ни чего нет на Меге.

                                      4. Самое противное, при заливке скетча MQTT на 2560 получаю странную картину - постоянно мигает светодиод L и Мега ни как не реагирует на поступающие данные, и не пингуется по своему адресу. в кодах ни чего не менял кроме ip адресов

                                      Куда рыть далее??? ` убери из кода ватчдог либо залей оптибут в мегу.

                                      1 Reply Last reply Reply Quote 0
                                      • I
                                        instalator last edited by

                                        @smoker_vvo:

                                        и еще в Count и MQTT есть такие строки

                                        Count

                                        #define PWR_CTRL A0

                                        MQTT

                                        #define PWR_CTRL A2 //Контроль напряжения

                                        прошу пояснить их назначение и схемку подключения ` контроль питания на порту. При пропадании питания сохраняются данные в епром

                                        1 Reply Last reply Reply Quote 0
                                        • S
                                          smoker_vvo last edited by

                                          Вачдог…

                                          Это

                                          void reboot() {

                                          save();

                                          delay(500);

                                          wdt_enable(WDTO_1S);

                                          for (;;) {}

                                          }

                                          1 Reply Last reply Reply Quote 0
                                          • S
                                            smoker_vvo last edited by

                                            для контроля питания, что то подавать надо, или это аппаратно решено??

                                            1 Reply Last reply Reply Quote 0
                                            • First post
                                              Last post

                                            Support us

                                            ioBroker
                                            Community Adapters
                                            Donate

                                            404
                                            Online

                                            31.8k
                                            Users

                                            80.0k
                                            Topics

                                            1.3m
                                            Posts

                                            3
                                            70
                                            12517
                                            Loading More Posts
                                            • Oldest to Newest
                                            • Newest to Oldest
                                            • Most Votes
                                            Reply
                                            • Reply as topic
                                            Log in to reply
                                            Community
                                            Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen
                                            The ioBroker Community 2014-2023
                                            logo