Keypad works only in active low

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hello, i am sure i am doing something wrong here and its most probably my coding. I have a ATmega164P and i am interfacing a 4x4 keypad with it. I know the working of keypad so here is the code which set a state to row1 and scans the columns

void r1(void)
{
	DDRC = 0xF0;
	PORTC=0x7F;
	
	_delay_ms(200);
		

	if ((PINC & (1<<PC3)) == 0) 
	{
		LCDdata('1');
		_delay_ms(200);
	}
	else if ((PINC & (1<<PC2)) == 0)
	{
		LCDdata('2');
		_delay_ms(200);
	}
	else if ((PINC & (1<<PC1)) == 0)
	{
		LCDdata('3');
		_delay_ms(200);
	}
	else if ((PINC & (1<<PC0)) == 0)
	{
		LCDdata('A');
		_delay_ms(200);
	}
}

The rows are connected to higher nibble of PORTC and Columns are connected to lower nibble.
Now in this code i am setting the MSB to Low, and then checking the lower nibble for low state.

My questions is: When i check the PIN register for a high state, the code does not work e.g:

	DDRC=0xF0;
	PORTC=0x80;
	
	if ((PINC & (1<<PC3)) == 1) //checking for a high
	{
		LCDdata('1');
		_delay_ms(200);
	}

For some reason this does not work... i want to know why?

a side question: as you can see the pin7 is state low, and when a key is pressed, it shorts a high pin with a low pin(i.e PIN1 with PIN7) i hope this is not a problem?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

HellsGuardian wrote:

For some reason this does not work... i want to know why?

Because if for example bit 4 is on, the value is not 1 but 16. You might want to compare if it is just not zero.

HellsGuardian wrote:

a side question: as you can see the pin7 is state low, and when a key is pressed, it shorts a high pin with a low pin(i.e PIN1 with PIN7) i hope this is not a problem?

No (but read below), because high nybble is output and low nybble is input. But if you have no pull-up resistors, floating inputs have no defined state and could read as one or zero. This is why the first one is better, it enables pull-ups on inputs, and all input pins are high if no button is pushed, and a pushed button reads low.

You do have a problem if you push more than one button, as it can short-circuit two outputs if you have no diodes in your circuit. Perhaps it would be best to use only open-collector output mode to pull low one row bit and leave other row bits as (pulled-up) inputs.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

There are tons of code already on the web, e.g.:

https://www.avrfreaks.net/index.p...

Peter