C Program to Demonstrates changing the keypad size and key values.

How to write a C Program to Demonstrates changing the keypad size and key values ?

Solution:

/* C Program to Demonstrates changing the keypad size and key values.*/
#include <Keypad.h>
#include <stdlib.h>
#include <pitches.h>

double notes[89] = {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};
const byte ROWS = 8; //four rows
const byte COLS = 8; //four columns
//define the cymbols on the buttons of the keypads
byte hexaKeys[ROWS][COLS] = {
  {1, 1, 9, 9, 17, 17, 25, 25},
  {2, 2, 10, 10, 18, 18, 26, 26},
  {3, 3, 11, 11, 19, 19, 27, 27},
  {4, 4, 12, 12, 20, 20, 28, 28},
  {5, 5, 13, 13, 21, 21, 29, 29},
  {6, 6, 14, 14, 22, 22, 30, 30},
  {7, 7, 15, 15, 23, 23, 31, 31},
  {8, 8, 16, 16, 24, 24, 32, 32}

};
byte rowPins[ROWS] = {2, 3, 4, 5, 6, 7, 8, 9}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {A8, A9, A10, A11, A12, A13, A14, A15}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad kpd = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

#define trigPin 53
#define echoPin 51

void setup(){
  Serial.begin(9600);
  pinMode(49, HIGH);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){
  if (kpd.getKeys()){
        for (int i=0; i<LIST_MAX; i++) {  // Scan the whole key list.
            if ( kpd.key[i].stateChanged ) {  // Only find keys that have changed state.
                char j = kpd.key[i].kchar + 40;
                switch (kpd.key[i].kstate) {  // Report active key state : IDLE, PRESSED, HOLD, or RELEASED
                    case PRESSED:
                    tone(13, (notes[j] * pitchBend()), 0);
                    Serial.print(pitchBend());
                    Serial.print("\n");
                    break;
             
                    case RELEASED:
                    tone(13, 0, 1);
                }
            }
        }
    }
}

double pitchBend(){
  double duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  Serial.print(distance);
  if (distance < 50){
    return distance/200+1;
  }
  else{
    return 1;
  }
}


Learn More :