HZ analyser

int adc_key_val[12] ={630,680,750,810,845,860,890,905,920,940,950,980};
int NUM_KEYS = 12;
int adc_key_in;
int key=-1;
int oldkey=-1;
int threshold = 83; // default frequency threshold

const int inputPin = A0; // analog input pin to read from
const int outputPin = 2; // digital output pin to write to

unsigned long previousMillis = 0; // previous time for frequency calculation
int count = 0; // counter for input signal edges

void setup() {
Serial.begin(9600);
pinMode(inputPin, INPUT);
pinMode(outputPin, OUTPUT);
}

void loop() {
// read the input pin
int sensorValue = analogRead(inputPin);

// convert the sensor value to a key position
adc_key_in = sensorValue;
key = get_key(adc_key_in);

// if a key position has changed, update the threshold value
if (key != oldkey) {
delay(50);
adc_key_in = analogRead(inputPin);
key = get_key(adc_key_in);

if (key != oldkey) {
oldkey = key;
if (key >= 0) {
switch(key) {
case 0:
threshold = 0;
break;
case 1:
threshold = 50;
break;
case 2:
threshold = 60;
break;
case 3:
threshold = 70;
break;
case 4:
threshold = 75;
break;
case 5:
threshold = 80;
break;
case 6:
threshold = 85;
break;
case 7:
threshold = 90;
break;
case 8:
threshold = 95;
break;
case 9:
threshold = 100;
break;
case 10:
threshold = 103;
break;
case 11:
threshold = 105;
break;
}
}
}
}

// calculate the current time
unsigned long currentMillis = millis();

// if the input signal has changed, increment the counter
if (sensorValue != lastSensorValue) {
count++;
}

// if 1 second has passed, calculate the frequency
if (currentMillis – previousMillis >= 1000) {
previousMillis = currentMillis;

// calculate the frequency in Hz
int frequency = count;
count = 0;

// if the frequency is over the threshold, turn on the output
if (frequency > threshold) {
digitalWrite(outputPin, HIGH);
}
// if the frequency is below the threshold, turn off the output
else {
digitalWrite(outputPin, LOW);
}
}
}

// Convert ADC value to key number
int get_key(unsigned int input)
{
int k;
for (k = 0; k < NUM_KEYS; k++)
{
if (input < adc_key_val[k])
{
return k;
}
}
if (k >= NUM_KEYS)k = -1;
return k;
}

Vastaa

Sähköpostiosoitettasi ei julkaista. Pakolliset kentät on merkitty *