Send array from C # to TwinCat 3 via ADS.Net

I want to create an automated graphic fountain using TwinCat 3 to control valves and Visual Studio C # to process the image I want to show on the fountain.

The final form of the image processing program is an image of a binary array (attached): Result of image processing 1 ; Image processing result 2 ;

I want to use the final form of image processing to control a valve on a machine (valve turns on when it is 1 and valve turns off when it is 0). I am very new to TwinCat 3, especially with the ADS library.

The sample from infosys beckhoff is not very helpful for me, can anyone help me with this?

thank

+3


source to share


2 answers


I made a sample console program that connects to a local PLC on port 851 and writes an array of 100 bools named "boolArray" to MAIN TC3 (TwinCAT 3):

using System;
using TwinCAT.Ads;
using System.Threading;

namespace WriteArrayToPLC
{

    class Program
    {
        static void Main(string[] args)
        {
            TcAdsClient adsClient = new TcAdsClient();
            byte[] boolArray = new byte[100];
            // Fill array with 010101010...
            for (int i = 0; i < 100; i++)
            {
                boolArray[i] = (i % 2 != 0) ? (byte)1 : (byte)0;
            }
            // Connect to PLC
            try
            {

                if (adsClient != null)
                {
                    Console.WriteLine("Connecting to PC");
                    adsClient.Connect(851);
                }
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                adsClient = null;
            }

            if (adsClient != null)
            {
                try
                {
                    // Get the handle for the array
                    int handle_array = adsClient.CreateVariableHandle("MAIN.boolArray");
                    // Write the array to PLC
                    Console.WriteLine("Writing the array at handle: " + handle_array.ToString());
                    adsClient.WriteAny(handle_array, boolArray);
                }
                catch (Exception err)
                {
                    Console.WriteLine(err.Message);
                }
                // The end
                Console.WriteLine("Done");
                Thread.Sleep(3000);
            }
        }
    }
}

      



This code represents a good way to write an array to TC3.

+1


source


I used with TwinCAT 3.1.4022.0System.Runtime.InteropServices.

MarshalAs

Array declaration:

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] data;

      



And then I can send it through

TcAdsClient.WriteAny( ixGroup, ixOffset, data )

      

+1


source







All Articles