#include <WiFi.h>
#include <ThingSpeak.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
WiFiClient client;
unsigned long myChannelNumber = 2246621;
const char * myWriteAPIKey = "MHL3L4SC8J098ZSU";
int sensorPin = 34; // select the input pin for the LM35 sensor
int digitalValue; // variable to store the value coming from the sensor
float analogVoltage;
float temp;
int statusCode;
void setup() {
Serial.begin(115200);
ThingSpeak.begin(client);
WiFi.mode(WIFI_STA);
pinMode(sensorPin, INPUT);
}
void loop() {
connectToCloud();
computeData();
writeData();
delay(1000);
}
void connectToCloud(){
if(WiFi.status() != WL_CONNECTED)
{
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED)
{
WiFi.begin(ssid, pass);
for(int i=0;i<5;i++)
{
Serial.print(".");
delay(1000);
}
}
Serial.println("\nConnected.");
}
}
void computeData(){
// Get the analog value from lm35 sensor and convert that value into digital value using ADC converter
digitalValue = analogRead(sensorPin);
Serial.print("digital value = ");
Serial.print(digitalValue); //print digital value on serial monitor
//convert digital value to analog voltage
//Analog voltage = digital value * (Vref/2^n – 1)
//Here Vref is 5V that we connected to lm35 sensor.If we connect 3.3V to sensor then Vref is 3.3V
//Here we use 10 bit ADC so n=10 bits so the values ranges from 0 to 1023
analogVoltage = (digitalValue * 3.3)/4095.00;
Serial.print(" analog voltage = ");
Serial.println(analogVoltage);
//To convert analog voltage to temperature in Celcius, we multiply by 100
//because the LM35 output is 0.010V per degree. ie 1 degree =0.010V or 1V=100 degree
temp=analogVoltage * 100;
Serial.print("temperature = ");
Serial.println(temp);
delay(1000);
}
void writeData(){
ThingSpeak.setField(1, temp);
statusCode = ThingSpeak.writeFields(myChannelNumber,myWriteAPIKey);
if(statusCode == 200) //successful writing code
Serial.println("Channel update successful.");
else
Serial.println("Problem Writing data. HTTP error code :" + String(statusCode));
delay(15000); // data to be uploaded every 15secs
}