Skip to content

Instantly share code, notes, and snippets.

Created August 19, 2023 20:30
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save barzik/727934d3182a99379ae7da844c6549c3 to your computer and use it in GitHub Desktop.
MQ-135 and ESP32 web server
import network
import socket
import machine
import ujson
import utime
def connect_to_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
if not wlan.isconnected():
print('Connecting to WiFi...')
wlan.connect(ssid, password)
while not wlan.isconnected():
print('Network config:', wlan.ifconfig())
def read_mq135():
adc = machine.ADC(machine.Pin(36))
adc.atten(machine.ADC.ATTN_11DB) # Set 11dB attenuation for readings up to approx. 3.3V
def handle_request(cl_file):
request = cl_file.readline().decode('utf-8')
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
if "GET /sensors" in request:
mq135_value = read_mq135()
data = {
"id": "mq-135",
"label": "Gas sensor",
"value": mq135_value
response = ujson.dumps(data)
headers = 'HTTP/1.0 200 OK\r\nContent-type: application/json\r\nAccess-Control-Allow-Origin: *\r\n\r\n'
return headers + response
elif "GET /" in request:
html = """
<title>MQ-135 Sensor Data</title>
function fetchData() {
.then(response => response.json())
.then(data => {
document.getElementById("sensorData").innerText = JSON.stringify(data, null, 4);
document.getElementById("sensorMeter").value = data.value;
setInterval(fetchData, 5000); // Fetch data every 5 seconds
<body onload="fetchData()">
<h1>MQ-135 Sensor Data:</h1>
<meter id="sensorMeter" min="0" max="4000" low="50" high="500" optimum="200"></meter>
<pre id="sensorData"></pre>
headers = 'HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n'
return headers + html
return 'HTTP/1.0 404 Not Found\r\nContent-type: text/plain\r\n\r\n404: Not Found'
def start_web_server():
addr = socket.getaddrinfo('', 80)[0][-1]
s = socket.socket()
print('Listening on', addr)
while True:
cl, addr = s.accept()
print('Client connected from', addr)
cl_file = cl.makefile('rwb', 0)
response = handle_request(cl_file)
utime.sleep(0.5) # Add a small delay
connect_to_wifi(SSID, PASSWORD)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment