/* Fill-in information from Blynk Device Info here */
#define BLYNK_TEMPLATE_ID "TMPL6GR6WxPfe"
#define BLYNK_TEMPLATE_NAME "health monitoring"
#define BLYNK_AUTH_TOKEN "IpFTILarxxtuBscNKKibVi9RyGHnJtlu"

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial


#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>

#define ADC_VREF_mV    3300.0 // in millivolt
#define ADC_RESOLUTION 4096.0
#define PIN_LM35       34 // ESP32 pin GPIO36 (ADC0) connected to LM35



// Define the pulse sensor settings
const int pulsePin = 32; // the pulse sensor pin
const int ledPin = 33; // the LED pin
int pulseValue; // the pulse sensor value
int bpms; // the heart rate in beats per minute

// Your WiFi credentials.
// Set password to "" for open networks.
char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Almor3b";
char pass[] = "espr8026";
BlynkTimer timer;

// MAX30100
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"

#define REPORTING_PERIOD_MS 2000

// Connections : SCL PIN - D1 , SDA PIN - D2 , INT PIN - D0
PulseOximeter pox;
 
float BPM, SpO2;
uint32_t tsLastReport = 0;

void setup()
 {
  // Start the serial communication
  Serial.begin(115200);
 
  // Connect to WiFi
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Connect to Blynk
  Blynk.begin(auth, ssid, pass);
  while (!Blynk.connected()) {
    Serial.println("Connecting to Blynk...");
    delay(1000);
  }
  Serial.println("Connected to Blynk");
  // Set up the pulse sensor
  pinMode(pulsePin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

}

void loop()
 {
  // Read the pulse sensor value
  pulseValue = analogRead(pulsePin);
  Serial.print("Pulse = ");Serial.println(pulseValue);

  float adcVal = analogRead(PIN_LM35);
  // convert the ADC value to voltage in millivolt
  float milliVolt = adcVal * (ADC_VREF_mV / ADC_RESOLUTION);
  // convert the voltage to the temperature in °C
  float tempC = milliVolt / 10;
  // convert the °C to °F
 // float tempF = tempC * 9 / 5 + 32;
  Serial.print("Temperature: ");
  Serial.println(tempC+16);  
  Blynk.virtualWrite(V1, tempC+16);

  // Detect the pulse
  if (pulseValue > 600) {

    digitalWrite(ledPin, HIGH); // turn on the LED
    delay(100); // wait for a short time
    digitalWrite(ledPin, LOW); // turn off the LED
    bpms = 246000 / pulseValue; // calculate the heart rate in beats per minute
    Serial.print("Heart rate: ");
    Serial.print(bpms);
    Serial.println(" BPM");

    // Send the heart rate to Blynk
    Blynk.virtualWrite(V0, bpms);

    //Print the heart rate on the serial monitor
   // String message = "Heart rate: " + String(bpms) + " BPMs";
    //Serial.println(message);

  }

  delay(1000);


  // Run the Blynk loop
  Blynk.run();
}