Author Topic: Reading variables from PLC (Beckhoff)  (Read 3269 times)

busarider29

  • Newbie
  • *
  • Posts: 18
    • View Profile
Reading variables from PLC (Beckhoff)
« on: February 09, 2016, 08:54:42 AM »
This is not related to AdvancedHMI as I am not using it for this particular project that I have.  I need to read variables in the Beckhoff PLC from my .NET application.  I can write to the PLC from my .NET application but I am running into difficulties reading the variables.  I am using Structs to write variables to the PLC and I would like to stick to that convention when reading as well.  I have two thermocouple values that I need to read (iTC1_Val, iTC2_Val) that are in the PLC program.  These are in a Struct in the PLC and the .NET application. 

Thank you in advance for any assistance that can be provided.

'Create Structure in .NET application with the two variables
Code: [Select]
Public Structure ST_PLCAIChannelsINTS
        Public iTC1_Value As Short
        Public iTC2_Value As Short
    End Structure

'Create instance of the Structure, Ads objects for reading/writing, etc.
Code: [Select]
Public Class frmMain
    Private tcClient As TwinCAT.Ads.TcAdsClient
    Private dataStreamWrite As TwinCAT.Ads.AdsStream
    Private dataStreamRead As TwinCAT.Ads.AdsStream
    Private binaryReader As System.IO.BinaryReader
    Private binaryWriter As System.IO.BinaryWriter
    Private plcData6 As ST_PLCAIChannelsINTS

'Create same Struct in the PLC with same name with variables
Code: [Select]
TYPE ST_PLCAIChannelsINTS :
STRUCT
iTC1_Value : INT;
iTC2_Value : INT;
END_STRUCT
END_TYPE

'Create instance of the Struct in MAIN in the PLC
Code: [Select]
PROGRAM MAIN
VAR
st_PLCAIChannelsINTS : ST_PLCAIChannelsINTS;
END_VAR

'Read the PLC variables in this Sub.  This is what I have so far for code.  Is this correct?  What code syntax needs to go in the Try Catch block to perform the actual read?   
Code: [Select]
Private Sub ReadRegisters()
        Dim hvar As Integer
        Dim errorBits As New BitArray(Errors)
        dataStreamRead = New AdsStream(32)
        binaryReader = New BinaryReader(dataStreamRead)
        dataStreamRead.Position = 0

        Try
            hvar = tcClient.CreateVariableHandle("Main.st_PLCAIChannelsINTS.iTC1_Value")
            'Insert code for reading the PLC Struct variables here
        Catch ex As AdsErrorException
            MessageBox.Show(ex.Message, "ADS Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

Archie

  • Administrator
  • Hero Member
  • *****
  • Posts: 5322
    • View Profile
    • AdvancedHMI
Re: Reading variables from PLC (Beckhoff)
« Reply #1 on: February 09, 2016, 09:26:54 AM »
It has been many years since I've used the ADS communication library, but I think you are looking for something like this:

tcClient.Read(hvar, dataStreamRead)
dim MyValue=binaryreader.read????