0
votes

I'm looking for code or help with AVR for this function. Or if not code can I get some clue how to do it?

R20 = (4 * R16 + 3 * R17 - R18) / 8

For now I have something like this:

.org 0x0000

start:
.DEF ANSL = R0
.DEF ANSH = R1  
.DEF    A = R19
.DEF    B = R21
.DEF    C = R22
.DEF    D = R20

        ldi A, 4
        ldi B, 3
        ldi C, 8

        ldi R16, 5
        ldi R17, 10
        ldi R18, 58

        MUL A,R16   (4 * R16)
        MUL B,R17   (3 * R17)
        add A,B     (4 * R16 + 3*R17)
        sub A, R18  (4 * R16+3*R17 - R18)

I'm not sure if it's code is correct.

1
The best way to find out if your code is correct is to test it. - Paul R
you might want to rewrite the formula to do the division as early as possible to avoid register overflow: 2 * R16 + (3* R17)/8 - R18/8 (Division is missing from your code anyhow) - tofro

1 Answers

1
votes

when multiplying/dividing with powers of 2, substitute MUL and DIV instructions by shift operations:

MOV r20, r17    ; start with r17*3
LSL r17         ; left shift is multiply by 2
ADD r20, r17    ; now r20 is 3* r17 (r17 + 2*r17)

LSL r16         ; each left shift is a multiplication by 2
LSL r16         ; 
ADD r20, r16    ; now r20 is 3* r17 + 4* r16

SUB r20, r18    ; now r20 is 3* r17 + 4* r16 - r18

LSR r20         ; each right shift is a division by 2
LSR r20
LSR r20