Can someone share a simple code with ino file split to .cpp and .h file

first .ino file
then .ino split to .cpp and .h

#include <Adafruit_Sensor.h> //Library for Adafruit sensors , we are using for DHT
#include <DHT.h> //DHT library which uses some func from Adafruit Sensor library
#include <ESP8266WiFi.h> //library for using ESP8266 WiFi 
#include <PubSubClient.h> //library for MQTT
#include <ArduinoJson.h> //library for Parsing JSON
#include <Wire.h>

//defining Pins
#define DHTPIN D4
#define Addr 0x51

//DHT parameters
#define DHTTYPE    DHT11     // DHT 11
DHT dht(DHTPIN, DHTTYPE);
uint32_t delayMS;

//MQTT Credentials
const char* ssid = "xxxxxx";//setting your ap ssid
const char* password = "xxxxxxx";//setting your ap psk
const char* mqttServer = "xxxxxxx"; //MQTT URL
const char* mqttUserName = "xxxxxxx";  // MQTT username
const char* mqttPwd = "xxxxxxx*";  // MQTT password
const char* clientID = "xxxxxxx"; // client id username+0001
const char* topic = "fxxxxxxx"; //publish topic

//parameters for using non-blocking delay
unsigned long previousMillis = 0;
const long TimeInMin = 10;
const long interval = (TimeInMin * 60000);

String msgStr = "";      // MQTT message buffer

float T1, T2, H1, H2;
int Chh;
String Status, Co, Te, Hu, Tv, Hc, Ch, out;


//setting up wifi and mqtt client
WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {
  delay(10);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

}

void reconnect() {
  while (!client.connected()) {
    if (client.connect(clientID, mqttUserName, mqttPwd)) {
      Serial.println("MQTT connected");
      client.subscribe("xxxxxxxd");
      Serial.println("Topic Subscribed");
    }
    else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);  // wait 5sec and retry
    }

  }

}

//subscribe call back
void callback(char*topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  Serial.print("Message size :");
  Serial.println(length);
  Serial.println();
  Serial.println("-----------------------");

  StaticJsonDocument<256> doc; //read JSON data
  deserializeJson(doc, payload, length); //deserialise it
  JsonObject command = doc["command"]; //get the values of command parameter

}


void setup() {
  Serial.begin(9600);
  //DHT11
  dht.begin();
  dht.readTemperature();
  dht.readHumidity();
  //RK14Z
  Wire.begin();
  Wire.beginTransmission(Addr);
  Wire.endTransmission();

  setup_wifi();

  client.setServer(mqttServer, 1883); //setting MQTT server
  client.setCallback(callback); //defining function which will be called when message is recieved.

}

void loop() {
  if (!client.connected()) { //if client is not connected
    reconnect(); //try to reconnect
  }
  client.loop();

  unsigned long currentMillis = millis(); //read current time

  if (currentMillis - previousMillis >= interval) { //if current time - last time > 5 sec
    previousMillis = currentMillis;

    //read temp and humidity dht11
    float hum1 = dht.readHumidity();
    float temp1 = dht.readTemperature();
    float tempd = temp1;
    float humd = hum1;
    String tempdh = String(tempd, 2);
    String humdh = String(humd, 2);
    Serial.print("Current humidity = ");
    Serial.print(humdh);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(tempdh);
    Serial.println("C  ");
    Wire.beginTransmission(Addr);

    //read data from RK14Z
    byte busStatus = Wire.endTransmission();
    if (busStatus != 0)
    {
      Serial.print("Sensor is not found!");
      while (1);
    }
    Serial.println("Sensor is found.");
    byte myData[13];
    byte m = Wire.requestFrom(0x51, 13);
    for (int i = 0; i < m; i++)
    {
      myData[i] = Wire.read();
    }
    for (int i = 0; i < m; i++)
    {
      Serial.print(myData[i], HEX);
      Serial.print(" ");
    }
    Serial.print("\n");
    if (myData[0] == 0xFF) //Message Header check
    {
      Serial.println("Data received!");
    }
    if (myData[3] == 0x00) //Status check
    {
      Serial.println("OK");
      Status = "OK";
    }
    else if (myData[3] == 0x01)
    {
      Serial.println("Heating");
      Status = "Heating";
    }
    else if (myData[3] == 0x02)
    {
      Serial.println("Error");
      Status = "Error";
    }
    uint16_t Co2 = word(myData[1], myData[2]);
    Co = String (Co2, DEC);
    Serial.print(Co);
    Serial.println(" ppm");
    uint16_t Temp = word(myData[4], myData[5]);
    Te = String(Temp, DEC);
    T2 = Te.toInt();
    T1 = (T2 - 669) / 10;
    String T3 = String(T1, 2);
    Serial.print(T3);
    Serial.println(" °C");
    uint16_t Hum = word(myData[6], myData[7]);
    Hu = String(Hum, DEC);
    H2 = Hu.toInt();
    H1 = (H2 - 125) / 10;
    String H3 = String(H1, 2);
    Serial.print(H3);
    Serial.println(" %RH");
    uint16_t TVOC = word(myData[8], myData[9]);
    Tv = String(TVOC, DEC);
    Serial.print(Tv);
    Serial.println(" ug/m3");
    uint16_t HCHO = word(myData[10], myData[11]);
    Hc = String (HCHO, DEC);
    Serial.print(Hc);
    Serial.println(" ug/m3");
    uint16_t sum = (myData[1] | myData[2] | myData[3] | myData[4] | myData[5] | myData[6] | myData[7] | myData[8] | myData[9] | myData[10] | myData[11]);
    Ch = String(sum, DEC);
    Chh = sum + 1;
    Serial.print("Check code :");
    Serial.println(Chh);
    DynamicJsonDocument doc(1024);
    doc["tempdht"] = tempdh;
    doc["humdht"] = humdh;
    doc["Sensor Status"] = Status;
    doc["Co2"] = Co;
    doc["temprk"] = T3;
    doc["humrk"] = H3;
    doc["TVOC"] = Tv;
    doc["HCHO"] = Hc;
    serializeJson(doc, msgStr);
    byte arrSize = msgStr.length() + 1;
    char msg[arrSize];
    Serial.print("PUBLISH DATA:");
    Serial.println(msgStr);
    msgStr.toCharArray(msg, arrSize);
    client.publish(topic, msg);
    msgStr = "";
    delay(50);
  }
}

to split this code to mqtt , Dht and Rk14z .cpp and .h files respectively

Why do you want to do this?

It seems to me that if you don't know how to do this, you wouldn't know when to do this.

The .ino does not split into this or that. New tabs can be added and then code moved to those new tabs which can be named this.h or that.cpp. Just select the New Tab drop down arrow located right under the Serial Monitor icon thingy.

Yeah exactly I don't know how to do this so i'am seeking help and this is to simplify my code and call mqtt and sensor data whenever i need it in future

Can you please provide me a sample code for reference I'm new to this

I think you are mistaken in this.

correct me please

I think you are wrong, is that not correction enough?

I'm asking for documentation or something which will give me proper idea about it

I don't think documents work like that, they work by telling you something is a good idea or an option. They do not work by telling you about everything else in the universe is not a good idea. For example what document tells you that urinating in your car's gas tank is not a good thing to do?

cool

I don't know something so i'm asking for help here if i knew how exactly to do this i wouldn't ask for help right the way you're speaking is like telling me to stop working on it if you have a solution help me with it

2 Likes

Here are some guidelines;

1 Like

thank you

Here is an example I wrote showing how to abstract part of a sketch into a .cpp/.h 'library':

When you are first starting out developing a library you can start with a simple demonstration sketch that shows what you want the library to do. Let's make a library that blinks an LED at a specified rate. We can start with something like File->Examples->02.Digital->BlinkWithoutDelay (I am removing most of the comments for compactness.)

const int ledPin =  LED_BUILTIN;
int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 1000; 

void setup() 
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  unsigned long currentMillis = millis();
  
  if (currentMillis - previousMillis >= interval)
  {
    previousMillis = currentMillis;

    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

The next step is to move the part you want the library to do into one or more functions. This sketch will do exactly the same thing as before but with very little in setup() and loop() and most code in a function:

const int ledPin =  LED_BUILTIN;
int ledState = LOW;
unsigned long previousMillis = 0;

void setup()
{
  pinMode(ledPin, OUTPUT);
}

void blink(unsigned long interval)
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval)
  {
    previousMillis = currentMillis;

    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

void loop()
{
  blink(1000);
}

Now comes the 'library' split. You start by creating a new tab. At the right end of the bar just above the sketch is a little triangle in a square. Click on that and select "New Tab". Name the new tab "BlinkLib.cpp". Now cut the 'blink' function out of the main tab and paste it into the new tab.

If you try to Verify your sketch now you will find some errors. The first is:

BlinkLib.cpp:3:33: error: 'millis' was not declared in this scope
   unsigned long currentMillis = millis();
                                 ^~~~~~

This is because, unlike the '.ino' files, the '.cpp' files don't automatically get
#include <Arduino.h>
inserted at compile time. Add that line to the top of BlinkLib.cpp and do another Verify.

The next error is:

BlinkLib.cpp:6:23: error: 'previousMillis' was not declared in this scope
   if (currentMillis - previousMillis >= interval)
                       ^~~~~~~~~~~~~~

This is because that global variable declaration didn't get moved to the library. In this case, only the library needs it so move the declaration to the top of BlinkLib.cpp. While you're at it, move 'ledState' and 'interval', too. Then try another Verify.

Now you get the error:

sketch_jan05a:13:3: error: 'blink' was not declared in this scope
   blink(1000);
   ^~~~~

That's because the main sketch no longer contains a declaration for the blink() function. This is a good time to create another tab to share declarations between the library and the sketch. Create a new tab named BlinkLib.h (h for 'header'). In that new tab, put the line:
void blink(unsigned long);
Then in the main sketch, add the line:
#include "BlinkLib.h"
This will allow the main sketch to see a declaration of "blink()".

That leads you to the next error:

BlinkLib.cpp:21:18: error: 'ledPin' was not declared in this scope
     digitalWrite(ledPin, ledState);
                  ^~~~~~

We used 'ledPin' in setup() so we left the declaration there, but now BlinkLib.cpp needs the declaration. We need a way for setup() to set the pin mode so we create another function in BlinkLib.cpp:

void setPin(int pin)
{
  ledPin = pin;
  pinMode(ledPin, OUTPUT);
}

Put the declaration of setPin() into BlinkLib.h so the sketch can use it:
void setPin(int);
Move the declaration of 'ledPin' into BlinkLib.cpp. Now you can have setup() call setPin().

All-together you have:
Main Sketch:

#include "BlinkLib.h"

void setup()
{
  setPin(LED_BUILTIN);
}

void loop()
{
  blink(1000);
}

Library header:

void blink(unsigned long);
void setPin(int);

Library source:

#include <Arduino.h>
#include "BlinkLib.h"

int ledState = LOW;
unsigned long previousMillis = 0;
int ledPin =  LED_BUILTIN;

void setPin(int pin)
{
  ledPin = pin;
  pinMode(ledPin, OUTPUT);
}

void blink(unsigned long interval)
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval)
  {
    previousMillis = currentMillis;

    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

Your library is complete!

3 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.