#include <Keypad.h>
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
uint8_t colPins[COLS] = { 5, 4, 3, 2 }; // Pins connected to C1, C2, C3, C4
uint8_t rowPins[ROWS] = { 9, 8, 7, 6 }; // Pins connected to R1, R2, R3, R4
// Create keypad object
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
bool distInput = false;
char dist[3] = "";
byte index = 0;
int targetDistance = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
char key = keypad.getKey();
switch (key)
{
case '0' ... '9':
if (distInput == true)
{
Serial.print(key);
if (index < 2)
{
dist[index] = key;
dist[index + 1] = '\0';
index++;
}
if (index == 2)
{
targetDistance = atoi(dist);
if ((targetDistance < 50) && (targetDistance > 2))
{
index = 0;
memset(dist, 0, 2); // Clear input
distInput = false;
Serial.print("\nYour target distance is:");
Serial.print(targetDistance);
Serial.println(" cm.");
distInput = false;
}
else if (targetDistance < 3)
{
index = 0;
memset(dist, 0, 2); // Clear input
distInput = false;
Serial.println("\nThe minimum distance is 03 cm.");
}
else
{
index = 0;
memset(dist, 0, 2); // Clear input
distInput = false;
Serial.println("\nThe maximum distance is 49 cm.");
}
}
}
break;
case '*':
if (distInput == false)
{
Serial.println("\nPlease input Target value 03-49 cm (2 digits).");
distInput = true;
}
break;
case '#':
if (distInput == false)
{
Serial.println("\nEnd of measurement."); // for the case of pressing a '#'
}
break;
default:
break;
}
}