How to read a port?!

How do you read an entire port (8 bits) and store that value?

For example, I want to read port A since I am using a Mega and I think I am using port A in parallel so pins 22-29, 22 being the LSB. I cannot find anything on google! Has google actually failed me? Or have I failed myself :frowning:

"direct port manipulation"

I looked on their port manipulation page and from what I understand, you have to make the port an input:

DDRA = 0;

and then read the port

value = PORTA

Am I right?

you have to make the port an input:

No, you can read both input and output bits at the same time.

That will work, but even if a pin is set as an output you can still read it's value.

Also bear in mind that not all ports have 8 pins.

EDIT: As Nick points out below, use PINx to read, PORTx to write.


Rob

I understand that all ports may not have 8 bits but I looked it up and in fact, PORTA has 8 bits (:

As far as an input or output, you're saying I don't have to make it an input?

So If I connect 5v to pin 22 I would be able to do a

value = PORTA

and value should now be 1?

even though PORTA is not set as an input?

You don't have to make it an input to read it, but if you read an output it will tell you the value the output is set to. If it's not set to an input, then it won't read the external signal.

For reading, it is PINA. For writing it is PORTA.

So If I connect 5v to pin 22 I would be able to do a

value = PORTA

and value should now be 1?

even though PORTA is not set as an input?

Er, the pin can't have two values. To read you use PINA. I think, but am not certain, that if you read PORTA (as you did above) you would find only the last value you wrote to PORTA. That isn't necessarily the current state of PINA.

In principle, assuming ports are set the right direction and so on, you could do this:

PORTB = PINA;

This would copy 8 inputs to 8 outputs.

njdurkin:
value = PORTA

and value should now be 1?/quote]

As Nick mentions, you need to read PINSA and not PORTA. Keep in mind that if the pins are floating you'll be reading random values on the unconnected pins.