Decimal to BCD conversion

fastgrandad

New Member
I have a project that uses the 1307 chip to provide reasonably accurate time. I want to be able to alter the time setting from the main program and have a routine that reads the individual clock parameters, any of which, after being converted from BCD to decimal, can be incremented/decremented and then written back to the clock. However, to be written back they need to be converted back from decimal to BCD.

I've written a few lines of code that seem to do the trick but wondered whether there is a more elegant way of doing the conversion to BCD.

b2=b1/10 'isolate MSD
b3=b1//10 'isolate LSD
b4=b2*16+b3 'shift MSD bits left 4 places (X16), add to LSD = BCD

where b1 is the decimal number and b4 has been converted to BCD.

Paul
 

westaust55

Moderator
You do not indicate which PICAXE chip you are using.

For the X1 and X2 parts, there is the BINTOBCD function. See PICAXE Manual 2 page26 or here: http://www.picaxe.com/BASIC-Commands/Variables/let/

Keep in mind that while you can be presented with decimal numbers, the PICAXE (as do nearly all computers) handle and store numbers in binary. They are just displayed in decimal or hexadecimal to help us.

For M and M2 parts you can reduce your 3 lines to 2 lines with:
b2=b1 / 10 * 16 'isolate MSD
b3=b1//10 + b2 'isolate LSD and merge in MSD
 

AllyCat

Senior Member
Hi,

Or there's hippy's "one-liner" code snippet , from post #5 : ;)

.... to convert a BCD ($12) byte to binary decimal (12) ...

bin = bcd / 16 * $FA + bcd

And to convert a binary decimal (12) byte to BCD ($12) ...

bcd = bin / 10 * 6 + bin


Cheers, Alan.
 

guydu99

New Member
I am using the DS1307 with a 08M2 in my project and I needed to reduce the number of registers. Here is my current code which is similar to Westaust55's code where b3 would be replaced with b1. The decimal data register is overwritten with the BCD data. This is working fine.

Code:
#MACRO Bin2bcd(val)		
b0 = val/10*16			
val = val // 10 + b0		
#ENDMACRO

Reading time, b7=minutes b8=hours

Code:
hi2csetup i2cmaster, ADR_DS1307, i2cslow, i2cbyte       
hi2cin DS1307_minutes, (b7,b8)
Writing back after incrementing/decrementing. Seconds are forced to 01.
Code:
Bin2bcd(b7)		                               			    
Bin2bcd(b8)				                                    	
hi2cout DS1307_seconds, ($01,b7,b8)
 

fastgrandad

New Member
Thanks for all the helpful replies. I'm using a 14M2.

I've used Hippy's code snippet for BCD to decimal but had missed the reverse version. Visualising it in binary is what led me to my method, although I'd overlooked the opportunity to save a line.

guydu99 has prompted me to investigate macros which I have, as yet, not looked at.

Thanks again

Paul
 
Top