#include "SimpleTimer.h"
// Define pin numbers
const int BUZZER_PIN = 22;
const int POT_PIN = 34;//A0;
const int LED_PIN = 23;
// Define beep threshold and default value of X
const int BEEP_THRESHOLD = 1000;
int X = BEEP_THRESHOLD;
// Define SimpleTimer object
SimpleTimer timer;
void setup() {
Serial.begin(9600);
Serial.println("");
Serial.println("..");
// Set pin modes
pinMode(BUZZER_PIN, OUTPUT);
pinMode(POT_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
// Set up timer
timer.setInterval(X, beepBuzzer);
timer.setInterval(X, blinkLed);
timer.setInterval(10, mainLoop);
}
void loop() {
// Run timer
timer.run();
}
void mainLoop() {
// Read pot value
int potValue = analogRead(POT_PIN);
// Calculate D based on pot value and voltage
float voltage = map(potValue, 0, 1023, 0, 3300) / 1000.0;
int D = 2 * X - (X - BEEP_THRESHOLD) * exp(-voltage);
// Calculate new X based on D and threshold
int median = (X + D + BEEP_THRESHOLD) / 2;
int smoothness = analogRead(POT_PIN) / 1023.0 * 10 + 1;
X = (smoothness * median + (10 - smoothness) * X) / 10;
// Output V, D, and X to serial monitor
Serial.print(voltage);
Serial.print(", ");
Serial.print(D);
Serial.print(", ");
Serial.println(X);
}
void beepBuzzer() {
digitalWrite(BUZZER_PIN, HIGH);
timer.setTimeout(BEEP_THRESHOLD, [](){
digitalWrite(BUZZER_PIN, LOW);
});
}
void blinkLed() {
digitalWrite(LED_PIN, !digitalRead(LED_PIN));
}