#include <Wire.h>
const int buttonPin = 26;
const int ledPin = 27;
const int tempSensorPin = 35;
// Parameters for the Voltage Divider
const float Vref = 3.3; // ESP32 ADC reference voltage
const int ADC_Max = 4095; // 12-bit ADC resolution
const int R_fixed = 10000; // Fixed resistor value (10kΩ)
bool buttonState = false; // Variable to hold the button state
void setup() {
// Initialize serial communication
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // Set LED pin as output
pinMode(buttonPin, INPUT_PULLUP); // Set button pin as input with internal pull-up resistor
}
void loop() {
bool currentButtonState = digitalRead(buttonPin) == HIGH;
if (currentButtonState != buttonState) {
if (currentButtonState) {
digitalWrite(ledPin, HIGH);
Serial.println("Button pressed");
} else {
digitalWrite(ledPin, LOW);
Serial.println("Button released");
}
buttonState = currentButtonState; // Update button state
}
// Read temperature sensor value (analog voltage) from the temperature sensor and store it in tempValue
int tempValue = analogRead(tempSensorPin);
// Avoid division by zero by checking if Vout is close to Vref
if (tempValue == 0 || tempValue == ADC_Max) { // If tempValue is 0 or equals ADC_Max (typically 1023 for a 10-bit ADC)
Serial.println("Invalid sensor reading."); // If an invalid reading is detected, it prints "Invalid sensor reading"
} else {
// Convert analog value to voltage
float Vout = tempValue * (Vref / ADC_Max); //Vout is computed by scaling tempValue to the reference voltage (Vref)
// Calculate the NTC resistance using the Voltage Divider formula
float R_NTC = (R_fixed * (Vref - Vout)) / Vout;
// Calculate Temperature using the Beta parameter equation
float Beta = 3950.0; // Beta parameter for the NTC thermistor
float T0 = 298.15; // Reference temperature (25°C in Kelvin)
float R0 = 10000.0; // NTC resistance at 25°C (10kΩ)
float temperatureK = (Beta * T0) / (Beta + (T0 * log(R_NTC / R0))); // Beta Parameter eauatioq
float temperatureC = temperatureK - 273.15; Converting to Celsius
// Print the temperature in Celsius to Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println(" °C");
}
delay(1000); // Delay 1 s before next reading
}