Code: Select all
void testtwo() {
unsigned long firstSampleTime = micros();
unsigned long nextSampleTime = firstSampleTime;
int samples = 0;
int value;
int normalizedValue;
int buff[8];
int readingAvg = 0;
int Xcrossings[4] = {0,0,0,0}; //last three durations of half waves
int prevNormalizedValue = 0;
int crossingcounts = 0; //a counter for moving through array of times the wave crosses the 0
int theData[512];
int bitCounter = 0;
digitalWrite(LED_BUILTIN, HIGH);
while(bitCounter < 256) {
//if its time to take a sample, do so
if ((unsigned long)(micros() >= nextSampleTime)) {
//read in audio via the ADC
value = analogRead(AUDIO_IN_PIN);
buff[samples % 8] = value; //put the raw reading in a rolling buffer - we are doing this so we can keep a rolling average
//set the next sample time in the future
nextSampleTime = firstSampleTime + samples * 125;
//If there are 8 samples in the buffer, start doing work on the data
if (samples > 7) {
//get avg
readingAvg = 0;
for (int b = 0; b < 8; b++) {
readingAvg += buff[b];
}
readingAvg = readingAvg / 8;
//the adc reads in all values as positive - to see the negative side of the audio waves, we've added ~1.5 volts to the input audio signal so the whole wave appears in the positive space.
//We subtract the average read from each sample to normalize the data, half the wave below zero, half above
normalizedValue = buff[samples % 8] - readingAvg;
//if current sample and previous smaple are oposite signs, the wave has crossed the zero amplitude mark
if((normalizedValue * prevNormalizedValue) <= 0){
Xcrossings[crossingcounts % 4] = ( -normalizedValue / ((normalizedValue-prevNormalizedValue)/125) ) + samples*125;
int one = Xcrossings[crossingcounts % 4] - Xcrossings[(crossingcounts-1) % 4];
int two = Xcrossings[(crossingcounts-1) % 4] - Xcrossings[(crossingcounts-2) % 4];
int three = Xcrossings[(crossingcounts-2) % 4] - Xcrossings[(crossingcounts-3) % 4];
if(one < 333 and two < 333 and three < 333){
theData[bitCounter] = 1;
bitCounter = bitCounter + 1;
}
if(one > 333 and two > 333){
theData[bitCounter] = 0;
bitCounter = bitCounter + 1;
}
crossingcounts++;
}
prevNormalizedValue = normalizedValue; //for use next time through the loop to see if the wave has crossed 0
//debugging output
//values[samples-8] = normalizedValue; // for visualizaiton of audio input
}
//add to the count of samples taken
samples++;
}
}
Serial.println("Digital Output");
for (int a = 0; a < 300; a++) {
Serial.println(String(theData[a]));
}
Serial.println("");
Serial.println("");
digitalWrite(LED_BUILTIN, LOW);
}