*
* Data input and output whit Arduino, Keypad 4x4, LCD 2x16 and buzzer
* 2015, by José Augusto Cintra (www.josecintra.com/blog)
*/
#include <Keypad.h>
#include <LiquidCrystal.h>
//keyPad definitions
const byte numRows= 4; //number of rows on the keypad
const byte numCols= 4; //number of columns on the keypad
char keyMap[numRows][numCols]=
{
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[numRows] = {9,8,7,6}; //Rows 0 to 3
byte colPins[numCols]= {5,4,3,2}; //Columns 0 to 3
Keypad keyPad= Keypad(makeKeymap(keyMap), rowPins, colPins, numRows, numCols);
//LCD Display
LiquidCrystal lcd(A0, A1, A2, A3, A4, A5);
//Buzzer
int buzzPin = 10; //connect a 100ohms resistor on this pin
void setup() {
lcd.begin(16, 2);
pinMode(buzzPin,OUTPUT); //Buzzer pin
randomSeed(analogRead(7));//Starts the random number generator on this analogic pin
}
void loop() {
lcd.clear();
lcd.setCursor(0, 0);
//Choose two numbers and displays them on the LCD
int num1 = random(2, 11);
int num2 = random(2, 11);
int result = num1 * num2;
String mult = String(num1) + " x " + String(num2) + " = ";
lcd.print(mult);
// Waiting for user response and evaluates the result
int hit = readVal().toInt();
lcd.setCursor(0, 1);
if (result == hit){
lcd.print(":-)");
}
else {
lcd.print(":-( " + String(result));
}
hit = readVal().toInt(); //Just waiting for you to press any key to continue
}
//Data input: Enter the values and press "#"
String readVal(){
String myString = "";
char keyPressed = keyPad.getKey();
while (keyPressed != '#'){
keyPressed = keyPad.getKey();
if ((keyPressed != NO_KEY) && (keyPressed != '#')) {
myString.concat(keyPressed);
lcd.print(keyPressed);
}
}
return(myString);
}