For this specific bit of code the answer is that the programmer wants to set the pins to a known state/voltage before setting them as outputs. But in general, the TRIS bits do more than just set a pin to input or output mode.
The TRIS mnemonic stands for tri-state. When a pin is tristated the resistance of that pin goes so high that they're effectively disconnected from the circuit.
If you've ever looked at busses you'd have seen tri-state circuits. They're the poor man's way of connecting multiple outputs together without using a multiplexer or a switch. All you need is to make sure that there is only one output on the bus that is not in tri-state mode at any point in time.
There is also a "safe" method of implementing busses by not allowing any device to output any voltage other than zero volts. The values on the bus gets VCC voltage via one or several pull-up resistors. Lots of serial busses do this. If I remember correctly CAN bus does this. Contention is never a problem with this scheme. You just need to take care of collisions which can be done in software.
Therefore in a lot of code I've worked with (and indeed in a lot of my own code) the PORT bits are hardcoded to 0
and the pins are driven by setting the TRIS bits to 1
or 0
. So you will sometimes see code in production where the outputs are controlled via the TRIS bits rather than the PORT bits.
PORTB = 0; // set PORTB to 0
, you know for certain that the programmer was not paying attention to what they were doing. \$\endgroup\$