using S7.Net; using S7.Net.Types; 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; namespace xicheji { public partial class MainForm : Form { private Plc plc; public MainForm() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { plc = new Plc(CpuType.S7200, "127.0.0.1", 1502, 0, 1); plc.Open(); richTextBox1.AppendText("连接成功!\n\n"); richTextBox1.ScrollToCaret(); } catch (Exception ex) { MessageBox.Show(ex.Message + ex.StackTrace); } } private void button2_Click(object sender, EventArgs e) { if (plc == null || !plc.IsConnected) return; //plc中类型与c#类型 bool => Bit //Byte => byte //word => ushort //DWord => uint //Int => short //DInt => int //Real => float //LReal => double //String => string //DateTimeLong=>datetime //s7wstring=>string //PLCAddress.Parse //1、DB100.DBB0 一个字节有8个位,分别为0-- - 7!例:0.0----0.7共8位 --Byte,byte //2、DB100.DBW0一个字有两个字节,分别为 DB100.DBB0和 DB100.DBB1 --Word,ushort //3、DB100.DBD0一个双字有两个字,分别为 DB100.DBW0和 DB100.DBW2 --DWord,uint //4、DB100.DBX0.0 一个位,这是最小单位 --Bit,bool try { var db = 1; var start = plc.Read(DataType.DataBlock, db, 0, VarType.Byte, 1); Log("start:", start); var start2 = plc.Read("DB1.DBB0"); Log("start2:", start2); var length = plc.Read(DataType.DataBlock, db, 1, VarType.Byte, 1); Log("length:", length); var length2 = plc.Read("DB1.DBB1"); Log("length2:", length2); var mac = plc.Read(DataType.DataBlock, db, 2, VarType.Byte, 6); Log("mac:", string.Join(":", (mac as byte[]).ToList().ConvertAll(a => "0x" + a.ToString("X2")))); var mac2 = plc.Read("DB1.DBD2-6"); Log("mac2:", mac2); var val = plc.Read(DataType.DataBlock, db, 10, VarType.Bit, 1, 1); Log("DB1.DBX10.1的值为:", val); val = plc.Read(DataType.DataBlock, db, 10, VarType.Bit, 1, 2); Log("DB1.DBX10.2的值为:", val); val = plc.Read(DataType.DataBlock, db, 20, VarType.DWord, 1); Log("读取DB1.DBX20 DWORD的洗车次数值为:", val); var bbb = (bool)plc.Read("DB1.DBX10.1"); Log("bbb:", bbb); var ccc = plc.Read("DB1.DBD20"); Log("ccc:", ccc); //DWord.FromByteArray } catch (Exception ex) { MessageBox.Show(ex.Message + ex.StackTrace); } } private void Log(params object[] msgs) { richTextBox1.AppendText(string.Join(" ", msgs)); richTextBox1.AppendText("\n\n"); richTextBox1.ScrollToCaret(); } private void button3_Click(object sender, EventArgs e) { plc?.Close(); } } }