Conditional branching and working with bits <br />One of the most important features of any microprocessor or microcontroller program is its <br />ability to make ‘decisions’, i.e. to act differently according to the state of logical variables. <br />Microprocessors generally have within their instruction sets a number of instructions which <br />allow them to test a particular bit, and either continue program execution if a condition is not <br />met or branch to another part of the program if it is. This is illustrated in Figure 5.3. These <br />variables are often bit values in condition code or Status registers. <br />ThePIC16Seriesmicrocontrollersarealittleunusualwhenitcomestoconditionalbranching <br />as they do not have branch instructions as such. They have instead four conditional ‘skip’ <br />instructions.Thesetestforacertaincondition,skippingjustoneinstructioniftheconditionis <br />met and continuing normal program execution if it is not. The most versatile and general- <br />purpose of these are the instructions: <br /> <br /> <br /> <br />Branching on Status register bits <br /> <br />Aswedevelopbiggerprograms,wequicklyfindthatthereareprogramsectionsthataresouseful <br />thatwewouldliketousethemindifferentplaces.Yetitistedious,andspace-andmemory- <br />consuming,towriteouttheprogramsectionwheneveritisneeded.Enterthesubroutine. <br />The subroutine is a program section structured in such a way that it can be called from <br />anywhere in the program. Once it has been executed the program continues to execute from <br />wherever it was before. The idea is illustrated in Figure 5.4. At some point in the main <br />program there is an instruction ‘Call SR1’. Program execution then switches to Subroutine 1, <br />identified by its label. The subroutine must end with a ‘Return from Subroutine’ instruction. <br />Program execution then continues from the instruction after the Call instruction. A little later <br />in the program another subroutine is called, followed a little later by another call to the <br />first routine. <br />TheactionoftheCallinstructionistwo-fold.ItsavesthecontentsoftheProgramCounteronto <br />theStacksothattheCPUwillknowwheretocomebacktoafterithasfinishedthesubroutine. <br />It then loads the subroutine start address into the Program Counter. Program execution thus <br />continuesatthesubroutine.ThereturninstructioncomplementstheactionoftheCall.Itloads <br />theProgramCounterwiththedataheldatthetopoftheStack,whichwillbetheaddressofthe <br />instruction following the Call instruction. Program execution then continues at this address. <br />SubroutineCallandReturninstructionsmustalwaysworkinpairs.GothroughProgramming <br />Exercise 5.3 to find out what happens if they don’t.