/*
* Example Code for pressure reading from I2C bus
* Used microcontroller: Microchip PIC24FV32KA302
* This code is not complete! Basic I2C functions have to be added
*
*/
//Read byte from I2C bus; send master ACK-bit
char i2c_read_ack(void) //does not reset bus!!!
{
int i = 0;
char data = 0;
//set I2C module to receive
I2C1CONbits.RCEN = 1;
//if no response, break
while (!I2C1STATbits.RBF)
{
i++;
if (i > 2000) break;
}
//get data from I2CRCV register
data = I2C1RCV;
//set ACK to high
I2C1CONbits.ACKEN = 1;
//wait before exiting
Delay(10);
//return data
return data;
}
//Read byte from I2C bus; don't send master ACK-bit
char i2c_read_nack(void) //does not reset bus!!!
{
int i = 0;
char data = 0;
//set I2C module to receive
I2C1CONbits.RCEN = 1;
//if no response, break
while (!I2C1STATbits.RBF)
{
i++;
if (i > 2000) break;
}
//get data from I2CRCV register
data = I2C1RCV;
//set ACK to low
I2C1CONbits.ACKEN = 0;
//wait before exiting
Delay(10);
//return data
return data;
}
//Read digital pressure value
unsigned int I2CreadP_digital(void)
{
// Two bytes have to be read
unsigned char i2c_byte1 =0;
unsigned char i2c_byte2 =0;
/*****
*
* The two most significant bits of the first byte are status bits!
* They don't contain pressure value information.
*
* Encoding of status bits:
* 00: Normal operation, good data packet
* 01: Device in Command Mode
* 10: Stale data: Data that has already been fetched since
* the last measurement cycle.
* 11: Diagnostic condition exists *
*
* For further information see Datasheet of ASIC ZSC31014
*
*******/
unsigned char status =0;
int digital_Pressure =0;
unsigned char i2c_relevant_bits = 0;
// Initialize I2C Connection
i2c_init();
// Start I2C Communication
i2c_start();
// Send Slave Adress+Read-Bit; wait for slave ACK-Bit
send_i2c_byte(0b10100001);
//Read first byte + sending ACK-Bit
//the two MSBs of this byte are status bits!!
i2c_byte1 = i2c_read_ack();
//Read second byte without sending ACK-Bit
i2c_byte2 = i2c_read_nack();
//extract status bits from first byte
strncpy(status, i2c_byte1, 2);
//extract relevant bits for pressure value from first byte
strcpy(i2c_relevant_bits, i2c_byte1 + 2);
//calculate digital pressure value
digital_Pressure = i2c_relevant_bits * 256 + i2c_byte2;
return digital_Pressure;
}
// Reading of actual decimal pressure value
double I2CreadP_decimal(double P_min, double P_max)
//Range setup with P_min and P_max
{
//read digital pressure value
unsigned int digital_Pressure = I2CreadP_digital();
//constant for digital analog conversion DAC = (2^14)-1
int DAC = 16383;
//calculate proportional pressure value of P_range
double prop_P_range = digital_Pressure/DAC;
/* calculate decimal pressure value out of
* proportional pressure and given range setup */
double decimal_Pressure = prop_P_range*(P_max-P_min)+P_min;
return decimal_Pressure;
}
厉害!请问楼主是在高校研究学习呢?还是在公司做产品开发?