This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

SW-EK-LM4F120XL: I2C configuration function

Part Number: SW-EK-LM4F120XL
Other Parts Discussed in Thread: EK-TM4C123GXL

I have made a function in order to configure I2C communication from an LM4F120H5QR microcontroller with an external sensor (HMC5883L).

I have used register definitions from lm4f120h5qr.h.

Does it look okay?


void I2C_Config(void)
    SYSCTL_RCGCI2C_R |= SYSCTL_RCGCI2C_R0; // Set bit 0/R0 in the Inter-Integrated Circuit Run Mode Clock Gating Control (RCGCI2C) register,
    //in order to enable and provide a clock to I2C module 0 in Run mode.

    SYSCTL_RCGCGPIO_R |= SYSCTL_RCGCGPIO_R1; // Set bit 1/R1 to enable and provide a clock to GPIO Port B in Run mode,
    //in the General-Purpose Input/Output Run Mode Clock Gating Control (RCGCGPIO) register.

    GPIO_PORTB_AHB_AFSEL_R |= 0xC; // Set PB2 & PB3 to enable the appropriate pins for their alternate function,
    //in the GPIO Alternate Function Select (GPIOAFSEL) register.

    GPIO_PORTB_AHB_ODR_R |= 0x8; // Set PB3 (I2C0SDA) for open-drain operation,
    //in the GPIO Open Drain Select (GPIOODR) register.

    GPIO_PORTB_AHB_PCTL_R |= 0x00003300; // Set the bit field PMC0 to 0011 in the GPIO Port Control (GPIOPCTL) register, in order to enable the
    //appropriate pins for their alternate function.

    I2C0_MASTER_MCR_R = 0x00000010; // Initialize the I2C Master by writing the I2C Master Configuration (I2CMCR) register with a value of 0x0000.0010.

    I2C0_MASTER_MTPR_R = 0x00000027; // Set the desired SCL clock speed by writing the I2C Master Timer Period (I2CMTPR) register with the equation:
    //TPR = (System Clock/(2*(SCL_LP + SCL_HP)*SCL_CLK))-1
    //SCL_LP & SCL_HP are fixed at 6 & 4 respectively, SCL_CLK is the desired clock speed of the I2C clock(100 Kbps, 400 Kbps & 1 Mbps)
    //and TPR is the Timer Period register value (range of 1 to 127).