Help with a pan+tilt flow and arduino ino to add a relay

I have gone brain dead...I have a nod-red flow and an arduino iso that I DID NOT WRITE but am trying to add a simple relay to them to switch cameras output to my system. The bad thing is I did it many weeks ago and it all worked...However my SD card crashed on the PI3b+ and I had not backed it up.(yes,my bad) I did try to recover but after a week I gave up and rebuilt all.So I now have a working PI and all new Flow and arduino code But I can't get the relay to work now...I have loaded the Flow and code below (I Hope) for someone to take a look and give me some pointers. I noted in the code lines I added. all work but the relay.Thank you
Ron.

ARDUINO CODE

 /*
 * Node-RED + MQTT + ESP8266 + PTZ servo kit (Pan-Tilt)
 * How to move pan-tilt system with Node-RED - MQTT and ESP8266
 * - Use Node-RED UI Dashboard to move Pan and Tilt servos
 * - Node-RED sequencer : scan Pan and tilt 
 * - Node-RED reset position to 90°/90°
 * 
 * Comment déplacer le système pan-tilt avec Node-RED - MQTT et ESP8266
 * - Utilisez le tableau de bord Node-RED UI pour dĂ©placer les servos Pan et Tilt
 * - SĂ©quenceur Node-RED: balayage panoramique (Pan) et inclinaison (Tilt)
 * - Reset des positions depuis Node-RED (90°/90°)
 * - Tutoriel complet
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Licence : MIT
 * Copyright (C) 2017 : www.projetsdiy.fr and www.diyprojects.io
 */
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h> 
Servo pan; 
Servo tilt;

// Paramètre WiFi, MQTT - WiFi, MQTT parameters
const char* ssid = "my ssid";                // WiFi SSID
const char* password = "my password";        // WiFi Password
const char* mqtt_server = "192.168.0.5";  // IP Broker MQTT
const char* topic_pan = "servo/pan";          // Topic MQTT pour servo Pan - Topic MQTT for Pan servor
const char* topic_tilt = "servo/tilt";        // Topic MQTT pour servo Tilt - Topic MQTT for Tilt servor
//ron added two lines
const char* topic_cam1 =" cam1";
const char* topic_cam2 = "cam2";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup() {

  Serial.begin(115200);
  //ron added 1 line
  pinMode(D1,OUTPUT);
  pan.attach(D2);
  tilt.attach(D3);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  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 callback(char* topic, byte* payload, unsigned int length) {
 String string;
 // Affiche le topic entrant - display incoming Topic
 Serial.print("Message arrived [");
 Serial.print(topic);
 Serial.print("] ");
 // décode le message - decode payload message
 for (int i = 0; i < length; i++) {
 string+=((char)payload[i]); 
 }
 // Affiche le message entrant - display incoming message
 Serial.print(string);
 Serial.print(" toInt ");
 // Conversion de la position en entier - convert position as an Integer
 int pos = string.toInt(); 
 Serial.println(pos);

 // Détermine quel servo doit être bougé - Determines which servo should be moved
 if ( strcmp(topic, topic_pan) == 0 ) {
 Serial.print("Move Pan to ");
 Serial.println(pos);
 pan.write(pos); 
 }
 if ( strcmp(topic, topic_tilt) == 0 ) {
 Serial.print("Move Tilt to ");
 Serial.println(pos);
 tilt.write(pos); 
 }
 //ron added 4 lines
 if ((char)payload[0] == '1'){
  digitalWrite(D1, HIGH);
 }
 if ((char)payload[0] == '2'){
 digitalWrite(D1, LOW);
 
 delay(15); 
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      client.subscribe(topic_pan); 
      client.subscribe(topic_tilt);
      //ron added 2 lines
      client.subscribe(topic_cam1);
      client.subscribe(topic_cam2); 
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void loop() {   
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  delay(100);
}

NODE-RED FLOW

[
    {
        "id": "4fc50ee3e29bd9b2",
        "type": "tab",
        "label": "P+T",
        "disabled": false,
        "info": ""
    },
    {
        "id": "34545562.076d7a",
        "type": "mqtt out",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "topic": "servo/pan",
        "qos": "1",
        "retain": "false",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "ceed5755.206c58",
        "x": 640,
        "y": 180,
        "wires": []
    },
    {
        "id": "f9a85217.59893",
        "type": "ui_slider",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "label": "Pan",
        "group": "9c59c1e2.8235f",
        "order": 4,
        "width": 6,
        "height": 1,
        "passthru": true,
        "topic": "",
        "min": 0,
        "max": "180",
        "step": 1,
        "x": 470,
        "y": 200,
        "wires": [
            [
                "34545562.076d7a",
                "d604bc1e.67691"
            ]
        ]
    },
    {
        "id": "d604bc1e.67691",
        "type": "ui_gauge",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "group": "9c59c1e2.8235f",
        "order": 6,
        "width": 6,
        "height": 3,
        "gtype": "donut",
        "title": "Pan servo position ",
        "label": "position ",
        "format": "{{value}}",
        "min": 0,
        "max": "180",
        "colors": [
            "#00b500",
            "#e6e600",
            "#ca3838"
        ],
        "x": 640,
        "y": 240,
        "wires": []
    },
    {
        "id": "3a393dcd.afa272",
        "type": "comment",
        "z": "4fc50ee3e29bd9b2",
        "name": "ESP8266 MQTT Pan Tilt PTZ Control Servo",
        "info": "",
        "x": 390,
        "y": 900,
        "wires": []
    },
    {
        "id": "4316c9.3c84a938",
        "type": "mqtt out",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "topic": "servo/tilt",
        "qos": "1",
        "retain": "false",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "ceed5755.206c58",
        "x": 640,
        "y": 400,
        "wires": []
    },
    {
        "id": "9087f6a0.b7e938",
        "type": "ui_slider",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "label": "Tilt",
        "group": "9c59c1e2.8235f",
        "order": 5,
        "width": 6,
        "height": 1,
        "passthru": true,
        "topic": "",
        "min": 0,
        "max": "180",
        "step": 1,
        "x": 370,
        "y": 440,
        "wires": [
            [
                "4316c9.3c84a938",
                "584bfb6e.86a1d4"
            ]
        ]
    },
    {
        "id": "584bfb6e.86a1d4",
        "type": "ui_gauge",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "group": "9c59c1e2.8235f",
        "order": 7,
        "width": 6,
        "height": 3,
        "gtype": "donut",
        "title": "Tilt servo position ",
        "label": "position ",
        "format": "{{value}}",
        "min": 0,
        "max": "180",
        "colors": [
            "#00b500",
            "#e6e600",
            "#ca3838"
        ],
        "x": 640,
        "y": 460,
        "wires": []
    },
    {
        "id": "6a8f2c2b.64bdb4",
        "type": "ui_button",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "group": "9c59c1e2.8235f",
        "order": 1,
        "width": 0,
        "height": 0,
        "passthru": false,
        "label": "Reset",
        "tooltip": "",
        "color": "",
        "bgcolor": "",
        "icon": "fa-undo",
        "payload": "",
        "payloadType": "str",
        "topic": "",
        "topicType": "str",
        "x": 90,
        "y": 500,
        "wires": [
            [
                "743cd12b.d31b5"
            ]
        ]
    },
    {
        "id": "798e642.411779c",
        "type": "mqtt out",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "topic": "servo/tilt",
        "qos": "1",
        "retain": "false",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "ceed5755.206c58",
        "x": 480,
        "y": 520,
        "wires": []
    },
    {
        "id": "743cd12b.d31b5",
        "type": "function",
        "z": "4fc50ee3e29bd9b2",
        "name": "Pan (90°) - Tilt(90°)",
        "func": "msg.payload = 90;\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 270,
        "y": 540,
        "wires": [
            [
                "d604bc1e.67691",
                "4336088.add08f8",
                "798e642.411779c",
                "d2553ca9.80fdd",
                "584bfb6e.86a1d4"
            ]
        ]
    },
    {
        "id": "d2553ca9.80fdd",
        "type": "mqtt out",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "topic": "servo/pan",
        "qos": "1",
        "retain": "false",
        "broker": "ceed5755.206c58",
        "x": 480,
        "y": 580,
        "wires": []
    },
    {
        "id": "3ba0147.632dcec",
        "type": "link in",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "links": [
            "4336088.add08f8",
            "56f0b2a7.b1c81c"
        ],
        "x": 375,
        "y": 200,
        "wires": [
            [
                "f9a85217.59893"
            ]
        ]
    },
    {
        "id": "4336088.add08f8",
        "type": "link out",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "links": [
            "3ba0147.632dcec",
            "8117306f.30c94"
        ],
        "x": 435,
        "y": 640,
        "wires": []
    },
    {
        "id": "8117306f.30c94",
        "type": "link in",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "links": [
            "4336088.add08f8",
            "56f0b2a7.b1c81c"
        ],
        "x": 275,
        "y": 440,
        "wires": [
            [
                "9087f6a0.b7e938"
            ]
        ]
    },
    {
        "id": "89f37cd6.f1a11",
        "type": "comment",
        "z": "4fc50ee3e29bd9b2",
        "name": "www.projetsdiy.fr | www.diyprojects.io",
        "info": "# Version française \nwww.projetsdiy.fr\n\n# English version\nwww.diyprojects.io",
        "x": 410,
        "y": 940,
        "wires": []
    },
    {
        "id": "d4ee4d5e.0ffcd",
        "type": "ui_button",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "group": "9c59c1e2.8235f",
        "order": 2,
        "width": 6,
        "height": 1,
        "label": "Scan Pan",
        "color": "",
        "icon": "",
        "payload": "-10",
        "payloadType": "num",
        "topic": "",
        "x": 140,
        "y": 120,
        "wires": [
            [
                "68869228.30d7fc"
            ]
        ]
    },
    {
        "id": "68869228.30d7fc",
        "type": "function",
        "z": "4fc50ee3e29bd9b2",
        "name": "+10°",
        "func": "var pos = msg.payload;\npos += 10;\nmsg.payload = pos;\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "x": 330,
        "y": 120,
        "wires": [
            [
                "18dca8a0.64c977",
                "f9a85217.59893"
            ]
        ]
    },
    {
        "id": "18dca8a0.64c977",
        "type": "delay",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "pauseType": "delay",
        "timeout": "500",
        "timeoutUnits": "milliseconds",
        "rate": "1",
        "nbRateUnits": "1",
        "rateUnits": "second",
        "randomFirst": "1",
        "randomLast": "5",
        "randomUnits": "seconds",
        "drop": false,
        "x": 500,
        "y": 120,
        "wires": [
            [
                "e5657f97.89ffd"
            ]
        ]
    },
    {
        "id": "fe1eebc1.8d83c8",
        "type": "ui_button",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "group": "9c59c1e2.8235f",
        "order": 3,
        "width": 6,
        "height": 1,
        "passthru": false,
        "label": "Scan Tilt",
        "tooltip": "",
        "color": "",
        "bgcolor": "",
        "icon": "",
        "payload": "-10",
        "payloadType": "num",
        "topic": "",
        "topicType": "str",
        "x": 80,
        "y": 380,
        "wires": [
            [
                "593953a.80dfbac"
            ]
        ]
    },
    {
        "id": "593953a.80dfbac",
        "type": "function",
        "z": "4fc50ee3e29bd9b2",
        "name": "+10°",
        "func": "var pos = msg.payload;\npos += 10;\nmsg.payload = pos;\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "x": 230,
        "y": 360,
        "wires": [
            [
                "4cfcf34c.3c7d3c",
                "9087f6a0.b7e938"
            ]
        ]
    },
    {
        "id": "4cfcf34c.3c7d3c",
        "type": "delay",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "pauseType": "delay",
        "timeout": "500",
        "timeoutUnits": "milliseconds",
        "rate": "1",
        "nbRateUnits": "1",
        "rateUnits": "second",
        "randomFirst": "1",
        "randomLast": "5",
        "randomUnits": "seconds",
        "drop": false,
        "x": 380,
        "y": 360,
        "wires": [
            [
                "549400d6.d1279"
            ]
        ]
    },
    {
        "id": "e5657f97.89ffd",
        "type": "repeat",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "repetitions": "18",
        "elseOutput": false,
        "outputs": 1,
        "x": 420,
        "y": 40,
        "wires": [
            [
                "68869228.30d7fc"
            ]
        ]
    },
    {
        "id": "549400d6.d1279",
        "type": "repeat",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "repetitions": "18",
        "elseOutput": false,
        "outputs": 1,
        "x": 320,
        "y": 280,
        "wires": [
            [
                "593953a.80dfbac"
            ]
        ]
    },
    {
        "id": "80a405ccc8bb97c4",
        "type": "inject",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "cam2",
        "payload": "2",
        "payloadType": "str",
        "x": 110,
        "y": 760,
        "wires": [
            [
                "54cc49f066be8176",
                "df0ebc28565af023"
            ]
        ]
    },
    {
        "id": "54cc49f066be8176",
        "type": "debug",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "true",
        "targetType": "full",
        "statusVal": "",
        "statusType": "auto",
        "x": 690,
        "y": 700,
        "wires": []
    },
    {
        "id": "4b58207916825454",
        "type": "inject",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "cam1",
        "payload": "1",
        "payloadType": "str",
        "x": 110,
        "y": 640,
        "wires": [
            [
                "54cc49f066be8176",
                "79246361e75a4fa4"
            ]
        ]
    },
    {
        "id": "1cdc5fc854a97f2b",
        "type": "debug",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "true",
        "targetType": "full",
        "statusVal": "",
        "statusType": "auto",
        "x": 710,
        "y": 540,
        "wires": []
    },
    {
        "id": "79246361e75a4fa4",
        "type": "mqtt out",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "topic": "cam1",
        "qos": "1",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "ceed5755.206c58",
        "x": 680,
        "y": 760,
        "wires": []
    },
    {
        "id": "df0ebc28565af023",
        "type": "mqtt out",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "topic": "cam2",
        "qos": "",
        "retain": "",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "ceed5755.206c58",
        "x": 680,
        "y": 820,
        "wires": []
    },
    {
        "id": "708529be06d716bb",
        "type": "ui_button",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "group": "9c59c1e2.8235f",
        "order": 7,
        "width": 0,
        "height": 0,
        "passthru": false,
        "label": "cam1",
        "tooltip": "",
        "color": "",
        "bgcolor": "",
        "icon": "",
        "payload": "1",
        "payloadType": "str",
        "topic": "cam1",
        "topicType": "msg",
        "x": 100,
        "y": 700,
        "wires": [
            [
                "54cc49f066be8176",
                "79246361e75a4fa4"
            ]
        ]
    },
    {
        "id": "8ee944654fdce99e",
        "type": "ui_button",
        "z": "4fc50ee3e29bd9b2",
        "name": "",
        "group": "9c59c1e2.8235f",
        "order": 8,
        "width": 0,
        "height": 0,
        "passthru": false,
        "label": "cam2",
        "tooltip": "",
        "color": "",
        "bgcolor": "",
        "icon": "",
        "payload": "2",
        "payloadType": "str",
        "topic": "cam2",
        "topicType": "msg",
        "x": 100,
        "y": 820,
        "wires": [
            [
                "54cc49f066be8176",
                "df0ebc28565af023"
            ]
        ]
    },
    {
        "id": "ceed5755.206c58",
        "type": "mqtt-broker",
        "broker": "localhost",
        "port": "1883",
        "clientid": "",
        "usetls": false,
        "compatmode": true,
        "keepalive": "60",
        "cleansession": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthPayload": "",
        "willTopic": "",
        "willQos": "0",
        "willPayload": ""
    },
    {
        "id": "9c59c1e2.8235f",
        "type": "ui_group",
        "name": "PTZ Servo Control",
        "tab": "84e11c13.a96e9",
        "order": 2,
        "disp": true,
        "width": "12",
        "collapse": false
    },
    {
        "id": "84e11c13.a96e9",
        "type": "ui_tab",
        "name": "ESP8266",
        "icon": "dashboard",
        "order": 2
    }
]

Please go back and edit your post so as to properly format both codes. Thanks.

Use the </> icon in the editor and place the code in-between the triple backticks.

image

Hello Gunner
Ok I think I did that now. Thanks for the tip. Ron.

Delete this from the end your node-red code. The last character should be a ] this will make is easier for someone to copy-paste into their own NR for testing.

As for your issue... do you have any coding experience with either Arduino or Node-Red?

I don't think anyone will write your Arduino code for you... but you should be able to Google and read through some MQTT how-too web pages to understand a clearer way to publish and subscribe to topics so as to make them easier to interpret on the Arduino side.

I would suggest adding in some print statements so you can track what your code is seeing (in the incoming subscriptions) and doing

Is this the example you followed the first time?

Why not follow it again?

1 Like

I guess you didn't read all the first post yes I have a lot experience with both node-red and arduino. I did what I need to do a couple weeks ago but I can't seem to get it back as I had it before I had lost all my files on the crashed SD card. I had many examples I used over several years but alas they are all gone. a better question would have been do I have any experience with this forum, Then no I don't I have not needed to ask for help before. I did not expect for someone to write my code just point out what I am not doing right. But thank you for the tips on using the forum. Ron.

Sir I did follow the the code but it does not include a relay now does it .I said the pan and tilt all work just not the added relay.

How about adding a serial print in the IF statements doing the digitalWrite(D1,HIGH) and LOW so you can see if it is getting to that area in the arduino code?

because I see what I am sending in the node-red debug window when I click the cam1 or 2 button from a second pc from the node-red dashboard. you mean in the arduino serial mon.? I'll try it. Thanks.

Yes, put some debugging in the arduino code so you can follow/see what is happening there.

Yes I read it... all I saw is that you didn't write the code you want modified. If you have experience, then just modify it :stuck_out_tongue:

Yes I could do it, but I am not going to rewrite some 3rd party code for another 2nd party post, particularly here as it is little to do with NR and mostly about Arduino coding.

What I did do is suggest you add in some tracking code (print statements), as did @zenofmud, so you can better follow what that other code is doing... thus determine best how to modify it yourself.

I also recommend using the same format of topic/sub topic for your relay as is for your servos. Keeping consistent makes for easier coding.

I have something like this in my current Arduino/MQTT tests (NOT complete code, just snippets from my own specific use case)

// Once connected, publish an announcement...
      client.publish("test/led", "0");
      // ... and subscribe
      client.subscribe("test/led");
      client.subscribe("test/time"); // Arduino code not currently using this
      client.subscribe("test/CPU"); // Arduino code not currently using this
      client.subscribe("test/relay");
// Interprets and processes incoming aubscriptions
void callback(char* topic, byte* payload, unsigned int length) {

  if (strncmp(topic, "test/relay", strlen("test/relay")) == 0) {
    Serial.print("RELAY Command Detected!");
    uint8_t relayValue = payload[0] - '0';  // Get payload of relay sub after stripping closing character
    digitalWrite(14, relayValue);
  }

  if (strncmp(topic, "test/led", strlen("test/led")) == 0) {
    Serial.print("LED Command Detected!");
    uint8_t LEDValue = payload[0] - '0';  // Get payload of LED sub after stripping closing character
    digitalWrite(2, !LEDValue);
  }

  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

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