Read multiple boolean variables into an array with one access

System requirements:

Task

Multiple boolean PLC variables can be read into Delphi applications with one access, provided the variables are stored at addresses that are sequentially located in the memory. It is, however, important that the first variable is located at a byte address.

Description

PLC program

PROGRAM MAIN
VAR
    varBoolean AT%MB6 : ARRAY[1..4] OF BOOL;
END_VAR

Delphi 7 program

unit Unit1;
interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, OleCtrls, ADSOCXLib_TLB, StdCtrls;

type
  TForm1 = class(TForm)
    btnRead: TButton;
    AdsOcx1: TAdsOcx;
    ListBox1: TListBox;
    procedure btnReadClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  varBoolArray : ARRAY[1..4] OF WordBool;

implementation
{$R *.dfm}

procedure TForm1.btnReadClick(Sender: TObject);
var     i, hVar, AdsResult:integer;
begin
    // Create variable handle
    AdsResult := AdsOcx1.AdsCreateVarHandle( 'MAIN.VARBOOLEAN', hVar );
    if AdsResult = 0 then
    begin
        // Read data 
        AdsResult := AdsOcx1.AdsSyncReadBoolVarReq( hVar, sizeof(varBoolArray), varBoolArray[1] );
        if AdsResult = 0 then
        begin
            // Clear list view and show data
            ListBox1.Clear();
            for i:=1 to 4 do
                ListBox1.Items.Add( Format('varBoolArray[%d] = %s', [i, BoolToStr(varBoolArray[i], true) ] ) );
        end
        else ShowMessage( Format( 'AdsSyncReadBooleanVarReq() error:%d', [AdsResult] ) );

        // Release variable handle
        AdsResult := AdsOcx1.AdsDeleteVarHandle( hVar );
        if AdsResult <> 0 then
            ShowMessage( Format( 'AdsDeleteVarHandle() error:%d', [AdsResult] ) );
    end
    else ShowMessage( Format( 'AdsCreateVarHandle() error:%d', [AdsResult] ) );
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
   // Connection Setup
   AdsOcx1.AdsAmsServerNetId := AdsOcx1.AdsAmsServerNetId;
   AdsOcx1.AdsAmsServerPort := 801;
end;

Initialization
   IsMultiThread := True;// Setting this system variable makes Delphi's memory manager thread-safe

end.

Language / IDE

Unpack sample program

Delphi XE2

Sample07.exe

Delphi 7 or higher (classic)