#include <Arduino.h>
#define LED 2
#define BUTTON_PIN 32
#define SLIDER_BPM 34
#define SLIDER_AMPLITUDE 35
hw_timer_t *My_timer = NULL;
volatile bool arythmiaMode = false;
volatile float adValue = -10;
volatile float bpm = 60; // Default BPM
volatile float amplitude = 1.0; // Full amplitude
void IRAM_ATTR onTimer() {
static int vector = 0;
if (!arythmiaMode) {
// Normal sinus rhythm
adValue = 120 + 120 * sin(vector * PI / 180) * amplitude; // Centered around 120, amplitude of 120
} else {
// Ventricular fibrillation simulation
adValue = 120 + 120 * (random(-100, 100) / 100.0) * amplitude; // Random fluctuations centered around 120
}
if (++vector >= 360) vector = 0;
}
void setup() {
pinMode(LED, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(SLIDER_BPM, INPUT);
pinMode(SLIDER_AMPLITUDE, INPUT);
My_timer = timerBegin(0, 80, true); // Prescaler 80, timer 0
timerAttachInterrupt(My_timer, &onTimer, true);
timerAlarmWrite(My_timer, 1000000 / (bpm / 60), true); // Correct timer period calculation
timerAlarmEnable(My_timer);
Serial.begin(115200);
}
void loop() {
if (digitalRead(BUTTON_PIN) == LOW) {
arythmiaMode = !arythmiaMode;
delay(500); // Debouncing
}
// Read and map BPM from the analog reading
int newBpmReading = analogRead(SLIDER_BPM);
bpm = map(newBpmReading, 0, 4095, 40, 240);
// Read and convert amplitude percentage directly
int newAmplitudeReading = analogRead(SLIDER_AMPLITUDE);
amplitude = map(newAmplitudeReading, 0, 4095, 10, 100) / 100.0;
// Update the timer based on the new BPM
timerAlarmWrite(My_timer, 1000000 / (bpm / 60), true);
if (adValue != -10) {
Serial.print(adValue, 6);
Serial.println();
dacWrite(GPIO_NUM_25, map(adValue * 10, -1, 1, 0, 255));
adValue = -10;
}
}