divide function in assembler

Hi,
I tried to write divide function (integer and rest) in assembler but the results are wrong and after hours of debugging I am hopeless :frowning:
here is my code:

#include <stdint.h>
uint16_t s1=0,s2=0;
uint32_t escape=0;

 
void setup() {
  Serial.begin(115200);
}

void loop() {
  if (Serial.available()){
    
    s1=Serial.parseInt();
    s2=Serial.parseInt();
    Serial.flush();
    escape=0;
  asm volatile(
    "mov %C0, 0\n\t"
    "mov %D0, 0\n\t"

    "Test: cp %B1,%B2\n\t"
    "breq LowBits \n\t"
    "cp %B1,%B2\n\t"
    "brsh Loop \n\t"
    "jmp Exit\n\t"

    "LowBits: cp %A1,%A2\n\t"
    "brsh Loop \n\t"
    "jmp Exit\n\t"

    "Loop: adiw %C0,1\n\t"
    "sub %A1,%A2\n\t"
    "sbc %B1,%B2\n\t"
    "jmp Test\n\t"
    
    "Exit:\n\t"
    "mov %A0, %A1\n\t"
    "mov %B0, %B1\n\t"
      :
      "=w" (escape):
      "w" (s1), "w" (s2));
  Serial.println(escape,HEX);
  Serial.println(escape&0xffff);
  Serial.println(escape>>16);
  }
}

Can you please tell me what’s wrong or give me a hint or something to move on?
Thanks in advance!

jdzejdzej: I tried to write divide function (integer and rest) in assembler but the results are wrong and after hours of debugging I am hopeless :(

You are the re-inventor of the wheel?

Why not use the AVR LIBC function for it? The "div" function of the AVR LIBC is written in assembler:

void setup() {
  Serial.begin(9600);
  Serial.println("Good night and good luck!");
  div_t result= div(12345, 67);
  Serial.print("12345 / 67= ");Serial.println(result.quot);   // quotient
  Serial.print("12345 % 67= ");Serial.println(result.rem);  // remainder
}

void loop() {}

If you need the assembler sources, you will have to download the assembler sources that belong to the AVR LIBC library.

P.S.: The AVR LIBC also comes with a "ldiv" function doing the same with "long" variables.

The AVR LIBC library reference is here.

It’s simply my homework - I don’t want to re-invent the wheel, I have to write it in assembler for my classes.

    Serial.flush();

Block until all pending outgoing serial data has been sent. In God's name, why? You are not sending anything.