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

        }
    }
}
相关推荐
开源技术2 分钟前
Python GeoPandas基础知识:地图、投影和空间连接
开发语言·ide·python
Cult Of5 分钟前
Alicea Wind的个人网站开发日志(2)
开发语言·python·vue
我找到地球的支点啦11 分钟前
通信扩展——扩频技术(超级详细,附带Matlab代码)
开发语言·matlab
微小冷30 分钟前
Rust异步编程详解
开发语言·rust·async·await·异步编程·tokio
A9better34 分钟前
C++——不一样的I/O工具与名称空间
开发语言·c++·学习
清水白石00836 分钟前
《为什么说 deque 是 Python 滑动窗口的“隐藏神器”?深入解析双端队列的高效之道》
开发语言·python
杜子不疼.37 分钟前
Ascend_C自定义算子开发
c语言·开发语言
WooaiJava1 小时前
流式TTS音频播放项目 - 面试问答(后端)
java·开发语言
新缸中之脑1 小时前
开发AI代理必备的8个Python 库
开发语言·人工智能·python
暴走十八步1 小时前
PHP+vscode开启调试debug
开发语言·vscode·php