Hi,
This is how I do it in my code for reading digital calipers. I think I found the basic method that this code uses somewhere on the web (I can't remember where.)
I use it on an ATtiny4313
.ORG 0x90
RBCD0: .BYTE 1 ;MSB These following variable must be in this sequence ( 7 bytes )
RBCD1: .BYTE 1
RBCD2: .BYTE 1
RBCD3: .BYTE 1 ;LSB
Rbin0: .BYTE 1 ;MSB
Rbin1: .BYTE 1
Rbin2: .BYTE 1 ;LSB
; ***************************************************************************************************************
; * See note at start of program about Variables used in this subroutine in SRM *
; * ;Using registers R16, R17, R18, R19, R28, R29 Some may need to save them on the stack *
; * *
; * BintoBCD *
; ***************************************************************************************************************
BintoBCD:
PUSH R28
PUSH R29
LDI R19,24 ; 24-Bits Use at counter
LDI R16,0x00 ; Clear result area
STS RBCD0,R16
STS RBCD1,R16
STS RBCD2,R16
STS RBCD3,R16
Loop:
LDI R28,LOW (RBCD0) ;Set Y register to point to RBCD0
LDI R29,0x00 ;Required for Attiny4313 Not required as Attiny2313 has less than 256 bytes of data space
LDI R18,4 ;use as counter
BintoBCD1:
LD R17,Y ;Load inderect
LDI R16,0x33
ADD R17,R16
ST Y,R17 ; I do not think I need to save it at this point
SBRC R17,3 ; top bit of low nibble ? (If the original nibble was 5 or greater then adding 3
; will cause the top bit of nibble to be set)
ANDI R16,0xF0 ;
SBRC R17,7 ; top bit of high nibble ? (If the original nibble was 5 or greater then adding 3
; will cause the top bit of nibble to be set
ANDI R16,0x0F
SUB R17,R16
ST Y+,R17 ;Store indirect and increment pointer
DEC R18 ;Decrement counter (Counts down from 4)
BRNE BintoBCD1
LDI R28,LOW (Rbin2 + 1) ;Set Y register to point to Rbin2 +1 as we are using pre decrement
LD R17,-Y ;Rbin LSB
ROL R17 ; Need to save back after rotate
ST Y,R17
LD R17,-Y
ROL R17
ST Y,R17
LD R17,-Y
ROL R17
ST Y,R17
LD R17,-Y
ROL R17
ST Y,R17
LD R17,-Y
ROL R17
ST Y,R17
LD R17,-Y
ROL R17
ST Y,R17
LD R17,-Y
ROL R17
ST Y,R17
DEC R19 ;Counts down from 24
BRNE Loop
POP R29
POP R28
RET
I also have code to deal with negative values if you find that you need it.
Les.