/* First version of nano timer nano_sound.ino and https://github.com/Staacks/phyphox-arduino#randomnumbersino are used Second version - b : send only time difference */ #include #include // buffer to read samples into, each sample is 16-bits short sampleBuffer[256]; // number of samples read volatile int samplesRead; unsigned long runs = 0L; short ntime = 0; float mtime[6]; float msound[6]; float threshold = 5000.0; float tDelay = 0.5; float intervalMax = 0; short nMax = 0; float t = 0.0; float t1; float dt; void setup() { // put your setup code here, to run once: PhyphoxBLE::start(); //Start the BLE server // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); Serial.begin(9600); while (!Serial); // blocks the program untill opening of the Serial Monitor. // It allows simple peparation of the arduino starting condition. runs = 0L; ntime = 0; mtime[0] = 0; msound[0] = 0; dt = 1.0 / 16000; // configure the data receive callback PDM.onReceive(onPDMdata); // initialize PDM with: // - one channel (mono mode) // - a 16 kHz sample rate if (!PDM.begin(1, 16000)) { Serial.println("Failed to start PDM!"); digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH voltage level) while (1); } } // end setup void loop() { // put your main code here, to run repeatedly: // wait for samples to be read if (samplesRead) { // looking for the maximum intervalMax = 0; nMax = 0; for (int n = 0; n < samplesRead; n++) { if (sampleBuffer[n] > intervalMax) { intervalMax = sampleBuffer[n]; nMax = n; } // end if 2 } // end for (looking for the maximum) t1 = t + nMax * dt; if ((intervalMax > threshold) && ((t1-mtime[ntime]) > tDelay)) { ++ntime; mtime[ntime] = t1; msound[ntime] = intervalMax; } t += samplesRead * dt; samplesRead = 0; // clear the read count } // end if (samplesRead) ++runs; if (ntime >= 2) { Serial.println("Ypa !"); // print samples to the serial monitor or plotter for (int i = 0; i <= ntime; i++) { Serial.println(mtime[i], 4); Serial.println(msound[i], 0); // printing max sound // PhyphoxBLE::write(mtime[i]); //Send value to phyphox delay(50); //Shortly pause before repeating } float deltaTime = mtime[2] - mtime[1]; Serial.println("--------------"); Serial.println(deltaTime, 4); Serial.println("--------------"); Serial.println(runs); PhyphoxBLE::write(deltaTime); delay(50); while (1){ blinking(ntime); delay(2000); // wait for 2 seconds } } } // end loop void onPDMdata() { // query the number of bytes available int bytesAvailable = PDM.available(); // read into the sample buffer PDM.read(sampleBuffer, bytesAvailable); // 16-bit, 2 bytes per sample samplesRead = bytesAvailable / 2; } void blinking(int blinks) { for (int i = 0; i < blinks; i++) { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(300); // wait for 300 ms digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(300); // wait for 300 ms } }