rtc_datetime_t drv_ds1307_read(void) { uint8_t ds1307_addr[] = {0x00}; twi_write_bytes(DS1307_I2C_ADDR, 1, ds1307_addr); rtc_datetime_t data; twi_read_bytes(DS1307_I2C_ADDR, sizeof(rtc_datetime_t), (uint8_t *) (&data)); data.seconds &= 0x7F; data.hours &= 0x3F; return data; }
void drv_ds1307_start(void) { uint8_t data [2]; data[0] = 0x00; /* Timekeeper Registers address */ twi_write_bytes(DS1307_I2C_ADDR, 1, &data[0]); twi_read_bytes(DS1307_I2C_ADDR, 1, &data[1]); data[1] &= 0x7F; /* Clear CH (enable clock generator) */ twi_write_bytes(DS1307_I2C_ADDR, 2, (uint8_t *)&data); }
void drv_ds1307_stop(void) { uint8_t data [2]; data[0] = 0x00; /* Timekeeper Registers address */ twi_write_bytes(DS1307_I2C_ADDR, 1, &data[0]); twi_read_bytes(DS1307_I2C_ADDR, 1, &data[1]); data[1] |= 0x80; /* Set CH (disable clock generator) */ twi_write_bytes(DS1307_I2C_ADDR, 2, (uint8_t *)&data); }
/* Writes num bytes starting from regAddrStart. Each subsequent byte will be written to the register above (newRegPtr = oldRegPtr + 1). Respects regMasks. * * 76543210 * 00010100 value[n] to write * 00011100 mask[n] byte * 01101101 original register[regAddrStart + n] * 01100001 original & ~mask * 01110101 masked | value * * Input: regAddrStart The register address to start reading bytes from * data Pointer to data to be written * regMasks Pointer to byte masks for each register * num The number of registers to be read * Return: 0 Succeeded * >0 Failed, see handle_error() for relavant error codes */ uint8_t twi_write_bits(uint8_t regAddrStart, uint8_t *data, uint8_t *regMasks, uint8_t num) { uint8_t i; uint8_t buffer[num]; twi_read_bytes(regAddrStart, buffer, num); for(i = 0; i < num; i++) { data[i] &= regMasks[i]; buffer[i] &= ~regMasks[i]; buffer[i] |= data[i]; } twi_write_bytes(regAddrStart, buffer, num); return 0; }
void drv_ds1307_write(const rtc_datetime_t rtc_datetime) { struct { uint8_t address; rtc_datetime_t datetime; } data; data.address = 0x00; data.datetime = rtc_datetime; /* Keep CH (clock enable) bit as it set */ uint8_t ch; /* Timekeeper Registers address */ uint8_t ds1307_addr[] = { 0x00 }; twi_write_bytes(DS1307_I2C_ADDR, 1, ds1307_addr); twi_read_bytes(DS1307_I2C_ADDR, 1, &ch); ch &= 0x80; data.datetime.seconds |= ch; twi_write_bytes(DS1307_I2C_ADDR, sizeof(data), (uint8_t *)&data); }