#define ntc_pin 4         // Pin, to which the voltage divider is connected
#define vd_power_pin 2        // 3.3V for the voltage divider
#define nominal_resistance 10000       //Nominal resistance at 25⁰C
#define nominal_temeprature 25   // temperature for nominal resistance (almost always 25⁰ C)
#define samplingrate 5    // Number of samples
#define beta 3950  // The beta coefficient or the B value of the thermistor (usually 3000-4000) check the datasheet for the accurate value.
#define Rref 10000   //Value of  resistor used for the voltage divider
#define led_channel 0 // channel that controls PWM signal for analog write purpose
int samples = 0;   //variable to store the samples


void setup() {
    // configure LED PWM functionalitites
  ledcSetup(led_channel, 5000, 8); //led_channel, frequency, width
  // attach the channel to the GPIO to be controlled
  ledcAttachPin(vd_power_pin, led_channel); //pin, led_channel
  Serial.begin(9600);   //initialize serial communication at a baud rate of 9600
}

void loop() {
  uint8_t i;
  float average;
  float ntc_res;
  samples = 0;
    // take voltage readings from the voltage divider
  ledcWrite(led_channel, 255); //width is 8, so max duty cycle is 255. Practically, turns on.
    for (i = 0; i < samplingrate; i++) {
    samples += analogRead(ntc_pin);
    delay(10);
    }
  ledcWrite(led_channel, 0); //Practically, turns off.
  average = 0;
  average = samples / samplingrate;
  Serial.print("ADC readings ");
  Serial.println(average);
  // Calculate NTC resistance - implement voltage divider and extract ntc_res
  ntc_res = 0;
  ntc_res = (Rref * average) / (4095 - average);  //4095 for esp32, 1023 for arduino
  Serial.print("Thermistor resistance ");
  Serial.println(ntc_res);
  float temperature;
  temperature = ntc_res / nominal_resistance;     // (R/Ro)
  temperature = log(temperature);                  // ln(R/Ro)
  temperature /= beta;                   // 1/B * ln(R/Ro)
  temperature += 1.0 / (nominal_temeprature + 273.15); // + (1/To)
  temperature = 1.0 / temperature;                 // Invert
  temperature -= 273.15;                         // convert absolute temp to C
  Serial.print("Temperature ");
  Serial.print(temperature);
  Serial.println(" *C");
  delay(1000);
}