/* To implement a integer calculator using a keypad and LCD */
#pragma SMALL DB OE
#include <reg51.h>
#include "io.h"
/* The functions to initialize and control the LCD are assumed to be in the file io.c */
/* Function to output the decimal value of the result on the LCD */
void PrintInt(int i) {
.
.
.
}
/* Routine to scan the key pressed */
unsigned char key_scan()
{
unsigned char i, j, temp1, temp2;
while( 1 ) /* keep waiting for a key to be pressed */
for(i=0; i<4; i++) {
/* Set each row to 0 */
P1 = 0xff & ~(1<<i);
/* Scan each column to see which key was pressed */
for (j=4; j<8; j++) {
/* Code to determine the position of the
key which was pressed */
/* return(position) */
}
}
}
void main() {
/* You can have a conversion table to convert the key position into a
valid number which indicates the operator or operand value. For eg:
the numbers 0 to 9 are valid operands and 100 to 103 denote
addition, subtraction, multiplication and division respectively */
char conv_table[] = {
1, 2, 3, 100 /* add */,
4, 5, 6, 101 /* sub */,
7, 8, 9, 102 /* mul */,
-1, 0, -1, 103 /* div */
};
char num1, num2, op;
int result;
InitIO();
while(1) {
ClearScreen();
/* read num1 */
GotoXY(0, 0);
PrintString("num1 : ");
do {
num1 = conv_table[key_scan()];
}
while( num1 < 0 || num1 > 9 );
/* read a valid operation */
GotoXY(0, 0);
PrintString("op : ");
do {
op = conv_table[key_scan()];
}
while( op < 100 );
/* read num2 */
GotoXY(0, 0);
PrintString("num2 : ");
do {
num2 = conv_table[key_scan()];
}
while( num2 < 0 || num2 > 9 );
/* compute result */
if( op == 100 ) {
/* Add numbers and display result on the LCD */
}
else if( op == 101 ) {
.
.
.
.
/* Continue similarly for other operations */
}
}
}