#include //Core Header for STM32F103C8T6 Processor #include #define EEPROM_DEVICE 0xA0 //All Addresspins grounded #define EEPROM_WRITE 0 #define EEPROM_READ 1 int main(void) { //Enable Clocks RCC->APB2ENR |= RCC_APB2ENR_IOPBEN; //Enable Clock for I/O Modul B (GPIOB) RCC->APB2ENR |= RCC_APB2ENR_AFIOEN; //Enable Clock for Alternate Function (AF) RCC->APB1ENR |= RCC_APB1ENR_I2C1EN; //Enable Clock for I2C1 Modul //Init I2C at 100KHz APB1=36MHz I2C1->CR1 &= ~(I2C_CR1_SWRST | I2C_CR1_SMBUS | I2C_CR1_PE); //No Software Reset and No SMBus Mode and disable I2C Bus I2C1->CR2 |= 36; //Set I2C Peripheral Clock to APB1 Bus Clock(36MHz) I2C1->CCR &= ~(I2C_CCR_FS); //Standard Mode selected I2C1->CCR |= 180; //Set Clock Generator 100 KHz I2C1->TRISE = 37; //Set Trise for SCL I2C1->CR1 |= I2C_CR1_ACK | I2C_CR1_PE; //Enable I2C Bus and ACK Generation //Configurate PB6/PB7 for SDA/SCL as Open Drain Alternate Function GPIOB->CRL |= GPIO_CRL_MODE6_1 | GPIO_CRL_CNF6; //Set PB6 to Output Mode Max 2 MHz Alternate Function Open drain GPIOB->CRL |= GPIO_CRL_MODE7_1 | GPIO_CRL_CNF7; //Set PB7 to Output Mode Max 2 MHz Altenrate Function Open drain GPIOB->CRL &= ~(GPIO_CRL_MODE6_0 | GPIO_CRL_MODE7_0); //Write 0x20 at Address 0x08 to EEPROM Chip //Step 1 generate Start and send device Address while(I2C1->SR2 & I2C_SR2_BUSY); //Check if I2C Bus is not Busy I2C1->CR1 |= I2C_CR1_ACK | I2C_CR1_START; //Enable ACK Generation and generate START Condition while(!(I2C1->SR1 & I2C_SR1_SB)); //Wait for START Condition been generated I2C1->DR = EEPROM_DEVICE + EEPROM_WRITE; //Set the EEPROM Address with Write Command while(!(I2C1->SR1 & I2C_SR1_ADDR)); //Wait for Address Match (void)I2C1->SR2; //Dummy Read to clear Flags. SR1 is already cleared during the while loop //Step 2 send Data //Send EEPROM Memory Address while(!(I2C1->SR1 & I2C_SR1_TXE)); //Check if TX Buffer is empty I2C1->DR = 0x08; //Set Internal EEPROM Memory Address while(!(I2C1->SR1 & I2C_SR1_BTF)); //Wait until Byte is send //Send Data to store in EEPROM while(!(I2C1->SR1 & I2C_SR1_TXE)); //Check if TX Buffer is empty I2C1->DR = 0x20; //Send Data while(!(I2C1->SR1 & I2C_SR1_BTF)); //Wait until Byte is send //Step 3 generate Stop Condition I2C1->CR1 |= I2C_CR1_STOP; //Generate STOP Condition while(1) { } }