#include <Wire.h>
#include "MAX30100_PulseOximeter.h"
#include <WiFi.h>
#include <HTTPClient.h>
#define REPORTING_PERIOD_MS 1000
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* serverName = "http://soufiane-arduino.000webhostapp.com/heart/rest_api.php";
const char* infobipApiUrl = "https://xl8n1l.api.infobip.com/sms/2/text/single";
const char* infobipApiKey = "073aa53348374e76e1d348bf747e79c8-78009172-1923-4828-b6c7-bcb8ec314656";
const char* sender = "Arduino Heart";
const char* recipient = "213549660362";
PulseOximeter pox;
uint32_t tsLastReport = 0;
void onBeatDetected() {
Serial.println("Beat!");
}
void setup() {
Serial.begin(9600);
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to WiFi");
Serial.print("Initializing pulse oximeter...");
if (!pox.begin()) {
Serial.println("FAILED");
for(;;);
} else {
Serial.println("SUCCESS");
}
pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA);
pox.setOnBeatDetectedCallback(onBeatDetected);
}
void loop() {
pox.update();
if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
float heartRate = pox.getHeartRate();
float spO2 = pox.getSpO2();
if (WiFi.status() == WL_CONNECTED) {
sendSensorData(heartRate, spO2);
if (heartRate < 50 || heartRate > 100 || spO2 < 90) {
sendSMSAlert(heartRate, spO2);
}
} else {
Serial.println("WiFi not connected");
}
tsLastReport = millis();
}
delay(10000);
}
void sendSensorData(float heartRate, float spO2) {
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String httpRequestData = "heartRate=" + String(heartRate) + "&spO2=" + String(spO2);
int httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.print("Error sending HTTP request. Response code: ");
Serial.println(httpResponseCode);
}
http.end();
}
void sendSMSAlert(float heartRate, float spO2) {
HTTPClient http;
http.begin(infobipApiUrl);
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "App " + String(infobipApiKey));
String message = "Alert! Heart Rate: " + String(heartRate) + " bpm, SpO2: " + String(spO2) + "%";
String jsonPayload = "{\"messages\":[{\"from\":\"" + String(sender) + "\",\"destinations\":[{\"to\":\"" + String(recipient) + "\"}],\"text\":\"" + message + "\"}]}";
int httpResponseCode = http.POST(jsonPayload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("SMS sent successfully.");
Serial.println(response);
} else {
Serial.print("Error sending SMS. Response code: ");
Serial.println(httpResponseCode);
Serial.println(http.errorToString(httpResponseCode).c_str());
}
http.end();
}