Networking and Communications


#MQTT #Wifi #esp8266


Trulli

For this week, I test the module esp8266(NodeMCU D1). This will be utilized for my final project to control modularized robot. My plan is to use the wifi module to communicate with the robot controlling interface through MQTT



Trulli

This is the interface simulating the motion, caculating an angle for each module, sending the angles in real time.


To use the module with MQTT, A library(ESP8266wifi-master.zip) is required.


The following is the way to set the library in Arduino IDE


Trulli


The following is the code I used

#include 
#include 

const char ssid[] = "MIT";
const char pass[] = "";

WiFiClient net;
MQTTClient client;

unsigned long lastMillis = 0;

void connect() {
  Serial.print("checking wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }

  Serial.print("\nconnecting...");
  while (!client.connect("arduino", "public", "public")) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");

  client.subscribe("chili");
  // client.unsubscribe("/hello");
}

void messageReceived(String &topic, String &payload) {
  Serial.println("incoming: " + topic + " - " + payload);

  // Note: Do not use the client in the callback to publish, subscribe or
  // unsubscribe as it may cause deadlocks when other things arrive while
  // sending and receiving acknowledgments. Instead, change a global variable,
  // or push to a queue and handle it in the loop after calling `client.loop()`.
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, pass);

  // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported
  // by Arduino. You need to set the IP address directly.
  client.begin("public.cloud.shiftr.io", net);
  client.onMessage(messageReceived);

  connect();
}

void loop() {
  client.loop();
  delay(10);  // <- fixes some issues with WiFi stability

  if (!client.connected()) {
    connect();
  }

  // publish a message roughly every second.
  if (millis() - lastMillis > 1000) {
    lastMillis = millis();
    client.publish("chili", "device is saying something....");
  }
}



GROUP ASSIGNMENT




Nov 16 2022