class Barometer
{
// Set Constants for Address and Clock Frequency
const ushort ADDRESS = 0x60;
const int CLOCK_FREQ = 100; // kHz max 400
const int TIMEOUT = 100;
//Init I2C Device Config
I2CDevice.Configuration config =
new I2CDevice.Configuration(ADDRESS, CLOCK_FREQ);
I2CDevice i2c;
public Barometer()
{
i2c = new I2CDevice(config);
ReadCoef();
}
public void Write(byte control, byte data)
{
i2c.Execute(new I2CDevice.I2CTransaction[1] {
I2CDevice.CreateWriteTransaction(new Byte[] { control, data }) }, TIMEOUT);
}
public int Read(byte Address)
{
byte[] Data = new byte[2];
i2c.Execute(new I2CDevice.I2CTransaction[1] { I2CDevice.CreateWriteTransaction(new Byte[] { Address }) }, TIMEOUT);
i2c.Execute(new I2CDevice.I2CTransaction[1] { I2CDevice.CreateReadTransaction(Data) }, TIMEOUT);
return Data[0] << 8 + Data[1];
}
public void Read(byte Address, byte[] Data)
{
i2c.Execute(new I2CDevice.I2CTransaction[1] { I2CDevice.CreateWriteTransaction(new Byte[] { Address }) }, TIMEOUT);
i2c.Execute(new I2CDevice.I2CTransaction[1] { I2CDevice.CreateReadTransaction(Data) }, TIMEOUT);
}
double a0;
double b1;
double b2;
double c12;
public double temperature { get; set; }
public void ReadCoef()
{
byte[] data = new byte[8];
Read(4, data);
a0 = ((short)((data[0] << 8) | data[1])) / 8.0;
b1 = ((short)((data[2] << 8) | data[3])) / 8192.0;
b2 = ((short)((data[4] << 8) | data[5])) / 16384.0;
c12 = ((data[6] << 8) + data[7]) / (double)(1<<(9+13+2));
}
public double GetPressure()
{
Write(0x12, 1);
CPU.delay(3);
byte[] data = new byte[4];
Read(0,data);
int Padc = ((data[0] << 8) | data[1])>>6 ;
int Tadc = ((data[2] << 8) | data[3])>>6;
double Pcomp = a0 + (b1 + c12 * Tadc) * Padc +b2 * Tadc;
temperature = 25 + ((Tadc - 497.0) / -5.35); // 472 counts at 25ºC, -5.35 counts/ºC
return (((650.0/1023.0)*Pcomp)+500);
}
public double GetTemperature()
{
return temperature;
}
}
|