Ejemplo n.º 1
0
/************************************************************************************************** 
  Function: 
    static BOOL I2CShared_TransmitOneByte(const I2C_MODULE i2c, const UINT8 data)
    
  Author(s): 
    mkobit
  
  Summary: 
    Transmits one byte of data to (i2c)
  
  Description: 
    Waits until transmitter is ready and sends the byte of data
    Static function, used by internal library
  
  Preconditions: 
    Transaction started
    I2C module configured
  
  Parameters: 
    const I2C_MODULE i2c - I2C module to be used for this transaction
    const UINT8 data - to be transmitted
  
  Returns: 
    TRUE - If successful
    FALSE - If unsuccessful
  
  Example: 
    <code>
    I2CShared_TransmitOneByte(I2C1, 0x43)
    </code>
  
  Conditions at Exit: 
    Transmission of byte complete
    I2C bus waiting for next action
  
**************************************************************************************************/
static BOOL I2CShared_TransmitOneByte(const I2C_MODULE i2c, const UINT8 data) {
  int fault_count = 0;
  
  // Wait for the transmitter to be ready
  while(!I2CTransmitterIsReady(i2c)) {
    if (fault_count++ == TIMEOUT) {
      //printf("I2CShared_TransmitOneByte: Timeout waiting for I2CTransmitterIsReady\n");
      return FALSE;
    }
  }

  // Transmit the byte
  if(I2CSendByte(i2c, data) == I2C_MASTER_BUS_COLLISION)
  {
    //printf("I2CShared_TransmitOneByte: Error, I2C Master Bus Collision , status = 0x%x\n", I2CGetStatus(i2c));
    return FALSE;
  }

  fault_count = 0;
  // Wait for the transmission to finish
  while(!I2CTransmissionHasCompleted(i2c)) {
    if (fault_count++ == TIMEOUT) {
      //printf("I2CShared_TransmitOneByte: Timeout waiting for I2CTransmissionHasCompleted\n");
      return FALSE;
    }
  }

  if(!I2CByteWasAcknowledged(i2c))
  {
    //printf("I2CShared_TransmitOneByte: Error, sent byte was not acknowledged, status = 0x%x\n", I2CGetStatus(i2c));
    //I2CShared_DebugStatus(i2c);
      return FALSE;
  }
  return TRUE;
}
Ejemplo n.º 2
0
/**
 * Send out a single byte of data over the I2C
 * 
 * @param data The byte of data to send
 */
bool I2C_TransmitOneByte(unsigned char data)
{
    // Wait for the transmitter to be ready
    while (!I2CTransmitterIsReady(I2C1));

    // Transmit the byte
    if (I2CSendByte(I2C1, data) == I2C_MASTER_BUS_COLLISION) {
        //serialPrint("Error: I2C Master Bus Collision\r\n");
        while (1);
    }

    // Wait for the transmission to finish
    while (!I2CTransmissionHasCompleted(I2C1));

    unsigned int i;
    for (i = 0; i < I2C_Timeout; i++) {
        if (I2CByteWasAcknowledged(I2C1)) {
            break;
        } else if (i == I2C_Timeout - 1) {
            //serialPrint("Error: I2C Slave Did Not Acknowledge\r\n");
            return FALSE;
        }
    }
    return TRUE;
}
int transfer_start(I2C_MODULE port, I2C_7_BIT_ADDRESS address, UINT8 rw)
{
    I2C_STATUS status;
    int result = 0;

    while(!I2CBusIsIdle(port));

    if(I2CStart(port) != I2C_SUCCESS)
        return -1;

    do {
        status = I2CGetStatus(port);
    } while(!(status & I2C_START));

    /* Send address */
    address.rw = rw;
    result = transmit_byte(port, address.byte);
    if(result < 0)
        return result;

    if(!I2CByteWasAcknowledged(port))
        return -1;
    
    return result;
}
Ejemplo n.º 4
0
}void i2cSendByte(I2C_MODULE id, BYTE data){
    while(!I2CTransmitterIsReady(id));//maybe comment this out
    I2CSendByte(id, data);
    //I2C_RESULT temp = I2CSendByte(id, data);
    //temp;
    while(!I2CTransmissionHasCompleted(id));
    while(!I2CByteWasAcknowledged(id));
}
Ejemplo n.º 5
0
Archivo: I2C.c Proyecto: sdajani/sdp
BOOL I2C_sendData(I2C_MODULE I2C_ID, uint8_t data){
    // Initiate a single byte transmit over the I2C bus
    if (!I2C_transmitOneByte(I2C_ID,data)){
        return FALSE;
    }

    // Verify that the byte was acknowledged
    if(!I2CByteWasAcknowledged(I2C_ID)){
        #ifdef DEBUG
        printf("Error: Sent byte was not acknowledged\n");
        #endif
        return FALSE;
    }
    return TRUE;
}
Ejemplo n.º 6
0
//------------------------------------------------------------------------------
// Function: I2C_WriteBlock
// Description: Write a block of bytes to the spacifed I2C slave address at the specified offset.
//              The offset address is one byte (8 bit offset only).
//              The return code is always 0.  There is no indication in case of error.
//------------------------------------------------------------------------------
BYTE I2C_WriteBlock(BYTE deviceID, BYTE offset, BYTE buffer, WORD length)
{
	BYTE write_buffer[256];
    //    memset(write_buffer, 0, sizeof(write_buffer));
	WORD count;
        BOOL Success = TRUE;

    write_buffer[0] = deviceID;
    write_buffer[1] = offset;
    write_buffer[2] = buffer;
    write_buffer[3] = 0x06;

    // Start the transfer to write data to the EEPROM
    if( !StartTransfer(FALSE) )
    {
        while(1);
    }

    // Transmit all data
    count = 0;

    while( Success && (count < (length + 2)) )
    {

             // Transmit a byte
            TransmitOneByte(write_buffer[count]);
        
            // Advance to the next byte
            count++;

            // Verify that the byte was acknowledged
            if(!I2CByteWasAcknowledged(OVM7690_I2C_BUS))
            {
                Success = FALSE;
            }

    }

    // End the transfer (hang here if an error occured)
    StopTransfer();

    if(!Success)
    {
        while(1);
    }

    return(0);
}
int gestic_message_write(gestic_t *gestic, void *msg, int size)
{
    I2C_MODULE port = gestic->io.I2cPort;
    const unsigned char * const buffer = (unsigned char*)msg;
    int result = 0;
    int i;

    GESTIC_ASSERT(buffer[0] == size);

    if(transfer_start(port, gestic->io.I2cSlaveAddr, 0))
        result = -1;

    for(i = 0; !result && i < size; ++i) {
        if(transmit_byte(port, buffer[i]) < 0)
            result = -1;
        
        if(!I2CByteWasAcknowledged(port))
            result = -1;
    }

    transfer_stop(port);

    return result;
}
Ejemplo n.º 8
0
//------------------------------------------------------------------------------
// Function: I2C_ReadBlock
// Description: Read a block of bytes from the spacifed I2C slave address at the specified offset.
//              The offset address is one byte (8 bit offset only).
//              The return code is always 0.  There is no indication in case of error.
//------------------------------------------------------------------------------
BYTE I2C_ReadBlock(BYTE deviceID, BYTE offset, BYTE *buffer, WORD length)
{
    BYTE write_buffer[2] = {0x00};
    BYTE count =0;
    BOOL                Success = TRUE;

    write_buffer[0] = deviceID;
    write_buffer[1] = offset;

    // Start the transfer to write data to the EEPROM
    if(!StartTransfer(FALSE) )
    {
        while(1);
    }

    // Transmit all data
    count = 0;

    while( Success && (count < (2)) )
    {
        // Transmit a byte
        TransmitOneByte(write_buffer[count]);

            // Advance to the next byte
            count++;

            // Verify that the byte was acknowledged
            if(!I2CByteWasAcknowledged(OVM7690_I2C_BUS))
            {
                Success = FALSE;
            }
    }

    // Start the transfer to read data
    StartTransfer(TRUE);

   // Transmit the address with the READ bit set
   deviceID |= 0x01;

   TransmitOneByte(deviceID);

    // Verify that the byte was acknowledged
    if(!I2CByteWasAcknowledged(OVM7690_I2C_BUS))
    {
        Success = FALSE;
    }

    for(count=0;count<length;count++)
    {

    // Read the data from the desired address
    if(Success)
    {
        if(I2CReceiverEnable(OVM7690_I2C_BUS, TRUE) == I2C_RECEIVE_OVERFLOW)
        {
            Success = FALSE;
        }
        else
        {
//            while(!I2CReceivedDataIsAvailable(OVM7690_I2C_BUS));
            *buffer++ = I2CGetByte(OVM7690_I2C_BUS);
        }

    }
    }
    // End the transfer (stop here if an error occured)
    StopTransfer();

    return(0);
}
Ejemplo n.º 9
0
/*
 Sends a byte on an i2c channel (with no strings attached)
 */
void sendByte(I2C_MODULE i2c, BYTE byte){
    I2CSendByte(i2c, byte);                     // Send and wait for finish
    while( ! I2CTransmissionHasCompleted(i2c));
    while( ! (I2CByteWasAcknowledged(i2c)));    // wait for ack
}
Ejemplo n.º 10
0
void SendPacket( UINT8* i2cData, int DataSz )
{
    int                 Index;
    UINT32              actualClock;
    BOOL                Acknowledged;
    BOOL                Success = TRUE;
    UINT8               i2cbyte;

    // Start the transfer to write data to the EEPROM
    if( !StartTransfer(FALSE) )
    {
        while(1);
    }

    // Transmit all data
    Index = 0;
    while( Success && (Index < DataSz) )
    {
        // Transmit a byte
        if (TransmitOneByte(i2cData[Index]))
        {
            // Advance to the next byte
            Index++;

            // Verify that the byte was acknowledged
            if(!I2CByteWasAcknowledged(EEPROM_I2C_BUS))
            {
                DBPRINTF("Error: Sent byte was not acknowledged\n");
                Success = FALSE;
            }
        }
        else
        {
            Success = FALSE;
        }
    }

    // End the transfer (hang here if an error occured)
    StopTransfer();
    if(!Success)
    {
        ErrorHalt();
    }

    // Wait for EEPROM to complete write process, by polling the ack status.
    Acknowledged = FALSE;
    do
    {
        // Start the transfer to address the EEPROM
        if( !StartTransfer(FALSE) )
        {
            while(1);
        }

        // Transmit just the EEPROM's address
        if (TransmitOneByte(i2cData[0]))
        {
            // Check to see if the byte was acknowledged
            Acknowledged = I2CByteWasAcknowledged(EEPROM_I2C_BUS);
        }
        else
        {
            Success = FALSE;
        }

        // End the transfer (stop here if an error occured)
        StopTransfer();
        if(!Success)
        {
            ErrorHalt();
        }

    } while (Acknowledged != TRUE);

    // End the transfer (stop here if an error occured)
    StopTransfer();
    if(!Success)
    {
        ErrorHalt();
    }
}
Ejemplo n.º 11
0
int main(void)
{
    UINT8               i2cData[10];
    I2C_7_BIT_ADDRESS   SlaveAddress;
    int                 Index;
    int                 DataSz;
    UINT32              actualClock;
    BOOL                Acknowledged;
    BOOL                Success = TRUE;
    UINT8               i2cbyte;


    // Initialize debug messages (when supported)
    DBINIT();

    // Set the I2C baudrate
    actualClock = I2CSetFrequency(EEPROM_I2C_BUS, GetPeripheralClock(), I2C_CLOCK_FREQ);
    if ( abs(actualClock-I2C_CLOCK_FREQ) > I2C_CLOCK_FREQ/10 )
    {
        DBPRINTF("Error: I2C1 clock frequency (%u) error exceeds 10%%.\n", (unsigned)actualClock);
    }

    // Enable the I2C bus
    I2CEnable(EEPROM_I2C_BUS, TRUE);
    

    //
    // Send the data to EEPROM to program one location
    //

    // Initialize the data buffer
    I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, EEPROM_ADDRESS, I2C_WRITE);
    i2cData[0] = SlaveAddress.byte;
    i2cData[1] = 0x05;              // EEPROM location to program (high address byte)
    i2cData[2] = 0x40;              // EEPROM location to program (low address byte)
    i2cData[3] = 0xAA;              // Data to write
    DataSz = 4;

    // Start the transfer to write data to the EEPROM
    if( !StartTransfer(FALSE) )
    {
        while(1);
    }

    // Transmit all data
    Index = 0;
    while( Success && (Index < DataSz) )
    {
        // Transmit a byte
        if (TransmitOneByte(i2cData[Index]))
        {
            // Advance to the next byte
            Index++;

            // Verify that the byte was acknowledged
            if(!I2CByteWasAcknowledged(EEPROM_I2C_BUS))
            {
                DBPRINTF("Error: Sent byte was not acknowledged\n");
                Success = FALSE;
            }
        }
        else
        {
            Success = FALSE;
        }
    }

    // End the transfer (hang here if an error occured)
    StopTransfer();
    if(!Success)
    {
        while(1);
    }


    // Wait for EEPROM to complete write process, by polling the ack status.
    Acknowledged = FALSE;
    do
    {
        // Start the transfer to address the EEPROM
        if( !StartTransfer(FALSE) )
        {
            while(1);
        }
        
        // Transmit just the EEPROM's address
        if (TransmitOneByte(SlaveAddress.byte))
        {
            // Check to see if the byte was acknowledged
            Acknowledged = I2CByteWasAcknowledged(EEPROM_I2C_BUS);
        }
        else
        {
            Success = FALSE;
        }

        // End the transfer (stop here if an error occured)
        StopTransfer();
        if(!Success)
        {
            while(1);
        }

    } while (Acknowledged != TRUE);


    //
    // Read the data back from the EEPROM.
    //

    // Initialize the data buffer
    I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, EEPROM_ADDRESS, I2C_WRITE);
    i2cData[0] = SlaveAddress.byte;
    i2cData[1] = 0x05;              // EEPROM location to read (high address byte)
    i2cData[2] = 0x40;              // EEPROM location to read (low address byte)
    DataSz = 3;
    
    // Start the transfer to read the EEPROM.
    if( !StartTransfer(FALSE) )
    {
        while(1);
    }
    
    // Address the EEPROM.
    Index = 0;
    while( Success & (Index < DataSz) )
    {
        // Transmit a byte
        if (TransmitOneByte(i2cData[Index]))
        {
            // Advance to the next byte
            Index++;
        }
        else
        {
            Success = FALSE;
        }

        // Verify that the byte was acknowledged
        if(!I2CByteWasAcknowledged(EEPROM_I2C_BUS))
        {
            DBPRINTF("Error: Sent byte was not acknowledged\n");
            Success = FALSE;
        }
    }

    // Restart and send the EEPROM's internal address to switch to a read transfer
    if(Success)
    {
        // Send a Repeated Started condition
        if( !StartTransfer(TRUE) )
        {
            while(1);
        }

        // Transmit the address with the READ bit set
        I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, EEPROM_ADDRESS, I2C_READ);
        if (TransmitOneByte(SlaveAddress.byte))
        {
            // Verify that the byte was acknowledged
            if(!I2CByteWasAcknowledged(EEPROM_I2C_BUS))
            {
                DBPRINTF("Error: Sent byte was not acknowledged\n");
                Success = FALSE;
            }
        }
        else
        {
            Success = FALSE;
        }
    }

    // Read the data from the desired address
    if(Success)
    {
        if(I2CReceiverEnable(EEPROM_I2C_BUS, TRUE) == I2C_RECEIVE_OVERFLOW)
        {
            DBPRINTF("Error: I2C Receive Overflow\n");
            Success = FALSE;
        }
        else
        {
            while(!I2CReceivedDataIsAvailable(EEPROM_I2C_BUS));
            i2cbyte = I2CGetByte(EEPROM_I2C_BUS);
        }

    }

    // End the transfer (stop here if an error occured)
    StopTransfer();
    if(!Success)
    {
        while(1);
    }


    // Validate the data read
    if( i2cbyte != 0xAA )
    {
        DBPRINTF("Error: Verify failed\n");
    }
    else
    {
        DBPRINTF("Success\n");
    }

    // Example complete
    while(1);
}
Ejemplo n.º 12
0
//=============================================
// Configure the I2C4 interrupt handler
//=============================================
void __ISR(_I2C_4_VECTOR, I2C4_INT_PRIORITY) I2c4InterruptHandler(void)
{
  sI2cCmdBuffer_t masterData;
  
  if (INTGetFlag(INT_I2C4B))  //Bus Collision interrupt
  {
    INTClearFlag(INT_I2C4B);
  }
  
  if (INTGetFlag(INT_I2C4M))  // Master interrupt
  {
    INTClearFlag(INT_I2C4M);

    if (I2c.Var.oReadDataInNextInterrupt[I2C4])   // If a read was started last interrupt
    {
      masterData.data  = I2C4RCV;   // Read from I2C buffer
      masterData.state = I2C_MASTER_RECEIVE_DATA;
      I2cFifoWrite((void *) &I2c.Var.i2cUserFifo[I2C4], &masterData);
      I2c.Var.oRxDataAvailable[I2C4] = 1;
      I2c.Var.oReadDataInNextInterrupt[I2C4] = 0;
    }
    
    if (I2c.Var.oI2cWriteIsRunning[I2C4])
    {
      I2cFifoRead((void *) &I2c.Var.i2cWriteQueue[I2C4], &masterData);
      switch (masterData.state)
      {
      //======================================================  
        case I2C_MASTER_RECEIVE_DATA : 
          I2C4CONbits.RCEN = 1;                         //Receive byte sequence
          I2c.Var.oReadDataInNextInterrupt[I2C4] = 1;   // Flag for the next interrupt to read the rx buffer
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_START_CONDITION : 
          I2C4CONbits.SEN = 1;                          //start condition sequence
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_STOP_CONDITION : 
          I2C4CONbits.PEN = 1;
          
          if (I2c.Var.oPoolSlaveAcknowledge[I2C4])
          {
            if (!I2c.Var.oSecondStopAfterPooling[I2C4])
            {
              masterData.state = I2C_MASTER_START_CONDITION;
              I2cFifoWrite((void *) &I2c.Var.i2cWriteQueue[I2C4], &masterData);
              
              masterData.state = I2C_MASTER_TRANSMIT_DATA;
              I2cFifoWrite((void *) &I2c.Var.i2cWriteQueue[I2C4], &masterData);
              
              masterData.state = I2C_MASTER_STOP_CONDITION;
              I2cFifoWrite((void *) &I2c.Var.i2cWriteQueue[I2C4], &masterData);
              
              I2c.Var.oSecondStopAfterPooling[I2C4] = 1;
            }
            else
            {
              if (!I2CByteWasAcknowledged(I2C4))
              {
                masterData.state = I2C_MASTER_START_CONDITION;
                I2cFifoWrite((void *) &I2c.Var.i2cWriteQueue[I2C4], &masterData);

                masterData.state = I2C_MASTER_TRANSMIT_DATA;
                I2cFifoWrite((void *) &I2c.Var.i2cWriteQueue[I2C4], &masterData);

                masterData.state = I2C_MASTER_STOP_CONDITION;
                I2cFifoWrite((void *) &I2c.Var.i2cWriteQueue[I2C4], &masterData);
              }
              else
              {
                masterData.state = I2C_MASTER_DONE;
                I2cFifoWrite((void *) &I2c.Var.i2cWriteQueue[I2C4], &masterData);
                I2c.Var.oSecondStopAfterPooling[I2C4] = 0;
              }
            }
          }
          break;
      //====================================================== 

      //======================================================    
        case I2C_MASTER_TRANSMIT_DATA : 
          I2C4TRN = masterData.data;
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_DONE : 
          if (I2c.Var.i2cWriteQueue[I2C4].bufEmpty)   // Nothing more to send
          {
            I2c.Var.oI2cWriteIsRunning[I2C4] = 0;       // Turn off writing process
          }
          else
          {
            INTSetFlag(INT_I2C4M);                    // Start another writing process
          }
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_REPEAT_START : 
          I2C4CONbits.RSEN = 1;   //repeated start condition sequence
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_SLAVE_SENT_STOP :
          LED_ERROR_ON;
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_SEND_ACK : 
          I2C4CONbits.ACKDT = 0;  //ACK
          I2C4CONbits.ACKEN = 1;  //Send ACK sequence
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_SEND_NACK : 
          I2C4CONbits.ACKDT = 1;  //NACK
          I2C4CONbits.ACKEN = 1;  //Send NACK sequence
          break;
      //====================================================== 

      //======================================================  
        case I2C_CMD_ERROR : 
          LED_ERROR_ON;
          break;
      //====================================================== 

      //======================================================  
        default : 
          break;
      //======================================================  
      } // end switch
    } // end if
    
    

    if (I2c.Var.oI2cReadIsRunning[I2C4])
    {
      I2cFifoRead((void *) &I2c.Var.i2cReadQueue[I2C4], &masterData);
      switch (masterData.state)
      {
      //======================================================  
        case I2C_MASTER_RECEIVE_DATA : 
          I2C4CONbits.RCEN = 1;   //Receive byte sequence
          I2c.Var.oReadDataInNextInterrupt[I2C4] = 1;
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_START_CONDITION : 
          I2C4CONbits.SEN = 1;    //start condition sequence
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_REPEAT_START : 
          I2C4CONbits.RSEN = 1;   //repeated start condition sequence
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_STOP_CONDITION : 
          I2C4CONbits.PEN = 1;
          break;
      //====================================================== 

      //======================================================    
        case I2C_MASTER_TRANSMIT_DATA : 
          I2C4TRN = masterData.data;
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_DONE : 
          if (I2c.Var.i2cReadQueue[I2C4].bufEmpty)            // Nothing more to send
          {
            I2c.Var.oI2cReadIsRunning[I2C4] = 0;              // Turn off reading process
          }
          else
          {
            INTSetFlag(INT_I2C4M);                    // Start another reading process
          }
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_SLAVE_SENT_STOP :
          LED_ERROR_ON;
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_SEND_ACK : 
          I2C4CONbits.ACKDT = 0;  //ACK
          I2C4CONbits.ACKEN = 1;  //Send ACK sequence
          break;
      //====================================================== 

      //======================================================  
        case I2C_MASTER_SEND_NACK : 
          I2C4CONbits.ACKDT = 1;  //NACK
          I2C4CONbits.ACKEN = 1;  //Send NACK sequence
          break;
      //====================================================== 

      //======================================================  
        case I2C_CMD_ERROR : 
          LED_ERROR_ON;
          break;
      //======================================================

      //======================================================  
        default : 
          break;
      //======================================================  
      } // end switch
    } // end if
  }  // end if
}   // end if
Ejemplo n.º 13
0
void i2c_isr(uint8_t p) {
    I2CModule_t * mod;

    // Get a reference to the module structure
    switch (p) {
        case I2C2:
            mod = &I2C_2;
            break;
            
        default:
            return;
    }

    switch (mod->state) {
        case IDLE:
            break;

        case START:
            I2CStart(mod->moduleName);
            mod->state = ADDRESS;
            I2C_2.dataDirection = WRITING;
            break;

        case ADDRESS:
            switch (mod->dataDirection) {
                case READING:
                    I2CSendByte(mod->moduleName, mod->frame->address + 1);
                    mod->state = CHECK_ACK;
                    break;

                case WRITING:
                    I2CSendByte(mod->moduleName, mod->frame->address);
                    mod->state = CHECK_ACK;
                    break;
            }

            break;

        case CHECK_ACK:
            if (I2CByteWasAcknowledged(mod->moduleName) == True) {
                switch (mod->dataDirection) {
                    case READING:
                        mod->state = READ;
                        break;

                    case WRITING:
                        mod->state = WRITE;
                        break;
                }
            } else {
                mod->frame->success = False;
                mod->state = STOP;
            }

            i2c_isr(mod->moduleName);
            
            break;

        case RESTART:
            I2CRepeatStart(mod->moduleName);
            mod->dataDirection = READING;
            mod->state = ADDRESS;
            break;

        case READ_START:
            I2CReceiverEnable(mod->moduleName, TRUE);
            mod->state = READ;
            break;

        case READ:
            mod->frame->rx_buf[mod->frame->rx_buf_index++] = I2CGetByte(mod->moduleName);
                
            // If we need to read more bytes send an ACK
            if (mod->frame->rx_buf_index <= mod->frame->bytesToRead) {
                I2CAcknowledgeByte(mod->moduleName, True); // Send an ACK
                mod->state = READ_START; // Prepare for the next byte
            } else {
                I2CAcknowledgeByte(mod->moduleName, False); // Send a NACK
                mod->frame->success = True;
                mod->state = STOP; // Prepare for a stop condition
            }

            break;

        case WRITE:
            // If there are still bytes to send
            if (mod->frame->tx_buf_index < mod->frame->tx_buf_size) {
                I2CSendByte(mod->moduleName, mod->frame->tx_buf[mod->frame->tx_buf_index++]);
            } else {
                // If we need to read some bytes
                if (mod->frame->bytesToRead > 0) {
                    mod->state = RESTART; // Send a restart condition
                } else {
                    mod->frame->success = True;
                    mod->state = STOP; // Send a stop condition
                }

                i2c_isr(mod->moduleName); // Re-run this function to call stop/restart
                // TODO: Perhaps there is a better way to do this..!
            }
            break;

        case STOP:
            I2CStop(mod->moduleName);
            mod->frameToSend = False;
            mod->state = IDLE;

            // Tell the owner of the frame that it has complete or failed
            if (mod->frame->success == True) {
                mod->frame->callback();
            } else {
                mod->frame->error();
            }

            break;

        case BUSERROR:
            led12 = 1;
            // TODO: Something..!
            while(1); // Don't know what to do here yet..!
            break;
    }
}
Ejemplo n.º 14
0
//------------------------------------------------------------------------------
// Function: I2C_ReadBlock
// Description: Read a block of bytes from the spacifed I2C slave address at the specified offset.
//              The offset address is one byte (8 bit offset only).
//              The return code is always 0.  There is no indication in case of error.
//------------------------------------------------------------------------------
uint8_t I2C_ReadBlock(uint8_t deviceID, uint8_t offset, uint8_t *buffer, uint16_t length)
{
    uint8_t write_buffer[2] = {0x00};
    uint8_t count =0;
    bool Success = true;

    write_buffer[0] = deviceID;
    write_buffer[1] = offset;

    I2C1CONbits.ACKDT = 0;

    // Start the transfer to write data to the EEPROM
    if(!StartTransfer(false) )
    {
        return(1);
    }

   // Transmit the address with the READ bit set
   deviceID |= 0x01;

   TransmitOneByte(deviceID);
   
    // Verify that the byte was acknowledged
    if(!I2CByteWasAcknowledged(OVM7690_I2C_BUS))
    {
        Success = false;
        return(1);
    }

    for(count=0;count<length;count++)
    {

        // Read the data from the desired address
        if(I2CReceiverEnable(OVM7690_I2C_BUS, true) == I2C_RECEIVE_OVERFLOW)
        {
            Success = false;
            return(1);
        }
        else
        {
            while(!I2CReceivedDataIsAvailable(OVM7690_I2C_BUS));
            *buffer  = I2C1RCV;
            buffer++;

          if(count == (length-1))
          {
           // I2C1CONbits.ACKDT = 1;
            I2C1CONSET = 0x20;
          }

            I2C1CONbits.ACKEN = 1;		// initiate bus acknowledge sequence

            while(I2C1CONbits.ACKEN == 1);
        }

    }

    // End the transfer (stop here if an error occured)
    StopTransfer();

    return(0);
}
Ejemplo n.º 15
0
BOOL MPU6050::writeReg(UINT8 regAddress, UINT8 data)
{
    UINT8               i2cData[10];
    I2C_7_BIT_ADDRESS   SlaveAddress;
    int                 Index;
    int                 DataSz;
    BOOL                Acknowledged = FALSE;
    BOOL                Success = TRUE;    

    //sprintf(filename, "Starting writeReg().\n");
    //putsUART1( filename );

    // Initialize the data buffer
    I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, this->deviceAddress, I2C_WRITE);
    i2cData[0] = SlaveAddress.byte;
    i2cData[1] = regAddress;        // Register Address to write
    i2cData[2] = data;              // Data to write
    DataSz = 3;

    

    // Start the transfer
    if( !StartTransfer(FALSE) )
    {
        Success = FALSE;
        sprintf( filename, "Error in #1 StartTransfer(): when writing address %u.\n", (unsigned)regAddress );
        putsUART1( filename );
    }

    // Transmit all data
    Index = 0;
    while( Success && (Index < DataSz) )
    {
        // Transmit a byte
        if (TransmitOneByte(i2cData[Index++]))
        {   
            // Verify that the byte was acknowledged
            if(!I2CByteWasAcknowledged( this->i2cBusId ))
            {               
                Success = FALSE;

                sprintf( filename, "Error in #1 I2CByteWasAcknowledged(): when writing address %u.\n", (unsigned)regAddress );
                putsUART1( filename );
            }
        }
        else
        {
            Success = FALSE;

            sprintf( filename, "Error in #1 TransmitOneByte(): when writing address %u.\n", (unsigned)regAddress );
            putsUART1( filename );
        }
    }    

    //sprintf(filename, "Before StopTransfer()\n");
    //putsUART1( filename );

    // End the transfer
    StopTransfer();

    //sprintf(filename, "After StopTransfer()\n");
    //putsUART1( filename );

    // Wait for device to complete write process, by polling the ack status.
    while(Acknowledged != TRUE && Success != FALSE)
    {
        //sprintf(filename, "Inside the loop\n");
        //putsUART1( filename );

        // Start the transfer
        if( StartTransfer(FALSE) )
        {            
            // Transmit just the device's address
            if (TransmitOneByte(SlaveAddress.byte))
            {
                // Check to see if the byte was acknowledged
                Acknowledged = I2CByteWasAcknowledged( this->i2cBusId );

                /*if( !Acknowledged )
                {
                    sprintf( filename, "!Acknowledged %u.\n", (unsigned)regAddress );
                    putsUART1( filename );
                }*/
            }
            else
            {
                Success = FALSE;

                sprintf( filename, "Error in #2 TransmitOneByte() - !starttranfer : when writing address %u.\n", (unsigned)regAddress );
                putsUART1( filename );


            }
                // End the transfer
            StopTransfer();
        }
        else
        {
            Success = FALSE;

            sprintf( filename, "Error in #2 StartTransfer(): when writing address %u.\n", (unsigned)regAddress );
            putsUART1( filename );
        }
    }

    //sprintf(filename, "After the loop\n");
    //putsUART1( filename );

    if( !Success )
    {
        sprintf( filename, "Error in writeReg(): when writing to address %u.\n", (unsigned)regAddress );
        putsUART1( filename );
    }
   
    return Success;
}
Ejemplo n.º 16
0
BOOL MPU6050::readReg( UINT8 regAddress, UINT8 &data )
{
    // Variable declarations
    UINT8               i2cData[10];
    I2C_7_BIT_ADDRESS   SlaveAddress;
    int                 Index;
    int                 DataSz;
    BOOL                Acknowledged;
    BOOL                Success = TRUE;
    UINT8               i2cbyte;


    // Initialize the data buffer
    I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, this->deviceAddress, I2C_WRITE);
    i2cData[0] = SlaveAddress.byte;
    i2cData[1] = regAddress;                 // MPU6050 data address to read (0x75 = WHO_AM_I which contains 0x68)
    DataSz = 2;


    // Start the transfer
    if( !StartTransfer(FALSE) )
    {
        //while(1);
        Success = FALSE;

        sprintf( filename, "Error in #1 StartTransfer(): when reading address %u.\n", (unsigned)regAddress );
        putsUART1( filename );
    }

    // Address the device.
    Index = 0;
    while( Success & (Index < DataSz) )
    {
        // Transmit a byte
        if (TransmitOneByte(i2cData[Index]))
            Index++;
        else
        {
            Success = FALSE;

            sprintf( filename, "Error in #1 TransmitOneByte(): when reading address %u.\n", (unsigned)regAddress );
            putsUART1( filename );
        }
        // Verify that the byte was acknowledged
        if(!I2CByteWasAcknowledged( this->i2cBusId ))
        {
            //DBPRINTF("Error: Sent byte was not acknowledged\n");
            Success = FALSE;

            sprintf( filename, "Error in #1 I2CByteWasAcknowledged(): when reading address %u.\n", (unsigned)regAddress );
            putsUART1( filename );
        }
    }

    // Restart and send the device's internal address to switch to a read transfer
    if(Success)
    {
        // Send a Repeated Started condition
        if( !StartTransfer(TRUE) )
        {
            //while(1);
            Success = FALSE;

            sprintf( filename, "Error in #2 StartTransfer(): when reading address %u.\n", (unsigned)regAddress );
            putsUART1( filename );
        }

        // Transmit the address with the READ bit set
        I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, this->deviceAddress, I2C_READ);
        if (TransmitOneByte(SlaveAddress.byte))
        {
            // Verify that the byte was acknowledged
            if(!I2CByteWasAcknowledged( this->i2cBusId ))
            {
                //DBPRINTF("Error: Sent byte was not acknowledged\n");
                Success = FALSE;

                sprintf( filename, "Error in #2 I2CByteWasAcknowledged(): when reading address %u.\n", (unsigned)regAddress );
                putsUART1( filename );
            }
        }
        else
        {
            Success = FALSE;

            sprintf( filename, "Error in #2 TransmitOneByte(): when reading address %u.\n", (unsigned)regAddress );
            putsUART1( filename );
        }
    }

    //i2cbyte = 9;

    // Read the data from the desired address
    if(Success)
    {
        if(I2CReceiverEnable( this->i2cBusId , TRUE) == I2C_RECEIVE_OVERFLOW)
        {
            //DBPRINTF("Error: I2C Receive Overflow\n");
            Success = FALSE;

            sprintf( filename, "Error I2CReceiverEnable(): when reading address %u. I2C Receive Overflow.\n", (unsigned)regAddress );
            putsUART1( filename );
        }
        else
        {
            while(!I2CReceivedDataIsAvailable( this->i2cBusId ));
            i2cbyte = I2CGetByte( this->i2cBusId );
        }
    }

    // End the transfer
    StopTransfer();

    data = i2cbyte;

    if(!Success)
    {

        //mPORTBSetBits(BIT_2);
        //mPORTBClearBits(BIT_3);

        sprintf( filename, "Error in readReg(): when reading address %u.\n", (unsigned)regAddress );
        putsUART1( filename );
    }    

    return Success;
}