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

        }
    }
}
相关推荐
molunnnn1 小时前
第四章 Agent的几种经典范式
开发语言·python
洛_尘2 小时前
JAVA EE初阶 2: 多线程-初阶
java·开发语言
@卞3 小时前
C语言常见概念
c语言·开发语言
wjs20243 小时前
Eclipse 关闭项目详解
开发语言
沐知全栈开发3 小时前
《隐藏(Hide)》
开发语言
lkbhua莱克瓦243 小时前
Java基础——方法
java·开发语言·笔记·github·学习方法
catchadmin4 小时前
PHP 依赖管理器 Composer 2.9 发布
开发语言·php·composer
范纹杉想快点毕业4 小时前
《嵌入式开发硬核指南:91问一次讲透底层到架构》
java·开发语言·数据库·单片机·嵌入式硬件·mongodb
毕设源码-邱学长4 小时前
【开题答辩全过程】以 基于Python的Bilibili平台数据分析与可视化实现为例,包含答辩的问题和答案
开发语言·python·数据分析