I am interfacing a 3X4 keypad to PIC16f877a uC on PORTD as:
In the first half of the C program I have set first four pins to Input (From LSB-RD0) and others to Output and store the value in a variable and in other half I have set last four pins to Input and others to Output and stored its value into another variable I have called this function in a continuous loop to get a pressed key. The code is as follows:
int getKey(void)
{
int toRet = 0;
int firstHalf = 0, secHalf = 0;
TRISD = 15, PORTD = 240;
firstHalf = PORTD;
TRISD = 240, PORTD = 15;
secHalf = PORTD;
switch (-((firstHalf + secHalf)-255))
{
case 20: toRet = 7; break; //1
case 36: toRet = 8; break; //2
case 68: toRet = 9; break; //3
case 18: toRet = 4; break; //4
case 34: toRet = 5; break; //5
case 66: toRet = 6; break; //6
case 17: toRet = 1; break; //7
case 33: toRet = 2; break; //8
case 65: toRet = 3; break; //9
case 40: toRet = 0; break; //0
case 24: toRet = 10; break; //*
case 72: toRet = 11; break; //#
default: toRet = 255; break; //null
}
return toRet;
}
The code is running fine on simulator but not on hardware it even doesn't generate any random key pressed. I am not using any pull up or pull down resistor because I think it may disturb the input mechanism. What should I do to solve this problem?
EDIT: After abdullah kahraman's answer I tried adding pull down resistors of 10k ohm on all keypad pins but the problem is stil the same. Also in simulation (Proteus ISIS simulator) the code runs fine with a warning Logic contention detected on net
on both pins input and output(+5V from uC) at that time. I am not using any pull resistor in simulation.