Menu

Integer square root for ATmega328p

jabcam
2017-03-16
2017-03-16
  • jabcam

    jabcam - 2017-03-16

    (This is also a test to see if I got the formatting correct:)

    Here comes a sqrt-routine, written in AVR-assembler for speed, takes some 90 cycles to run, i.e. 5.6 µs on Arduino@16 MHz.

    \ square root of unsigned cell. 
    : sqrt ( u --- u )
        [ R16 $00 ldi,         ]
        [ R17 $80 ldi,         ]
        [ begin,               ]
        [     R16 R17   eor,   ]
        [     R16 R16   mul,   ]
        [     R0  R24   cp,    ]
        [     R1  R25   cpc,   ]
        [     lo, not, if,     ]    
        [         R16 R17 eor, ]
        [     then,            ]
        [     R17 lsr,         ]
        [ eq, until,           ]
        [ R24 R16 movw,        ]
    ;
    
     
  • Mikael Nordman

    Mikael Nordman - 2017-03-20

    4 sqrt gives one as a result. It should be two. I added one to the input number to get correct results for 2 4 9 16 etc.

    Here is the code written with the new tabledriven assembler which I published today.

    \ square root of unsigned cell.
    : sqrt ( u --- u )
      as: adiw r24 1
      as: ldi r16 $00
      as: ldi r17 $80
      as: begin
      as:   eor r16 r17
      as:   mul r16 r16
      as:   cp  r0  r24
      as:   cpc r1  r25
      as:   if  sh
      as:     eor r16 r17
      as:   then
      as:   lsr r17
      as: until eq
      as: movw  r24 r16
    ;
    
     

    Last edit: Mikael Nordman 2017-03-20

Log in to post a comment.