www.gusucode.com > opc 案例源码 matlab代码程序 > opc/opcdemo_readwrite.m

    %% Read and Write Data to an OPC Data Access Server
% This example shows you how to use OPC Toolbox(TM) synchronous read and
% write operations to exchange data with an OPC server.
%
% *PREREQUISITES:*
%
% * <docid:opc_examples.example-ex84291595>

% Copyright 2004-2016 The MathWorks, Inc. 

%% 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)

%%
% Specify the source of the read as |'device'| to force the server to read a value from the device.
% This process may take long if the OPC server is on the
% network or the device takes some time to produce a value.
r = read(itm1, 'device')

%% Perform Synchronous Write Operations
% Add a writable item to the group.
itm2 = additem(grp, 'Bucket Brigade.Real8')

%%
% Write the value 10 to the item.
write(itm2, 10)

%%
% Read the value back into MATLAB(R).
r = read(itm2, 'device')

%% Read From Multiple Items
% You can read data from multiple items using the group object.
r = read(grp)

%%
% Extract individual item information using indexing.
r(1)

%%
% Use concatenation of MATLAB list creation operations to extract multiple values.
itmIDs = {r.ItemID}
vals = [r.Value]

%% 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})

%%
% This particular example returns a warning, since the first item will not allow you to write data
% to the item. However, the second item will have the value 5.432 written.
r = read(itm2, 'device')

%% 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.