回到 Arduino
Source code
/*
* 使用 1 個 PIN 判斷 16 個 KEY 的 INPUT
*
*/
#define key_pin 0 // define key sensor pin
#define key_val_size 11 // define key value's size
int key_val[key_val_size] = {0}; // store key sensor value
byte index = 0; // key sensor array's index
byte button_up_count = 0;
boolean is_button_down = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(analogRead(key_pin) > 215 && analogRead(key_pin) < 610 && index < key_val_size)
{
is_button_down = 1;
key_val[index++] = analogRead(key_pin);
}
else if(analogRead(key_pin) == 0)
{
button_up_count++;
if (button_up_count > 5 && is_button_down == 1)
{
index = 0;
button_up_count = 0;
is_button_down = 0;
switch ( detectKey() )
{
case 1:
Serial.println("key 1");
break;
case 2:
Serial.println("key 2");
break;
case 3:
Serial.println("key 3");
break;
case 4:
Serial.println("key 4");
break;
case 5:
Serial.println("key 5");
break;
case 6:
Serial.println("key 6");
break;
case 7:
Serial.println("key 7");
break;
case 8:
Serial.println("key 8");
break;
case 9:
Serial.println("key 9");
break;
case 10:
Serial.println("key 10");
break;
case 11:
Serial.println("key 11");
break;
case 12:
Serial.println("key 12");
break;
case 13:
Serial.println("key 13");
break;
case 14:
Serial.println("key 14");
break;
case 15:
Serial.println("key 15");
break;
case 16:
Serial.println("key 16");
break;
default:
break;
} // end of switch
} // end of if
}
}
byte detectKey()
{
for (byte i = 0; i < key_val_size; i++)
{
for (byte j = i+1; j < key_val_size; j++)
{
if (key_val[i] > key_val[j])
{
int temp = key_val[i];
key_val[i] = key_val[j];
key_val[j] = temp;
}
}
}
int average_val = key_val[key_val_size - 2];
for (byte i = 0; i < key_val_size; i++)
key_val[i] = 0;
if (average_val < 216)
return 0;
else if (average_val < 234)
return 13;
else if (average_val < 247)
return 14;
else if (average_val < 257)
return 15;
else if (average_val < 263)
return 16;
else if (average_val < 275)
return 9;
else if (average_val < 293)
return 10;
else if (average_val < 307)
return 11;
else if (average_val < 326)
return 12;
else if (average_val < 356)
return 5;
else if (average_val < 387)
return 6;
else if (average_val < 412)
return 7;
else if (average_val < 434)
return 8;
else if (average_val < 475)
return 1;
else if (average_val < 530)
return 2;
else if (average_val < 578)
return 3;
else if (average_val < 611)
return 4;
}