Read and Write Data to an OPC Data Access Server
This example shows you how to use synchronous read and write operations to exchange data with an OPC server.
PREREQUISITES:
Connect to Server and Create Objects
Create an opcda
client and connect that client to the OPC server.
da = opcda('localhost','Matrikon.OPC.Simulation.1'); connect(da);
Add a group to the client, and an item to the group.
grp = addgroup(da);
itm1 = additem(grp,'Random.Real8');
Perform Synchronous Read Operations
The default read operation gets values from the server cache.
r = read(itm1)
r = struct with fields: ItemID: 'Random.Real8' Value: 0 Quality: 'Bad: Out of Service' TimeStamp: [2016 8 30 11 55 24.4130] Error: ''
To force the server to read a value from the device, specify that option. This process can take a while if the OPC server is on the network or the device takes some time to produce a value.
r = read(itm1,'device')
r = struct with fields: ItemID: 'Random.Real8' Value: 20.8848 Quality: 'Good: Non-specific' TimeStamp: [2016 8 30 11 55 24.7220] Error: ''
Perform Synchronous Write Operations
Add a writable item to the group.
itm2 = additem(grp,'Bucket Brigade.Real8')
itm2 = Summary of OPC Data Access Item Object: Bucket Brigade.Real8 Object Parameters Parent : Group0 Access Rights : read/write Object Status Active : on Data Parameters Data Type : double Value : Quality : Bad: Out of Service Timestamp :
Write the value 10 to the item.
write(itm2,10)
Read the value back into MATLAB.
r = read(itm2,'device')
r = struct with fields: ItemID: 'Bucket Brigade.Real8' Value: 10 Quality: 'Good: Non-specific' TimeStamp: [2016 8 30 11 55 24.8520] Error: ''
Read From Multiple Items
You can read data from multiple items using the group object.
r = read(grp)
r = 2×1 struct array with fields: ItemID Value Quality TimeStamp Error
Display individual item information by indexing.
r(1)
ans = struct with fields: ItemID: 'Random.Real8' Value: 20.8848 Quality: 'Good: Non-specific' TimeStamp: [2016 8 30 11 55 24.7220] Error: ''
Extract multiple values from item.
itmIDs = {r.ItemID} vals = [r.Value]
itmIDs = 1×2 cell array 'Random.Real8' 'Bucket Brigade.Real8' vals = 20.8848 10.0000
Write to Multiple Items
Write to multiple items, passing the values for the items in the group as a cell array.
write(grp,{1.234,5.432})
Warning: One or more items could not be written. Random.Real8 returned 'The item's access rights do not allow the operation.'
The previous command returns a warning, because the first item does not allow you to write data to it. However, the second has the value 5.432 written. You can verify that be reading it.
r = read(itm2,'device')
r = struct with fields: ItemID: 'Bucket Brigade.Real8' Value: 5.4320 Quality: 'Good: Non-specific' TimeStamp: [2016 8 30 11 55 24.9070] Error: ''
Clean Up
Disconnect from the server and delete the client object.
disconnect(da) delete(da)
Deleting the client object automatically deletes the group and item objects.