IoT MQTT DIY Hardware

Posted on
Fri Sep 18, 2020 8:29 pm
FlyingDiver offline
User avatar
Posts: 7189
Joined: Jun 07, 2014
Location: Southwest Florida, USA

Re: IoT MQTT DIY Hardware

mundmc wrote:
But i need to learn about this JasonObject& part:

Code: Select all
 JsonObject& root = jsonBuffer.parseObject(inData); 



I think that defines root as a pointer to a jsonObject created by the parseObject call.

joe (aka FlyingDiver)
my plugins: http://forums.indigodomo.com/viewforum.php?f=177

Posted on
Tue Sep 22, 2020 7:31 am
mundmc offline
User avatar
Posts: 1060
Joined: Sep 14, 2012

Re: IoT MQTT DIY Hardware

For perpetuity, this sketch allows the arduino with ethernet shield to connect to network, subscribe to mqtt, receive payload, then control a big a$$ stepper motor using an a4988 driver the payload is formatted in Indigo as (no single quotes) '{"top":200, "bottom":50, "left":-200, "right":100}'

Thanks FlyingDiver!
It's time for me to get weird with controlling motors from Indigo :)

Code: Select all
// This sketch allows the arduino with ethernet shield to connect to network, subscribe to mqtt,
// receive payload, then control a big a$$ stepper motor using an a4988 driver
// The payload is formatted in Indigo as (no single quotes) '{"top":200, "bottom":50, "left":-200, "right":100}'

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <AccelStepper.h>
#include <ArduinoJson.h>

// Define stepper motor connections and motor interface type. Motor interface type must be set to 1 when using a driver:
#define leftDirPin 2
#define leftStepPin 3
#define motorInterfaceType 1

///////////////////////////////////////////////////////////////

// Create a new instance of the AccelStepper class:
AccelStepper stepper = AccelStepper(motorInterfaceType, leftStepPin, leftDirPin);

// Ethernet and MQTT related objects
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);

// Set your MAC address and IP address here
byte mac[] = { 0xDE, 0xAA, 0xBB, 0xCC, 0xDD, 0x00 };
IPAddress ip(192, 168, 1, 159);
 
//Enter your mqtt server configurations
const char* mqttServer = "192.168.1.REDACTED";    //Enter Your mqttServer address
const int mqttPort = 1883;                  //Port number
const char* mqttUser = "REDACTED";        //User
const char* mqttPassword = "REDACTED";  //Password

void setup()
{
  // Useful for debugging purposes
  Serial.begin(9600);
 
  // Set the maximum speed in steps per second:
  stepper.setMaxSpeed(1000);
 
  // initialize the Ethernet shield using DHCP:
  Serial.println("Obtaining an IP address using DHCP");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to obtain an IP address");

    // check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware)
      Serial.println("Ethernet shield was not found");

    // check for Ethernet cable
    if (Ethernet.linkStatus() == LinkOFF)
      Serial.println("Ethernet cable is not connected.");
  }
 
  // BELOW IS ERROR CHECKING FOR IP CONNECTIVITY
  Serial.print("- Arduino's IP address   : ");
  Serial.println(Ethernet.localIP());
  Serial.print("- Gateway's IP address   : ");
  Serial.println(Ethernet.gatewayIP());
  Serial.print("- Network's subnet mask  : ");
  Serial.println(Ethernet.subnetMask());
  Serial.print("- DNS server's IP address: ");
  Serial.println(Ethernet.dnsServerIP());
 
  // Ethernet takes some time to boot!
  delay(3000);                         
 
  // Set the MQTT server to the server stated above ^
  mqttClient.setServer(mqttServer, mqttPort);
  mqttClient.setCallback(MQTTcallback);
  while (!mqttClient.connected()) {
    Serial.println("Connecting to MQTT...");
    if (mqttClient.connect("NewEthernetShield", mqttUser, mqttPassword )) {
      Serial.println("Connected"); 
    } else {
      Serial.print("failed with state ");
      Serial.println(mqttClient.state());  //If you get state 5: mismatch in configuration
      delay(2000);
    }
  }
 
  mqttClient.publish("ethernetshield/test", "Hello from EthernetShield v2");
  mqttClient.subscribe("ethernetshield/test");
}

//////////////////////////////////////THIS IS THE THING////////////////////////////////////////
void MQTTcallback(char* topic, byte* payload, unsigned int length) {
  int speed = 400;
  int targetPosition;
  StaticJsonBuffer<54> jsonBuffer;
  //char inData[80]; // I THINK THIS IS THE CAHR ARRAY INTO WHICH THE BYTE ARRAY GOES< STARTING WITH BYTe NUMBER 26 WHY???
 
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Payload: ");
  for(int i =0; i<length; i++)Serial.print((char)payload[i]);
 
  Serial.println(); 

  //THIS NEXT PART USES A {POINTER TO THE ROOT OF THE PARSED JSON, I THINK
   JsonObject& root = jsonBuffer.parseObject((char[])payload);

  //CHECK THE CONTENTS
  Serial.println("Instructions:");
  Serial.print("Top:");
  Serial.println((int)root["top"]);
  Serial.print("Bottom:");
  Serial.println((int)root["bottom"]);
  Serial.print("Left:");
  Serial.println((int)root["left"]);
  Serial.print("Right:");
  Serial.println((int)root["right"]);

  //TELL IT WHAT ROLLER's INFO TO TURN
  targetPosition = (int)root["left"];

  // SET CURRENT POSITION
  stepper.setCurrentPosition(0);
  Serial.println("Stepper current position set to 0");
  Serial.print("Stepper target position is:");
  Serial.println((int)root["left"]);

  //MAKE THE SPEED NEGATIVE IF TARGET IS NEGATIVE
  if(targetPosition<0) speed*=-1;

  int lastPosition = 0;
  while(stepper.currentPosition() != targetPosition)
  {
    stepper.setSpeed(speed);
    stepper.runSpeed();
    /*int currentPosition = stepper.currentPosition();
    if(currentPosition%20==0 && currentPosition>lastPosition){
      Serial.print(currentPosition);
      Serial.print(" ");
      lastPosition = currentPosition;
    }*/
  }
  Serial.print("\n");
  Serial.println("Done");
  Serial.println("-----------------------"); 
}

void loop()
{
  mqttClient.loop();
}

Who is online

Users browsing this forum: No registered users and 2 guests