aboutsummaryrefslogtreecommitdiff
path: root/esp32/lego-piano.ino
blob: d67a75a42c7fa454ad53ce2ec8e913b28f201d83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
  matrix-scan a set of LEDs
 
  pins:
 
  "rows" 12 & 13 go to a 220Ω resistor, then to 2 LEDs each (positive
  / long stem side); also to a 10kΩ resistor then to 2
  phototransistors (collector / long stem side)
 
  also, from between the 10kΩ and the phototransistors, wire goes to
  A1 & A2
 
  "columns"
  14 & 15 go to 2 LEDs each (negative / short stem side)
 
  so that given one of 12|13 and one of 14|15, one LED is identified
 */
 
int currentLed = 0;
int lastSeen = 100;
 
void setup() {
  Serial.begin(19200);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
  currentLed = 0;
  lastSeen = 100;
}
 
void tristate(int pin) {
  pinMode(pin,OUTPUT);
  digitalWrite(pin,LOW);
  pinMode(pin,INPUT);
}
 
void power(int pin) {
  pinMode(pin,OUTPUT);
  digitalWrite(pin,HIGH);
}
 
void ground(int pin) {
  pinMode(pin,OUTPUT);
  digitalWrite(pin,LOW);
}
 
void enableLed(int led) {
  int row = led/2;
  int col = led%2;
  /* Serial.print("enabling "); */
  /* Serial.print(row); */
  /* Serial.print(" "); */
  /* Serial.println(col); */
 
  if (row==0{
    power(12); ground(13);
  }
  else {
    ground(12); power(13);
  }
 
  if (col==0{
    ground(14); tristate(15);
  }
  else {
    tristate(14); ground(15);
  }
}
 
int sense(int led) {
  int row = led/2;
 
  int value = analogRead(row == 0 ? A1 : A2);
 
  //Serial.println(value); 
  return value < 500;
}
 
void loop() {
  /* Serial.print("current led "); */
  /* Serial.println(currentLed); */
 
  enableLed(currentLed);
  delay(1);
  if (sense(currentLed)) {
    if (lastSeen != currentLed) {
      lastSeen = currentLed;
      Serial.print(currentLed);
      Serial.println(" proximity!");
    }
  }
  else if (lastSeen == currentLed) {
    lastSeen = 100;
  }
 
  currentLed = (currentLed+1)%4;
}