#include <float.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
const int data_points = 10;
const int speaker_pin = 3;
//const int notes[] = {0, 2, 4, 5, 7, 9, 11, 12, 14, 16, 17, 19, 21, 23, 24, 26, 28, 29, 31, 33, 35, 36};
const int notes[] = {-3, -1, 0, 2, 4, 5, 7, 9, 11, 12, 14, 16, 17, 19, 21, 23, 24, 26, 28, 29, 31, 33, 35, 36};
const int dynamic_pitch_factor = 5;
const int dynamic_duration_factor = 30;
const int base_duration_ms = 40;
const float base_freq = 160;
const float note_interval = 1.05946;
const float detection_threshold = 0.4;
Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified();
void setup(void) {
while (!accel.begin()) {
delay(100);
}
accel.setRange(ADXL345_RANGE_16_G);
accel.setDataRate(ADXL345_DATARATE_3200_HZ);
pinMode(speaker_pin, OUTPUT);
}
void loop(void) {
static float old_max = 0;
float max = FLT_MAX * -1;
for (int i = 0; i < data_points; i++) {
sensors_event_t event;
accel.getEvent(&event);
max = max(event.acceleration.x, max);
}
const bool detected = (max - old_max) > detection_threshold;
if (detected) {
int degree = dynamic_pitch_factor * (max - old_max) - 4;
degree = max(degree, 0);
degree = min(degree, (sizeof(notes) - 1));
const float freq = base_freq * pow(note_interval, notes[degree]);
tone(speaker_pin, freq, base_duration_ms + dynamic_duration_factor * degree);
}
old_max = max;
}