void main(void)
{
    unsigned char outputData[2];
    unsigned int result = 0;
    unsigned char data = 0;
    Delay100TCYx(10); //let the device startup
    usart_init();
    i2c_init();
    printf("Starting\r\n");



    /*	******************************* Compass code and ADSL Code ********************** */
    //Tests compass by getting slave address
    //it should be 0x21
    Delay10TCYx(0);
    printf("Slave Address: 0x%02X \r\n", HMC6352_getSlaveAddress());
    HMC6352_setOpMode(HMC6352_CONTINUOUS , 1, 20);
    printf("Op Mode: 0x%02X \r\n", HMC6352_getOpMode());
    printf("Output Mode: 0x%02X \r\n", HMC6352_getOutputMode());


    while(1)
    {
        StartI2C();
        WriteI2C((HMC6352_I2C_ADDRESS << 1) | 1);
        outputData[0] = ReadI2C();
        NotAckI2C();
        outputData[1] = ReadI2C();
        NotAckI2C();
        StopI2C();

        result = outputData[0];
        result = result << 8;
        result = result | outputData[1];

        /*
        if(data2 <275 || data2 > 3599)
        	printf("North \r\n");
        */

        printf("Heading: %i \r\n", result-255);
    }

}
Example #2
0
/*********************************************************************
 * Function:        XEE_RESULT XEEEndRead(void)
 *
 * PreCondition:    XEEInit() && XEEBeginRead() are already called.
 *
 * Input:           None
 *
 * Output:          XEE_SUCCESS if successful
 *                  other value if failed.
 *
 * Side Effects:    None
 *
 * Overview:        Ends sequential read cycle.
 *
 * Note:            This function ends seuential cycle that was in
 *                  progress.  It releases I2C bus.
 ********************************************************************/
XEE_RESULT XEEEndRead(void)
{
    getcI2C();
    while( EEPROM_SPICON2bits.RCEN );  // check that receive sequence is over.

    NotAckI2C();
    while( EEPROM_SPICON2bits.ACKEN );

    StopI2C();
    while( EEPROM_SPICON2bits.PEN );

    return XEE_SUCCESS;
}
Example #3
0
unsigned char ITG3200_read(unsigned char reg) {
	unsigned char buf;
	
	StartI2C();
	WriteI2C(ITG3200_ADDR_WRITE);
	WriteI2C(reg);
	RestartI2C();
	WriteI2C(ITG3200_ADDR_READ);
	buf = ReadI2C();
	NotAckI2C();
	StopI2C();
	
	return buf;
}
Example #4
0
char readEEPROMexterna (char endereco)
{

		//while(!DataRdyI2C());
		IdleI2C();
		StartI2C(); IdleI2C();
		WriteI2C(0xA0); IdleI2C();
		WriteI2C(0x00); IdleI2C();   //HB
		WriteI2C(endereco); IdleI2C();
		RestartI2C(); IdleI2C();
		WriteI2C(0xA1); IdleI2C();
		value = ReadI2C(); IdleI2C(); //Dados
		NotAckI2C(); IdleI2C();
		StopI2C();IdleI2C();
		return value;
}
Example #5
0
/*********************************************************************
* Function:        LDSequentialReadI2C()
* Input:			ControlByte, address, *rdptr, length.
* Overview:		Performs a sequential read of length bytes starting at address
*				and places data in array pointed to by *rdptr
********************************************************************/
unsigned int LDSequentialReadI2C(unsigned char ControlByte, unsigned char address, unsigned char *rdptr, unsigned char length)
{
	IdleI2C();						//Ensure Module is Idle
	StartI2C();						//Initiate start condition
	WriteI2C(ControlByte);			//write 1 byte
	IdleI2C();						//Ensure module is Idle
	WriteI2C(address);				//Write word address
	IdleI2C();						//Ensure module is idle
	RestartI2C();					//Generate I2C Restart Condition
	WriteI2C(ControlByte | 0x01);	//Write 1 byte - R/W bit should be 1 for read
	IdleI2C();						//Ensure bus is idle
	getsI2C(rdptr, length);			//Read in multiple bytes
	NotAckI2C();					//Send Not Ack
	StopI2C();						//Send stop condition
	return(0);
}
Example #6
0
/*********************************************************************
* Function:        LDByteReadI2C()
* Input:		Control Byte, Address, *Data, Length.
* Overview:		Performs a low density read of Length bytes and stores in *Data array
*				starting at Address.
********************************************************************/
unsigned int LDByteReadI2C(unsigned char ControlByte, unsigned char Address, unsigned char *Data, unsigned char Length)
{
	IdleI2C();					//wait for bus Idle
	StartI2C();					//Generate Start Condition
	WriteI2C(ControlByte);		//Write Control Byte
	IdleI2C();					//wait for bus Idle
	WriteI2C(Address);			//Write start address
	IdleI2C();					//wait for bus Idle

	RestartI2C();				//Generate restart condition
	WriteI2C(ControlByte | 0x01);	//Write control byte for read
	IdleI2C();					//wait for bus Idle

	getsI2C(Data, Length);		//read Length number of bytes
	NotAckI2C();				//Send Not Ack
	StopI2C();					//Generate Stop
}
Example #7
0
/*
 *   Gyro i2c interface, Read/Write
 */
UINT8 Gyro_I2C_R(UINT8 Address)
{
    UINT8 Data;
    IdleI2C();                              //wait for bus Idle
    StartI2C();                             //Generate Start Condition
    WriteI2C(Gyro_MPU6050_Address);         //Write Control Byte
    IdleI2C();                              //wait for bus Idle
    WriteI2C(Address);                      //Write start address
    IdleI2C();                              //wait for bus Idle

    RestartI2C();                           //Generate restart condition
    WriteI2C(Gyro_MPU6050_Address | 0x01);  //Write control byte for read
    IdleI2C();                              //wait for bus Idle

    Data = getI2C();                        //read Length number of bytes
    NotAckI2C();                            //Send Not Ack
    StopI2C();                              //Generate Stop

    return Data;
}
Example #8
0
int i2ReadData(char SlaveAddress, unsigned char Address, int Bytes, unsigned char *Dades) {
// Pre: Bytes >= 0; Dades t‚ espai per a NumBytes
// Pre: El bit m‚s baix de Address no t‚ informaci¢ (ser… read o write)
// Post: retorna 0 si tot OK o 1 si hi ha un timeout d'un msegon
// en un ack
	IdleI2C();					//wait for bus Idle
	StartI2C();					//Generate Start Condition
	WriteI2C((SlaveAddress<<1));		//Write Control Byte
	IdleI2C();					//wait for bus Idle
	WriteI2C(Address);			//Write start address
	IdleI2C();					//wait for bus Idle

	RestartI2C();				//Generate restart condition
	WriteI2C((SlaveAddress<<1 | 0x01));	//Write control byte for read
	IdleI2C();					//wait for bus Idle

	getsI2C(Dades, Bytes);		//read Length number of bytes
	NotAckI2C();				//Send Not Ack
	StopI2C();					//Generate Stop
	return 0;
}
Example #9
0
/*********************************************************************
* Function:        HDByteReadI2C()
*
* Input:		Control Byte, HighAdd, LowAdd, *Data, Length.
*
* Output:		None.
*
* Overview:		Performs a low density read of Length bytes and stores in *Data array
*				starting at Address formed from HighAdd and LowAdd.
*
* Note:			None
********************************************************************/
unsigned int HDByteReadI2C(unsigned char ControlByte, unsigned char HighAdd, unsigned char LowAdd, unsigned char *Data, unsigned char Length)
{
	IdleI2C();						//Wait for bus Idle
	StartI2C();						//Generate Start condition
	WriteI2C(ControlByte);			//send control byte for write
	IdleI2C();						//Wait for bus Idle

	WriteI2C(HighAdd);				//Send High Address
	IdleI2C();						//Wait for bus Idle
	WriteI2C(LowAdd);				//Send Low Address
	IdleI2C();						//Wait for bus Idle

	RestartI2C();					//Generate Restart
	WriteI2C(ControlByte | 0x01);	//send control byte for Read
	IdleI2C();						//Wait for bus Idle

	getsI2C(Data, Length);			//Read Length number of bytes to Data
	NotAckI2C();					//send Not Ack
	StopI2C();						//Send Stop Condition
	return(0);
}
Example #10
0
// wait for device to reply, and read the data into RX buffer
void master_I2C_read(unsigned int device_ID, int registerAddr)
{
    int i;
    IdleI2C();
    c_StartI2C();                        // Send START condition
    IdleI2C();                     // Wait for the end of the START condition
    c_WriteI2C( device_ID << 1 | 0x01 ); // Send address with R/W set for read
    IdleI2C();
    check_ack();
    // wait for data sent and acked
    for(i=0; i< RX_buffer_size-1; i++)
    {
	I2C_RX_buffer_ptr[i] = c_ReadI2C();
        // Read first byte of data
         c_ackI2C();	//send ACK
         IdleI2C();
    }
    I2C_RX_buffer_ptr[RX_buffer_size-1] = c_ReadI2C();               // Read nth byte of data
    NotAckI2C();                       // Send NACK
    c_stopI2C();                         // Hang up, send STOP condition
}
Example #11
0
static void EEPROM_read_seq(BYTE devaddr, BYTE *data, BYTE size)
{
    BYTE i = 0;
    
    StartI2C();
    IdleI2C();
    WriteI2C( (devaddr << 1) | 0x01 );
    IdleI2C();
    
    for(; i < size; ++i)
    {
        data[i] = ReadI2C();
        if(i < size-1) {
            AckI2C();
        } else {
            NotAckI2C();
        }
    }

    StopI2C();
}
Example #12
0
void ADXL345_multiByteRead(unsigned char startAddress, char* buffer, unsigned char size) {

    
	#if I2C
		unsigned char i;
		StartI2C();
		WriteI2C(ADXL343_ADDR_WRITE); 
		WriteI2C(startAddress);
		RestartI2C();
		WriteI2C(ADXL343_ADDR_READ);

	    for (i = 0; i < size; i++) {
	        buffer[i] = ReadI2C();	//keep the clock pulsing
			// if not last byte, send ack
			// if last byte, send nack
			if(i < size-1)
			{
				AckI2C();
			} 
			else
			{
				NotAckI2C();
			}
	    }
		StopI2C();
    #elif SPI
		unsigned char tx = (ADXL345_SPI_READ | ADXL345_MULTI_BYTE | (startAddress & 0x3F));	// the &0x3F restricts reading from only the XYZ data registers
		unsigned char i;
		SPI_CS_PIN = 0;	//CS pin low, ie enable chip
		Delay1TCY();	// delay at least 5 ns
		WriteSPI(tx);	//Send address to start reading from.
		

	    for (i = 0; i < size; i++) {
	        buffer[i] = ReadSPI();	//keep the clock pulsing
	    }

		SPI_CS_PIN = 1;	//CS pin high, ie disable chip
	#endif
}
unsigned char HDByteReadI2C( unsigned char ControlByte, unsigned char HighAdd, unsigned char LowAdd, unsigned char *data, unsigned char length )
{
  IdleI2C();                      // ensure module is idle
  StartI2C();                     // initiate START condition
  while ( SSPCON2bits.SEN );      // wait until start condition is over 
  WriteI2C( ControlByte );        // write 1 byte 
  IdleI2C();                      // ensure module is idle
  WriteI2C( HighAdd );            // WRITE word address to EEPROM
  IdleI2C();                      // ensure module is idle
  while ( SSPCON2bits.RSEN );     // wait until re-start condition is over 
  WriteI2C( LowAdd );             // WRITE word address to EEPROM
  IdleI2C();                      // ensure module is idle
  RestartI2C();                   // generate I2C bus restart condition
  while ( SSPCON2bits.RSEN );     // wait until re-start condition is over 
  WriteI2C( ControlByte | 0x01 ); // WRITE 1 byte - R/W bit should be 1 for read
  IdleI2C();                      // ensure module is idle
  getsI2C( data, length );       // read in multiple bytes
  NotAckI2C();                    // send not ACK condition
  while ( SSPCON2bits.ACKEN );    // wait until ACK sequence is over 
  StopI2C();                      // send STOP condition
  while ( SSPCON2bits.PEN );      // wait until stop condition is over 
  return ( 0 );                   // return with no error
}
Example #14
0
static int
i2c_read(struct i2c_platform_data *adap, unsigned char *buf,
		    unsigned int len)
{
	int	i;
	u32	data;

	pr_debug("i2c_read\n");

	i = 0;
	while (i < len) {
		data = MasterReadI2C(adap);
		buf[i++] = data;
		if (i < len)
			AckI2C(adap);
		else
			NotAckI2C(adap);
	}

	StopI2C(adap);
	IdleI2C(adap);
	return 0;
}
Example #15
0
unsigned char ADXL345_oneByteRead(unsigned char address) {
	unsigned char data = 0;

	#if I2C
	    StartI2C();
		WriteI2C(ADXL343_ADDR_WRITE); 
		WriteI2C(address);
		RestartI2C();
		WriteI2C(ADXL343_ADDR_READ);
		data = ReadI2C();
		NotAckI2C();
		StopI2C();
		return data;
	#elif SPI
		SPI_CS_PIN = 0;	//CS pin low, ie enable chip
		Delay1TCY();		// delay at least 5 ns
		address = address | ADXL345_SPI_READ;
		WriteSPI(address);		// read bit, multibyte bit, A5-A0 address
		data = ReadSPI();
		SPI_CS_PIN = 1;	//CS pin high, ie disable chip
		Delay1TCY();		// delay at least 5 ns
		return data;
	#endif
}
Example #16
0
void main (void)
{
    TRISC0=0;   // Led Amar
    TRISC1=0;   // Led Verd
    TRISC2=0;   // LED Verm
    TRISC6=0;   // saida TX EUSART
    ADCON1=0x0F;    // coloca pinos I/O em modo digital (nao analogico)

    acordar();

    unsigned int D0, D1, D2, D3, minAnterior, contador, segInicial;
    char msg[30];

    LED_VERM=1;
     // inicia porta serial com 9600 bps @ 8mhz

    initExt7SegLCD();   // inicia barramento I2C e escreve ".12:34."
    pausa(1); piscaSeg(0);

    // Inicio do Relogio e Display

    contador=0;    // o contador esta acima do limite (59)
    minAnterior=10; // o minuto nunca chegaria a 10 (forca display)

    while (1)
    {

        
        getDS1307();

        sprintf(msg," _[%x:%x:%x]_", hora, minuto, segundo );
            while(BusyUSART());
            putsUSART( msg );

        D0 = (hora & 0b00110000) >> 4;  // utiliza somente 2 bits da nibble esq
        D1 = hora & 0b00001111;         // utiliza somente 4 bits da nibble dir
        D2 = (minuto & 0b11110000) >> 4;// utiliza somente 4 bits da nibble esq
        D3 = minuto & 0b00001111;       // utiliza somente 4 bits da nibble dir

            /*
            sprintf(msg,"___ %d%d:%d%d ...%xseg_ \r\n",
                D0, D1, D2, D3 ,segundo);
            while(BusyUSART());
            putsUSART( msg );
             */

        if (D3 != minAnterior)  // se mudou o minuto, entao mostre novo horario
        {
            StartI2C();
                __delay_us(16); // delay experimental
                WriteI2C(HT16K33_ADDR << 1);

                WriteI2C(0x00);

                WriteI2C(numbertable[D0] & 0xff ); // preenche todos os bits
                WriteI2C(numbertable[D0] >> 8);    // qualquer byte
                // obs: acima como foram usados somente 2 bits, alguma "sujeira"
                // poderia ter ficado escrita no registrador, por isso a necessidade
                // de "preencher" os outros bits com & 0xff

                WriteI2C(numbertable[ D1 ] & 0xFF ); // preenche todos os bits
                WriteI2C(numbertable[ D1 ] >> 8);    // qualquer byte

                WriteI2C(0xFF); // escreve ":" sempre no segundo 0 de mostrar
                WriteI2C(0xFF >> 8);    // qualquer byte

                WriteI2C(numbertable[ D2 ] & 0xFF );// preenche todos os bits
                WriteI2C(numbertable[ D2 ] >> 8);    // qualquer byte

                WriteI2C(numbertable[ D3 ] & 0xFF );// preenche todos os bits
                WriteI2C(numbertable[ D3 ] >> 8);    // qualquer byte

                NotAckI2C();    // encerra envio
                __delay_us(16); // delay experimental
            StopI2C();
            minAnterior=D3; // variavel para proxima checagem e mudanca
        }

        pausa(1);   // utiliza TIMER0 para realizar contagem precisa de 1 seg
        
        
        if ( (contador % 2) == 0) piscaSeg(1);  // gera a piscada ":" par
        else piscaSeg(0); // ou impar " ", a cada mudanca de contador (seg)

        
        sprintf(msg,"\r\nSeg=%d, Cont=%d", segundo, contador );
            while(BusyUSART());
            putsUSART( msg );


            // rotina abaixo de calculo de desvio de segundos
            // ainda deve ser corrigida para o algoritmo correto

            if (contador >= 2 ) // cont >= 40+10
                { 
                    
                    dormir();

                    sprintf(msg,"\r\nSeg=%d, Cont=%d (volta do sleep)", segundo, contador );
                    while(BusyUSART());
                    putsUSART( msg );
                    contador=0;
            
                }

        contador++; // incrementa controle de contagem de segundos
    }
Example #17
0
unsigned int EERandomRead( unsigned char control, unsigned char address )
{
  IdleI2C();                      // ensure module is idle
  StartI2C();                     // initiate START condition
  while ( SSPCON2bits.SEN );      // wait until start condition is over 
  if ( PIR2bits.BCLIF )           // test for bus collision
  {
    return ( -1 );                // return with Bus Collision error 
  }
  else
  {
    if ( WriteI2C( control ) )    // write 1 byte
    {
	  StopI2C(); 
      return ( -3 );              // return with write collision error
    }

    //IdleI2C();                    // ensure module is idle
    if ( !SSPCON2bits.ACKSTAT )   // test for ACK condition, if received
    {
      if ( WriteI2C( address ) )  // WRITE word address for EEPROM
      {
	    StopI2C(); 
        return ( -3 );            // return with write collision error
      }

      //IdleI2C();                  // ensure module is idle
      if ( !SSPCON2bits.ACKSTAT ) // test for ACK condition, if received
      {
        RestartI2C();             // generate I2C bus restart condition
        while ( SSPCON2bits.RSEN );// wait until re-start condition is over 
        if ( PIR2bits.BCLIF )     // test for bus collision
        {
          return ( -1 );          // return with Bus Collision error 
        }
                          
        if ( WriteI2C( control+1 ) )// write 1 byte - R/W bit should be 1
        {
		  StopI2C(); 
          return ( -3 );          // return with write collision error
        }

        //IdleI2C();                // ensure module is idle
        if ( !SSPCON2bits.ACKSTAT )// test for ACK condition, if received
        {
          SSPCON2bits.RCEN = 1;       // enable master for 1 byte reception
          while ( SSPCON2bits.RCEN ); // check that receive sequence is over
          NotAckI2C();              // send ACK condition
          while ( SSPCON2bits.ACKEN ); // wait until ACK sequence is over 
          StopI2C();              // send STOP condition
          while ( SSPCON2bits.PEN ); // wait until stop condition is over 
          if ( PIR2bits.BCLIF )   // test for bus collision
          {
           return ( -1 );         // return with Bus Collision error 
          }
        }
        else
        {
		  StopI2C(); 
          return ( -2 );          // return with Not Ack error
        }

      }
      else
      {
	    StopI2C(); 
        return ( -2 );            // return with Not Ack error
      }
    }
    else
    {
	  StopI2C(); 
      return ( -2 );              // return with Not Ack error
    }
  }
  return ( (unsigned int) SSPBUF );     // return with data
}
Example #18
0
void readTempSensor(unsigned char *byte1, unsigned char *byte2,
					unsigned char *slope, unsigned char *counter)
{
	StartI2C();
	IdleI2C();
	WriteI2C(0x9E); // slave address + W
	IdleI2C();
	WriteI2C(0xAA); // read two bytes command
	IdleI2C();

	RestartI2C();
	IdleI2C();
	WriteI2C(0x9F); // slave address + R
	IdleI2C();
	(*byte1) = ReadI2C();
	IdleI2C();
	AckI2C();
	IdleI2C();
	(*byte2) = ReadI2C();
	IdleI2C();
	NotAckI2C();
	IdleI2C();
	StopI2C();

	Delay10KTCYx(1);

	// read counter
	StartI2C();
	IdleI2C();
	WriteI2C(0x9E); // slave address + W
	IdleI2C();
	WriteI2C(0xA8); // read counter command
	IdleI2C();

	RestartI2C();
	IdleI2C();
	WriteI2C(0x9F); // slave address + R
	IdleI2C();

	(*counter) = ReadI2C();
	IdleI2C();
	NotAckI2C();
	IdleI2C();
	StopI2C();

	Delay10KTCYx(1);

	// read slope
	StartI2C();
	IdleI2C();
	WriteI2C(0x9E); // slave address + W
	IdleI2C();
	WriteI2C(0xA9); // read slope command
	IdleI2C();

	RestartI2C();
	IdleI2C();
	WriteI2C(0x9F); // slave address + R
	IdleI2C();

	(*slope) = ReadI2C();
	IdleI2C();
	NotAckI2C();
	IdleI2C();
	StopI2C();

	Delay10KTCYx(1);
}
byte I2CReadByte ( byte Device, byte Address )
{
    byte Data = 0;

    // Ensure I2C module is idle
    IdleI2C();

    // Transmit a Start condition
    StartI2C();

    // Wait till Start sequence is completed
    while(I2CCONbits.SEN );

    // Write Slave address and set master for transmission  (R/W bit should be 0)
    MasterWriteI2C(Device);

    // Wait till address is transmitted
    while(I2CSTATbits.TBF);

    // Test for ACK condition received
    while(I2CSTATbits.ACKSTAT);

    // Ensure I2C module is idle
    //IdleI2C();

    // Write word address for serial EEPROM
    MasterWriteI2C(Address);

    // Wait till address is transmitted
    while(I2CSTATbits.TBF);

    // Test for ACK condition received
    while(I2CSTATbits.ACKSTAT);

    // Ensure I2C module is idle
    //IdleI2C();

    // Generate the I2C bus restart condition
    RestartI2C();

    // Wait until re-start condition is over
    while (I2CCONbits.RSEN);

    // WWrite Slave address and set master for reception  (R/W bit should be 1)
    MasterWriteI2C( Device+1 );

    // Wait till address is transmitted
    while(I2CSTATbits.TBF);

    // Ensure I2C module is idle
    //IdleI2C();

    // Test for ACK condition received
    while(I2CSTATbits.ACKSTAT);

    // Ensure I2C module is idle
    //IdleI2C();

    // Read the data byte

    Data = MasterReadI2C();

    // Ensure I2C module is idle
    //IdleI2C();

    // send NACK condition back to the I2C slave indicating master received the data byte
    NotAckI2C();

    // wait until NACK sequence is over
    while (I2CCONbits.ACKEN);

    // Ensure I2C module is idle
    //IdleI2C();

    // send STOP condition
    StopI2C();

    // Wait till Stop sequence is completed
    while(I2CCONbits.PEN);

    // Ensure I2C module is idle
    IdleI2C();

    return ( Data );     // return with data
}