Skip to content

Instantly share code, notes, and snippets.

@barzik
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
SSID = 'NAME'
PASSWORD = 'PASSWORD'
def connect_to_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to WiFi...')
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
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
return adc.read()
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':
break
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 = """
<html>
<head>
<title>MQ-135 Sensor Data</title>
<script>
function fetchData() {
fetch('/sensors')
.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
</script>
</head>
<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>
</body>
</html>
"""
headers = 'HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n'
return headers + html
else:
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('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
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)
cl.send(response)
utime.sleep(0.5) # Add a small delay
cl.close()
connect_to_wifi(SSID, PASSWORD)
start_web_server()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment