In this post, I've showed, how to setup Mosquitto on an Windows 8 machine. Now let me describe, howto connect an Arduino via Ethernet to the running Mosquitto MQTT broker.
My hardware configuration is really simple. An Arduino-Mega with an Arduino-Ethernet-Shield.
- Download this sketch
- Adopt your IP-adress to your local mosquitto server.
#define MQTT_SERVER_NAME "192.168.2.100"
- Adopt your MAC-adress to your local lan.
// MAC Address of Arduino Ethernet Sheild (on sticker on shield)
byte MAC_ADDRESS[] = { 0x90, 0xA2, 0x01, 0x02, 0x03, 0x04 };
- Upload your sketch to your arduino and start the serial monitor (I used the Arduino IDE 1.5.5 - but it should work also with older and newer IDEs).
- Now you should see in the Arduino IDEs serial window messages like this
Local IP=192.168.2.120
Reconnect to mqtt
Connect client [Arduino_MEGA] OK
Publishing alive message to [dl2sba.de/Arduino_MEGA/light] OK
Subscribe to [dl2sba.de/Arduino_MEGA/control] OK
- Now look in the first command window (the server). You should see there the messages received and forwarded
1400927225: Received PUBLISH from Arduino_MEGA (d0, q0, r0, m0, 'dl2sba.de/Arduino_MEGA/light', ... (22 bytes))
1400927225: Sending PUBLISH to mosqsub/5916-DL2SBA-5 (d0, q0, r0, m0, 'dl2sba.de/Arduino_MEGA/light', ... (22 bytes))
- The first line shows the message published from your arduino to the MQTT broker. The second line shows this message forwarded to your mosquitto_sub client running in the second command window.
- Switch to your second command window and you should see lines like this
Client mosqsub/5916-DL2SBA-5 received PUBLISH (d0, q0, r0, m0, 'dl2sba.de/Arduino_MEGA/light', ... (22 bytes))
dl2sba.de/Arduino_MEGA/light {"L": "37", "R": "41"}
Now let us test, whether message forwarding from a local mosquitto_pub.exe client via the Mosquitto server to the connected arduino works.
- Open another command line window
- Send a test message to your arduino
mosquitto_pub.exe -t dl2sba.de/Arduino_MEGA/control -h 192.168.2.100 -u XXXXXX -P YYYYYY -m "Hello world"
- Now you should see in the Arduino IDEs serial window messages like this
Message arrived: topic: dl2sba.de/Arduino_MEGA/control
Length: 11
Payload: Hello world
- In the command window of the Mosquitto server you should see the message forwarding
1400928136: Received PUBLISH from mosqpub/3572-DL2SBA-5 (d0, q0, r0, m0, 'dl2sba.de/Arduino_MEGA/control', ... (11 bytes))
1400928136: Sending PUBLISH to Arduino_MEGA (d0, q0, r0, m0, 'dl2sba.de/Arduino_MEGA/control', ... (11 bytes))
So far so good - bidirectional communication from/to your Arduino works ... welcome to Mosquitto and Arduino ... :-)