ESP8266 Web Server python Home Automation - Black keyhole

welcome to our keyhole, we provide you various knowledge from various sources such as Electric&Electronic, Health, Arduino, IOT, Diy projects, A/l past paper and model paper, Even though you can keep in touch with current technology

ESP8266 Web Server python Home Automation

Share This

In this tutorial I will show you how to make ESP8266 webserver that controls relay using MicroPython firmware. If you didn't see my previous post about how to coonect MicroPython firmware with ESP8266 click here to continue.

Components that I have used

     1. 5v Relay module

     2. A/C bulb

     3. Bulb holder

     4. NodeMCU

     5.Jumper wires



Creating the file on your board

           1. Press the new file button to create a new file

           2. Press the Save file button to save the file in your computer

           3. Then a new window will open and save that file with a name as per your wish. and don't forget to add ".py" extension with that file.

          4. After that, you should see that file with file. if you did't see that file with file press the Reset button of your NodeMCU board and click the link button to un link and again click it for make link. then you should see that file with file. You can check the tutorial  video from You Tube.

  Click here to Download the  Code

 Code Explanation

We need to create our webserver using sockets and the Python socket API. So we need to import the library as follows.

  import usocket as socket
  import socket
we need to import pin class from machine module to able to interact with GPIO pins

from machine import Pin

next we need to import networ library to connect ESP8266 with WIFI-network

import network

 The following lines turn off vendor OS debugging messages:

import esp

Then, we run a garbage collector. A garbage collector is a form of automatic memory management. This is a way to reclaim memory occupied by objects that are no longer in used by the program. This is useful to save space in the flash memory.

import gc

next we need to put the network credentials

ssid = 'your network name'
password = 'your network password'

set ESP8266 as a WIFI-station

station = network.WLAN(network.STA_IF)

 After that, activate the station:

ESP8266 connects to your router using the SSID and password defined earlier:

station.connect(ssid, password)

The following statement ensures that the code doesn’t proceed while the ESP is not connected to your network.

while station.isconnected() == False:

After successful, print network parameters
print('Connection successful')

here we have created GPIO output:

relay = Pin(5, Pin.OUT)
  This function returns a variable called html that contains the HTML text to build the web page

 def web_page():

The web page displays the current GPIO state.

if relay.value() == 1:
    relay_state = ''
    relay_state = 'checked'

html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1">
  body{font-family:Arial; text-align: center; margin: 0px auto; padding-top:30px;}
  </style><script>function toggleCheckbox(element) { var xhr = new XMLHttpRequest(); 
if(element.checked){"GET", "/?relay=on", true); }
  else {"GET", "/?relay=off", true); } xhr.send(); }</script></head><body>
  <h1>ESP Relay Web Server</h1>
  <a href="">
Subcribe Black keyhole</a></h2>
  <a href="">Visit my web page for more project</a></h3>
  <label class="switch"><input type="checkbox" onchange="toggleCheckbox(this)" %s><span
  </span></label></body></html>""" % (relay_state)
  return html

After creating the HTML to build the web page, we need to create a listening socket to listen for incoming requests and send the HTML text in response.

To create a socket:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Next, bind the socket to an address


The next line enables the server to accept connections; it makes a “listening” socket. The argument specifies the maximum number of queued connections. The maximum is 5.


In the while loop is where we listen for requests and send responses. When a client connects, the server calls the accept() method to accept the connection. When a client connects, it saves a new socket object to accept and send data on the conn variable, and saves the client address to connect to the server on the addr variable.

while True:
    if gc.mem_free() < 102000:
    conn, addr = s.accept()
    print('Got a connection from %s' % str(addr))
    request = conn.recv(1024)
    request = str(request)
    print('Content = %s' % request)
    relay_on = request.find('/?relay=on')
    relay_off = request.find('/?relay=off')
    if relay_on == 6:
      print('RELAY ON')
    if relay_off == 6:
      print('RELAY OFF')
    response = web_page()
    conn.send('HTTP/1.1 200 OK\n')
    conn.send('Content-Type: text/html\n')
    conn.send('Connection: close\n\n')
  except OSError as e:
    print('Connection closed')

    Finaly everything is done, Upload the and file to ESP8266. You should see that your wifi is established and it has been printing your IP address. copy that IP address and past it in your browser. then should see the effect on your web page and Play with that button😉. Hope You have like this post also keep share this post between your friends or family members who aspiring to make these kind of stuffs. and don't forget to press the subscribe button for my You Tube channel that I had provided above in this article.😊


  1. Bro ur awesome ... Expecting more contents from u ... Keep rocking🙌

    1. Thank you , keep in touch with my YouTube channel also

  2. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. Take me to another useless website

  3. I don t have the time at the moment to fully read your site but I have bookmarked it and also add your RSS feeds. I will be back in a day or two. thanks for a great site. SEO Guadalajara

  4. You can consider automation achieving repeatable errands without human intercession, and arrangement as the way toward hanging together a progression of these assignments to achieve a cycle or work process. AGV solution

  5. Micropython
    Is that can support for Arduino Uno


business queries