Electronic – How to use the SET_TRIS_B function in PIC C

cmicrocontrollerpic

Suppose I want the following settings

B7 B6 B5 B4 B3 B2 B1 B0
0  0  0  0  0  1  0  1

I want B0 and B2 to be input and the rest to be output so I did the following

 set_tris_b(0x05);

This does make B0 and B2 Input but it also does not make B5 and B4 have a high logic level by default instead they have low logic level? Why is that ? Am I doing something wrong ?

Best Answer

I was just writing this answer to your other question but you deleted it. Since this question is related to the other I will post it here as it should answer both:

Setting a pin to input does not set it to any value, the pin itself is floating. This means it looks like a very high impedance to anything that connects to it (like an open circuit)

Another way to explain the difference is with the pin set to an output and logic 0, you could sink up to 20mA or so of current through it, for example to turn on an LED (LED anode connected to Vdd through appropriate resistor, LED cathode connected to pin - to turn on set pin to logic 0, to turn off set to logic 1)
If you do this with the pin set to input, the LED won't light as there is no current path to ground.
The TRIS register only controls the high impedance state, by disconnecting the output driver from the pin:

tristate driver

The high impedance is good for an input, since it means whatever is connected to it can drive the pin high or low easily.

These type of pins are called "tristate" pins, since they can be in three states: high, low, or high impedance ("1", "0" or "Z")

When the pin is set to input, if you want to ensure it is at high or low you can set what is called a "weak pullup" or "weak pulldown" if the microcontroller has this available. This looks like a high resistor connected between Vdd (or ground) and the pin, which pulls it high or low weakly, so something can drive it to another state easily without using too much current (an output connected to an output is a bad idea, and called "bus contention" since the two outputs fight to set the line to their particular state. The line will generally end up in between states, where exactly depends on the relative strength of each driver)