• Уважаемые посетители сайта esp8266.ru!
    Мы отказались от размещения рекламы на страницах форума для большего комфорта пользователей.
    Вы можете оказать посильную поддержку администрации форума. Данные средства пойдут на оплату услуг облачных провайдеров для сайта esp8266.ru
  • Система автоматизации с открытым исходным кодом на базе esp8266/esp32 микроконтроллеров и приложения IoT Manager. Наша группа в Telegram

Нужна помощь Работа скетча без подключения wifi

zorgg

New member
Всем привет. Нужна ваша помощь как сделать чтобы без подключения к wifi работал скетч.
За сам скетч не пинайте сильно только учусь.
Скрипт для автономной работы.

Допустим во время включения esp нет wifi но нужно чтобы он выполнял некоторые функции, а когда wifi повляется то уже конектица до mqtt брокера

Например система протечки воды не хорошо если вдруг пропадет WIFI и система перестанет работать.

Код:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "******";
const char* password = "******";
const char* mqtt_server = "192.168.0.100";

const int buttonPin = 15;     // the number of the pushbutton pin
const int ledPin =  5;      // the number of the LED pin

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;


// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status


void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
  }

  randomSeed(micros());

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

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
   Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
   digitalWrite(ledPin, LOW);   // Turn the LED on (Note that LOW is the voltage level
   // but actually the LED is on; this is because
   // it is active low on the ESP-01)
  } else {
   digitalWrite(ledPin, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
   Serial.print("Attempting MQTT connection...");
   // Create a random client ID
   String clientId = "ESP8266Client-";
   clientId += String(random(0xffff), HEX);
   // Attempt to connect
   if (client.connect(clientId.c_str())) {
     Serial.println("connected");
     // Once connected, publish an announcement...
     client.publish("outTopic", "hello world");
     // ... and resubscribe
     client.subscribe("inTopic");
   } 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() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
   // turn LED on:
   digitalWrite(ledPin, LOW);
  } else {
   // turn LED off:
   digitalWrite(ledPin, HIGH);
  }
  if (!client.connected()) {
   reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
   lastMsg = now;
   ++value;
   snprintf (msg, 50, "hello world #%ld", value);
   Serial.print("Publish message: ");
   Serial.println(msg);
   client.publish("outTopic", msg);
  }
}
 

CodeNameHawk

Moderator
Команда форума
Так и никто не ответил?
Так если нужна помощь, то в программе должны быть комментарии, что каждая строка по вашему должна делать и вам укажут, где ошибка.
  • while (WiFi.status() != WL_CONNECTED) {
  • delay(500);
  • Serial.print(".");
}
Эта часть кода не даст проге запустится если нет подключения к wifi.

Пустой скетч работает и без подключения к wifi.
Просто не добавляйте команд, которые не дают работать, если нет подключения к wifi.
 
Сверху Снизу