I/O port clarification

Thread Starter

buddih09

Joined Dec 21, 2010
5
Hi,

I understand by reading the documents that when a port is read it reads the value of the pin and not the value of the output latch. With that can you please examine the following code sample (not the exact C code but just for explaining my question);

TRISA = 0;
PORTA=0; (Can I write this as I have already set PORTA as an output? I want to keep the output low on PORTA)
....
....

if (PORTA==0) (Can I write this? And if I write this what will be value that is going to be read?)
....
....
Thank you very much.

Buddi
 

takao21203

Joined Apr 28, 2012
3,702
Normally this should work as intended. But can depend on what you have connected to the port, and the frequency as well.

Especially in assembler, where indeed it can be required to wait a little.

If you only set a bit also C compiler will usually only use one assembler instruction!

But, if you use high frequency + long wires/PCB tracks, the immediate result is not guaranteed anymore.

You'd have to deal with damping resistors, compensation coils and things like this, which is beyond my knowledge to explain properly, even if I can get along with these problems.

There are also some PIC models which have extra latch registers, for instance the new extended midrange.

Generally if I want to set multiple bits, I don't work on the port all the time, but prepare this in memory, then write once when it is completed!

If you have the full port set to output, then logically you also will obtain the same value that you write to the output latch.
 

Dodgydave

Joined Jun 22, 2012
11,307
Tris just tells the port to be input or output, if you want port A bit 0 to stay low, then write : movlw 0 : movwf portA,0: this will make bit zero on port A low.
 

ErnieM

Joined Apr 24, 2011
8,377
You can write to any PORT irregardless of the value of the associated TRIS register. It is common to write before setting TRIS such that when pins become outputs for the first time the start off at their proper levels.

When a port also has a LATCH register it is far preferred to write to the LATCH as it gives better (consistent) results.

Reading a PORT reads the current pin status of the pins themselves, not the register. If a pin is heavily loaded (or even shorted) the port bit and the pin value may not be the same.
 

Thread Starter

buddih09

Joined Dec 21, 2010
5
OK thank you. I think it is clear to me that I can write to latch register. But still not very clear what will happen if I try to read the latch register while TRISA = 0.

Can someone please explain this to me. Will it try to read the pins or the content that I put to the latch register?

Thank you :)
 

takao21203

Joined Apr 28, 2012
3,702
"the document" could be anything.

If you read the port register, you get the value from the port.
If you read the latch then you get what you wrote to the latch.

If the TRIS is 0, then port=latch otherwise it's input.
 
Top