void RCC_Configuration(void){ /* GPIOA and GPIOB clock enable */ RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC | RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOE, ENABLE ); /* clock enable *//* AFIO clock enable == remap */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); FLASH_SetLatency(FLASH_Latency_2); RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE); } void i2c1_init(void){ I2C1->CR1 = I2C_CR1_SWRST; //reset + all disabled --> ordre = 1 0x8000 I2C1->CR1 &= ~I2C_CR1_SWRST; I2C1->CR2 = 0x0024; // 0x24=36MHz I2C1->CCR = 0x00B4; //100.000Hz I2C1->TRISE = 0x0009; I2C1->CR1 |= I2C_CR1_PE; //ENABLE } void config_i2c1_init(void) //50kHz - i2c1 { NVIC_InitTypeDef NVIC_InitStructure; GPIOB->CRL = (GPIOB->CRL & 0x00FFFFFF | 0xFF000000); //I2C1_scl I2C1_sda NVIC_InitStructure.NVIC_IRQChannel = I2C1_EV_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; //menos prioritat que TIM1(PWM) NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); NVIC_InitStructure.NVIC_IRQChannel = I2C1_ER_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; //menos prioritat que TIM1(PWM) NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE); i2c1_init(); punter2=0; } u8 readI2C1(u8 SUB) //read 1byte { add[0] = 0x31; add[1] = SUB; add[2] = 0; si = 1; idx2 = indx = 0; punter2 = 5; I2C1->CR1 |= I2C_CR1_ACK; I2C1->CR1 |= I2C_CR1_START; I2C1->CR2 |= I2C_CR2_ITEVTEN; I2C1->CR2 |= I2C_CR2_ITERREN; return 1; } void I2C1_EV_IRQHandler(void) { u8 i, punter; u16 aux; switch (punter2){ case 5: //read-LIS3DH if (I2C1->SR1&0x0001){ // Bit 0 SB: Start bit (Master mode) 1: Start condition generated. punter2++; I2C1->DR = add[0] & 0xFE; } break; case 6: //read-LIS3DH if(I2C1->SR1&0x0002){ //ADDR: Address sent (master mode) if(I2C1->SR2); punter2++; I2C1->DR = add[1]; } break; case 7: //read-LIS3DH if (I2C1->SR1&0x0004){ punter2++; I2C1->CR1 |= I2C_CR1_START; } break; case 8: if (I2C1->SR1&0x0001){ punter2++; I2C1->DR = add[0]; } break; case 9: if (I2C1->SR1&0x0002) { if (I2C1->SR2); punter2++; } break; case 10: /* If RXNE is set */ if (I2C1->SR1&0x0040){ sendi2c1[indx++] = I2C2->DR; if(indx==1){ I2C2->CR1 &= ~I2C_CR1_ACK; }else if(indx==2){ I2C2->CR1 |= I2C_CR1_STOP; }else{ I2C2->CR2 &= ~I2C_CR2_ITEVTEN; I2C2->CR2 &= ~I2C_CR2_ITERREN; punter2 = 0; } } break; default: I2C1->CR2 &= ~I2C_CR2_ITEVTEN; I2C1->CR2 &= ~I2C_CR2_ITERREN; } } void I2C1_ER_IRQHandler(void) { __IO uint32_t SR1Register =0; /* Read the I2C1 status register */ SR1Register = I2C1->SR1; I2C1->SR1 &=~0x0F00; //reset all the error bits to clear the interrupt I2C1->CR2 &= ~I2C_CR2_ITEVTEN; I2C1->CR2 &= ~I2C_CR2_ITERREN; i2c1_init(); } int main(void){ RCC_Configuration(); config_i2c1_init(); readI2C1(1,0x0F); while(1); }