Skip to content

Instantly share code, notes, and snippets.

@sdrshnptl
Last active September 16, 2017 12:38
Show Gist options
  • Save sdrshnptl/4298f589d9bc6e87c59ffce3e779541d to your computer and use it in GitHub Desktop.
Save sdrshnptl/4298f589d9bc6e87c59ffce3e779541d to your computer and use it in GitHub Desktop.
Toggle LED from NodeMCU using WIFI.
/*
open browser and hit
192.168.1.167/?1 to ON
192.168.1.167/?0 to OFF
*/
#include <ESP8266WiFi.h>
const char* ssid = "Your_WiFi_SSID";
const char* password = "Your_WiFi_Password";
const int ledPin = 2;
WiFiServer server(1337);
void printWiFiStatus();
void setup(void) {
Serial.begin(115200);
WiFi.begin(ssid, password);
IPAddress ip(192, 168, 1, 167);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
WiFi.config(ip, gateway, subnet);
// Configure GPIO2 as OUTPUT.
pinMode(ledPin, OUTPUT);
// Start TCP server.
server.begin();
}
void loop(void) {
// Check if module is still connected to WiFi.
if (WiFi.status() != WL_CONNECTED)
{
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
// Print the new IP to Serial.
printWiFiStatus();
}
WiFiClient client = server.available();
if (client)
{
Serial.println("Client connected.");
while (client.connected())
{
if (client.available())
{
char command = client.read();
if (command == '0')
{
digitalWrite(ledPin, HIGH); Serial.println("LED is now on."); client.stop();
}
else if (command == '1')
{
digitalWrite(ledPin, LOW); Serial.println("LED is now off."); client.stop();
}
}
}
Serial.println("Client disconnected.");
//client.stop();
}
}
void printWiFiStatus() {
Serial.println("");
Serial.print("Connected to "); Serial.println(ssid);
Serial.print("IP address: "); Serial.println(WiFi.localIP());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment