reading input pin - stupid question

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

ok I'm simply trying to see if a buttons been pressed, initially I was using debounce code but it didn't work, so I thought I'd simply read the pin, however its not working.

Using mega 32, port D pin 7 has a 10k pullup resistor to 5V, and also a button to ground. I've check the hardware and its correct, no button press pin @ 5V, press button pin @ ground (0V).
The Led2 circuit has also been tested and is working.

initio.c

.
.
DDRD = 0x00; 
PORTD = 0x00; /*no pull up*/
.

reading of pin

if((PORTD & BIT7)== 0x00) /* if button pressed (active low) */ 
{ 
	Led2_off;
}
else
{
	Led2_on;
}

The led2 should be on and go off when I push the button, however when I run this, Led2 is ALWAYS off even though the voltages at the pin are correct.

As I have an external pull up I don't need the internal pull up enabled.
But if I enable the internal pull up

.
PORTD = 0xC0;   /* pull ups enabeled on buttons */
DDRD = 0x00;
.

When I run this, Led2 is ALWAYS on even though the voltages at the pin are correct.

Can anoyone (or perhaps everyone) see where I'm going wrong?

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

To read a port you need to use PINx, not PORTx. PORTx is only for setting the port.

Regards,
Steve A.

The Board helps those that help themselves.

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

Cheer, that did the trick.
So write to a port use PORTX and to read from a port use PINX?

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

Quote:
So write to a port use PORTX and to read from a port use PINX?

Yes. You can read from PORTX, but what you get is what you last wrote to PORTX. This means that when the port is set to input, what you get back is the state of the pull-ups. Some of the newer AVRs also let you write to PINX. On these chips, writing a one to PINX for a pin that is set as an output toggles the output value on that pin.

Regards,
Steve A.

The Board helps those that help themselves.