VisualStudio2010-C#跟西门子1200(Sharp7)-简单上位机界面②-按钮
上期回顾(上期主要是新建项目,然后创建窗体程序,添加sharp7的类库,先建立了几个按钮启动,停止,复位,清零)
本期就要开始对这几个基本操作按钮赋予功能了
1.0 双击button按钮启动,生成按钮代码,正常事这样写的,建立通讯,新建缓冲区,然后设置目标数据格式,发送,源代码如下:
private void button1_Click(object sender, EventArgs e)
{
var client = new S7Client();//建立通讯
client.ConnectTo("192.168.0.1", 0, 1);//接受来次通讯的结果
var writeBuffer = new byte[1];//新建一个字节的writeBuffer输出缓冲区,
S7.SetBitAt(ref writeBuffer, 0, 0, true);
//输出给PLC的DB数据块1,从地址0开始的,一个字节的传输
int writeReswlt = client.DBWrite(1, 14, writeBuffer.Length, writeBuffer);
client.Disconnect();//断开
}
2.0 停止,清零,复位按钮的代码写法更这个也差不多,就是要注意PLC的DB块地址,其他都差不多,具体代码如下
//停止A按钮
private void button2_Click(object sender, EventArgs e)
{
//var client = new S7Client();//建立通讯
//client.ConnectTo("192.168.0.1", 0, 1);//接受来次通讯的结果
//var writeBuffer = new byte[1];//新建一个字节的writeBuffer输出缓冲区,
//S7.SetBitAt(ref writeBuffer, 0, 1, true);
//输出给PLC的DB数据块1,从地址0开始的,一个字节的传输
//int writeReswlt = client.DBWrite(1, 14, writeBuffer.Length, writeBuffer);
//client.Disconnect();//断开
}
//复位A按钮
private void button3_Click(object sender, EventArgs e)
{
//var client = new S7Client();//建立通讯
//client.ConnectTo("192.168.0.1", 0, 1);//接受来次通讯的结果
//var writeBuffer = new byte[1];//新建一个字节的writeBuffer输出缓冲区,
//S7.SetBitAt(ref writeBuffer, 0, 2, true);
//输出给PLC的DB数据块1,从地址0开始的,一个字节的传输
//int writeReswlt = client.DBWrite(1, 14, writeBuffer.Length, writeBuffer);
//client.Disconnect();//断开
}
//清零A按钮
private void button4_Click(object sender, EventArgs e)
{
//var client = new S7Client();//建立通讯
//client.ConnectTo("192.168.0.1", 0, 1);//接受来次通讯的结果
//var writeBuffer = new byte[1];//新建一个字节的writeBuffer输出缓冲区,
//S7.SetBitAt(ref writeBuffer, 0, 0, true);
//输出给PLC的DB数据块1,从地址0开始的,一个字节的传输
//int writeReswlt = client.DBWrite(1, 24, writeBuffer.Length, writeBuffer);
//timer2.Start();
//client.Disconnect();//断开
}
3.0 保存,按F5调试,结果应该是PLC那边受到控制,但是有没有感觉代码很臃肿,可读性太差,下期教你个简单点的办法
,