#include #include #include // Define LCD LiquidCrystal_I2C lcd(0x27, 16, 2); // Define constants const int BUTTON_PIN = 3; const int ACOUSTIC_GUITAR_IN = A0; const int ELECTRIC_GUITAR_IN = A1; bool isAcousticMode = true; const int SAMPLES = 128; const int SAMPLING_FREQUENCY = 800; arduinoFFT FFT = arduinoFFT(); unsigned int sampling_period_us; unsigned long microseconds; // Define the acceptable frequency ranges for each note const float noteRanges[][2] = { { 80, 85 }, // E2 { 107, 113 }, // A2 { 141, 149 }, // D3 { 193, 199 }, // G3 { 257, 266 }, // B3 { 339, 359 } // E4 }; String notes[] = {"E2", "A2", "D3", "G3", "B3", "E4"}; double vReal[SAMPLES]; double vImag[SAMPLES]; void setup() { sampling_period_us = round(1000000 * (1.0 / SAMPLING_FREQUENCY)); lcd.init(); lcd.backlight(); lcd.setCursor(0, 0); lcd.print("Arduino guitar"); lcd.setCursor(0, 1); lcd.print("tuner - Baki P"); delay(2000); pinMode(ACOUSTIC_GUITAR_IN, INPUT); pinMode(ELECTRIC_GUITAR_IN, INPUT); pinMode(BUTTON_PIN, INPUT_PULLUP); Serial.begin(9600); } int frequency_to_note(float frequency) { float frequencies[] = {82.41, 110.00, 146.83, 196.00, 246.94, 329.63}; int numNotes = sizeof(notes) / sizeof(notes[0]); int closestIndex = 0; float closestDifference = abs(frequency - frequencies[0]); for (int i = 1; i < numNotes; i++) { float difference = abs(frequency - frequencies[i]); if (difference < closestDifference) { closestIndex = i; closestDifference = difference; } } return closestIndex; } void displayNoteAndTune(float frequency) { int note_idx = frequency_to_note(frequency); String note=notes[note_idx]; lcd.clear(); lcd.setCursor(0, 0); lcd.print(isAcousticMode ? "Acoustic Guitar" : "Electric Guitar"); lcd.setCursor(0, 1); lcd.print(note); if(frequencynoteRanges[note_idx][0]){ lcd.setCursor(7, 1); lcd.print("Go Lower"); } else { lcd.setCursor(8, 1); lcd.print("Good"); } } void loop() { // Check if the button is pressed if (digitalRead(BUTTON_PIN) == LOW) { // Invert the input mode isAcousticMode = !isAcousticMode; while(digitalRead(BUTTON_PIN) == LOW) delay(10); // wait for button to unpress } float frequency = FindFrequency(); if (frequency != 0) { displayNoteAndTune(frequency); } else { lcd.clear(); lcd.setCursor(0, 0); lcd.print("No input signal"); } delay(300); } float FindFrequency() { int GUITAR_IN = isAcousticMode ? ACOUSTIC_GUITAR_IN : ELECTRIC_GUITAR_IN; for (int i = 0; i < SAMPLES; i++) { microseconds = micros(); int sample = analogRead(GUITAR_IN); while (micros() < (microseconds + sampling_period_us)); vReal[i] = static_cast(sample); vImag[i] = 0; } FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD); FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD); FFT.ComplexToMagnitude(vReal, vImag, SAMPLES); float peak = static_cast(FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY)); Serial.println(peak); return peak; }