ESP32 – HTTP Web Server – HTML – CSS – Simple Counter As the Subject of “Visitors and Parking Lot Occupancy Counter”.

by PugazhM in Circuits > Wireless

6736 Views, 2 Favorites, 0 Comments

ESP32 – HTTP Web Server – HTML – CSS – Simple Counter As the Subject of “Visitors and Parking Lot Occupancy Counter”.

Circuit_V01.jpeg

This experimentation is about creating an ESP32 (Station Mode), stand-alone HTTP web server and processing / populating incremented counter value at regular interval on HTTP client interface. The web page is developed by using HTML - CSS, as the subject of “Visitors and Parking Lot Occupancy Counter”.

Visit the "VESZLE - The Art Of Electronics" you tube channel for further information and videos.

https://www.youtube.com/channel/UCY4mekPLfeFinbQHp...

ESP32 – HTTP Web Server HTML – CSS – Simple Counter You tube Video

Abstract

The ESP32 is constructed with Xtensa dual-core (or single-core) 32-bit RISC architecture, operating at 160MHz or 240MHz, with up to 520KiB internal SRAM, integrated with Wi-Fi (802.11 b/g/n) and Bluetooth (v4.2 BR/EDR and BLE (shares the radio with Wi-Fi). The ESP32 provides peripheral interfaces like ADC, DAC, touch sensors, SPI, I2C, I2S, UART, CAN, PWM etc. The ESP32 supports all IEEE 802.11 standard security feature (WFA, WPA/WPA2 and WAPI), and cryptographic hardware acceleration (AES, RSA, SHA-2, ECC, RNG etc). It supports wake up from GPIO / Sensor interrupts, timers and 5uA deep sleep current consumption.

ESP32 Wi-Fi interface provides

· Station Mode

· Soft Access Point Mode

· Both at the same time, (Station + Access Point)

This experimentation is about creating an ESP32 (Station Mode), stand-alone HTTP web server and processing / populating incremented counter value at regular interval on HTTP client interface. The web page is developed by using HTML - CSS, as the subject of “Visitors and Parking Lot Occupancy Counter”

Reference

“ESP32 – Getting Started MicroPython -- on Board Blink LED” Instruct-able / You-tube by PugazhM

https://www.instructables.com/ESP32-Getting-Start...

MicroPython Network TCP sockets

https://docs.micropython.org/en/latest/esp8266/tu...

Components

ESP32.jpg

ESP32 Development Board

Micro USB Cable

Wi-Fi Router

Tablet or Laptop

Schematic

Circuit_V01.jpeg

Connect the ESP32 board to USB port of the PC / Laptop as illustrated.

The ESP32 development board provides on board LED, which is connected to GPIO2.

It has inbuilt Wi-Fi 802.11 b/g/n module / stack, can be configured as Wi-Fi station mode.

The Wi-Fi router provides the wireless connectivity between Wi-Fi client to Wi-Fi station and then to external internet world, can form a Local Area Network (LAN)

The Google Brower running on Laptop or Tablet, connected to a Wi-Fi network act as a Wi-Fi client.

ESP32 HTTP Web Server

WebServerCommunication_V01.jpeg

The ESP32 web server is representing the ESP32 hardware and firmware

ESP32 web server hardware stores / provides the web server software and needed files (example, HTML page, CSS stylesheet, Java Scripts, fonts, video, audio, images etc.) to “web client”, on request.

An HTTP server is a software that understands URLs (web addresses) and HTTP protocol. The web browser uses HTTP protocol to view webpages.

An HTTP server can be accessed through the domain name or IP address. HTTP server stores, and delivers the content of these hosted websites to the end user's device (Desktop PC, laptop, tablet, mobile phone etc.)

A “Static web server” sends, hosted HTML web pages / files, as is to “web client”.

A “Dynamic web server” updates the hosted HTML web pages / files, and then sends to “web client”.

Usually the ESP32 is a “dynamic web server” and it updates the HTML web pages / files with real time connected sensor data (example temperature, humidity, pressure, key event, GPIO, ADC, DAC, system parameters etc.) and then sends it to “web client”

A “web client” is nothing but a web browser (Google Chrome, Microsoft Edge, Firefox, Safari, Internet Explorer, Opera etc.)

A web server provides support for Hyper Text Transfer Protocol (HTTP), is a “Textual” (all commands are plain human readable text), “State less” (neither the server nor the client remembers previous communications) protocol.

Generally, “web clients” make HTTP request to “web server”, and then “web server” responds to the request.

A “web server” can also populate data into “web client” via sever push mechanism.

The “web server” must answer every HTTP request, at least with error message (404 error).

Cascading Style Sheet (CSS)

Cascading Style Sheet (CSS) is a stylesheet language used for describing the HTML presentation, those can be displayed on screen, paper or in other media.

CSS is designed to enable the separation of presentation and content, including layout, colors, and fonts.

CSS describes how elements should be rendered on screen, on paper, in speech, or on other media

CSS uses a number of simple English keywords to specify the names of various style properties.

CSS is among the core languages of the open web and is standardized across Web browsers according to W3C specifications

The CSS structure consists of list of rules. Each rule or ruleset consists of one or more Selectors, Declarations, Properties and Property Values

ESP32 HTTP Web Server System Overview

SYStemOverView_V01.jpeg

A simple counter implementation is deployed on “web-server” as illustrated above

ESP32 act as “web-server” and Google Chrome running on a laptop act as a “web-client”

timer_1 is initiated and toggles the on-board LED at regular interval, via “BlinkLED()”call back function

timer_2 is initiated and updates the visitor_count, bi_cycle_count, motor_cycle_count and car_count variables at a regular interval, via “UpdateCounter()”call back function, validates the counters for upper limit. If counter value exceeds upper limit, then the python program resets the counters to initial value.

Whenever the “web-client” requests data via “HTTP Client Request” method, then the “web-server”, will construct the complete web page with updated values and then sends back to “web-client” via “HTTP Server Response” method.

The “web-client” refreshes the “web page” at 5 seconds interval.

ESP32 HTTP Web Server GUI

WebServer_GUI.jpg

A simple counter deployment on a “web-server”, with “Visitors and Parking Lot Occupancy Counter” as theme is illustrated above.

Google fonts provides fonts and material icons, those can used for constructing a web page.

Google icons are designed to be simple, modern, friendly, and sometimes quirky. Each icon is reduced to its minimal form, expressing essential characteristics.

The style sheet uses “https://fonts.googleapis.com/icon?family=Material+Icons”, for constructing a web page.

The web page is divided into equal 4 vertical columns.

A box type drawing which uses icon and fonts for populating the needed information is used for constructing the end user information / GUI.

ESP32 Web Server MicroPython Program

TaskEvent_V01.jpeg

The timer_one is initialized and callbacks the “BlinkLED” functionality for toggling on board LED at 200mS duration. (frequency = 5)

The timer_two is initialized and callbacks the “UpdateCounter” functionality for updating the system variables at 2S duration. (frequency = 0.5)

The MicroPython program, first creates and configures the ESP32 as Station Mode, and then connects to the Wi-Fi router using user provided SSID and Password

§ ssid = 'WiFi Router SSID'

§ password = 'WiFi Router Password'

§ station = network.WLAN(network.STA_IF)

§ station.active(True)

§ station.connect(ssid, password)

§ # Wait until the ESP32 get connected to the router

§ while station.isconnected() == False:

§ pass

The MicroPython program creates a stream TCP web-server socket and then binds it into HTTP port 80. Listens from maximum five web clients

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

§ s.bind(('', 80))

§ s.listen(5)

The system checks the web-client request at endless while loop.

Whenever the web-server receives the “HTTP Client request”, then it reconstruct the web page and sends the “HTTP Server Response” to web-client.

'''
 Demonstrates HTML and CSS ESP32 Web server implementation
 Simple Counter usage as "Visitors and Parking Lot Occupancy Counter
 Simple counter example for counting visitors and parking occupancy at regular interval
 ESP32 Web server count event happens at 2 seconds interval, and validates / resets against the MAX count
 Web client request at 5 Seconds interval.
    
 * The ESP32 onboard LED pin connections
 * On board LED pin to GPI2
 
 Name:- M.Pugazhendi
 Date:-  04thOct2021
 Version:- V0.1
 e-mail:- muthuswamy.pugazhendi@gmail.com
'''
from machine import Pin, Timer
import network
import time
import socket
import esp

esp.osdebug(None)

import gc
gc.collect()

ssid = 'WiFi Router SSD'
password = 'WiFi Router Password'

station = network.WLAN(network.STA_IF) # Congigure WLAN as station
station.active(True) # Activate the Station
station.connect(ssid, password) # Connect to the router using SSID and password

# Wait until the ESP32 get connected to the router
while station.isconnected() == False:
  pass

print('Connection successful')
print(station.ifconfig())

led = Pin(2, Pin.OUT)
timer_one = Timer(0) # Initialize timer_one. Used for toggling the on-board LED
timer_two = Timer(1) # Initialize timer_two. Used for updating counter variables

toggle = 1
visitor_count = 0
bi_cycle_count = 0
motor_cycle_count = 0
car_count = 0

def UpdateCounter(timer_two):
    global visitor_count
    global bi_cycle_count
    global motor_cycle_count
    global car_count

    visitor_count = visitor_count + 1
    
    if visitor_count > 800:
        visitor_count = 1
    
    bi_cycle_count = int(visitor_count / 3)
    
    if bi_cycle_count > 250:
        bi_cycle_count = 250
    
    motor_cycle_count = int(visitor_count / 5)
    car_count = int(visitor_count / 16)  

def BlinkLED(timer_one):
    global toggle
    if toggle == 1:
        led.value(0)
        toggle = 0
    else:
        led.value(1)
        toggle = 1

def ConstructWebPage():
  html = """<html>   
<head>   
    <meta http-equiv="refresh" content="5">
    <!-- add the following google font / icon to the webpage -->  
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
     
<style>   
    * {   
        box-sizing: border-box;   
    }
    
    body {  
    background-color: #a255ff;  
    background-size: cover;  
     }
      
    .column {   
        /* box toward left of the window screen */  
        float: left;   
        /*divide each counter box in equal size*/  
        /* 4 counters of 25% of screen size*/  
        width: 25%;   
        /*spacing between each box */  
        padding: 4px;   
    }   
          
    .row {   
        /* Specify the margin for the row class */  
        margin: 3px;  
    }   
          
    /* Style the class named block*/  
    .block {   
        padding: 10px;   
        text-align: center;   
        background-color: #0100ca;   
        color: white;   
        }   
   /* Style the class named block*/  
    .block2 {   
        padding: 10px;   
        text-align: center;   
        background-color: #5efc82;   
        color: white;   
        }             
    .fa {   
        font-size: 50px;   
    }
    </style>   
      
</head>

<body>   
<center>  
    <h1 style="color:black"> ESP32 HTTP Web Server </h1>
    <h1 style="color:black"> Simple Counter </h1>
    <h3> HTML and CSS ESP32 Web server implementation </h3>   
    <h3> Visitors and Parking Lot Occupancy Counter  </h3>
    <p style="color:white"> Simple counter example for counting visitors and parking occupancy at regular interval</p>
    <p style="color:white"> ESP32 Web server count event happens at 2 seconds interval, and validates / resets against the MAX count</p>
    <p style="color:white"> Web client update at 5 Seconds interval </p>
    
     <div class="row">   
    <div class="column">   
        <div class="block">
        <h3> Visitor Count </h3>
            <!-- Add visitor icon -->  
        <p><i class="material-icons" style="font-size:90px;">accessibility</i></p>   
        <h1>"""+str(visitor_count)+"""</h1>   
        </div>
        <div class="block2">  
            <h1 style="color:black"> 800 </h1>   
            <h3 style="color:black"> Visitor Max Limit </h3>   
        </div>
    </div>  
          
    <div class="column">   
        <div class="block"> 
        <h3> Bi Cycle Count </h3>
                <!-- Add bi cycle  icon -->  
        <p><i class="material-icons" style="font-size:90px;">pedal_bike</i></p>   
        <h1>"""+str(bi_cycle_count)+"""</h1>   
        </div>
        <div class="block2">  
            <h1 style="color:black"> 250 </h1>   
            <h3 style="color:black"> Bi Cycle Max Limit </h3>   
        </div>
    </div>   
          
    <div class="column">   
        <div class="block">
        <h3> Motor Bike Count </h3>
            <!-- Add motor bike icon -->  
        <p><i class="material-icons" style="font-size:90px;">two_wheeler</i></p>   
        <h1>"""+str(motor_cycle_count)+"""</h1>    
        </div>
        <div class="block2">  
            <h1 style="color:black"> 160 </h1>   
            <h3 style="color:black"> Motor Bike Max Limit </h3>   
        </div>
    </div>   
  
    <div class="column">   
        <div class="block">
        <h3> Car Count </h3>
            <!-- Add car icon -->  
        <p><i class="material-icons" style="font-size:90px;color:white;">directions_car</i></p>   
        <h1>"""+str(car_count)+"""</h1>   
        </div>
        <div class="block2">  
            <h1 style="color:black"> 50 </h1>   
            <h3 style="color:black"> Car Max Limit </h3>   
        </div>
    </div>   
    </div>
</center>  
</body>   
</html> 
"""
  return html

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create Stram TCP web-server socket
s.bind(('', 80)) # Assign and bind port 80 for HTTP web-server socket
s.listen(5) # Configure for listening maximum 5 web-clients

# Timer one initialization for on board blinking LED at 200mS interval
timer_one.init(freq=5, mode=Timer.PERIODIC, callback=BlinkLED)

# Timer two initialization for updating the counter variables at 500mS interval
timer_two.init(freq=2, mode=Timer.PERIODIC, callback=UpdateCounter)

while True:
    try:
        if gc.mem_free() < 102000:
          gc.collect()
        conn, addr = s.accept() # Call accpept method for collecting the client address
        conn.settimeout(3.0)
        print('Got a connection from %s' % str(addr)) # Print the client address
        request = conn.recv(1024) # Collect client request
        conn.settimeout(None)
        request = str(request)
        print('Content = %s' % request) # Print the web-client request
        response = ConstructWebPage() # Construct the web page      
        conn.send('HTTP/1.1 200 OK\n') # Send the web-server response to web-client
        conn.send('Content-Type: text/html\n')
        conn.send('Connection: close\n\n')
        conn.sendall(response)
        
        # Clsoe connection
        conn.close()
        
    except OSError as e:
        conn.close()
        print('Connection closed')


Conclusion

C1.jpg

The project is successfully completed with ESP32 development board, Wi-Fi router and Tablet.

The web-server provides HTML response with visitor, bi-cycle, motor bike and car counts, at regular interval to web-client running on tablet and laptop google chrome, and updates the end user GUI.

Results and Video Links

Please Visit You Tube for the Videos:,

Visit the "VESZLE - The Art Of Electronics" you tube channel for further information and videos. https://www.youtube.com/channel/UCY4mekPLfeFinbQH...

ESP32 – HTTP Web Server – HTML – CSS – Simple Counter You tube Video