Example Code for Arduino-Read Key Value

Press a key on the board, serial print the corresponding key value.

Hardware Preparation

Software Preparation

Wiring Diagram

Connection

Sample Code

#define RESOLUTION 10   //ADC resoltuion
#define MAXVALUE pow(2,RESOLUTION)  //Resolution corresponding value 
#define PRECISION 10   //Admissible error 
#define ADPIN A0      //Read pin 

uint32_t ADKeyVal[10] = {0};   //Corresponding key value 
uint32_t ADCKeyIn = 0;


void setup() {
  Serial.begin(115200);
  ADKeybegin();
}

void loop() {
  ADCKeyIn = analogRead(ADPIN);
  if(ADCKeyIn < (MAXVALUE-PRECISION)){
    Serial.print("K = ");
    Serial.println(getKey());
  }
  delay(10);
}


void ADKeybegin(){
  float RESValue[10] = {0, 3, 6.2, 9.1, 15, 24, 33, 51, 100, 220};  //Resistor resistance 
  for(uint8_t i = 0; i < 10; i++){
    ADKeyVal[i] = RESValue[i]/(RESValue[i]+22)*MAXVALUE;
  }
}

int8_t getKey(){
  for(uint8_t i = 0; i < 10;i++){
    if(ADCKeyIn > ADKeyVal[i]){
      if((ADCKeyIn - ADKeyVal[i]) < PRECISION){
        return i;
      }
    } else{
      if((ADKeyVal[i] - ADCKeyIn) < PRECISION){
        return i;
      }
    }
  }
  return -1;
}

Result

Print the key values through the serial port.
Result 2

Was this article helpful?

TOP