
Real-time temperature monitoring with LavinMQ
Written by: Lovisa Johansson
This guide will show you how to build a real-time temperature monitoring system. We will use a basic microcontroller and a sensor to create a project that sends live temperature data to a message broker. The data will then be displayed on a webpage in real time.
The project communicates via MQTT, a lightweight messaging protocol designed for this kind of Internet of Things (IoT) communication. The data displayed on a webpage is consumed via MQTT WebSockets to ensure real-time updates.
An overview of the Internet of Things (IoT)
The Internet of Things (IoT) is a network of physical objects—”things”—that are embedded with sensors, software, and other technologies to connect and exchange data with other devices and systems over the internet.
A typical IoT system consists of four fundamental components:
- Devices/Sensors: A sensor’s job is to bridge the gap between the physical world and the digital world. It takes a real-world input, like temperature, pressure, light, or motion, and translates it into an output that a machine or system can understand and process. This guide use a temperature and humidity sensor.
- Connectivity: This is the communication network that allows the data to travel from the sensors to the internet. It can use Wi-Fi, Bluetooth, cellular networks (4G/5G), Zigbee, or other protocols. This guide use Wi-Fi.
- Data Processing: This is the brain of the system. The data is sent here to be understood and analyzed (often in the cloud). Here, you can use machine learning algorithms to find patterns and generate insights.
- User Interface (UI): Finally, the processed data is presented to the user via an app, a web dashboard, or another interface. The user can then monitor the system and, in some cases, send commands back to the device (e.g., to turn off a light).
What you’ll build with this guide
It’s time to learn how to set up a microcontroller with a temperature sensor. You’ll learn to send temperature data to a message broker (LavinMQ) and then retrieve that data to display it on a webpage.
You might be wondering, “Why do I need to send the data to a message broker?” In many IoT systems, a broker serves as a central hub that manages all data traffic. This approach, known as the publish/subscribe model, allows devices to send and receive information without needing to know anything about one another.
Here’s how it works:
- Publisher: The device (an NodeMCU board/microcontroller) with a temperature sensor publish a message with temperature data to a specific topic in MQTT. E.g:
lavinmq/home/temperature
. - Broker: The message broker (LavinMQ) Receives the message and acts as a central post office. It knows which applications or devices are interested in data from that topic.
- Subscriber: An application (the web page) subscribes to the data from a topic and receives the message from the broker.
Get your free starting kit for this project
For this project, you can get a free LavinMQ IoT starting kit. Just send an email to marketing@cloudamqp.com to request one, or you can buy it yourself.
The starter kit includes:
- Microcontroller (In the starter kit: NodeMCU board)
- Sensor
- Jumper cables (In the starter kit: 2 female - to - female)
- Power cable
Step-by-step guide
Step 1: Create a LavinMQ instance
To begin, you need to set up a new CloudAMQP server. CloudAMQP provides a managed LavinMQ broker, which is fully compatible with our IoT project’s needs for message handling.
- Navigate to CloudAMQP. Sign up for an account, or if you already have one, log in.
- Once you are logged in, you will be con the control panel. Click the “Create New Instance” button.
- For a basic IoT project or a proof-of-concept, the free Loyal Lemming plan is perfect. Select this plan to proceed.
- Give your new instance a name that is descriptive of your project, for example, “iot-temperature-project.”
- Choose a data center region that is geographically close to your devices. This helps to minimize latency and improve performance.
- Review your selections and then click the “Create Instance” button. CloudAMQP will then provision your new LavinMQ server.
- Once the instance is active, you will be provided with the necessary connection details. This includes the hostname, user, and password that you will use in your microcontroller.
You now have a live message broker ready to handle the data from your IoT devices. The following steps involve using these connection details to set up your publisher (the microcontroller) and your subscriber (the webpage).
Step 2: Configure the microcontroller
- Connect the power outlet of the board to the computer.
- A Demo WiFi will appear. Connect to this wifi: “DEMO/WIFI”. (Please note that this wifi is only available for a few minutes. If you are not connected to the wifi within that time, just re-plug the power again.)
- Once connected, enter the web page:
HTTP://192.168.4.1
- Enter the credentials for the LavinMQ instance and press save. This will configure the message broker on the microcontroller. You can find your credentials in the CloudAMQP control panel for your created instance.
- In the network section, select your home network and enter the password. This will connect the microcontroller to your network. (The board only supports the 2.4GHz band, which could cause a problem if you share a hotspot from your phone. Most modern smartphones create a hotspot on the 5GHz band by default because it’s faster. A device that only supports 2.4GHz simply can’t “see” or connect to a 5GHz network.)
- The microcontroller will start sending data to the message broker.
- Verify that the data is sent by opening the management interface of the broker. Here, press the queue tab and select the queue for your session. Press on it and go down to bindings, you should see:
lavinmq/home/temperature
andlavinmq/home/humidity
.
Wi-Fi and MQTT credentials are now stored on the board.
If you plug it in again to the computer later on, you will need to wait about one minute for the ‘Demo_wifi’ network to disappear from the list of available networks; the device will then connect to Wi-Fi.
Step 3: Conumse a message via the terminal
Here’s a Python MQTT subscriber using the Paho MQTT library.
import paho.mqtt.client as mqtt
BROKER = "<host-name>"
PORT = 1883 # use 8883 + TLS block if your instance requires TLS
TOPICT = "lavinmq/home/temperature "
TOPICH = " lavinmq/home/humidity"
# IMPORTANT: vhost goes after @ in the username (RabbitMQ/LavinMQ)
USERNAME = "<vhost:username>" # change vhost if needed
PASSWORD = "<password>"
def on_connect(client, userdata, flags, reason_code, properties=None):
if reason_code == 0:
print("Connected to broker.")
client.subscribe([(TOPICT, 1), (TOPICH, 1)])
print(f"Subscribed to: {TOPICT}, {TOPICH}")
else:
print(f"Connect failed. reason_code={reason_code}")
def on_message(client, userdata, msg):
print(f"[{msg.topic}] {msg.payload.decode('utf-8', errors='replace')}")
def on_disconnect(client, userdata, disconnect_flags, reason_code, properties=None):
print(f"Disconnected. reason_code={reason_code}, flags={disconnect_flags}")
client = mqtt.Client(
callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
protocol=mqtt.MQTTv311
)
client.username_pw_set(USERNAME, PASSWORD)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.reconnect_delay_set(min_delay=1, max_delay=30)
client.connect(BROKER, PORT, keepalive=60)
client.loop_forever()
Replace the placeholders (<BROKER>, <USERNAME>, <PASSWORD>)
with the values from your LavinMQ instance’s Overview → MQTT details.
Step 4: Create the web page
It’s time to subscribe to the data from the message broker and show it on a web page. We have prepared a web page for you to download here.
- Clone the wep page project from GitHub.
-
Configure the broker URL in the code.
const MQTT_URL = "wss://HOSTNAME.lmq.cloudamqp.com/mqtt"; const TOPIC_TEMP = "lavinmq/home/temperature"; const TOPIC_HUM = "lavinmq/home/humidity"; const MQTT_OPTIONS = { username: "USERNAME:USERNAME", password: "*****", clientId: "webclient-" + Math.random().toString(16).slice(2), clean: true, keepalive: 60, reconnectPeriod: 2000, protocolVersion: 4, protocolId: "MQTT", };
- Run the web page.
Have fun!
We can’t wait to see what you build! If you want to dive deeper, get some hands-on help, or share your project with fellow developers, join our Slack community. It’s a place to ask questions, get advice from our team, and connect with other innovators using LavinMQ for their projects.