/* Read register 0 (second count) of DS3231 * * This program reads register at address 0 in the DS3231, the second count, * repetitively and dump the data to the LEDs. Since the second count uses * binary coded decimal format, the LEDs will count up from 0 to 9 in binary * and wrap around to 0. * * I2C1SCL P6.5 * I2C1SDA P6.4 * * Built and tested with MSP432P401R Rev. C, Keil MDK-ARM v5.24a and MSP432P4xx_DFP v3.1.0 */ #include "msp.h" void delayMs(int n); void I2C1_init(void); unsigned char I2C1_byteRead(int slaveAddr, unsigned char memAddr, unsigned char* data); void display(int data); #define SLAVE_ADDR 0x68 // 1101 000. int main(void) { unsigned char readback; unsigned char error; P2->DIR |= 0x30; /* P2.5, P2.4 set as output for LEDs */ P3->DIR |= 0x0C; /* P3.3, P3.2 set as output for LEDs */ I2C1_init(); for (;;) { // use second count to turn LEDs on or off error = I2C1_byteRead(SLAVE_ADDR, 0, &readback); if (error) for(;;) ; // replace with error handling display(readback); delayMs(200); } } /* configure UCB1 as I2C */ void I2C1_init(void) { extern uint32_t SystemCoreClock; EUSCI_B1->CTLW0 |= 1; /* disable UCB1 during config */ EUSCI_B1->CTLW0 = 0x0F81; /* 7-bit slave addr, master, I2C, synch mode, use SMCLK */ EUSCI_B1->BRW = 30; /* set clock prescaler for 100kHz */ P6->SEL0 |= 0x30; /* P6.5, P6.4 for UCB1 */ P6->SEL1 &= ~0x30; EUSCI_B1->CTLW0 &= ~1; /* enable UCB1 after config */ } // Read one byte of data at memAddr unsigned char I2C1_byteRead(int slaveAddr, unsigned char memAddr, unsigned char* data) { EUSCI_B1->CTLW1 &= ~0x000C; /* no automatic stop generation */ EUSCI_B1->I2CSA = slaveAddr; /* send slave address */ EUSCI_B1->CTLW0 |= 0x0010; /* enable transmitter */ EUSCI_B1->CTLW0 |= 0x0002; /* generate start */ while((EUSCI_B1->CTLW0 & 2)); /* wait until slave address is sent */ EUSCI_B1->TXBUF = memAddr; /* send memory address to slave */ while(!(EUSCI_B1->IFG & 2)); /* wait till it's ready to transmit */ EUSCI_B1->CTLW0 &= ~0x0010; /* enable receiver */ EUSCI_B1->CTLW0 |= 0x0002; /* generate restart */ while(EUSCI_B1->CTLW0 & 2); /* wait till restart is finished */ /* receive one byte data */ EUSCI_B1->CTLW0 |= 0x0004; /* send STOP */ while(!(EUSCI_B1->IFG & 1)); /* wait till data is received */ *data++ = EUSCI_B1->RXBUF; while(EUSCI_B1->CTLW0 & 4) ; /* wait until stop is sent */ return 0; /* no error */ } /* system clock at 3 MHz, MSP432P401R Rev. C, Start-up v2.2.1 */ void delayMs(int n) { int i, j; for (j = 0; j < n; j++) for (i = 750; i > 0; i--); /* Delay */ } void display(int data) { if (data & 8) /* bit 3 -> LED3 */ P2->OUT |= 0x10; else P2->OUT &= ~0x10; if (data & 4) /* bit 2 -> LED2 */ P2->OUT |= 0x20; else P2->OUT &= ~0x20; if (data & 2) /* bit 1 -> LED1 */ P3->OUT |= 8; else P3->OUT &= ~8; if (data & 1) /* bit 0 -> LED0 */ P3->OUT |= 4; else P3->OUT &= ~4; }