Electronic – How to compare time-of-day numbers stored in Binary Coded Decimal in PIC

pic

I am using a PIC18f which has an internal real-time clock. The the day, month and year values are stored in BCD format. The data sheet says these values are stored in BCD format in Registers.

I want to compare time. E.g. if (time==10.20) // 10 hours twenty minutes

Do I need to do some conversions to other data type like int/char while dealing with BCD in Registers?

Best Answer

Binary-coded (BCD) decimal simply simply means each decimal digit is encoded in 4 bits (0-9, or 0000 to 1001), with the remaining six values (10-15, or 1010 to 1111) unused. Usually two BCD digits are placed side by side inside an 8-bit byte, so values of 0-99 can be encoded.

So a minutes value of 59 would be encoded as:

0101 1001     0x05  0x09

instead of its binary representation:

0011 1011    0x3B    (3*16 + 11 = 59)

Encoding digits this way makes it easy to display them, since you only have to shift and mask them, no binary to decimal conversion is necessary. E.g. if you have two BCD digits in a byte BCDdigits (which might represent one of the registers in the RTCC module), then

ones = BCDdigits & 0xf;
tens = BCDdigits >> 4;

These examples all assume unsigned variables.

Two multi-digit numbers both in BCD format can be compared directly, as long as they are aligned correctly.

For example, the registers in the PIC18 RTCC are all 8 bit. So you have to either do this:

if ((HOURS == 0x10) && (MINUTES == 0x20))

or this

if ((HOURS << 8) | MINUTES ) == 0x1020)

where HOURS and MINUTES are the hours and minutes registers in the PIC18 RTCC.

If the second number to be compared is not in BCD, then you will need to convert them to a common base, such as minutes. So if you have one byte containing minutes in BCD, and another containing hours in BCD, you could compute:

unsigned short minutes;
minutes = 600*(HOURS >> 4) + 60*(HOURS & 0x0f)
         + 10*(MINUTES >> 4) + (MINUTES & 0x0f);

and then compare that with your other value also converted to minutes.