How to use and code with OPC UA Protocol:

OPC UA is a standardized protocol used for communication between various components. In this tutorial you will learn how to use OPC UA for a connection between laptop and a PLC. The benefits of OPC UA between laptop and PLC is that you can easily adjust PLC variables without using sockets or other connections. So with OPC UA you don’t have to send string messages and then parse them, but you can directly adjust the variables. This makes it really easy to change variables on the PLC from the laptop. To get better visuals on the setup on the PLC and laptop connection you can check this video: video link. Following this video allows you to get visuals on the setup part and use it in combination with the tutorial below.

Requirements:
Connection
To get OPC UA working both the PLC and the laptop should be on the same network. So make sure both components are connected to each other via a network switch.
Downloads:

  • Codesys:
    o Codesys will be used to code the PLC and to simulate a PLC. In this tutorial a PLC will be simulated with Codesys with OPC UA running
  • UaExpert:
    o UaExpert is a good tool to easily connect to a PLC and read and write data on it. This app is mainly used to get the route of the variables off the PLC for the script
  • Any python IDE:
    o The main script of the laptop communication will be programmed in Python IDE with this tool. In this tutorial PyCharm is used.

Setup OPC UA on PLC:
Make a new standard project and select the “Codesys Control Win V3 x64” as device and PLC_PRG in ST. That is the Codesys PLC we use to simulate a PLC. In the project overview right click on application and add “Symbol configuration”. Make sure the “Support OPC UA features” is selected.
In the PLC_PRG you can add the variables you need for your project. In this tutorial we will use bool and integer variables. You can use the following code for a simple OPC UA test:

VAR
    Xhoek : INT;
    Yhoek : INT;
END_VAR

After adding the variables go to the Symbol Configuration page and click build. After building you will see different scripts, select the one used for your project(probably PLC_PRG). After opening the script, you will see all your variables of your project. Select the variables you want to be able to be edited by the laptop and click build again.
Before running the PLC make sure you the Codesys gateway and control win is opened. You can see it in the taskbar status area. If you don’t see any Codesys symbol, search it on windows search and open it.
Now you can make the PLC online by clicking login and start on Codesys.

Client/student side connection on laptop
Once the PLC is running open UaExpert. On UaExpert click on the plus symbol and on the advanced page add this is as endpoint URL:

  • opc.tcp://localhost:4840

After pressing ok you will see it as a server and click the Connect server to connect to the PLC. After connected you can easily see the variables of the PLC. This connection is important as we need the node ID of our variables to change it in the script. You can move through the tabs on you see when youre connected to the PLC. Search for you program file in these tabs. Once you have found the program file you can open it, and you will get an overview of all the variables changeable by OPC UA.

Copy the node ID you want to change. You will get the node ID like this:

  • NS4|String|var|CODESYS Control Win V3 x64.Application.PLC_PRG.Xhoek
    Remove the front part before |var| and replace it with:
    ns=4;s=
    Then you will get this as node ID:
    ns=4;s=|var|CODESYS Control Win V3 x64.Application.PLC_PRG.Xhoek
    We will use these these strings as the node id on the laptopcode.

Coding with OPC UA protocol:
Before coding make sure to install these packages:

  • opcua
    • Used to get the functions to connect and change variables
  • time
    • Only used for print function, you dont need this to get OPC UA working
from opcua import Client, ua
import time
#endpoints url 
#if localhost doesnt work change it to your ip address
url = "opc.tcp://localhost:4840"
client = Client(url)

try:
    client.connect()
    print("Connected to OPC UA Server")

    # Use correct NodeId with 
    x_node = client.get_node("ns=4;s=|var|CODESYS Control Win V3 x64.Application.PLC_PRG.Xhoek")
    y_node = client.get_node("ns=4;s=|var|CODESYS Control Win V3 x64.Application.PLC_PRG.Yhoek")

    print("Current values:")
    print(f"Xhoek: {x_node.get_value()}")
    print(f"Yhoek: {y_node.get_value()}")

    while True:
        x_value = 123
        y_value = 456
        x_node.set_value(x_value, ua.VariantType.Int16)
        y_node.set_value(y_value, ua.VariantType.Int16)
        print(f"Sent to PLC -> X: {x_node.get_value()}, Y: {y_node.get_value()}")
        time.sleep(0.5)

except Exception as e:
    print(f"Error: {e}")

finally:
    client.disconnect()
    print("Disconnected from OPC UA Server")

With this code you will see the x and y variable change on the PLC. You can use this technique to easily pass variables from the laptop to the PLC without any worries.
Example video of a fully implemented OPC UA script(this code is not the same as this tutorial, but you clearly see the variables change):