Работа скетча без подключения wifi
- Войдите на сайт для отправки комментариев
Пт, 22/03/2019 - 01:00
Всем привет. Нужна ваша помощь как сделать чтобы без подключения к wifi работал скетч.
За сам скетч не пинайте сильно только учусь.
001 | #include <ESP8266WiFi.h> |
002 | #include <PubSubClient.h> |
003 |
004 | const char * ssid = "******" ; |
005 | const char * password = "******" ; |
006 | const char * mqtt_server = "192.168.0.100" ; |
007 |
008 | const int buttonPin = 15; // the number of the pushbutton pin |
009 | const int ledPin = 5; // the number of the LED pin |
010 |
011 | WiFiClient espClient; |
012 | PubSubClient client(espClient); |
013 | long lastMsg = 0; |
014 | char msg[50]; |
015 | int value = 0; |
016 |
017 |
018 | // variables will change: |
019 | int buttonState = 0; // variable for reading the pushbutton status |
020 |
021 |
022 | void setup_wifi() { |
023 |
024 | delay(10); |
025 | // We start by connecting to a WiFi network |
026 | Serial .println(); |
027 | Serial .print( "Connecting to " ); |
028 | Serial .println(ssid); |
029 |
030 | WiFi.begin(ssid, password); |
031 |
032 | while (WiFi.status() != WL_CONNECTED) { |
033 | delay(500); |
034 | Serial .print( "." ); |
035 | } |
036 |
037 | randomSeed(micros()); |
038 |
039 | Serial .println( "" ); |
040 | Serial .println( "WiFi connected" ); |
041 | Serial .println( "IP address: " ); |
042 | Serial .println(WiFi.localIP()); |
043 | } |
044 |
045 | void callback( char * topic, byte * payload, unsigned int length) { |
046 | Serial .print( "Message arrived [" ); |
047 | Serial .print(topic); |
048 | Serial .print( "] " ); |
049 | for ( int i = 0; i < length; i++) { |
050 | Serial .print(( char )payload[i]); |
051 | } |
052 | Serial .println(); |
053 |
054 | // Switch on the LED if an 1 was received as first character |
055 | if (( char )payload[0] == '1' ) { |
056 | digitalWrite(ledPin, LOW); // Turn the LED on (Note that LOW is the voltage level |
057 | // but actually the LED is on; this is because |
058 | // it is active low on the ESP-01) |
059 | } else { |
060 | digitalWrite(ledPin, HIGH); // Turn the LED off by making the voltage HIGH |
061 | } |
062 |
063 | } |
064 |
065 | void reconnect() { |
066 | // Loop until we're reconnected |
067 | while (!client.connected()) { |
068 | Serial .print( "Attempting MQTT connection..." ); |
069 | // Create a random client ID |
070 | String clientId = "ESP8266Client-" ; |
071 | clientId += String(random(0xffff), HEX); |
072 | // Attempt to connect |
073 | if (client.connect(clientId.c_str())) { |
074 | Serial .println( "connected" ); |
075 | // Once connected, publish an announcement... |
076 | client.publish( "outTopic" , "hello world" ); |
077 | // ... and resubscribe |
078 | client.subscribe( "inTopic" ); |
079 | } else { |
080 | Serial .print( "failed, rc=" ); |
081 | Serial .print(client.state()); |
082 | Serial .println( " try again in 5 seconds" ); |
083 | // Wait 5 seconds before retrying |
084 | delay(5000); |
085 | } |
086 | } |
087 | } |
088 |
089 |
090 | void setup () { |
091 | // initialize the LED pin as an output: |
092 | pinMode(ledPin, OUTPUT); |
093 | // initialize the pushbutton pin as an input: |
094 | pinMode(buttonPin, INPUT); |
095 | Serial .begin(115200); |
096 | setup_wifi(); |
097 | client.setServer(mqtt_server, 1883); |
098 | client.setCallback(callback); |
099 | } |
100 |
101 | void loop () { |
102 | // read the state of the pushbutton value: |
103 | buttonState = digitalRead(buttonPin); |
104 |
105 | // check if the pushbutton is pressed. If it is, the buttonState is HIGH: |
106 | if (buttonState == HIGH) { |
107 | // turn LED on: |
108 | digitalWrite(ledPin, LOW); |
109 | } else { |
110 | // turn LED off: |
111 | digitalWrite(ledPin, HIGH); |
112 | } |
113 | if (!client.connected()) { |
114 | reconnect(); |
115 | } |
116 | client. loop (); |
117 |
118 | long now = millis(); |
119 | if (now - lastMsg > 2000) { |
120 | lastMsg = now; |
121 | ++value; |
122 | snprintf (msg, 50, "hello world #%ld" , value); |
123 | Serial .print( "Publish message: " ); |
124 | Serial .println(msg); |
125 | client.publish( "outTopic" , msg); |
126 | } |
127 | } |
что он по вашему должен делать без ВИФИ?
что он по вашему должен делать без ВИФИ?
При нажатии на buttonPin = 15 должен включится ledPin = 5
Или чтото не так?
ну закоментарьте строки 96-98 и 113-126
Допустим во время включения esp нет wifi но нужно чтобы он выполнял некоторые функции, а когда wifi повляется то уже конектица до mqtt брокера
Например система протечки воды не хорошо если вдруг пропадет WIFI и система перестанет работать.
в данном исполнении - не выйдет. функция
setup_wifi()
не отдаст управление пока не появится сеть.переписывать алгоритм.
в данном исполнении - не выйдет. функция
setup_wifi()
не отдаст управление пока не появится сеть.переписывать алгоритм.
А можете дать пример как это сделать?
в смысле, переписать весь код?
в смысле, переписать весь код?
Хм я думал уже гдето подобное было. Ну да ладно будем учится если знаний хватит.
Можете подсказать по каким критерия задавать поиск гугле?
зачем гуголь, прямая ссылка http://arduino.ru/forum/obshchii/pesochnitsa-dlya-vsekh-novichkov#comment-406075