先在NuGet上搜索S7netplus,并安装,如下图所示
搜索s7.net进行安装。
选择VisualStudio2022编程环境。
对s7.net进行引用
连接PLC:
读取PLC数据:
运用myPLC.Read()方法读取PLC数据
运用 myPLC.Write()方法写入plc数据
源码分享:
using S7.Net;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Net;
namespace 西门子S7通讯读取PLC数据
{
public partial class Form1 : Form
{
public Plc myPLC;
public bool LJzhuangtia;
public S7.Net.DataType dataType;
public int sint1,sint2;
public Form1()
{
InitializeComponent();
IPtextBox.Text = '192.168.0.1';
JTtextBox.Text = '0';
CCtextBox.Text = '1';
}
#region
class AutoSizeFormClass
{
public struct controlRect
{
public int Left;
public int Top;
public int Width;
public int Height;
}
public List<controlRect> oldCtrl = new List<controlRect>();
int ctrlNo = 0;
//重要方法一:记录窗体和其控件的初始位置和大小controllInitializeSize()
public void controllInitializeSize(Control mForm)
{
controlRect cR;
cR.Left = mForm.Left; cR.Top = mForm.Top; cR.Width = mForm.Width; cR.Height = mForm.Height;
oldCtrl.Add(cR);
AddControl(mForm);
}
private void AddControl(Control ctl)
{
foreach (Control c in ctl.Controls)
{
controlRect objCtrl;
objCtrl.Left = c.Left; objCtrl.Top = c.Top; objCtrl.Width = c.Width; objCtrl.Height = c.Height;
oldCtrl.Add(objCtrl);
if (c.Controls.Count > 0)
AddControl(c);
}
}
//重要方法二:控件自适应大小方法controlAutoSize()
public void controlAutoSize(Control mForm)
{
if (ctrlNo == 0)
{
controlRect cR;
cR.Left = 0; cR.Top = 0; cR.Width = mForm.PreferredSize.Width; cR.Height = mForm.PreferredSize.Height;
oldCtrl.Add(cR);
AddControl(mForm);
}
float wScale = (float)mForm.Width / (float)oldCtrl[0].Width;
float hScale = (float)mForm.Height / (float)oldCtrl[0].Height;
ctrlNo = 1;
AutoScaleControl(mForm, wScale, hScale);
}
private void AutoScaleControl(Control ctl, float wScale, float hScale)
{
int ctrLeft0, ctrTop0, ctrWidth0, ctrHeight0;
foreach (Control c in ctl.Controls)
{
ctrLeft0 = oldCtrl[ctrlNo].Left;
ctrTop0 = oldCtrl[ctrlNo].Top;
ctrWidth0 = oldCtrl[ctrlNo].Width;
ctrHeight0 = oldCtrl[ctrlNo].Height;
c.Left = (int)((ctrLeft0) * wScale);
c.Top = (int)((ctrTop0) * hScale);//
c.Width = (int)(ctrWidth0 * wScale);
c.Height = (int)(ctrHeight0 * hScale);//
ctrlNo++;
if (c.Controls.Count > 0)
AutoScaleControl(c, wScale, hScale);
if (ctl is DataGridView)
{
DataGridView dgv = ctl as DataGridView;
Cursor.Current = Cursors.WaitCursor;
int widths = 0;
for (int i = 0; i < dgv.Columns.Count; i++)
{
dgv.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells); // 自动调整列宽
widths += dgv.Columns[i].Width; // 计算调整列后单元列的宽度和
}
if (widths >= ctl.Size.Width) // 如果调整列的宽度大于设定列宽
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; // 调整列的模式 自动
else
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; // 如果小于 则填充
Cursor.Current = Cursors.Default;
}
}
}
}
//第二步,实例化上面定义的类
AutoSizeFormClass asc = new AutoSizeFormClass();
//第三步,初始化窗口时记录控件的大小和位置
private void Form1_Load(object sender, EventArgs e)
{
asc.controllInitializeSize(this);
}
//第四步,主窗口大小发生变化触发的事件
private void Form1_SizeChanged(object sender, EventArgs e)
{
asc.controlAutoSize(this);
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
if (CPUcomboBox.Text != '')
{
CpuType cpu = (CpuType)Enum.Parse(typeof(CpuType), CPUcomboBox.Text, true);
myPLC = new Plc(cpu, IPtextBox.Text, Convert.ToInt16(JTtextBox.Text), Convert.ToInt16(CCtextBox.Text));
if (LJzhuangtia != true)
{
if (CPUcomboBox.Text != '' ||
IPtextBox.Text != '' ||
JTtextBox.Text != '' ||
CCtextBox.Text != '')
{
NewMethod();
}
else
{
MessageBox.Show('请填写真确的连接参数!', '提示');
}
}
else
{
MessageBox.Show('请勿重复连接', '提示');
}
}
else
{
MessageBox.Show('请先选择PLC!');
}
}
private void NewMethod()
{
try
{
myPLC.Open();
LJzhuangtia = true;
MessageBox.Show('连接成功', '提示');
LJBTN.BackColor = Color.Green;
DKBTN.BackColor = Color.FromArgb(224, 224, 224);
}
catch (Exception)
{
MessageBox.Show('连接异常,\r\n 请检查线路! ', '提示');
return;
throw;
}
}
private void DKBTN_Click(object sender, EventArgs e)
{
if (LJzhuangtia == true)
{
try
{
DialogResult dr = MessageBox.Show('确认断开PLC吗?', '提示', MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dr == DialogResult.Yes)
{
LJzhuangtia = false;
timer1.Enabled = false;
timer2.Enabled = false;
myPLC.Close();
LJBTN.BackColor = Color.FromArgb(224, 224, 224);
}
}
catch (Exception)
{
return;
throw;
}
}
else
{
MessageBox.Show('当前没有连接');
}
}
private void button3_Click(object sender, EventArgs e)
{
duqu();
}
private void duqu()
{
if (LJzhuangtia != false)
{
try
{
switch (SHUjucomboBox.Text)
{
case 'BOOL':
bool num1 = Convert.ToBoolean(myPLC.Read('DB' + DBtextBox.Text + '.' + 'DBX' + addresstextBox.Text));
readshuj.Text += '【' + DateTime.Now + '】' + 'DB' + DBtextBox.Text + '.' + 'DBX' + addresstextBox.Text + ':' + num1.ToString() + '\r\n';
break;
case 'BYTE':
var num2 = Convert.ToByte(myPLC.Read('DB' + DBtextBox.Text + '.' + 'DBB' + addresstextBox.Text));
int num2_1 = (byte)num2;
if (num2_1 > 127)
{
num2_1 = num2_1 - 256;
}
readshuj.Text += '【' + DateTime.Now + '】' + 'DB' + DBtextBox.Text + '.' + 'DBB' + addresstextBox.Text + ':' + num2_1.ToString() + '\r\n';
break;
case 'READ':
float num3 = ((uint)myPLC.Read('DB' + DBtextBox.Text + '.' + 'DBD' + addresstextBox.Text)).ConvertToFloat();
readshuj.Text += '【' + DateTime.Now + '】' + 'DB' + DBtextBox.Text + '.' + 'DBD' + addresstextBox.Text + ':' + num3.ToString() + '\r\n';
break;
case 'INT':
int num4 = (ushort)myPLC.Read('DB' + DBtextBox.Text + '.' + 'DBW' + addresstextBox.Text);
if (num4 > 32767)
{
num4 = num4 - 65536;
}
readshuj.Text += '【' + DateTime.Now + '】' + 'DB' + DBtextBox.Text + '.' + 'DBW' + addresstextBox.Text + ':' + num4.ToString() + '\r\n';
break;
case 'DNIT':
var num5 = (uint)(myPLC.Read('DB' + DBtextBox.Text + '.' + 'DBD' + addresstextBox.Text));
readshuj.Text += '【' + DateTime.Now + '】' + 'DB' + DBtextBox.Text + '.' + 'DBD' + addresstextBox.Text + ':' + num5.ToString() + '\r\n';
break;
case 'WORD':
var num6 = (ushort)myPLC.Read('DB' + DBtextBox.Text + '.' + 'DBW' + addresstextBox.Text);
if (num6 > 32767)
{
num6 = (ushort)(num6 - 65536);
}
readshuj.Text += '【' + DateTime.Now + '】' + 'DB' + DBtextBox.Text + '.' + 'DBW' + addresstextBox.Text + ':' + num6.ToString() + '\r\n';
break;
case 'DWORD':
var num7 = (uint)myPLC.Read('DB' + DBtextBox.Text + '.' + 'DBD' + addresstextBox.Text);
readshuj.Text += '【' + DateTime.Now + '】' + 'DB' + DBtextBox.Text + '.' + 'DBD' + addresstextBox.Text + ':' + num7.ToString() + '\r\n';
break;
case 'STRING':
//S7String读取
byte[] bytes = myPLC.ReadBytes(dataType, 1, 18, 40);
break;
case 'PLCNUMBER':
PLCdu();
break;
}
}
catch (Exception)
{
return;
}
}
else
{
MessageBox.Show('请先连接PLC', '提示');
}
}
private void PLCdu()
{
if (sint1 == 1)
{
bool num9 = Convert.ToBoolean(myPLC.Read(PLCcomboBox.Text + addresstextBox.Text));
readshuj.Text += '【' + DateTime.Now + '】' + PLCcomboBox.Text + addresstextBox.Text + ':' + num9.ToString() + '\r\n';
}
if (sint1 == 2)
{
var num10 = Convert.ToByte(myPLC.Read(PLCcomboBox.Text + addresstextBox.Text));
int num10_1 = (byte)num10;
if (num10_1 > 127)
{
num10_1 = num10_1 - 256;
}
readshuj.Text += '【' + DateTime.Now + '】' + PLCcomboBox.Text + addresstextBox.Text + ':' + num10_1.ToString() + '\r\n';
}
if (sint1 == 3)
{
var num11 = (ushort)myPLC.Read(PLCcomboBox.Text + addresstextBox.Text);
if (num11 > 32767)
{
num11 = (ushort)(num11 - 65536);
}
readshuj.Text += '【' + DateTime.Now + '】' + PLCcomboBox.Text + addresstextBox.Text + ':' + num11.ToString() + '\r\n';
}
}
private void PLCcomboBox_SelectedIndexChanged(object sender, EventArgs e)
{
switch (PLCcomboBox.Text)
{
case 'I':
sint1 = 1;
break;
case 'Q':
sint1 = 1;
break;
case 'M':
sint1 = 1;
break;
case 'IB':
sint1 = 2;
break;
case 'QB':
sint1 = 2;
break;
case 'MB':
sint1 = 2;
break;
case 'IW':
sint1 = 3;
break;
case 'QW':
sint1 = 3;
break;
case 'MW':
sint1 = 3;
break;
}
}
bool a = false;
private void button4_Click(object sender, EventArgs e)
{
try
{
if (a != true&&LJzhuangtia==true)
{
timer1.Enabled = true;
button4.Text = '读取中…';
a = true;
}
else
{
timer1.Enabled = false;
a = false;
button4.Text = '连续读取';
}
}
catch (Exception)
{
throw;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
duqu();
}
private void readshuj_TextChanged(object sender, EventArgs e)
{
readshuj.SelectionStart = readshuj.Text.Length;
readshuj.ScrollToCaret();
}
private void button5_Click(object sender, EventArgs e)
{
readshuj.Text = string.Empty;
}
private void SHUjucomboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (SHUjucomboBox.Text == 'PLCNUMBER')
{
PLCcomboBox.Visible = true;
NUMBERlabe6.Text = '数据类型:';
}
else
{
PLCcomboBox.Visible = false;
NUMBERlabe6.Text = 'DB号:';
}
}
private void button6_Click(object sender, EventArgs e)
{
xieru();
}
private void xieru()
{
if (LJzhuangtia != false)
{
try
{
switch (WirtcomboBox.Text)
{
case 'BOOL':
myPLC.Write('DB' + WDBtextBox.Text + '.DBX' + WADDtextBox.Text, Convert.ToBoolean( BoolcomboBox.Text));
WirtrichTextBo.Text += '【' + DateTime.Now + '】' + 'DB' + WDBtextBox.Text +'.DBX'+ WADDtextBox.Text + '写入:' + BoolcomboBox.Text+'\r\n';
break;
case 'BYTE':
myPLC.Write('DB' + WDBtextBox.Text + '.DBB' + WADDtextBox.Text, Convert.ToByte(wirtnumber.Text));
WirtrichTextBo.Text += '【' + DateTime.Now + '】' + 'DB' + WDBtextBox.Text + '.DBB' + WADDtextBox.Text + '写入:' + wirtnumber.Text + '\r\n';
break;
case 'READ':
//float numuint = (Convert.ToUInt32( wirtnumber.Text)).ConvertToFloat();
float numfloat = (float)Convert.ToDouble(wirtnumber.Text);
myPLC.Write('DB' + WDBtextBox.Text + '.DBD' + WADDtextBox.Text, numfloat);
WirtrichTextBo.Text += '【' + DateTime.Now + '】' + 'DB' + WDBtextBox.Text + '.DBD' + WADDtextBox.Text + '写入:' + wirtnumber.Text + '\r\n';
break;
case 'INT':
myPLC.Write('DB' + WDBtextBox.Text + '.DBW' + WADDtextBox.Text, Convert.ToInt16(wirtnumber.Text));
WirtrichTextBo.Text += '【' + DateTime.Now + '】' + 'DB' + WDBtextBox.Text + '.DBW' + WADDtextBox.Text + '写入:' + wirtnumber.Text + '\r\n';
break;
case 'DNIT':
myPLC.Write('DB' + WDBtextBox.Text + '.DBD' + WADDtextBox.Text, Convert.ToInt32(wirtnumber.Text));
WirtrichTextBo.Text += '【' + DateTime.Now + '】' + 'DB' + WDBtextBox.Text + '.DBD' + WADDtextBox.Text + '写入:' + wirtnumber.Text + '\r\n';
break;
case 'WORD':
myPLC.Write('DB' + WDBtextBox.Text + '.DBW' + WADDtextBox.Text, Convert.ToInt16(wirtnumber.Text));
WirtrichTextBo.Text += '【' + DateTime.Now + '】' + 'DB' + WDBtextBox.Text + '.DBW' + WADDtextBox.Text + '写入:' + wirtnumber.Text + '\r\n';
break;
case 'DWORD':
myPLC.Write('DB' + WDBtextBox.Text + '.DBD' + WADDtextBox.Text, Convert.ToInt32(wirtnumber.Text));
WirtrichTextBo.Text += '【' + DateTime.Now + '】' + 'DB' + WDBtextBox.Text + '.DBD' + WADDtextBox.Text + '写入:' + wirtnumber.Text + '\r\n';
break;
case 'STRING':
//S7String读取
break;
case 'PLCNUMBER':
PLCwirt();
break;
}
}
catch (Exception)
{
return;
}
}
else
{
MessageBox.Show('请先连接PLC', '提示');
}
}
private void PLCwirt()
{
if (sint2 == 1)
{
myPLC.Write(PLCwitbox.Text+ WADDtextBox.Text, Convert.ToBoolean(BoolcomboBox.Text));
WirtrichTextBo.Text += '【' + DateTime.Now + '】' + PLCwitbox.Text + WADDtextBox.Text + '写入:' + BoolcomboBox.Text + '\r\n';
}
if (sint2== 2)
{
myPLC.Write(PLCwitbox.Text + WADDtextBox.Text, Convert.ToByte(wirtnumber.Text));
WirtrichTextBo.Text += '【' + DateTime.Now + '】' + PLCwitbox.Text + WADDtextBox.Text + '写入:' + wirtnumber.Text + '\r\n';
}
if (sint2 == 3)
{
myPLC.Write(PLCwitbox.Text + WADDtextBox.Text, Convert.ToInt16(wirtnumber.Text));
WirtrichTextBo.Text += '【' + DateTime.Now + '】' + PLCwitbox.Text + WADDtextBox.Text + '写入:' + wirtnumber.Text + '\r\n';
}
}
private void WDBtextBox_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void WirtcomboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(WirtcomboBox.Text=='BOOL')
{
BoolcomboBox.Visible = true;
wirtnumber.Visible= false;
}
else
{
BoolcomboBox.Visible = false;
wirtnumber.Visible = true;
}
if(WirtcomboBox.Text == 'PLCNUMBER')
{
PLCwitbox.Visible = true;
}
else
{
PLCwitbox.Visible = false;
}
}
private void PLCwitbox_SelectedIndexChanged_1(object sender, EventArgs e)
{
switch (PLCwitbox.Text)
{
case 'I':
sint2 = 1;
break;
case 'Q':
sint2 = 1;
break;
case 'M':
sint2 = 1;
break;
case 'IB':
sint2 = 2;
break;
case 'QB':
sint2 = 2;
break;
case 'MB':
sint2 = 2;
break;
case 'IW':
sint2 = 3;
break;
case 'QW':
sint2 = 3;
break;
case 'MW':
sint2 = 3;
break;
}
if(sint2==1)
{
BoolcomboBox.Visible = true;
wirtnumber.Visible = false;
}
else
{
BoolcomboBox.Visible = false;
wirtnumber.Visible = true;
}
}
private void groupBox5_Enter(object sender, EventArgs e)
{
}
bool b;
private void button7_Click(object sender, EventArgs e)
{
if (b != true&LJzhuangtia==true)
{
timer2.Enabled = true;
button7.Text = '写入中…';
b = true;
}
else
{
timer2.Enabled = false;
b = false;
button7.Text = '连续写入';
}
}
private void timer2_Tick(object sender, EventArgs e)
{
xieru();
}
private void button8_Click(object sender, EventArgs e)
{
WirtrichTextBo.Text = '';
}
private void WirtrichTextBo_TextChanged(object sender, EventArgs e)
{
WirtrichTextBo.SelectionStart = WirtrichTextBo.Text.Length;
WirtrichTextBo.ScrollToCaret();
}
}
}
联系客服