{"id":24732699,"url":"https://github.com/gonzalo123/mqtt_example","last_synced_at":"2025-10-10T01:32:47.680Z","repository":{"id":66582126,"uuid":"88423160","full_name":"gonzalo123/mqtt_example","owner":"gonzalo123","description":"Playing with Raspberry Pi, Arduino, NodeMcu and MQTT","archived":false,"fork":false,"pushed_at":"2017-04-16T15:37:35.000Z","size":155,"stargazers_count":10,"open_issues_count":0,"forks_count":4,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-06-05T07:02:30.095Z","etag":null,"topics":["arduino","iot","mqtt","nodemcu","raspberry-pi"],"latest_commit_sha":null,"homepage":null,"language":"Arduino","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gonzalo123.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-04-16T15:36:42.000Z","updated_at":"2024-02-18T17:21:14.000Z","dependencies_parsed_at":null,"dependency_job_id":"5dd1df06-9c42-41c8-8e78-a10c760a23a5","html_url":"https://github.com/gonzalo123/mqtt_example","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/gonzalo123/mqtt_example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gonzalo123%2Fmqtt_example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gonzalo123%2Fmqtt_example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gonzalo123%2Fmqtt_example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gonzalo123%2Fmqtt_example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gonzalo123","download_url":"https://codeload.github.com/gonzalo123/mqtt_example/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gonzalo123%2Fmqtt_example/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279002406,"owners_count":26083374,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-09T02:00:07.460Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["arduino","iot","mqtt","nodemcu","raspberry-pi"],"created_at":"2025-01-27T17:53:46.308Z","updated_at":"2025-10-10T01:32:47.674Z","avatar_url":"https://github.com/gonzalo123.png","language":"Arduino","funding_links":[],"categories":[],"sub_categories":[],"readme":"Playing with Raspberry Pi, Arduino, NodeMcu and MQTT\n======\n\nThis days I'm playing with IoT. Today I want to use MQTT protocol to comunicate between different devices. First I've start a mqtt broker in my Laptop. For testing I'll use https://mosquitto.org/ server. In production we can use RabbitMQ or even a 3party server such a iot.eclipse.org or even Amazon's IoT.\n\nThe idea is emit one value with one device and listen this value whit the rest of devices and perform one action depending on the value. For example I will use one potentiometer connected to on NodeMcu micro controller. \n\n![Circuit](img/nodemcu.png \"NodeMcu\")\n\nThis controller will connect to the mqtt broker and will emit the value of the potentiometer (reading the analog input) into one topic (called \"potentiometer\"). We can code our NodeMcu with Lua but I'm more confortable with C++ and Arduino IDE. First I need to connect to my Wifi and then connect to broker and start emiting potentiometer's values\n\n```c\n#include \u003cPubSubClient.h\u003e\n#include \u003cESP8266WiFi.h\u003e\n\n// Wifi configuration\nconst char* ssid = \"MY_WIFI_SSID\";\nconst char* password = \"my_wifi_password\";\n\n// mqtt configuration\nconst char* server = \"192.168.1.104\";\nconst char* topic = \"potentiometer\";\nconst char* clientName = \"com.gonzalo123.nodemcu\";\n\nint value;\nint percent;\nString payload;\n\nWiFiClient wifiClient;\nPubSubClient client(wifiClient);\n\nvoid wifiConnect() {\n  Serial.println();\n  Serial.print(\"Connecting to \");\n  Serial.println(ssid);\n\n  WiFi.begin(ssid, password);\n\n  while (WiFi.status() != WL_CONNECTED) {\n    delay(500);\n    Serial.print(\".\");\n  }\n  Serial.println(\"\");\n  Serial.print(\"WiFi connected.\");\n  Serial.print(\"IP address: \");\n  Serial.println(WiFi.localIP());\n\n  if (client.connect(clientName)) {\n    Serial.print(\"Connected to MQTT broker at \");\n    Serial.print(server);\n    Serial.print(\" as \");\n    Serial.println(clientName);\n    Serial.print(\"Topic is: \");\n    Serial.println(topic);\n  }\n  else {\n    Serial.println(\"MQTT connect failed\");\n    Serial.println(\"Will reset and try again...\");\n    abort();\n  }\n}\n\nvoid mqttReConnect() {\n  while (!client.connected()) {\n    Serial.print(\"Attempting MQTT connection...\");\n    // Attempt to connect\n    if (client.connect(clientName)) {\n      Serial.println(\"connected\");\n      client.subscribe(topic);\n    } else {\n      Serial.print(\"failed, rc=\");\n      Serial.print(client.state());\n      Serial.println(\" try again in 5 seconds\");\n      delay(5000);\n    }\n  }\n}\n\nvoid setup() {\n  Serial.begin(9600);\n  client.setServer(server, 1883);\n  wifiConnect();\n  delay(10);\n}\n\nvoid loop() {\n  value = analogRead(A0);\n  percent = (int) ((value * 100) / 1010);\n  payload = (String) percent;\n  if (client.connected()) {\n    if (client.publish(topic, (char*) payload.c_str())) {\n      Serial.print(\"Publish ok (\");\n      Serial.print(payload);\n      Serial.println(\")\");\n    } else {\n      Serial.println(\"Publish failed\");\n    }\n  } else {\n    mqttReConnect();\n  }\n\n  delay(200);\n}\n```\n\nNow we will use another Arduino (with a ethernet shield).\n\n![Circuit](img/arduino.png \"Arduino\")\n\nWe'll move one servomotor depending to NodeMcu's potentiomenter value. This Arduino only needs to listen to MQTT's topic and move the servo.\n\n```c\n#include \u003cSPI.h\u003e\n#include \u003cServo.h\u003e\n#include \u003cEthernet.h\u003e\n#include \u003cPubSubClient.h\u003e\n\n#define SERVO_CONTROL 9\nbyte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };\n\nServo servo;\nEthernetClient ethClient;\n\n// mqtt configuration\nconst char* server = \"192.168.1.104\";\nconst char* topic = \"potentiometer\";\nconst char* clientName = \"com.gonzalo123.arduino\";\n\nPubSubClient client(ethClient);\n\nvoid callback(char* topic, byte* payload, unsigned int length) {\n  Serial.print(\"Message arrived [\");\n  Serial.print(topic);\n  Serial.print(\"] angle:\");\n\n  String data;\n  for (int i = 0; i \u003c length; i++) {\n    data += (char)payload[i];\n  }\n\n  double angle = ((data.toInt() * 180) / 100);\n  constrain(angle, 0, 180);\n  servo.write((int) angle);\n  Serial.println((int) angle);\n}\n\nvoid mqttReConnect() {\n  while (!client.connected()) {\n    Serial.print(\"Attempting MQTT connection...\");\n    // Attempt to connect\n    if (client.connect(clientName)) {\n      Serial.println(\"connected\");\n      client.subscribe(topic);\n    } else {\n      Serial.print(\"failed, rc=\");\n      Serial.print(client.state());\n      Serial.println(\" try again in 5 seconds\");\n      delay(5000);\n    }\n  }\n}\n\nvoid setup()\n{\n  Serial.begin(9600);\n  client.setServer(server, 1883);\n  client.setCallback(callback);\n  servo.attach(SERVO_CONTROL);\n  if (Ethernet.begin(mac) == 0) {\n    Serial.println(\"Failed to configure Ethernet using DHCP\");\n  }\n\n  delay(1500); // Allow the hardware to sort itself out\n}\n\nvoid loop()\n{\n  if (!client.connected()) {\n    mqttReConnect();\n  }\n  client.loop();\n}\n```\n\nFinally we'll use one Raspberry Pi with a Sense Hat and we'll display within its led matrix different colors and dots depending on the NodeMcu's value. In the same way than the Arduino script here we only need to listen to the broker's topic and perform the actions with the sense hat.\n\n```python\nimport paho.mqtt.client as mqtt\nfrom sense_hat import SenseHat\n\nsense = SenseHat()\nsense.clear()\nmqttServer = \"192.168.1.104\"\n\nred = [255, 0, 0]\ngreen = [0, 255, 0]\nyellow = [255, 255, 0]\nblack = [0, 0, 0]\n\ndef on_connect(client, userdata, rc):\n    print(\"Connected!\")\n    client.subscribe(\"potentiometer\")\n\ndef on_message(client, userdata, msg):\n    value = (64 * int(msg.payload)) / 100\n    O = black\n    if value \u003c 21:\n        X = red\n    elif value \u003c 42:\n        X = yellow\n    else:\n        X = green\n\n    sense.set_pixels(([X] * value) + ([O] * (64 - value)))\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.connect(mqttServer, 1883, 60)\nclient.loop_forever()\n```\n\n\n# Hardware:\n* 1 Arduino Uno\n* 1 NodeMCU (V3)\n* 1 potentiometer\n* 1 Servo (SG90)\n* 1 Raspberry Pi 3 (with a Sense Hat)\n\n# Demo\n[![Playing with Raspberry Pi, Arduino, NodeMcu and MQTT](http://img.youtube.com/vi/28ylDY4LzB0/0.jpg)](https://www.youtube.com/watch?v=28ylDY4LzB0)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgonzalo123%2Fmqtt_example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgonzalo123%2Fmqtt_example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgonzalo123%2Fmqtt_example/lists"}