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)
        {

        }
    }
}
相关推荐
爱学习的阿磊5 分钟前
C++中的策略模式应用
开发语言·c++·算法
郝学胜-神的一滴6 分钟前
Python中的bisect模块:优雅处理有序序列的艺术
开发语言·数据结构·python·程序人生·算法
Remember_9938 分钟前
Spring 事务深度解析:实现方式、隔离级别与传播机制全攻略
java·开发语言·数据库·后端·spring·leetcode·oracle
看得见的风11 分钟前
Claude Code + CCR配置(含OpenRouter、GLM、Kimi Coding Plan)
开发语言
L_090712 分钟前
【Linux】进程状态
linux·开发语言·c++
roman_日积跬步-终至千里13 分钟前
【Java并发】用 JMM 与 Happens-Before 解决多线程可见性与有序性问题
java·开发语言·spring
2401_8384725114 分钟前
C++异常处理最佳实践
开发语言·c++·算法
m0_7369191017 分钟前
C++中的类型标签分发
开发语言·c++·算法
天桥下的卖艺者21 分钟前
使用R语言编写一个生成金字塔图形的函数
开发语言·数据库·r语言
2301_7903009624 分钟前
C++与微服务架构
开发语言·c++·算法