Integrate part of sketch into existing sketch

Hello, newbie here, just learning arduino. Any help appreciated

Am trying to copy a part of a sketch and integrate it into my main sketch but am having issues getting it to work, this is the code im trying to integrate -

unsigned long previousMillis = 0; // Stores last time relay was updated
const long interval = 60000; // Interval at which to cycle relay (60 seconds)
float percentageTimeOn = 0.0; // Percentage of time relay is on (0% by default)

void setup() {
  pinMode(CONTROLLINO_R0, OUTPUT);

  Ethernet.begin(mac);
 

  connectToMqtt();
}

void loop() {
  if (!client.connected()) {
    connectToMqtt();
  }
  client.loop(); 
  
 
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= (interval * percentageTimeOn)) {
    digitalWrite(CONTROLLINO_R0, LOW); // Turn relay off
  }
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    digitalWrite(CONTROLLINO_R0, HIGH); // Turn relay on
    

// Multiply percentageTimeOn by 100 and publish as number
    float percent = percentageTimeOn * 100;
    char percentageTimeOnString[8];
    dtostrf(percent, 2, 1, percentageTimeOnString); // Convert float to string with 1 decimal
    client.publish(mqtt_topicpub, percentageTimeOnString);

   
  } 
}

void mqttCallback(char* topic, byte* payload, unsigned int length) {
  // Convert payload to string
  char msg[5];
  if (length < 4) { // Assuming the percentage won't be more than 3 digits
    strncpy(msg, (char*)payload, length);
    msg[length] = '\0';
    percentageTimeOn = constrain(atof(msg) / 100.0, 0.0, 1.0); // Convert to fraction and constrain between 0 and 1
  }
}

And i want to integrate it into this one -

#include <Controllino.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <TinyGPS++.h>
#include <SPI.h>
#include <SoftwareSerial.h>



#define RELAY_R0 CONTROLLINO_R0
#define RELAY_R1 CONTROLLINO_R1
#define RELAY_R2 CONTROLLINO_R2
#define RELAY_R3 CONTROLLINO_R3
#define MQTT_SERVER "broker.hivemq.com"
#define MQTT_PORT 1883
#define MQTT_USERNAME "randy"
#define MQTT_PASSWORD "123456"
#define TOPIC_SUB "testpivotcode"
#define TOPIC_PUB "testpivotcodepub"
// Define the MQTT payload values for each relay
#define FORWARD "Forward"
#define REVERSE "Reverse"
#define PIVOTON "Pivot ON"
#define PIVOTOFF "Pivot OFF"
// Define the momentary duration in milliseconds
#define MOMENTARY_DURATION 1000



byte mac[] = {
  random(0, 255),
  random(0, 255),
  random(0, 255),
  random(0, 255),
  random(0, 255),
  random(0, 255)
};

EthernetClient ethClient;
PubSubClient client(ethClient);



void setup() {
  setup1();
}

void loop() {
  loop1();
}

void setup1() {
  pinMode(RELAY_R1, OUTPUT);
  pinMode(RELAY_R2, OUTPUT);
  pinMode(RELAY_R3, OUTPUT);
  Ethernet.begin(mac);
  client.setServer(MQTT_SERVER, MQTT_PORT);
  client.setCallback(callback);
}

void loop1() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

// MQTT callback function
void callback(char* topic, byte* payload, unsigned int length) {
  // Convert the payload to a string
  String message = "";
  for (int i = 0; i < length; i++) {
    message += (char)payload[i];
  }

  {
    // Check the payload for each relay
    if (message.equals(FORWARD)) {
      
    digitalWrite(RELAY_R1, HIGH);
    delay(MOMENTARY_DURATION);
    digitalWrite(RELAY_R1, LOW);

    } else if (message.equals(REVERSE)) {
      
    digitalWrite(RELAY_R2, HIGH);
    delay(MOMENTARY_DURATION);
    digitalWrite(RELAY_R2, LOW);

    } else if (message.equals(PIVOTON)) {
      
    digitalWrite(RELAY_R3, HIGH);

    } else if (message.equals(PIVOTOFF)) {
      
    digitalWrite(RELAY_R3, LOW);
    }
  }
}

void reconnect() {
  while (!client.connected()) {
    if (client.connect("test", MQTT_USERNAME, MQTT_PASSWORD)) {
      client.subscribe(TOPIC_SUB);
    } else {
      delay(1000);
    }
  }
}

Thanks in advance for any help.

Can you please be a bit more specific on your issues?

Am wondering about the rest of the partial sketch.

I suggest you reduce the sketch to be added to the minimum functionality that you wish to add.

Post that complete reduced sketch that compiles. If it also functions, state why you ar having issues adding it to your existing sketch.

If it doesn't work, say what it does that it shouldn't, or does not do that it should.

Working with the partial sketch is difficult as you have not supplied important context details, like libraries and so forth.

a7

Sorry about the confusion of my question but as you can see in my main code im using Relays R1, R2 and R3 and opening and closing them based on a message from mqtt broker so my idea is to add the Relay R0 which is part of the partial sketch which uses a percentage received via mqtt to open and close relay as a timer, I would like to add it so it uses the same loop and same callback as the other relays but can't seem to get them to work together.

I did try this but neither one works then if i upload it to my arduino as this -

#include <Controllino.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <TinyGPS++.h>
#include <SPI.h>
#include <SoftwareSerial.h>



#define RELAY_R0 CONTROLLINO_R0
#define RELAY_R1 CONTROLLINO_R1
#define RELAY_R2 CONTROLLINO_R2
#define RELAY_R3 CONTROLLINO_R3
#define MQTT_SERVER "broker.hivemq.com"
#define MQTT_PORT 1883
#define MQTT_USERNAME "randy"
#define MQTT_PASSWORD "123456"
#define TOPIC_SUB "TESTSUB"
#define TOPIC_PUB "TESTPUB"
// Define the MQTT payload values for each relay
#define FORWARD "Forward"
#define REVERSE "Reverse"
#define PIVOTON "Pivot ON"
#define PIVOTOFF "Pivot OFF"
// Define the momentary duration in milliseconds
#define MOMENTARY_DURATION 1000



byte mac[] = {
  random(0, 255),
  random(0, 255),
  random(0, 255),
  random(0, 255),
  random(0, 255),
  random(0, 255)
};

EthernetClient ethClient;
PubSubClient client(ethClient);



void setup() {
  setup1();
  setup2();
}

void loop() {
  loop1();
  loop2();
}

void setup1() {
  pinMode(RELAY_R1, OUTPUT);
  pinMode(RELAY_R2, OUTPUT);
  pinMode(RELAY_R3, OUTPUT);
  Ethernet.begin(mac);
  client.setServer(MQTT_SERVER, MQTT_PORT);
  client.setCallback(callback);
}

void loop1() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

// MQTT callback function
void callback(char* topic, byte* payload, unsigned int length) {
  // Convert the payload to a string
  String message = "";
  for (int i = 0; i < length; i++) {
    message += (char)payload[i];
  }

  {
    // Check the payload for each relay
    if (message.equals(FORWARD)) {
      
    digitalWrite(RELAY_R1, HIGH);
    delay(MOMENTARY_DURATION);
    digitalWrite(RELAY_R1, LOW);

    } else if (message.equals(REVERSE)) {
      
    digitalWrite(RELAY_R2, HIGH);
    delay(MOMENTARY_DURATION);
    digitalWrite(RELAY_R2, LOW);

    } else if (message.equals(PIVOTON)) {
      
    digitalWrite(RELAY_R3, HIGH);

    } else if (message.equals(PIVOTOFF)) {
      
    digitalWrite(RELAY_R3, LOW);
    }
  }
}

void reconnect() {
  while (!client.connected()) {
    if (client.connect("REmTech", MQTT_USERNAME, MQTT_PASSWORD)) {
      client.subscribe(TOPIC_SUB);
    } else {
      delay(1000);
    }
  }
}

// MQTT Broker settings
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883; // Default MQTT port, change if yours is different
const char* mqtt_topicsub = "randytestpercentage";
const char* mqtt_topicpub = "randytestpub";

unsigned long previousMillis = 0; // Stores last time relay was updated
const long interval = 60000; // Interval at which to cycle relay (60 seconds)
float percentageTimeOn = 0.0; // Percentage of time relay is on (0% by default)



void setup2() {
  pinMode(CONTROLLINO_R0, OUTPUT);

  Ethernet.begin(mac);
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(mqttCallback);

  connectToMqtt();
}

void loop2() {
  if (!client.connected()) {
    connectToMqtt();
  }
  client.loop(); 
  
 
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= (interval * percentageTimeOn)) {
    digitalWrite(CONTROLLINO_R0, LOW); // Turn relay off
  }
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    digitalWrite(CONTROLLINO_R0, HIGH); // Turn relay on
    

// Multiply percentageTimeOn by 100 and publish as number
    float percent = percentageTimeOn * 100;
    char percentageTimeOnString[8];
    dtostrf(percent, 2, 1, percentageTimeOnString); // Convert float to string with 1 decimal
    client.publish(mqtt_topicpub, percentageTimeOnString);

   
  } 
}

void mqttCallback(char* topic, byte* payload, unsigned int length) {
  // Convert payload to string
  char msg[5];
  if (length < 4) { // Assuming the percentage won't be more than 3 digits
    strncpy(msg, (char*)payload, length);
    msg[length] = '\0';
    percentageTimeOn = constrain(atof(msg) / 100.0, 0.0, 1.0); // Convert to fraction and constrain between 0 and 1
  }
}

void connectToMqtt() {
  while (!client.connected()) {
    if (client.connect("ControllinoClient")) {
      client.subscribe(mqtt_topicsub);
    } else {
      delay(5000); // Wait 5 seconds before retrying
    }
  }
}


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