#include <Adafruit_LiquidCrystal.h>
Adafruit_LiquidCrystal lcd(0);
int threshold[16] = {0, 72, 128, 174, 230, 259, 285, 306, 335, 351, 365, 377, 395, 404, 413, 422};
char keypad[16] = {'1', '2', '3', '+', '4', '5', '6', '-', '7', '8', '9', '*', '.', '0', '/', '='};
void setup() {
lcd.begin(16, 2);
lcd.print("Threshold Example");
lcd.setBacklight(1);
}
void loop() {
static String displayText = ""; // String to store the displayed text
int sensorValue = analogRead(A0);
char character = findCharacter(sensorValue);
// Check if any button is pressed
if (sensorValue < 610) {
// Append the character to the displayed text
displayText += character;
// Update the LCD display
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(displayText);
lcd.setBacklight(1);
// Delay to avoid multiple rapid button presses
delay(100);
}
// Check if equals button is pressed
if (character == '=') {
// Parse and evaluate the expression
float result = evaluateExpression(displayText);
// Display the result on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Result: ");
lcd.setCursor(0, 1);
lcd.print(result);
lcd.setBacklight(1);
// Clear the displayText for the next input
displayText = "";
// Delay to avoid multiple rapid button presses
delay(100);
}
}
char findCharacter(int value) {
for (int i = 0; i < 16; i++) {
if (value <= threshold[i]) {
return keypad[i];
}
}
// Handle the case where no button is pressed
return ' '; // Space character as an example
}
float evaluateExpression(String expression) {
// Replace '*' with 'x' for easier parsing
expression.replace("*", "x");
// Evaluate the expression using the toFloat method
return evaluate(expression);
}
float evaluate(String expression) {
// Find the operator and split the expression
int operatorIndex = findOperator(expression);
if (operatorIndex != -1) {
String left = expression.substring(0, operatorIndex);
String right = expression.substring(operatorIndex + 1);
float operand1 = left.toFloat();
float operand2 = right.toFloat();
// Perform the calculation based on the operator
switch (expression[operatorIndex]) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case 'x':
return operand1 * operand2;
case '/':
// Check for division by zero
if (operand2 != 0) {
return operand1 / operand2;
} else {
return 0; // Handle division by zero error
}
default:
return 0; // Invalid operator
}
} else {
// If no operator is found, parse the entire expression as a float
return expression.toFloat();
}
}
int findOperator(String expression) {
// Find the index of the first operator ('+', '-', 'x', '/')
for (int i = 0; i < expression.length(); i++) {
if (expression[i] == '+' || expression[i] == '-' || expression[i] == 'x' || expression[i] == '/') {
return i;
}
}
return -1; // No operator found
}