views:

74

answers:

4

This is actually part of a project I'm working on using an avr. I'm interfacing via twi with a DS1307 real-time clock IC. It reports information back as a series of 8 chars. It returns in the format:

// Second : ds1307[0]
// Minute : ds1307[1]
// Hour   : ds1307[2]
// Day    : ds1307[3]
// Date   : ds1307[4]
// Month  : ds1307[5]
// Year   : ds1307[6]

What I would like to do is take each part of the time and read it bit by bit. I can't think of a way to do this. Basically lighting up an led if the bit is a 1, but not if it's a 0.

I'd imagine that there is a rather simple way to do it by bitshifting, but I can't put my finger on the logic to do it.

+2  A: 

Checking whether the bit N is set can be done with a simple expression like:

(bitmap & (0x1 << N)) != 0

where bitmap is the integer value (e.g. 64 bit in your case) containing the bits.

Finding the seconds:

(bitmap & 0xFF)

Finding the minute:

(bitmap & 0xFF00) >> 8

Finding the hour:

(bitmap & 0xFF0000) >> 16
Cătălin Pitiș
+1  A: 

If I'm interpreting you correctly, the following iterates over all the bits from lowest to highest. That is, the 8 bits of Seconds, followed by the 8 bits of Minutes, etc.

unsigned char i, j;
for (i = 0; i < sizeof(ds1307); i++)
{
  unsigned char value = ds1307[i];  // seconds, minutes, hours etc
  for (j = 0; j < 8; j++)
  {
    if (value & 0x01)
    {
      // bit is 1
    }
    else
    {
      // bit is 0
    }
    value >>= 1;
  }
}
Mania
That looks like it would work. I think I've got a problem with my I2C implementation.
Bocochoco
+1  A: 

Yes - you can use >> to shift the bits right by one, and & 1 to obtain the value of the least significant bit:

unsigned char ds1307[7];
int i, j;

for (i = 0; i < 7; i++)
    for (j = 0; j < 8; j++)
        printf("byte %d, bit %d = %u\n", i, j, (ds1307[i] >> j) & 1U);

(This will examine the bits from least to most significant. By the way, your example array only has 7 bytes, not 8...)

caf
A: 

essentially, if the 6 LEDs to show the seconds in binary format are connected to PORTA2-PORTA7, you can PORTA = ds1307[0] to have the seconds automatically lit up correctly.

lImbus
There are 20 LED's being used for the display. I charlieplexed them, so its not quite that simple.
Bocochoco
thanks for showing/teaching me charlieplexing :)
lImbus