#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
unsigned int foo = 0;
unsigned int index = 0;
char inputs[20];
char intToChar(int input);
int charToInt(char input);
bool backlighted = false;
void calculate();
void retour();
int pow(int input, int power);
bool isOperator(char input);
bool isDigit(char input);
int parseInteger(int index);
LiquidCrystal_I2C OUT(0x27, 20, 4);
const byte ROWS = 4;
const byte COLS = 4;
char hexaKeys[ROWS][COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '/'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {12, 11, 10, 9};
byte colPins[COLS] = {8, 7, 6, 5};
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void setup() {
pinMode(2, INPUT);
Serial.begin(9600);
OUT.init();
OUT.setCursor(0, 0);
}
void loop() {
char input = customKeypad.getKey();
if (digitalRead(2) == 0 && !backlighted) {
OUT.backlight();
backlighted = true;
} else if (digitalRead(2) == 1 && backlighted) {
OUT.noBacklight();
backlighted = false;
}
if (input) {
switch (input) {
case 'D':
memset(inputs, 0, 20);
index = 0;
OUT.clear();
OUT.setCursor(0, foo*2);
break;
case '#':
if (foo == 1) {
foo = 0;
} else {
foo = 1;
}
OUT.setCursor(0, foo*2);
calculate();
memset(inputs, 0, 20);
index = 0;
break;
default:
if (index < 20) {
inputs[index] = input;
OUT.print(input);
index++;
}
break;
}
}
}
void calculate() {
char output[20];
int outputIndex = 0;
char operatorStack[20];
int operatorIndex = 0;
memset(output, 0, 20);
for (int i = 0; i < 20; i++) {
char current = inputs[i];
if (isDigit(current)) {
output[outputIndex]=parseInteger(i);
outputIndex++;
} else if (isOperator(current)) {
operatorStack[operatorIndex]=current;
operatorIndex++;
}
}
if (operatorIndex == 0) {
displayResult(output);
} else {
for (int i = 0; i < operatorIndex; i++) {
output[outputIndex+i] = operatorStack[i];
}
}
}
int parseInteger(int index) {
int last = 0;
int result[] = {};
int lastIndex = 0;
for (int i = index; i < 20; i++) {
if (isDigit(inputs[i])) {
result[lastIndex]=charToInt(inputs[i]);
lastIndex++;
}
}
for (int i = 0; i < lastIndex; i++) {
last += result[i]*(pow(10, lastIndex-i));
}
Serial.println(last);
return last;
}
int pow(int input, int power) {
int start = input;
if (power==0) {
return 1;
}
for (int i = 1; i < power; i++) {
input *= start;
}
return input;
}
bool isDigit(char input) {
return (input >= 48 && input <= 57);
}
bool isOperator(char input) {
return (input == '+' || input == '-' || input == '/' || input == '*');
}
int charToInt(char input) {
return input-48;
}
char intToChar(int input) {
return input+48;
}
void displayResult(char* result) {
OUT.print(" ");
OUT.setCursor(0, (foo*2)-1);
OUT.print(" ");
OUT.setCursor(0, (foo*2)-1);
OUT.print(result);
OUT.setCursor(0, foo*2);
memset(inputs, 0, 20);
index = 0;
}FPS: 0
Power: 0.00W
Power: 0.00W