c# S7通信测试

cs 复制代码
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 S7demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //加载参数
            this.cbType.DataSource = Enum.GetNames(typeof(CpuType));
            
            
        }

        private Plc siemens;

        private void btnConnect_Click(object sender, EventArgs e)
        {
            CpuType type = (CpuType)Enum.Parse(typeof(CpuType),cbType.Text,false);
            try
            {
                siemens = new Plc(type, textBoxIp.Text, 0, 1);
                siemens.Open();
                MessageBox.Show("sucess");
            }
            catch (Exception)
            {
                MessageBox.Show("connect failed");

            }
          
            
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            siemens.Close();
            MessageBox.Show("断开连接");
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
    
            byte[] data = siemens.ReadBytes(DataType.DataBlock,1,0,20);
    
            UInt16 res = BitConverter.ToUInt16(new byte[2] {data[1],data[0]}, 0); //2个字节 VW0

            float num = BitConverter.ToSingle(new byte[4] { data[7], data[6], data[5], data[4] }, 0);//4 个字节  VD4
         
            MessageBox.Show(res.ToString());
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            ushort num = ushort.Parse(textBoxWrite.Text);
            byte[] a = BitConverter.GetBytes(num);
            siemens.WriteBytes(DataType.DataBlock, 1, 0, new byte[] { a[1],a[0]});
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }
    }
}
相关推荐
1uther25 分钟前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
C_Liu_1 小时前
C++:类和对象(下)
开发语言·c++
coderxiaohan1 小时前
【C++】类和对象1
java·开发语言·c++
阿幸软件杂货间1 小时前
Office转PDF转换器v1.0.py
开发语言·pdf·c#
扯淡的闲人2 小时前
多语言编码Agent解决方案(5)-IntelliJ插件实现
开发语言·python
丑小鸭是白天鹅2 小时前
Kotlin协程详细笔记之切线程和挂起函数
开发语言·笔记·kotlin
sali-tec2 小时前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
java搬砖工-苤-初心不变2 小时前
基于 lua_shared_dict 的本地内存限流实现
开发语言·junit·lua
charlie1145141912 小时前
Kotlin 的 apply / with / run 详解
开发语言·kotlin·程序设计·面对对象
Tiger_shl2 小时前
【层面一】C#语言基础和核心语法-02(反射/委托/事件)
开发语言·c#