Last active
May 3, 2021 14:32
-
-
Save fisherds/cad2c1b70f6fccc0357fe51e70bad14a to your computer and use it in GitHub Desktop.
MQTT in MATLAB example using JSON messags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function jsonMQTTTest | |
clc | |
fprintf("Connecting...\n"); | |
mqttClient = mqtt('tcp://broker.hivemq.com') | |
subscribe(mqttClient,'fisherds',"Callback",@myCallback); | |
for k = 60:20:100 | |
currentMessage = sprintf('{"type": "motor/go", "payload": [%d, %d]}', k, k); | |
publish(mqttClient, 'fisherds', currentMessage); | |
pause(1); | |
end | |
publish(mqttClient, 'fisherds', '{"type": "motor/stop"}'); | |
pause(1); % Allow the last message to finish before closing | |
unsubscribeAll(mqttClient) | |
end | |
function myCallback(topic, message) | |
fprintf("Received message: %s\n", message) | |
messageCell = jsondecode(message) | |
messageType = messageCell.type | |
payload = messageCell.payload | |
leftWheelSpeed = payload(1) | |
rightWheelSpeed = payload(2) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment