#include "lcd_1.h"
#include <Arduino.h>
// Global Declaration:
char get_key(uint8_t row, uint8_t col) {
const char keys[4][4] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'d', '0', '=', '/'}
};
return keys[row][col];
}
long output_1, num1, num2;
char action, key;
boolean result = false;
boolean error = false;
void write_data(char);
void write_string(char *ptr);
void setup() {
init_program(); // Initialize program
lcd_init(); // Initialize LCD
Serial.begin(9600);
}
void write_data(char wr_data)
{
out_data(wr_data);
out_con(0x01); // RS = 1, E = 0
delay1(1);
out_con(0x03); // RS = 1, E = 1
delay1(1);
out_con(0x01); // RS = 1, E = 0
delay1(1);
}
void loop() {
// Intentionally left empty
for (int row = 0; row < 4; row++) {
switch_in(1 << row); // Activate one row at a time
uint8_t colValue = switch_out(); // Read column values
for (int col = 0; col < 4; col++) {
if (colValue & (1 << col)) { // Check if column is active
key = get_key(row, col);
write_data(key);
Serial.print(key);
delay1(5); // Debounce delay
capture_key();
if(result)
{
calculate();
if (!error) { // Only print if no error
write_long(output_1);
Serial.print(output_1);
Serial.println();
}
delay1(5);
result=false;
out_data(0x02); // Reset Display
lcd_control();
out_data(0x01); // Clear Display
lcd_control();
}
}
}
}
}
void write_long(long data) {
char str[20]; // Buffer to hold the string representation of the number
sprintf(str, "%ld", data); // Convert long to string using sprintf
for (char *ptr = str; *ptr != '\0'; ++ptr) { // Loop through each character
write_data(*ptr); // Output the character one by one
}
}
void capture_key() {
if (key == 'd') {
lcd_step_back(); // Step back and clear the last character
output_1 /= 10; // Remove the last digit from the number
return;
}
if (key >= '0' && key <= '9') {
int digit = key - '0';
output_1 = (output_1 * 10) + digit;
return;
}
if (key == '+' || key == '-' || key == '*' || key == '/') {
num1 = output_1;
action = key;
output_1 = 0;
return;
}
if (key == '=') {
num2 = output_1;
result = true;
}
}
void calculate() {
output_1 = 0; // Reset output
if (action == '+') {
output_1 = num1 + num2;
}
else if (action == '-') {
output_1 = num1 - num2;
}
else if (action == '*') {
output_1 = num1 * num2;
}
else if (action == '/') {
if (num2 == 0) {
// Handle division by zero
Serial.println("Illegal Operation: Division by Zero\n");
write_string("Illegal");
error = true; // Set error flag
return; // Exit function to avoid incorrect computation
} else {
output_1 = num1 / num2;
}
}
else {
out_data(0x02); // Reset Display
lcd_control();
out_data(0x01); // Clear Display
lcd_control();
write_string("Illegal");
error = true; // Set error flag
}
// Reset input numbers
num1 = 0;
num2 = 0;
}
void write_string(char *ptr) {
while (*ptr) {
write_data(*ptr++);
}
}