Reputation: 169
I´m looking for the best way to split arduino files, the code that I had pasted below it just for compiled test is only to understand how this works. In this example I try to split my MQTT code.
This the enviroment:
main.ino file:
#include "file.h"
//and more libraries
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
setup_mqtt(); //declared in file.h
}
// a lot of code here
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect(); //declared in file.h
mqtt_mensaje(); //declared in file.h
}
}
file.h file:
void setup_mqtt();
void callback(char* topic, byte* payload, unsigned int length);
void reconnect();
void mqtt_mensaje();
file.cpp file
#include <Arduino.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#define LED_BUILTIN 4
const char* mqtt_server = "192.168.1.18";
// Connectión WiFi + Broker
WiFiClient espClient;
PubSubClient client(espClient);
// Function MQTT ------------------------
void reconnect() {
//code
}
void callback(char* topic, byte* payload, unsigned int length) {
//code
reconnect();
}
void mqtt_mensaje() {
//code PUB message
}
//End Functions MQTT-----------------------
void setup_mqtt(){
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
// Configuración MQTT
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
When I run this code in my Arduino IDE I get :
/Users/charlysan/Projects/works/arduino/main/main.ino: In function 'void loop()': main:9:10: error: 'client' was not declared in this scope if (!client.connected()) { ^
Any help will be appreciated
Upvotes: 0
Views: 332
Reputation: 28950
There is no best way to split C++ code. An answer to that would always be opinionated.
Regarding your error message add
#include <PubSubClient.h>
extern PubSubClient client;
to get rid of that error message you could declare it as extern so the compiler knows it is instanciated somewhere else. Add
#include <PubSubClient.h>
extern PubSubClient client;
to your .ino.
I personally don't see a reason why you should instanciate that in another file though.
Upvotes: 1