// IoT-based Heart Rate Monitoring System for ThingSpeak
// Adapted from the soil moisture irrigation system
// ThingSpeak channel: https://thingspeak.com/channels/3034579
#include <WiFi.h>
#include "ThingSpeak.h"
const int PULSE_PIN = 34;
const int ALERT_PIN = 19;
int BPM_THRESHOLD_LOW = 60; // Set low BPM threshold for alert
int BPM_THRESHOLD_HIGH = 100; // Set high BPM threshold for alert
bool ALERT_STATUS = false;
char* WIFI_NAME = "Wokwi-GUEST";
char* WIFI_PASSWORD = "";
int myChannelNumber = 3034579; // ThingSpeak channel ID
char* myApiKey = "RMLHD5UVCICTEO83"; // ThingSpeak write API key
WiFiClient client;
void setup()
{
Serial.begin(115200);
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
Serial.println("Connecting...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Wi-Fi connected");
Serial.println("Local IP: " + String(WiFi.localIP()));
Serial.println("-------------");
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
pinMode(ALERT_PIN, OUTPUT);
}
void loop()
{
// Sample for 10 seconds to calculate BPM
unsigned long startTime = millis();
int beatCount = 0;
int threshold = 2457; // Threshold for detecting rising edge (adjusted for signal range ~0.2-0.8 -> analog 819-3276)
int previous = analogRead(PULSE_PIN);
while (millis() - startTime < 10000) {
int current = analogRead(PULSE_PIN);
if (current > threshold && previous <= threshold) {
beatCount++;
}
previous = current;
delay(2); // Sample every 2ms
}
int bpm = beatCount * 6; // Since 10 seconds, multiply by 6 for BPM
// Alert threshold check
if (bpm < BPM_THRESHOLD_LOW || bpm > BPM_THRESHOLD_HIGH) {
ALERT_STATUS = true;
digitalWrite(ALERT_PIN, HIGH); // Turn on alert LED
} else {
ALERT_STATUS = false;
digitalWrite(ALERT_PIN, LOW); // Turn off alert LED
}
// Print status
Serial.print("BPM: ");
Serial.print(bpm);
Serial.println("");
Serial.print("Alert: ");
Serial.println(ALERT_STATUS ? "on" : "off");
// Send data to ThingSpeak
ThingSpeak.setField(1, bpm);
ThingSpeak.setField(2, ALERT_STATUS);
int x = ThingSpeak.writeFields(myChannelNumber, myApiKey);
if (x == 200) {
Serial.println("Data sent to ThingSpeak successfully");
} else {
Serial.println("Error sending data to ThingSpeak: " + String(x));
}
Serial.println("-------------");
delay(5000); // Wait 5 seconds before next measurement (total cycle ~15s)
}