Sei sulla pagina 1di 3

Using NodeMCU to control an LED in LAN network

Requirements:
Arduino IDE with an esp8266 board community.
Pc with putty software installed.
NodeMCU.
led
connecting wires/cables

Process:

Here we connect the NodeMcu to a wifi network and a mobile or a PC is also connected
to the same wifi network. When NodeMCU is connected to Wifi using DHCP an IP
address is assigned to the NodeMCU by the router and this will be printed on the serial
monitor.

NodeMCU listens to incoming data on a port specified (80 in a program below) until a
special character ‘#’ has occurred or until the timeout reached. If there is any String that
contains ‘ON’/’OFF’ cmd it will turn ON/OFF the LED.

Now in pc open putty application and select connection type to telnet and enter the IP
address and port number (check in code) and click open. The connection is established
and you can send and receive data from NodeMCU.

Type ‘ON#’ and Hit enter. You will see the LED glowing. And also you will see the
status of the led on your putty screen.

CODE:
#include <ESP8266WiFi.h> // librery for wifi
const char* ssid = "Your WiFI network name ";
const char* password = "ypur WiFi network password";
int ledPin = D4; // D4 (GPIO4)
WiFiServer server(80); //Nodemcu listining on port 80
void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print(WiFi.localIP());
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String request = client.readStringUntil('#');
Serial.println(request);
client.flush();
// Match the request
int value = LOW;
if (request.indexOf("ON") >= 0) {
digitalWrite(ledPin, HIGH);
value = HIGH;
}
else if (request.indexOf("OFF") >= 0) // indenOf returns -1 if there is no
such word in request string
{
digitalWrite(ledPin, LOW);
value = LOW;
}
client.print("Led pin is now: ");
if(value == HIGH) {
client.print("On");
} else {
client.print("Off");
}
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}

Potrebbero piacerti anche