import network
import socket
import time
from machine import ADC, Pin
from web import WEBSITE_TEMPLATE
LM35_PIN = 33
adc = ADC(Pin(LM35_PIN))
# INIT PIN FUNCTION
# Set the attenuation. Adjust as needed based on your voltage range.
# For typical LM35 output (0-1V), ADC.ATTN_11DB is suitable.
adc.atten(ADC.ATTN_11DB)
# Optionally, set the width (resolution) of the ADC reading.
# ADC.WIDTH_12BIT gives values from 0 to 4095.
adc.width(ADC.WIDTH_12BIT)
def get_temperature():
"""Reads the analog value from the LM35 and converts it to Celsius."""
try:
# Read the analog value (0 - 4095 for 12-bit resolution)
adc_value = adc.read()
# Convert the ADC value to voltage.
# The ESP32 ADC has a voltage range of 0V to 3.3V (when ATTN_11DB is used).
# The formula is: voltage = (adc_value / 4095) * 3.3
voltage = (adc_value / 4095) * 3.3
# The LM35 has a linear output of 10mV per degree Celsius.
# So, temperature (in Celsius) = voltage (in mV) / 10
temperature_celsius = (voltage * 1000) / 10
return temperature_celsius
except Exception as e:
print(f"Error reading temperature: {e}")
return None
# INIT WEBSITE CONNECTION
SSID = '-'
PASSWORD = '-'
station = network.WLAN(network.STA_IF) # WiFi station
station.active(True)
station.connect(SSID, PASSWORD) # connect out esp board to our router
while station.isconnected() == False:
pass
print("WIFI Connected")
print(station.ifconfig())
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
if __name__ == "__main__":
while True:
temperature = get_temperature()
if temperature is not None:
print(f"Temperature: {temperature:.2f} °C")
conn, addr = s.accept()
print('Got a connection from %s' % str(addr))
request = conn.recv(1024)
request = str(request)
response = WEBSITE_TEMPLATE % (temperature)
conn.send('HTTP/1.1 200 OK\n')
conn.send('Content-Type: text/html\n')
conn.send('Connection: close\n\n')
conn.sendall(response)
conn.close()
print('Content = %s' % request)
time.sleep(1) # Read temperature every 1 second