Lesson 10: Bit Operators

The PIC12F508 includes a set of bit (Boolean) instructions that allow you to set, clear and test individual bits in a register. These are very useful for simplifying many common embedded programming tasks and for making more efficient use of the limited amount of memory available. One common use is setting the state of an external pin:

// Configure GP0 as output (explained in Lesson 12) movlw 00111110b tris 6 // Bit clear/set instructions bcf GPIO, 0 // The LED is turned on bsf GPIO, 1 // The LED is turned off

The instructions accept a register address as the first operand and a bit index (between 0-7) as the second.

Another useful bit operation is the rrf and rlf instructions. These shift all the bits in the specified register along by one digit and are used in many sorts of programming algorithms such as multiplication or when implementing a software serial port:

// Load a test value movlw 10000000b movwf my_var // Shift Right rrf my_var, f // my_var contains 01000000b rrf my_var, f // my_var contains 00100000b rrf my_var, f // my_var contains 00010000b // Shift Left rlf my_var, f // my_var contains 00100000b rlf my_var, f // my_var contains 01000000b rlf my_var, f // my_var contains 10000000b

Note that the shift operations are actually circular, and bits move around in a loop via the Carry (C) bit in the STATUS special function register. In this way they differ slightly from the << and >> operators you might be familiar with from the C language. See Page 63 of the datasheet for more information on how this works.

Next Lesson >>