Vladimir Akopyan / Chirp Featured

Dependents:   Test_Chirp

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers Chirp.cpp Source File

Chirp.cpp

00001 #include "mbed.h"
00002 #include "Chirp.h"
00003 
00004 //Chirp Docs are at https://github.com/Miceuz/i2c-moisture-sensor and https://www.tindie.com/products/miceuz/i2c-soil-moisture-sensor/
00005 
00006 Chirp::Chirp(PinName sda, PinName scl, char slave_adr)
00007     :i2c_p(new I2C(sda, scl)), i2c(*i2c_p), address(slave_adr)
00008 {
00009     i2c.frequency(10000);
00010 }
00011 
00012 float Chirp::getCapacitance(){
00013     i2c.frequency(10000);
00014     short capacitance = 0;
00015     char i2cData[2]= {0}; 
00016     
00017     char dataReg = 0; //Capacitance is stored in 2 bytes at address 0
00018     i2c.write(address, &dataReg, 1); 
00019     int success = i2c.read(address, i2cData, 2);
00020     
00021     if(success != 0)
00022         return -1000000; 
00023     else
00024     {
00025         //I2C bytes are in different byte order, write into short bytes 0 and 1 in reverse order!
00026         *((char*)&capacitance) = i2cData[1];
00027         *(((char*)(&capacitance)) + 1) = i2cData[0];
00028         return capacitance;
00029     }
00030 }
00031 
00032 float Chirp::getTemperature(){
00033     i2c.frequency(10000);
00034     short temperature = 0;
00035     char i2cData[2]= {0}; 
00036     
00037     
00038     char dataReg = 5; //Temperature is stored in 2 bytes at address 5
00039     i2c.write(address, &dataReg, 1); 
00040     int success = i2c.read(address, i2cData, 2);
00041     
00042     if(success != 0)
00043         return -1000000; 
00044     else
00045     {
00046         *((char*)&temperature) = i2cData[1];
00047         *(((char*)(&temperature)) + 1) = i2cData[0];
00048         return (float) temperature / 10.0;
00049     }
00050 }
00051