Lesson 8: Arithmetic

Almost all microcontrollers include some kind of arithmetic capability and in the case of the PIC12F508 this is limited to simple 8-bit additions and subtractions. Both operations require one of the operands to be loaded into the Working Register so we normally need to use our movf/movlw instructions to set things up before we can do the actual calculation:

// my_var = 10 movlw 10 movwf my_var // Calculate my_var = my_var + 20 movlw 20 addwf my_var, f // Calculate my_var = my_var - 30 movlw 30 subwf my_var, f

Remember that the second operand in addwf and subwf simply tells the ALU where to put the result of the calculation, as was explained in Lesson 5.

One issue with these instructions is that if you try to add two large number the result may exceed the maximum value (255) that can be stored in an 8-bit memory location. This is called an overflow and your code can check for this by looking at the Carry (C) bit in the STATUS special function register. If the result of an arithmetic operation is an overflow (or underflow in the case of subtraction), the flag will be set.

movlw 200 movwf my_var movlw 100 addwf my_Var, f // carry flag will be set

We will learn how our code can test the state of this flag in Lesson 11. Also note that the STATUS register contains another useful flag called Zero (Z) that is set when the result of executing an instruction is 0. Keep in mind that these flags are not updated by all instructions, so make sure you check Page 58 of the datasheet if you are unsure.

Next Lesson >>