We will create a Function Block to handle the MQTT connection.
Variable Declaration:
VAR // MQTT Configuration MqttClient : MQTT.MqttClient; sBrokerIp : STRING := '192.168.1.100'; // IP of PC running Mosquitto uiPort : UINT := 1883;// Topics sTopicPub : STRING := 'plc/odom'; sTopicSub : STRING := 'plc/cmd_vel'; // Payload Handling PublishPayload : STRING; SubscribePayload : STRING; // Control Flags bConnect : BOOL := TRUE; bConnected : BOOL; xPublishTrigger : BOOL; // Example Data rVelocity : REAL := 0.0; rPosition : REAL := 0.0;
END_VAR
Implementation Code:
// 1. Configure Client MqttClient.sHostName := sBrokerIp; MqttClient.uiPort := uiPort; MqttClient.xConnect := bConnect;// 2. Handle Connection Status bConnected := MqttClient.xConnected;
// 3. Publish Data (Every 100ms for example) // Assuming you have a timer or cyclic task set to 100ms IF bConnected THEN // Construct a simple JSON payload (String format) // In real apps, use a JSON Serialize library for robustness PublishPayload := CONCAT('"pos":', REAL_TO_STRING(rPosition)); PublishPayload := CONCAT(PublishPayload, '');
MqttClient.Publish( sTopic := sTopicPub
ROS 2 is an open-source software framework for building robot applications. It provides a set of tools and libraries for developing robot software, including device drivers, message passing, and more.
In your CODESYS project:
Imagine an Autonomous Mobile Robot (AMR) designed for a warehouse. Here is how the responsibilities are split:
The CODESYS Layer:
The ROS2 Layer:
The Interface:
The ROS2 Nav2 stack calculates a velocity command (Twist message). It publishes this to a topic /cmd_vel. Through a DDS bridge or Gateway, this data arrives in the CODESYS controller as a structure containing linear and angular velocities. The CODESYS logic then checks if the velocity is within safe limits, applies ramping (smooth acceleration), and sends the command to the motor drives.
As of 2025 (and looking beyond), several trends are accelerating this integration: