|
#include <WiFiNINA.h>
#include <PDM.h>
static const char channels = 1;
static const int frequency = 16000;
short sampleBuffer[512];
volatile int samplesRead;
void setup() {
//pinMode(LEDB, OUTPUT);
pinMode(LEDR,OUTPUT);
pinMode(LEDG,OUTPUT);
analogWrite(LEDR,255);
analogWrite(LEDG,255);
Serial.println("Hello DigiKey & EEWorld!");
Serial.println();
Serial.begin(9600);
while (!Serial);
PDM.onReceive(onPDMdata);
if (!PDM.begin(channels, frequency)) {
Serial.println("Failed to start PDM!");
while (1);
}
}
void rgbledShow(float level) {
unsigned short value = level / 128;
unsigned char r,g,b;
Serial.print("value : ");
Serial.print(value);
Serial.print(" level: ");
Serial.println(level);
r = value;
g = 255 - value;
analogWrite(LEDR,r);
analogWrite(LEDG,g);
}
void micHandle() {
float level = 0;
if (samplesRead) {
for (int i = 0; i < samplesRead; i++) {
level += (sampleBuffer[i] * sampleBuffer[i]);
}
level /= samplesRead;
level = sqrt(level);
rgbledShow(level);
samplesRead = 0;
}
}
void loop() {
micHandle();
}
void onPDMdata() {
// Query the number of available bytes
int bytesAvailable = PDM.available();
PDM.read(sampleBuffer, bytesAvailable);
samplesRead = bytesAvailable / 2;
}
总结