/* P9_1.c - I2C byte write to a DS3231 * * This program initializes the I2C and sends a * command to the DS3231 to turn on the 1 Hz output. * 1 Hz output is an open-drain output. It needs a pull-up * to observe the signal. * No errors or acknowledgment are checked. * * The connections * I2C1_SCL - PB8 * I2C1_SDA - PB9 * * This program was tested with Keil uVision v5.23 with DFP v2.0.0 */ #include "stm32f0xx.h" #define SLAVE_ADDR 0x68 /* 1101 000. DS3231 */ void delayMs(int n); void I2C1_init(void); int I2C1_byteWrite(char saddr, char maddr, char data); int Main(void) { I2C1_init(); I2C1_byteWrite(SLAVE_ADDR, 0x0E, 0x00); while(1) { } } void I2C1_init(void) { RCC->AHBENR |= 0x00040000; /* Enable GPIOB clock */ RCC->APB1ENR |= 0x00200000; /* Enable I2C1 clock */ /* configure PB8, PB9 pins for I2C1 */ GPIOB->MODER &= ~0x000F0000; /* PB8, PB9 use alternate function */ GPIOB->MODER |= 0x000A0000; GPIOB->AFR[1] &= ~0x000000FF; /* PB8, PB9 I2C1 SCL, SDA */ GPIOB->AFR[1] |= 0x00000011; GPIOB->OTYPER |= 0x00000300; /* output open-drain */ GPIOB->PUPDR &= ~0x000F0000; /* with pull-ups */ GPIOB->PUPDR |= 0x00050000; I2C1->CR1 = 0; /* software reset I2C1 */ I2C1->TIMINGR = 0x10420F13; /* 100 KHz, peripheral clock is 8 MHz */ I2C1->CR1 = 0x00000001; /* enable I2C1 module */ } /* this function writes a byte of data to the memory location maddr of * a device with I2C slave device address saddr. * For simplicity, no error checking or error report is done. */ int I2C1_byteWrite(char saddr, char maddr, char data) { while (I2C1->ISR & 0x8000); /* wait until bus not busy */ I2C1->CR2 = 0x02002000| (2 << 16) /* generate start, autoend, byte count 2 */ | (saddr << 1); /* and send slave address */ while (!(I2C1->ISR & 0x02)); /* wait until TXIS is set */ I2C1->TXDR = maddr; /* send register address */ while (!(I2C1->ISR & 0x02)); /* wait until TXIS is set */ I2C1->TXDR = data; /* send data */ while (!(I2C1->ISR & 0x20)); /* wait until stop flag is set */ I2C1->ICR = 0x20; /* clear stop flag */ I2C1->CR2 = 0x02000000; /* clear configuration register 2 */ return 0; }