Created
April 22, 2020 04:25
-
-
Save nuntipat/396aa91ccc98e683e281b073a66f817b to your computer and use it in GitHub Desktop.
CPE328 (2/2019) RTC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define F_CPU 8000000UL | |
#include <avr/io.h> | |
#include <util/delay.h> | |
void sendMax7219Command(uint8_t address, uint8_t data) | |
{ | |
PORTB &= ~(1 << PORTB2); | |
SPDR = address; | |
while (!(SPSR & (1 << SPIF))); | |
SPDR = data; | |
while (!(SPSR & (1 << SPIF))); | |
PORTB |= (1 << PORTB2); | |
} | |
uint8_t readDS1307(uint8_t address, uint8_t* data) | |
{ | |
// send start bit | |
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN); | |
while (!(TWCR & (1 << TWINT))); | |
if ((TWSR & 0xF8) != 0x08) | |
return 1; | |
// send SLA + W | |
TWDR = 0b11010000; | |
TWCR = (1 << TWINT) | (1 << TWEN); | |
while (!(TWCR & (1 << TWINT))); | |
if ((TWSR & 0xF8) != 0x18) | |
return 2; | |
// send register adress | |
TWDR = address; | |
TWCR = (1 << TWINT) | (1 << TWEN); | |
while (!(TWCR & (1 << TWINT))); | |
if ((TWSR & 0xF8) != 0x28) | |
return 3; | |
// repeat start | |
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN); | |
while (!(TWCR & (1 << TWINT))); | |
if ((TWSR & 0xF8) != 0x10) | |
return 4; | |
// send SLA + R | |
TWDR = 0b11010001; | |
TWCR = (1 << TWINT) | (1 << TWEN); | |
while (!(TWCR & (1 << TWINT))); | |
if ((TWSR & 0xF8) != 0x40) | |
return 5; | |
// get data and return NACK | |
TWCR = (1 << TWINT) | (1 << TWEN); | |
while (!(TWCR & (1 << TWINT))); | |
*data = TWDR; | |
if ((TWSR & 0xF8) != 0x58) | |
return 6; | |
// send stop | |
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN); | |
return 0; | |
} | |
int main() | |
{ | |
DDRB |= (1 << PORTB2) | (1 << PORTB3) | (1 << PORTB5); | |
PORTB |= (1 << PORTB2); | |
SPCR |= (1 << SPE) | (1 << MSTR); | |
// initialize TWI module | |
TWBR = 8; // SCL 100KHz | |
TWSR |= (1 << TWPS0); // prescalar / 4 | |
TWCR |= (1 << TWEN); | |
// set decode mode | |
sendMax7219Command(0x09, 0xFF); | |
sendMax7219Command(0x0B, 0x01); | |
sendMax7219Command(0x0A, 0x07); | |
sendMax7219Command(0x0C, 0x01); | |
while (1) | |
{ | |
uint8_t second = 0; | |
uint8_t error = readDS1307(0x00, &second); | |
sendMax7219Command(0x01, (second & 0x70) >> 4); | |
sendMax7219Command(0x02, second & 0x0F); | |
_delay_ms(500); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment