Discussion in "PIC Microcontroller Discussion" started by    navintiwari08    Jul 28, 2013.
Sun Jul 28 2013, 01:31 am
#1
hello everyone..
I'm trying to interface a 4x4 matrix keypad to 16f877a.. the following code written in hi tech c is not working.. the program is printing characters of the array randomly without a keypress.. please help.. i'm using mplab 8.85.. using lcd 16x2..
NOTE: if I change the value of TRISC to 0x00, the code works fine.. but then i'm not making any input ports.. so how is it scanning a key press..?
thanks in advance..

#include<htc.h>

#define _XTAL_FREQ 20000000
#define lcd PORTB 
#define key PORTC
#define rs RE0
#define rw RE1
#define en RE2

__CONFIG(FOSC_HS&LVP_OFF&BOREN_OFF&CP_OFF&PWRTE_OFF&WRT_OFF&WDTE_OFF);

void lcd_init();
void lcd_cmd(unsigned char);
void lcd_data(unsigned char);

void main()
{
	unsigned char col,row;
	unsigned char i[4][4]={'0','1','2','3',
					   	   '4','5','6','7',
				       	   '8','9','A','B',
					   	   'C','D','E','F'};
	TRISB=0x00;
	TRISE=0X00;
	__delay_ms(2);
	ADCON1=0x07;
	lcd_init();
	while(1)
	{
		do
		{
			TRISC=0x0f;
			key=0x0f;
			col=key;
			col=col&0x0f;
		}
		while(col!=0x0f);
		
		do
		{	
			do
			{
				__delay_ms(5);
				col=key;
				col&=0x0f;
			}
			while(col==0x0f);
			__delay_ms(10);
			col=key;
			col&=0x0f;
		}
		while(col==0x0f);
			
		while(1)
		{
			key=0x7f;
			col=key;
			col&=0x0f;
			if(col!=0x0f)
			{
				row=3;
				break;
			}
			
			key=0xbf;
			col=key;
			col&=0x0f;
			if(col!=0x0f)
			{
				row=2;
				break;
			}

			key=0xdf;
			col=key;
			col&=0x0f;
			if(col!=0x0f)
			{
				row=1;
				break;
			}

			key=0xef;
			col=key;
			col&=0x0f;
			if(col!=0x0f)
			{
				row=0;
				break;
			}
		
		}
		if(col==0x0e)
			lcd_data(i[row][0]);
		else if(col==0x0d)
			lcd_data(i[row][1]);
		else if(col==0x0b)
			lcd_data(i[row][2]);
		else if(col==0x07)
			lcd_data(i[row][3]);
	}
}

void lcd_init()
{
	unsigned char cmd[]={0x38,0x0e,0x01,0x06,0x80};
	unsigned char i;
	for(i=0;i<=4;i++)
	{
		lcd_cmd(cmd[i]);
		__delay_ms(10);
	}
}

void lcd_cmd(unsigned char x)
{
	rs=0;
	rw=0;
	lcd=x;
	en=1;
	__delay_us(2);
	en=0;
}

void lcd_data(unsigned char x)
{
	rs=1;
	rw=0;
	lcd=x;
	en=1;
	__delay_us(2);
	en=0;
}	 
Wed Jul 31 2013, 10:12 am
#2
commenting your code would make it helpful to understand. anyway,
                        TRISC=0x0f;
                        key=0x0f;

In your source code, You are moving data to PortC after making it as input port. so it will not work, however if you change this to TRISC = 0, this will make lower nibble as output port and key=0x0f works.

Get Social

Information

Powered by e107 Forum System

Downloads

Comments

KevinTab
Sun Apr 28 2024, 05:35 am
Tumergix
Sun Apr 28 2024, 12:59 am
StevenDrulk
Sat Apr 27 2024, 08:47 pm
StephenHauct
Sat Apr 27 2024, 09:38 am
Adamsaf
Sat Apr 27 2024, 07:12 am
Robertphype
Sat Apr 27 2024, 12:23 am
ktaletrryp
Fri Apr 26 2024, 10:55 pm
Robertrip
Fri Apr 26 2024, 11:20 am