PIC initialization for I2C

Discussion in 'Programmer's Corner' started by rwallace, Jan 25, 2013.

  1. rwallace

    Thread Starter New Member

    Jan 16, 2013
    3
    0
    I am trying to setup the PIC18Lf4520 for Master I2C communication with some MPU 6050's however I cant seem to get the proper frequency on the I2C bus. I have 1k pull ups on the the SCL and SDA lines. I am aiming for about 100khz I2c speed but the following code gives me about 80khz. The problem is that the SSPADD register does not change the frequency of the lines by much, it appears to change the duty cycle instead.
    Based on the data sheets I should have set the SSPADD register at 0x09 to provide 100kHz at 4Mhz internal osc but it does not seem to correlate properly.
    Am I missing anything here? I am fairly new to PIC programming so any help would be greatly appreciated.

    #include <stdio.h>
    #include <stdlib.h>
    #include <p18f4520.h>
    #include <i2c.h>

    #pragma config OSC = INTIO7 //internal osc port function on RA6 and RA7
    #pragma config WDT = OFF
    #pragma config LVP = OFF

    void main(void)
    {

    TRISC=0x00;
    PORTC=0x00;

    OSCCON =0b01110010; //8MHZ internal osc
    SSPSTAT &= 0x3F;
    SSPCON1 = 0b00101000; //initialize master i2c
    SSPCON2 = 0x00;
    TRISCbits.TRISC3 = 1;
    TRISCbits.TRISC4 = 1;

    SSPADD = 0; // Should be 0x09 to provide 100kHz at 4Mhz int osc.

    }
     
  2. ErnieM

    AAC Fanatic!

    Apr 24, 2011
    7,386
    1,605
    Well, you set the internal oscillator to 8MHz, not 4MHz. Table 17.3 says to use 0x27 and not 0x09 to get 100 KHz.

    While not documented, the formula here seems to be ((Fosc / Fbus) + 1) to get the SSPADD setting.

    So for 100K out of an 8MHz osc I believe a value os 0x4F should do nice.
     
  3. rwallace

    Thread Starter New Member

    Jan 16, 2013
    3
    0
    Thank you for your response.

    Yes my mistake, that was my intended internal osc speed. For some reason I changed it for a test and forgot to change the oscconn back to 4mhz. I believe I tried the 27h sspadd but I will try again tomorrow to be sure. Thanks again.
     
  4. ErnieM

    AAC Fanatic!

    Apr 24, 2011
    7,386
    1,605
    Hey... you're welcome. Let us know how it goes.
     
Loading...