Back
Featured image of post Siemens PLC and Csharp communication (Simatic Step7-PlcSim-VisualStudio)

Siemens PLC and Csharp communication (Simatic Step7-PlcSim-VisualStudio)

How to communicate between a C# application and a Siemens PLC

New visual studio project

Create a new project :

New project
New project

S7.net Plus

S7.net Plus is a Siemens communication library.

2.1 Installation

Install it with the NuGet package manager :

NuGET
NuGET
S7netplus
S7netplus
S7netplus
S7netplus

Program

We just create one label (label1) :

New label
New label

And we switch to the code :

Code
Code

And the code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using S7.Net;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        S7.Net.Plc plc;
        public Form1()
        {
            //Form initialization
            InitializeComponent();
            //New timer
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
            t.Interval = 500; // specify interval time as you want
            t.Tick += new EventHandler(timer_Tick);
            t.Start();
        }
        void timer_Tick(object sender, EventArgs e)
        {
            CpuType MyCpuType = S7.Net.CpuType.S7300;
            String MyCpuIp = "192.168.1.9";
            short MyCpuRack = 0;
            short MyCpuSlot = 2;
            using (var plc = new Plc(MyCpuType, MyCpuIp, MyCpuRack, MyCpuSlot))
            {
                //IP is responding
                if (plc.IsAvailable)
                {
                    ErrorCode connectionResult = plc.Open();
                    //Connection successful
                    if (connectionResult.Equals(ErrorCode.NoError))
                    {
                        //Get data
                        label1.Text = plc.Read("DB1.DBX0.0").ToString();
                    }
                    else
                    {
                        MessageBox.Show("Device available but connection failed", "Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Device unavailable", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}

Running :

Simulation
Simulation

Built with Hugo
Theme Stack designed by Jimmy