Compiling Another Program

Here's another example of hand-compiling a program for the HC11, using the flowcharting ideas from last time. Let's start with a program to sum the absolute values of the elements of a buffer.

sum = 0;
pnt = bufstrt;
while (pnt != bufend) {
    if (*pnt < 0)
        sum = sum - *pnt;
    else
        sum = sum + *pnt;
    pnt++;
}

Now, a flow chart:

Flowchart of sum algorithm

And now the assembly code (we'll assume the buffer we are summing is in EEPROM so we don't have to worry about initializing it):


        org EEPROM
bufstrt fcb 5, -2, 7, -3, 6, 5
bufend

start
        clra
        ldx   #bufstrt
loop    cpx   #bufend
        beq   done
        ldab  0,x
        bge   noneg
        sba
        bra   eloop
noneg   aba
eloop   inx
        bra   loop

done    staa  sum

mloop   bra   mloop

Here's a picture showing the original code and the final assembly code. You can see the structure of the program through the nested boxes; the lines of assembly code were generated from the C code to their left.

Original and assembly code