петля arduino не работает с двумя процессами

Я не большой программист, поэтому я спрашиваю вас, ребята, если вы знаете, как я могу решить мою проблему. В Arduino я написал первую программу с моим датчиком DS18B20, который отображает температуру в openHAB по протоколу MQTT. Вторая программа - это то же самое (openhab, mqtt), просто переключающая лампа, что означает, что когда я нажимаю переключатель, лампа или светодиод включаются или выключаются через функцию обратного вызова в Arduino. По отдельности обе программы работают нормально, но когда я пытаюсь соединить их вместе, получается не так, как хотелось бы. Мне кажется, что проблема в функции цикла. Когда я нажимаю переключатель ON или OFF, иногда (редко) я могу включить или выключить лампу. Итак, мой вопрос... что не так? Это проблема с циклом, потому что arduino не может выполнять две вещи в цикле одновременно? Можно ли это решить, я действительно не знаю, что делать дальше. Пожалуйста, помогите мне и спасибо заранее!

#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <PubSubClient.h>
#include "WiFiEsp.h"

// Emulate Serial1 on pins 3/2 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(3, 2); // RX, TX
#endif

char ssid[] = "SSID;     // your network SSID (name)
char pwd[] = "password";  // your network password

float temp = 0;

byte server[] = { 192, 168, 1, 71 }; // IP Address of your MQTT Server
WiFiEspClient espClient;
PubSubClient client(espClient);


#define ONE_WIRE_BUS 4
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);



void callback(char* topic, byte* payload, unsigned int length) {
Serial.println("Callback");

Serial.println(topic);
Serial.println(length);
Serial.write(payload,length);
Serial.println();

 if (strcmp(topic,"home/luc")==0) { 
   if (payload[0] == '0') 
    {
    digitalWrite(7, LOW);
    delay(100);
    client.publish("home/luc/state","OFF");
  }  
  else if (payload[0] == '1')
  {

  digitalWrite(7, HIGH);  
  delay(100);
  client.publish("home/luc/state","ON");
    }

}
}



void temperaturni_senzor ()
{
  sensors.requestTemperatures();  
  temp = sensors.getTempCByIndex(0);
  Serial.print("Temperatura je: ");
  Serial.println(temp); // Why "byIndex"? You can have more than one IC on the same bus. 0 refers to the first IC on the wire
  //Update value every 1 sec.


  client.publish("home/temperature", String(temp).c_str(),TRUE);
  delay(50);
  }
void reconnect() {
 // Loop until we're reconnected
 while (!client.connected()) {
 Serial.print("connecting to mqtt...");
 // Attempt to connect
 if (client.connect("ESP8266 client")) {
  Serial.println("connection good");
  // ... and subscribe to topic
  client.subscribe("home/luc");
 } else {
  Serial.print("failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 5 seconds");
  // Wait 5 seconds before retrying
  delay(5000);
  }
 }
}

void setup()
{
  Serial1.begin(9600);
  Serial.begin(9600); //Begin serial communication
  WiFi.init(&Serial1);
  WiFi.begin(ssid, pwd);
  client.setServer(server, 1883);
  client.setCallback(callback);

 if (client.connect("arduinoClient")) 
  {
    Serial.println ("mqqt is connected");
     client.publish("outTopic","hsubscribello world");
      client.subscribe("home/luc");  // Subscribe to all messages for this device
      client.subscribe("home/temperature");
      }
    pinMode(7, OUTPUT);
    digitalWrite(7, LOW);
  sensors.begin();

}

void loop() 
{
 client.loop();

  if (!client.connected()) 
  {
  reconnect();
  }

     temperaturni_senzor ();

  }

}

person janez novak    schedule 08.03.2017    source источник
comment
Отредактируйте вопрос, включив в него код, который у вас есть, чтобы нам не пришлось угадывать   -  person hardillb    schedule 08.03.2017
comment
В Arduino нет процессов. Что вы имеете в виду под arduino не может обрабатывать две вещи в цикле одновременно? Arduino выполняет все действия последовательно в том порядке, в котором вы их укажете.   -  person Patrick Trentin    schedule 09.03.2017


Ответы (2)


У вас есть образец серийного вывода?

Также для вашей функции reconnect() я думаю, что Serial должен быть Serial1 для вашего вывода ESP8266, так как вы использовали WiFi.init(&Serial1) в настройке.

В цикле у вас есть

if (!client.connected()) { reconnect(); }

Он зацикливается, чтобы увидеть, подключился ли клиент, если нет, то он пытается переподключиться. При повторном подключении он пытается подключиться, и если это не удается, он ждет 5 секунд каждый раз, когда не может подключиться. Это может быть ваша проблема.

У вас есть код для обеих отдельных программ?

person Omar    schedule 09.03.2017
comment
tnx для ответа Омар, но, как я проверял, переподключение вообще не влияет. Проблема в том, что я пишу в функции цикла, когда client.loop(); в представленном, он перестает работать. Так что, может быть, у меня не может быть ничего другого в цикле, когда там есть client.loop? - person janez novak; 10.03.2017

Это код для DS18B20, и он работает.

#include <OneWire.h>
    #include <DallasTemperature.h>
    #include <SPI.h>
    #include <PubSubClient.h>
    #include "WiFiEsp.h"
    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(3, 2); // RX, TX
    #endif


    byte server[] = { 192, 168, 1, 71 }; // IP Address of your MQTT Server



    WiFiEspClient espClient;
    PubSubClient client(espClient);


    float temp = 0;
    char ssid[] = "SSID";     // your network SSID (name)
    char pwd[] = "password";  // your network password




    #define ONE_WIRE_BUS 4
    // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);
    // Pass our oneWire reference to Dallas Temperature. 
    DallasTemperature sensors(&oneWire);


    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Attempt to connect
        if (client.connect("arduinoClient_temperature_sensor")) {
          Serial.println("connected");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying
          delay(5000);
        }
      }
    }


    void setup()
    {
    Serial1.begin(9600);
    Serial.begin(9600); //Begin serial communication
    WiFi.init(&Serial1);
    WiFi.begin(ssid, pwd);
     client.setServer(server, 1883);
     sensors.begin();
    }

   void temp_senz ()
   {
    sensors.requestTemperatures();  
      temp = sensors.getTempCByIndex(0);
      Serial.print("Temperatura je: ");
      Serial.println(temp);
      client.publish("home/temperature", String(temp).c_str(),TRUE);
      delay(1000);
    } 
    void loop()
    { 
      {
      if (!client.connected()) {
        reconnect();
      }
      client.loop();
     temp_senz ();

      }
    }

И это для лампы, и это тоже работает.

#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <PubSubClient.h>
#include "WiFiEsp.h"

// Emulate Serial1 on pins 7/6 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(3, 2); // RX, TX
#endif

char ssid[] = "SSID";     // your network SSID (name)
char pwd[] = "password";  // your network password


byte server[] = { 192, 168, 1, 71 }; // IP Address of your MQTT Server



WiFiEspClient espClient;
PubSubClient client(espClient);


void callback(char* topic, byte* payload, unsigned int length) {
Serial.println("Callback");

Serial.println(topic);
Serial.println(length);
Serial.write(payload,length);
Serial.println();

 if (strcmp(topic,"home/luc")==0) { 
   if (payload[0] == '0') 
    {
    digitalWrite(7, LOW);
    delay(100);
    client.publish("home/luc/state","OFF");
  }  
  else if (payload[0] == '1')
  {

  digitalWrite(7, HIGH);  
  delay(100);
  client.publish("home/luc/state","ON");
    }

}
}


void setup()
{
  Serial1.begin(9600);
  Serial.begin(9600); //Begin serial communication
  WiFi.init(&Serial1);
  WiFi.begin(ssid, pwd);
  client.setServer(server, 1883);
  client.setCallback(callback);

 if (client.connect("arduinoClient")) 
  {
    Serial.println ("mqqt je konektan");
     client.publish("outTopic","hsubscribello world");
      client.subscribe("home/luc");  // Subscribe to all messages for this device
      }

    pinMode(7, OUTPUT);
    digitalWrite(7, LOW);

}



void loop() {

client.loop();

}

Изображение последовательного монитора для обоих примеров, объединенных вместе

person janez novak    schedule 09.03.2017