#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Base ECG waveform data points for one cycle (simulated for Lead II)
const uint8_t BASE_ECG_POINTS[] = {
32, 34, 36, 38, 36, 34, 32, // P Wave
32, 32, 32, // Baseline
28, 24, 48, 20, 56, 30, // QRS Complex
32, 32, 32, // Baseline
32, 34, 36, 38, 40, 38, 36, 34, 32, // T Wave
32, 32, 32, 32, 32, 32, 32 // Rest of baseline
};
const int DATA_LENGTH = sizeof(BASE_ECG_POINTS) / sizeof(BASE_ECG_POINTS[0]);
int heartRate = 80; // Initial heart rate (in bpm)
int potPin = 34; // Analog pin connected to potentiometer
int dataIndex = 0;
void setup() {
Serial.begin(115200);
// Initialize OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("ECG Signal");
display.display();
delay(2000);
}
void loop() {
// Read the potentiometer and map the value to a heart rate range (60–150 bpm)
int potValue = analogRead(potPin);
heartRate = map(potValue, 0, 4095, 60, 150);
// Calculate the R-R interval in milliseconds based on heart rate
int rrInterval = 60000 / heartRate; // ms per beat
// Clear display before drawing the new waveform frame
display.clearDisplay();
// Display the heart rate on the screen
display.setCursor(0, 0);
display.print("Heart Rate: ");
display.print(heartRate);
display.println(" bpm");
// Adjust the ECG speed based on heart rate (scroll faster at higher heart rates)
int pointsPerBeat = map(heartRate, 60, 150, 70, 30); // Adjust points per beat to change waveform length
// Draw the ECG waveform across the screen width, based on heart rate
for (int i = 0; i < SCREEN_WIDTH - 1; i++) {
int index1 = (dataIndex + i * DATA_LENGTH / pointsPerBeat) % DATA_LENGTH;
int index2 = (dataIndex + (i + 1) * DATA_LENGTH / pointsPerBeat) % DATA_LENGTH;
// Calculate y-coordinates to flip the waveform vertically
int y1 = SCREEN_HEIGHT - BASE_ECG_POINTS[index1];
int y2 = SCREEN_HEIGHT - BASE_ECG_POINTS[index2];
// Draw the line between two consecutive points
display.drawLine(i, y1, i + 1, y2, SSD1306_WHITE);
}
display.display();
// Increment dataIndex to shift the waveform, creating a scrolling effect
dataIndex = (dataIndex + 1) % DATA_LENGTH;
// Control the speed of the scrolling based on heart rate
int delayTime = rrInterval / pointsPerBeat; // Delay per frame to match heart rate
delay(delayTime);
}