1 /* ESP MCP9808 Sensor/I2C C++ Example
2
3 This example code is in the Public Domain (or CC0 licensed, at your option.)
4
5 Unless required by applicable law or agreed to in writing, this
6 software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
7 CONDITIONS OF ANY KIND, either express or implied.
8 */
9
10 #include <iostream>
11 #include "i2c_cxx.hpp"
12
13 using namespace std;
14 using namespace idf;
15
16 #define ADDR 0x18
17 #define I2C_MASTER_NUM I2C_NUM_0 /*!< I2C port number for master dev */
18 #define I2C_MASTER_SCL_IO 19 /*!< gpio number for I2C master clock */
19 #define I2C_MASTER_SDA_IO 18 /*!< gpio number for I2C master data */
20
21 #define MCP_9808_TEMP_REG 0x05
22
23 /**
24 * Calculates the temperature of the MCP9808 from the read msb and lsb. Loosely adapted from the MCP9808's datasheet.
25 */
calc_temp(uint8_t msb,uint8_t lsb)26 float calc_temp(uint8_t msb, uint8_t lsb) {
27 float temperature;
28 msb &= 0x1F;
29 bool sign = msb & 0x10;
30 if (sign) {
31 msb &= 0x0F;
32 temperature = 256 - (msb * 16 + (float) lsb / 16);
33 } else {
34 temperature = (msb * 16 + (float) lsb / 16);
35 }
36
37 return temperature;
38 }
39
app_main(void)40 extern "C" void app_main(void)
41 {
42 try {
43 // creating master bus, writing temperature register pointer and reading the value
44 shared_ptr<I2CMaster> master(new I2CMaster(I2C_MASTER_NUM, I2C_MASTER_SCL_IO, I2C_MASTER_SDA_IO, 400000));
45 master->sync_write(ADDR, {MCP_9808_TEMP_REG});
46 vector<uint8_t> data = master->sync_read(ADDR, 2);
47
48 cout << "Current temperature: " << calc_temp(data[0], data[1]) << endl;
49 } catch (const I2CException &e) {
50 cout << "I2C Exception with error: " << e.what();
51 cout << " (" << e.error<< ")" << endl;
52 cout << "Coulnd't read sensor!" << endl;
53 }
54 }
55