Go Down

Topic: How to read a port?! (Read 870 times) previous topic - next topic

njdurkin

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 :(

AWOL

"direct port manipulation"
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

njdurkin

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?

Grumpy_Mike

Quote
you have to make the port an input:

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

Graynomad

#4
May 05, 2012, 12:22 am Last Edit: May 05, 2012, 05:01 pm by Graynomad Reason: 1
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
Rob Gray aka the GRAYnomad www.robgray.com

njdurkin

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?

Delta_G

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.

Nick Gammon

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

Quote
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.
http://www.gammon.com.au/electronics

Nick Gammon

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

Code: [Select]
PORTB = PINA;

This would copy 8 inputs to 8 outputs.
http://www.gammon.com.au/electronics

James C4S


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.
Capacitor Expert By Day, Enginerd by night.  ||  Personal Blog: www.baldengineer.com  || Electronics Tutorials for Beginners:  www.addohms.com

Go Up