#include <driver/dac.h>
int currentLed = 0;
int lastSeen = -1;
#define DEBUG 0
const size_t row_count = 5;
const size_t col_count = 5;
const int rows[row_count] = { 5, 23, 19, 18, 26 };
const int cols[col_count] = { 17, 33, 16, 21, 22 };
const int adc[row_count] = { 2, 4, 12, 27, 14 };
const int ampEnable = 32;
const int octave_shift = 4;
void setup() {
Serial.begin(115200);
pinMode(ampEnable, OUTPUT);
digitalWrite(ampEnable, LOW);
dac_i2s_disable();
dac_output_enable(DAC_CHANNEL_1);
for (int i=0;i<row_count;++i) {
pinMode(rows[i], OUTPUT|PULLUP);
pinMode(adc[i], INPUT);
}
for (int i=0;i<col_count;++i) {
pinMode(cols[i], OUTPUT|PULLDOWN);
}
currentLed = 0;
lastSeen = -1;
}
void play(uint32_t freq) {
dac_cw_config_t wave_config = {
en_ch: DAC_CHANNEL_1,
scale: DAC_CW_SCALE_2,
phase: DAC_CW_PHASE_0,
freq: octave_shift*freq,
offset: 0,
};
dac_cw_generator_config(&wave_config);
dac_cw_generator_enable();
digitalWrite(ampEnable, HIGH);
}
void mute() {
digitalWrite(ampEnable, LOW);
dac_cw_generator_disable();
}
void tristate(int pin) {
pinMode(pin,OUTPUT|PULLDOWN);
digitalWrite(pin,LOW);
pinMode(pin,INPUT);
}
void power(int pin) {
pinMode(pin,OUTPUT|PULLUP);
digitalWrite(pin,HIGH);
}
void ground(int pin) {
pinMode(pin,OUTPUT|PULLDOWN);
digitalWrite(pin,LOW);
}
void enableLed(int led) {
int row = (led/col_count) % row_count ;
int col = led%col_count;
#if DEBUG & 0x02
Serial.print("enabling ");
Serial.print(row);
Serial.print(" ");
Serial.println(col);
#endif
for (int i=0;i<row_count;++i) {
if (i==row) { power(rows[i]); }
else { ground(rows[i]); }
}
for (int i=0;i<col_count;++i) {
if (i==col) { ground(cols[i]); }
else { tristate(cols[i]); }
}
}
int sense(int led) {
int row = (led/col_count)%row_count;
int value = analogRead(adc[row]);
#if DEBUG & 0x04
Serial.println(value);
#endif
return value < 500;
}
uint32_t notes[] = {
261,
277,
294,
311,
330,
349,
370,
392,
415,
440,
466,
494,
523,
554,
587,
622,
659,
698,
740,
783,
831,
880,
932,
988,
1046,
};
void loop() {
#if DEBUG & 0x01
Serial.print("current led ");
Serial.println(currentLed);
#endif
enableLed(currentLed);
delay(5);
if (sense(currentLed)) {
if (lastSeen != currentLed) {
lastSeen = currentLed;
Serial.print(currentLed);
Serial.println(" proximity!");
play(notes[currentLed]);
}
}
else if (lastSeen == currentLed) {
lastSeen = -1;
mute();
}
currentLed = (currentLed+1)%(row_count*col_count);
}