Lesson 12: I/O Ports

A microcontroller interacts with its surroundings using its external interface pins. Groups of these that share common functionality are referred to as ports and on the PIC12F508 there are six pins that make up a single port called GPIO. The hardware maps each pin to a bit in the GPIO special function register, and this can be used in your code to read the state of input pins and control the state of outputs.

Each pin can be individually configured as either an input or an output using a special instruction (note on many other chips this is done using a special function register instead) called tris. This moves the current value of the working register to a hidden register that controls the pin directions. If a bit position is set to 1, the pin is configured as an input. If it is set to 0, the pin is an output. All the pins are inputs by default so make sure you remember to setup any outputs you require before you try to use them:

// Set GP0 and GP2 as outputs, everything else inputs movlw 00111010b tris 6

Note that the tris instructions must always be called with the operand 6 passed to it. This is just a safety mechanism to prevent a glitch from changing the pin directions by accident. In the world of microcontrollers, setting a pin incorrectly can physically damage the chip.

If a pin is configured as an output, you can change its state by setting or clearing the corresponding GPx bit in the GPIO register:

bsf GPIO, 0 // Set the GP0 pin (high) bcf GPIO, 0 // Clear the GP0 pin (low)

If it is configured as an input you can use the bit test operations to check whether it is high or low:

btfss GPIO, 1 // Check if GP1 pressed (low) goto button_pressed btfsc GPIO, 1 // Check if GP1 released (high) goto button_not_pushed

The simulator lets you test out the I/O system by connecting virtual switches and LEDs to each of the microcontroller's pins. To change what is assigned simply click on the pin name (GPx text) and the options will cycle. When a switch is selected you can turn it on and off by clicking on its image.

Note that the microcontroller has internal pullup resistors on all input lines. These hold the pin high when it is left disconnected, and allows us to use the switch-to-ground configuration shown in the Simulation Window circuit diagram.

Also note that the GP3 pin can only be configured as an input.

Next Lesson >>