Sunday, October 14, 2018

Remote Controlling LED Using NodeMCU (ESP8266) Board

Been tinkering around with the NodeMCU (ESP8266) more after I published the original tutorial about Getting Started To Use NodeMCU (ESP8266) With Arduino IDE. Before reading this further, I would recommend you go through it to make sure the board is already setup on your PC with the Arduino IDE (if not already).

I came to notice its quite easy to jump into the interesting world of IoT with this particular board. Since the board has on-board WiFi chip from Espressif, you can control just about anything you want remotely.

I have shared below a simplest possible example of how you can control state of an LED connected to the NodeMCU board remotely (from your phone). Let's start by putting connecting the LED as shown below:


Connect the board to the PC using a/the Micro-USB cable. Go to Tools, Board, select NodeMCU 0.9 (ESP-12 Module). Go to Tools, Port & select COMX port on which the board is connected to PC.

Replace below example code into your Sketch in Arduino IDE. Let me describe what the above code actually does. At startup, it tries to and waits for a successful connection with the SSID & password you have specified. Once connected, it then starts and listens for incoming connections over port 80 (HTTP default). This is what it does in the setup stage.

Now in the main loop, it waits for an incoming HTTP client connection which if found, the checks if the request method is GET and URL contains a specific command like /state/OFF or /state/ON and then reacts accordingly i.e., put the specified pin LOW or HIGH which in turn, sets the LED off or on respectively. In either case, it also responds with a HTML page that shows current state of LED and a link to change the state.

To access the HTML page, you need to be connected to the same WiFi network as the NodeMCU (ESP8266) board and browse the board's local IP address in your favorite browser. To know the IP address easily, the above code writes some useful messages over the serial port it is connected to which you can see by open the Serial Monitor from Tools, Serial Monitor from the Arduino IDE.

No comments:

Post a Comment