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

        }
    }
}
相关推荐
c2385638 分钟前
把 C++ 内存分配拆透:new 与 malloc 的三层血缘
开发语言·c++·算法
moonsims1 小时前
星闪在跨域无人化系统作用
开发语言·php
Iruoyaoxh2 小时前
栈和队列~
java·开发语言
Hrain-AI2 小时前
2026 企业 AI 编程智能体实战:Codex 与 Claude Code
开发语言·人工智能·kotlin
wdfk_prog3 小时前
嵌入式面试真题第 13 题:单硬件 Timer 下的高精度多路软件定时器架构设计
c语言·开发语言·面试·职场和发展·嵌入式
oort1233 小时前
吃上了自家的细糠,还挺丝滑,用起来手感还行,OortCloud发布新版AI编程平台,下载 OortCodex,Token多,免费薅
大数据·开发语言·人工智能·ai编程
slandarer3 小时前
MATLAB | 泰勒图绘制,支持各种角度范围
开发语言·数学建模·matlab·nature·顶刊·泰勒图
Xin_ye100863 小时前
第三章:内存泄漏的常见“案发现场”
c#·wpf
mct1233 小时前
c++ iconv 字符utf-8转换gb2312失败
开发语言·c++
Marst Code5 小时前
Python 3.9 已停止维护!从 3.9 到 3.14 全版本深度对比,生产环境该选哪个?
开发语言·python