#include #include const char* ssid = "ssid"; //Add SSID const char* pass = "ssid password"; // Add Wi-Fi password const char* brokerUser = ("user"); // Add broker username const char* brokerPass = ("pass"); // Add broker password const char* broker = ("broker.emqx.io"); const char* outTopic = ("test1"); //Add Server name const char* inTopic = ("test1"); //Add same name as in outTopic //String joy_d; //String to store data from server char messages[100]; String MegaData; #define RXD2 16 //ESP32 UART2 pins #define TXD2 17 WiFiClient espClient; PubSubClient client(espClient); void setupwifi() { delay(100); Serial.println("\nConnecting to"); Serial.println(ssid); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(100); Serial.print("-"); } Serial.print("\nConnected to"); Serial.println(ssid); } void reconnect() { while (!client.connected()) { Serial.print("\nConnecting to"); Serial.println(broker); if (client.connect("asdf123", brokerUser, brokerPass)) { Serial.println("\nConnected to"); Serial.println(broker); client.subscribe(inTopic); } else { Serial.println("\nTrying connect again"); delay(5000); } } } void callback(char* topic, byte* payload, unsigned int length) { // This portion reads data from the server String messageout = ""; for (int i = 0; i < length; i++) { ((char) payload[i]); messageout += (char) payload[i]; if (messageout.indexOf("Ship_destroy") >= 0) { Serial1.println("Shipping station destroyed"); } if (messageout.indexOf("Right") >= 0) { //If anywhere in the server data there are consecutive characters xval=255, string joy_d="Right" Serial1.println("right"); } if (messageout.indexOf("Left") >= 0) { //If anywhere in the server data there are consecutive characters xval=0, string joy_d="Left" Serial1.println("left"); } if (messageout.indexOf("Up") >= 0) { Serial1.println("up"); } if (messageout.indexOf("Down") >= 0) { Serial1.println("down"); } if (messageout.indexOf("Stop") >= 0) { Serial1.println("stop"); } } } void setup() { Serial.begin(115200); Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2); // ESP32 UART 2 pins Serial1.begin(9600, SERIAL_8N1, RXD2, TXD2); //Mega UART 1 pins setupwifi(); client.setServer(broker, 1883); client.setCallback(callback); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); if (Serial2.available()) { // This portion of the code reads the Arduino Mega serial monitor output through the ESP32 UART2 pins. It then sends the data to the MQTT server. String MegaData = Serial2.readString(); // Changes the string to a char and publishes to the server. Serial.println(MegaData); MegaData.toCharArray(messages, 10); client.publish(outTopic, messages); delay(500); } }