Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ryuzakyl
Created March 1, 2020 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryuzakyl/50784f459229d5e1da3a02fde4a85dad to your computer and use it in GitHub Desktop.
Save ryuzakyl/50784f459229d5e1da3a02fde4a85dad to your computer and use it in GitHub Desktop.
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#define WIFI_SSID "<ssid>"
#define WIFI_PASSWORD "<password>"
// ---------------------------------------------------------------
// LM35 temperature sensor is connected to GPIO 33 (Analog ADC1_5)
const int lm35InputPin = 33;
const int esp32BitsPrecision = 10;
const float esp32MaxVolts = 1.5;
// ---------------------------------------------------------------
float analog_to_volts(float value, float max_volts, int n_bits) {
// compute analog resolution
float resolution = pow(2, n_bits) - 1;
// transform value in [0, 2^n_bits] interval, to [0, max_volts] interval
float volts = (value / resolution) * max_volts;
return volts;
}
float volts_to_celcius(float volts) {
// for LM35: divide by 10 mV (i.e., multiply by 100)
return 100.0 * volts;
}
float analog_to_celcius(float value) {
// converts analog value to volts
float volts = analog_to_volts(value, esp32MaxVolts, esp32BitsPrecision);
// converts volts value to celcius
float celcius = volts_to_celcius(volts);
return celcius;
}
float celcius_to_farenheit(float celcius) {
float fahrenheit;
/* celsius to fahrenheit conversion formula */
fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
float get_lm35_temperature() {
// read analog value from input GPIO
int analog_value = analogRead(lm35InputPin);
// convert analog input to temperature (in celcius)
float t_celcius = analog_to_celcius(analog_value);
return t_celcius;
}
// ---------------------------------------------------------------
AsyncWebServer server(80);
// this sets the ground pin to LOW and the input voltage pin to high
void setup() {
// using 9600 baud rate
Serial.begin(9600);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println(WiFi.localIP());
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
// get current LM35 temperature
float t_celcius = get_lm35_temperature();
float t_farenheit = celcius_to_farenheit(t_celcius);
Serial.print(t_celcius);
Serial.println(" C");
Serial.println("");
// formatting the json content to be sent
char json_content[100];
sprintf(
json_content,
"{ msg: 'The current temperature is %.2f celcius degrees'}\r\n",
t_celcius
);
request->send(200, "text/plain", json_content);
});
server.begin();
}
// ---------------------------------------------------------------
// main loop
void loop() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment