andi r20, 0x0f
masks the upper nibble to produce 0x05 = 0b00000101.
* Next we need to add 0x30 (since '0' = 0x30):
subi r20, -'0'
We use SUBI because the ATmega32 does not have an ADDI instruction.
Adding 0x30 to 0x05 gets us: 0x35 which is '5'.
This works as long as the result is between '0' and '9', but if the result is greater than '9', then we need a letter.
We can get this by adding 7… 'A' = 0x41 = 0x40 + 7.
cpi r20, '9' + 1
brlo done
subi r20, -7
done:
ret
; Converts lower nibble of r20 into its ASCII equivalent
; The result is stored in r20
convertLowerNibble:
andi r20, 0x0f ; masking: clear upper nibble
; Convert to ASCII
subi r20, -'0' ; add '0' to r20
; Correct conversion if digit is greater than '9'
cpi r20, '9' + 1
brlo done
subi r20, -7
done:
ret