int photoPin = A5;
int buzzerPin = 9;
String msg = "Lux value: ";
String msg2 = "Note value: ";
int minLuxValue = 8;
int maxLuxValue = 1015;
int baudRate = 9600;
int delayMs = 1000;
int notes[] = {31, 33, 35, 37, 39, 41, 44, 46, 49, 52, 55, 58, 62, 65, 69, 73, 78, 82, 87, 93, 98, 104, 110, 117, 123, 131, 139, 147, 156, 165, 175, 185, 196, 208, 220, 233, 247, 262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494, 523, 554, 587, 622, 659, 698, 740, 784, 831, 880, 932, 988, 1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1976, 2093, 2217, 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951, 4186, 4435, 4699, 4978};
int noteGraduation = (notes[(sizeof(notes)/sizeof(notes[0])) - 1] - notes[0]) / (maxLuxValue - minLuxValue);
int notesCount = sizeof(notes) / sizeof(notes[0]);
void setup() {
// put your setup code here, to run once:
pinMode(photoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
Serial.begin(baudRate);
}
int calculateNoteValue(int luxValue) {
int noteValueGuess = luxValue * noteGraduation;
for (int i = 0; i < notesCount; i++) {
int note = notes[i];
if (note == noteValueGuess) {
return note;
} else if (i == notesCount - 1) {
return notes[notesCount - 1];
} else {
// the next note is greater than this one
if (noteValueGuess < notes[i+1]) {
if (abs(noteValueGuess - notes[i]) < abs(noteValueGuess - notes[i+1])) {
// return notes[i]
return notes[i];
} else {
// return the next note
return notes[i+1];
}
}
// otherwise find the next note
}
}
}
void loop() {
// put your main code here, to run repeatedly:
int luxValue = analogRead(photoPin);
Serial.println(msg + luxValue);
int noteValue = calculateNoteValue(luxValue);
Serial.println(msg2 + noteValue);
//tone(buzzerPin, noteValue, delayMs);
delay(delayMs);
}