Site icon Elektrologi

Sensor Temperatur MCP9808

Contoh kode ESP32 untuk menghubungkan MCP9808 ke ThingsBoard. Kode ini menggunakan library MCP9808 dari Adafruit

// CJMCU-9808
// Adafruit MCP9808 Library https://github.com/adafruit/Adafruit_MCP9808_Library

#include <WiFi.h>           // WiFi control for ESP32
#include <ThingsBoard.h>    // ThingsBoard SDK
#include <Wire.h>
#include "Adafruit_MCP9808.h"
#include <Arduino.h>
#include <Wire.h>

Adafruit_MCP9808 tempsensor = Adafruit_MCP9808();

// WiFi access point
#define WIFI_AP_NAME        "WIFI_AP_NAME"
// WiFi password
#define WIFI_PASSWORD       "WIFI_PASSWORD"
#define TOKEN               "THINGSBOARD_TOKEN"

#define BUILTIN_LED 22
// ThingsBoard server instance.
#define THINGSBOARD_SERVER  "192.168.0.90"

#define I2C_SDA 15
#define I2C_SCL 13

// Initialize ThingsBoard client
WiFiClient espClient;
// Initialize ThingsBoard instance
ThingsBoard tb(espClient);
// the Wifi radio's status
int status = WL_IDLE_STATUS;

// main application loop delay (ms)
int quant = 20;

// Period of sending a temperature/humidity data.
int send_delay = 2000;

// Time passed after telemetry data was sent, milliseconds.
int send_passed = 0;

char mac_str[20]; // storing MAC address string
byte mac_byte[6]; // storing MAC address bytes

int led_counter = 0; //blinking built int led

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(1000);

  //wait for serial connection to open (only necessary on some boards)
  while (!Serial);

  Wire.begin(I2C_SDA, I2C_SCL);

  I2C_Scan() ; // just for verifying

  if (!tempsensor.begin(0x18)) {
    Serial.println("Couldn't find MCP9808! Check your connections and verify the address is correct.");
    while (1);
  }
  tempsensor.setResolution(3);

  WiFi.begin(WIFI_AP_NAME, WIFI_PASSWORD);
  InitWiFi();
  WiFi.macAddress(mac_byte);
  sprintf(mac_str, "%02x%02x%02x%02x%02x%02x", mac_byte[0], mac_byte[1], mac_byte[2], mac_byte[3], mac_byte[4], mac_byte[5]);
  Serial.print("ESP board MAC address:  ");
  Serial.println(WiFi.macAddress());
  Serial.print("ESP board  IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  float temperature = 25;
  float pressure = 0;
  float humidity = 60; // default humidity
  float co2 = 0;
  float tvoc = 0;

  delay(quant);
  send_passed += quant;

  // Reconnect to WiFi, if needed
  if (WiFi.status() != WL_CONNECTED) {
    reconnect();
    return;
  }

  // Reconnect to ThingsBoard, if needed
  if (!tb.connected()) {
    // Connect to the ThingsBoard
    Serial.print("Connecting to: ");
    Serial.print(THINGSBOARD_SERVER);
    Serial.print(" with token ");
    Serial.println(TOKEN);
    if (!tb.connect(THINGSBOARD_SERVER, TOKEN)) {
      Serial.println("Failed to connect");
      return;
    }
  }

  // Check if it is a time to send sensor data
  if (send_passed > send_delay) {
//    Serial.println("wake up MCP9808.... "); // wake up MCP9808 - power consumption ~200 mikro Ampere
    tempsensor.wake();   // wake up, ready to read!

    // Read and print out the temperature, also shows the resolution mode used for reading.
    //    Serial.print("Resolution in mode: ");
    //    Serial.println (tempsensor.getResolution());
    float c = tempsensor.readTempC();
    //    Serial.print("Temp: ");
    //    Serial.print(c, 4);
    //    Serial.print("*C\t and ");
    //    Serial.println("Shutdown MCP9808.... ");
    tempsensor.shutdown_wake(1); // shutdown MSP9808 - power consumption ~0.1 mikro Ampere, stops temperature sampling
//    Serial.println("");

    Serial.print("Sending telemetry data...");
    Serial.print("Temp ");
    Serial.print(c);
    Serial.println(" ");
    tb.sendTelemetryFloat("temperature", c);
    send_passed = 0;
  }

  // Process messages
  tb.loop();

  led_counter++; // LED blink at 1 Hz
  if (led_counter > 50) {
    led_counter = 0;
  }
  if (led_counter > 25) {
    digitalWrite(BUILTIN_LED , LOW);
  } else {
    digitalWrite(BUILTIN_LED , HIGH);
  }
}

void I2C_Scan() {
  byte error, address;

  int nDevices;
  Serial.println("I2C Scanning...");
  nDevices = 0;
  for (address = 1; address < 127; address++ ) {
    Wire.beginTransmission(address);
    error = Wire.endTransmission();
    if (error == 0) {
      Serial.print("I2C device found at address 0x");
      if (address < 16) {
        Serial.print("0");
      }
      Serial.println(address, HEX);
      nDevices++;
    }
    else if (error == 4) {
      Serial.print("Unknow error at address 0x");
      if (address < 16) {
        Serial.print("0");
      }
      Serial.println(address, HEX);
    }
  }
  if (nDevices == 0) {
    Serial.println("No I2C devices found\n");
  }
  else {
    Serial.println("done\n");
  }
}

void InitWiFi()
{
  Serial.println("Connecting to AP ...");
  // attempt to connect to WiFi network

  WiFi.begin(WIFI_AP_NAME, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to AP");
}

void reconnect() {
  // Loop until we're reconnected
  status = WiFi.status();
  if ( status != WL_CONNECTED) {
    WiFi.begin(WIFI_AP_NAME, WIFI_PASSWORD);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("Connected to AP");
  }
}

update: ditambah dengan watch dog timer

// CJMCU-9808
// Adafruit MCP9808 Library https://github.com/adafruit/Adafruit_MCP9808_Library

#include <WiFi.h>           // WiFi control for ESP32
#include <ThingsBoard.h>    // ThingsBoard SDK
#include <Wire.h>
#include "Adafruit_MCP9808.h"
#include <Arduino.h>
#include <Wire.h>
#include <esp_task_wdt.h>

Adafruit_MCP9808 tempsensor = Adafruit_MCP9808();

#define WDT_TIMEOUT 60
#define WIFI_AP_NAME        "abc" // WiFi access point
#define WIFI_PASSWORD       "123"
#define TOKEN               "jiowre43278feowjk4"

#define BUILTIN_LED 22
// ThingsBoard server instance.
#define THINGSBOARD_SERVER  "192.168.0.114"

#define I2C_SDA 15
#define I2C_SCL 13

// Initialize ThingsBoard client
WiFiClient espClient;
// Initialize ThingsBoard instance
ThingsBoard tb(espClient);
// the Wifi radio's status
int status = WL_IDLE_STATUS;

// main application loop delay (ms)
int quant = 20;

// Period of sending a temperature/humidity data.
int send_delay = 2000;

// Time passed after telemetry data was sent, milliseconds.
int send_passed = 0;

char mac_str[20]; // storing MAC address string
byte mac_byte[6]; // storing MAC address bytes

int led_counter = 0; //blinking built int led

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(1000);
  Serial.print(__FILE__);
  //wait for serial connection to open (only necessary on some boards)
  while (!Serial);

  Wire.begin(I2C_SDA, I2C_SCL);

  I2C_Scan() ; // just for verifying

  if (!tempsensor.begin(0x18)) {
    Serial.println("Couldn't find MCP9808! Check your connections and verify the address is correct.");
    while (1);
  }
  tempsensor.setResolution(3);

  WiFi.begin(WIFI_AP_NAME, WIFI_PASSWORD);
  InitWiFi();
  WiFi.macAddress(mac_byte);
  sprintf(mac_str, "%02x%02x%02x%02x%02x%02x", mac_byte[0], mac_byte[1], mac_byte[2], mac_byte[3], mac_byte[4], mac_byte[5]);
  Serial.print("ESP board MAC address:  ");
  Serial.println(WiFi.macAddress());
  Serial.print("ESP board  IP address: ");
  Serial.println(WiFi.localIP());

  // setup WDT
  esp_task_wdt_init(WDT_TIMEOUT, true); //enable panic so ESP32 restarts
  esp_task_wdt_add(NULL); //add current thread to WDT watch

}

void loop() {
  float temperature = 25;
  float pressure = 0;
  float humidity = 60; // default humidity
  float co2 = 0;
  float tvoc = 0;

  delay(quant);
  send_passed += quant;

  // Reconnect to WiFi, if needed
  if (WiFi.status() != WL_CONNECTED) {
    reconnect();
    sleep(5); // wait to reconnect
  }

  // Reconnect to ThingsBoard, if needed
  if (!tb.connected()) {
    // Connect to the ThingsBoard
    Serial.print("Connecting to: ");
    Serial.print(THINGSBOARD_SERVER);
    Serial.print(" with token ");
    Serial.println(TOKEN);
    if (!tb.connect(THINGSBOARD_SERVER, TOKEN)) {
      Serial.println("Failed to connect");
      return;
    }
  }

  // Check if it is a time to send sensor data
  if (send_passed > send_delay) {
    //    Serial.println("wake up MCP9808.... "); // wake up MCP9808 - power consumption ~200 mikro Ampere
    tempsensor.wake();   // wake up, ready to read!

    // Read and print out the temperature, also shows the resolution mode used for reading.
    //    Serial.print("Resolution in mode: ");
    //    Serial.println (tempsensor.getResolution());
    float c = tempsensor.readTempC();
    //    Serial.print("Temp: ");
    //    Serial.print(c, 4);
    //    Serial.print("*C\t and ");
    //    Serial.println("Shutdown MCP9808.... ");
    tempsensor.shutdown_wake(1); // shutdown MSP9808 - power consumption ~0.1 mikro Ampere, stops temperature sampling
    //    Serial.println("");

    Serial.print("Sending telemetry data...");
    Serial.print("Temp ");
    Serial.print(c);
    Serial.println(" ");
    tb.sendTelemetryFloat("temperature", c);
    send_passed = 0;
    esp_task_wdt_reset(); // WDT reset setelah berhasil mengirim data
  }

  // Process messages
  tb.loop();

  led_counter++; // LED blink at 1 Hz
  if (led_counter > 50) {
    led_counter = 0;
  }
  if (led_counter > 25) {
    digitalWrite(BUILTIN_LED , LOW);
  } else {
    digitalWrite(BUILTIN_LED , HIGH);
  }
}

void I2C_Scan() {
  byte error, address;

  int nDevices;
  Serial.println("I2C Scanning...");
  nDevices = 0;
  for (address = 1; address < 127; address++ ) {
    Wire.beginTransmission(address);
    error = Wire.endTransmission();
    if (error == 0) {
      Serial.print("I2C device found at address 0x");
      if (address < 16) {
        Serial.print("0");
      }
      Serial.println(address, HEX);
      nDevices++;
    }
    else if (error == 4) {
      Serial.print("Unknow error at address 0x");
      if (address < 16) {
        Serial.print("0");
      }
      Serial.println(address, HEX);
    }
  }
  if (nDevices == 0) {
    Serial.println("No I2C devices found\n");
  }
  else {
    Serial.println("done\n");
  }
}

void InitWiFi()
{
  Serial.println("Connecting to AP ...");
  // attempt to connect to WiFi network

  WiFi.begin(WIFI_AP_NAME, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to AP");
}

void reconnect() {
  // Loop until we're reconnected
  status = WiFi.status();
  if ( status != WL_CONNECTED) {
    WiFi.begin(WIFI_AP_NAME, WIFI_PASSWORD);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("Connected to AP");
  }
}

Referensi:

Exit mobile version