Skip to content

Instantly share code, notes, and snippets.

@nuntipat
Created May 7, 2019 04:03
Show Gist options
  • Save nuntipat/b180160f7970c3c566fa9262ae550f01 to your computer and use it in GitHub Desktop.
Save nuntipat/b180160f7970c3c566fa9262ae550f01 to your computer and use it in GitHub Desktop.
CPE326_RTC
#include <stdio.h>
#include <avr/io.h>
#define F_CPU 8000000UL
#include <util/delay.h>
typedef struct
{
uint8_t sec;
uint8_t min;
uint8_t hour;
uint8_t weekDay;
uint8_t date;
uint8_t month;
uint8_t year;
} rtc_t;
rtc_t DS1307_Read()
{
TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN); // send start bit
while (!(TWCR & (1<<TWINT))); // wait until start bit is send
TWDR = 0xD0; // send address (in write mode)
TWCR = (1<<TWINT) | (1<<TWEN);
while (!(TWCR & (1<<TWINT)));
TWDR = 0x00; // set read pointer to address 0
TWCR = (1<<TWINT) | (1<<TWEN);
while (!(TWCR & (1<<TWINT)));
TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWSTO); // send stop bit
rtc_t currentTime;
TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN); // send start bit
while (!(TWCR & (1<<TWINT))); // wait until start bit is send
TWDR = 0xD1; // send address (in read mode)
TWCR = (1<<TWINT) | (1<<TWEN);
while (!(TWCR & (1<<TWINT)));
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
while (!(TWCR & (1<<TWINT)));
currentTime.sec = ((TWDR & 0x70) >> 4) * 10 + (TWDR & 0x0F);
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
while (!(TWCR & (1<<TWINT)));
currentTime.min = ((TWDR & 0x70) >> 4) * 10 + (TWDR & 0x0F);
TWCR = (1<<TWINT) | (1<<TWEN);
while (!(TWCR & (1<<TWINT)));
currentTime.hour = ((TWDR & 0x30) >> 4) * 10 + (TWDR & 0x0F);
TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWSTO); // send stop bit
return currentTime;
}
int main(void)
{
TWBR = 32; // 100Khz at 8Mhz Fcpu
TWCR |= (1 << TWEN); // enable TWI module
// Enable RX and TX module
UCSR0B |= (1 << RXEN0) | (1 << TXEN0);
// Set data to 8bit
UCSR0C |= (1 << UCSZ01) | (1 << UCSZ00);
// Set baud rate to 9600 at 8MHz
UBRR0 = 51;
int i;
char buffer[32];
while (1)
{
rtc_t currentTime = DS1307_Read();
sprintf(buffer, "%d:%d:%d\r", currentTime.hour, currentTime.min
, currentTime.sec);
// wait until transmit buffer ready
i = 0;
while (buffer[i] != '\0')
{
while (!(UCSR0A & (1 << UDRE0)));
UDR0 = buffer[i];
i++;
}
_delay_ms(1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment