Skip to content

Instantly share code, notes, and snippets.

@fisherds
Last active May 3, 2021 14:32
Show Gist options
  • Save fisherds/cad2c1b70f6fccc0357fe51e70bad14a to your computer and use it in GitHub Desktop.
Save fisherds/cad2c1b70f6fccc0357fe51e70bad14a to your computer and use it in GitHub Desktop.
MQTT in MATLAB example using JSON messags
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