## simple branch/compare question

4 posts / 0 new
Author
Message

here is a simple predicament that seems to have me temporarily baffled due to a lack of sleep. My program was acting up & I found a simple branch might be the problem.

say temp=r18 contains 33 hex. I want to add 20 hex to this value & and branch whenever volts=r19 is less than this sum:

ldi temp, data ;get the value
subi temp, \$E0 ; "ADD" 20
cp volts, temp
brlo do_it ;volts<= temp+20

This seems to work, but if temp is, say \$F3, then adding \$20 gives \$13. Then a value such as \$F5 will not be "lower" than the sum as intended. Essentially the rollover will screw everything up. I can program a workaround with a lot of tests & manipulations--but is there a simple wayto avoid these types of rollover problems?

When in the dark remember-the future looks brighter than ever.   I look forward to being able to predict the future!

What is the range of "data" and "volts"? Your description above implies that both "data+20" and "volts" can exceed \$FF.

In this case, the straightforward method to solve this problem is to use 16bit calculations:

```ldi tempL, data        ; get the 8bit data
clr tempH              ; zero-extend data to 16bits

subi tempL, low(-\$20)  ; "ADD" \$20 to temp
sbci tempH, high(-\$20)

cp voltsL, tempL
cpc voltsH, tempH

brlo do_it             ;volts < temp+\$20```

So, that will work. But it does require a couple of extra registers to store tempH and voltsH.

For your example where "data"=\$F3, "temp" will be \$0113, and the brlo branch will be taken when "volts" is in the range of \$0000..\$0112.

If volts is always >= \$20, there's another solution you can use. Instead of adding \$20 to "data", subtract \$20 from "volts":

```ldi temp, data         ; get the value

mov temp2, volts
subi temp2, \$20        ; subtract \$20 from volts

cp temp2, temp
brlo do_it             ; volts < temp+\$20
```

In this case, if "data"=\$F3, the branch will be taken when "volts" is between \$20..\$F2 or \$00..\$12.

The lower range causes a branch because the code subtracts \$20 from "volts". So, when "volts"=\$12, "temp2"=(\$12 - \$20)=\$F2, which is less-than \$F3.

I'd suggest using the 16bit version, unless you absolutely, positively know that the range of "data" and "volts" will allow the 8bit code to work.

--Brian

PS. Rather than directly typing "\$E0", I find it more convenient to type what I mean: "-\$20", and let the assembler figure out that it equals \$E0.

PPS. You original comment for brlo had a "<=" in it, but brlo branches only for "<".