以下是一个简单的 WPF 与西门子 PLC 连接 C# 的程序示例:

  1. 首先,需要在项目中添加 Siemens S7-1200/1500 驱动程序。在 Visual Studio 中,选择'项目'->'添加引用'->'浏览',找到 Siemens.Simatic.S7.WebServer.dll 文件并添加。

  2. 在 MainWindow.xaml.cs 文件中,添加以下代码:

using Siemens.Simatic.S7.WebServer.API;
using System.Windows;

namespace WpfPLCConnection
{
    public partial class MainWindow : Window
    {
        private S7WebApiClient client;

        public MainWindow()
        {
            InitializeComponent();
            client = new S7WebApiClient('PLC IP地址'); //替换为实际 PLC 的 IP 地址
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (client != null)
            {
                var result = client.Read('DB1.DBD0'); //读取 DB1.DBD0 的值
                if (result.Success)
                {
                    txtResult.Text = result.Value.ToString(); //显示读取的值
                }
                else
                {
                    txtResult.Text = '读取失败';
                }
            }
        }
    }
}
  1. 在 MainWindow.xaml 文件中,添加以下 XAML 代码:
<Window x:Class='WpfPLCConnection.MainWindow'
        xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
        Title='MainWindow' Height='250' Width='350'>
    <Grid>
        <StackPanel Orientation='Vertical' Margin='20'>
            <Button Content='读取 PLC 数值' Click='Button_Click' />
            <TextBlock Margin='0 20 0 0' Text='PLC 数值:' />
            <TextBox x:Name='txtResult' IsReadOnly='True' />
        </StackPanel>
    </Grid>
</Window>
  1. 运行程序,点击'读取 PLC 数值'按钮,程序将会连接到 PLC 并读取 DB1.DBD0 的值,并将其显示在界面上的文本框中。

注意:在使用 S7WebApiClient 之前,需要在 PLC 中启用 Web 服务功能,并在 Web 服务设置中开启 API 接口。同时,需要在程序中替换实际 PLC 的 IP 地址。


原文地址: https://www.cveoy.top/t/topic/nCx7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录