Loading

西门子PLC S7-200接编码器开发

最近需要在电子秤上面接编码器,通过一定周期内转速变化大小来判断机台加减速还是匀速状态。

一、硬件接线

image

二、PLC梯形图程序

image

梯形图程序编写好之后,就可以上传到PLC,让PLC处于Run状态就好了。

三、上位机程序

  1. C#版上位机程序
    通过nuget包搜索Sharp7开发包进行安装,然后就可以通过如下代码获取PLC的高速计数器的值。
     S7Client client = new S7Client();
     client.SetConnectionType(3);
     int connectionResult = client.ConnectTo("10.10.30.59", 0, 1);
     if (connectionResult == 0) //连接成功
     {
         MessageBox.Show("PLC连接成功");
     } 
     var buffer = new byte[4];
     int readResult = client.DBRead(1, 1, buffer.Length, buffer);
     if (readResult == 0)
     {
         ushort value0 = (ushort)buffer[0];
         ushort value1 = (ushort)buffer[1];
         ushort value2 = (ushort)buffer[2];
         ushort value3 = (ushort)buffer[3];
     }
     client.Disconnect();
    
  2. Java版上位机程序
    Java连接西门子PLC可以通过s7connector开源项目连接。
    github地址:https://github.com/s7connector/s7connector/ , 下载下来之后将源码拷贝到项目中或者通过maven安装jar包均可。
    S7Connector connector = S7ConnectorFactory
                        .buildTCPConnector()
                        .withHost("10.10.30.59")
                        .withPort(102)
                        .withType(3)
                        .withRack(0)
                        .withSlot(1)
                        .build();
    
    byte[] buffer = connector.read(DaveArea.DB, 1, 4, 1);
    int value0 = buffer[0]&0xFF; //0xFF是为了将负数转为无符号整数
    int value1 = buffer[1]&0xFF;
    int value2 = buffer[2]&0xFF;
    int value3 = buffer[3]&0xFF;
    
    connector.close();
    
posted @ 2025-05-25 18:26  guwei4037  阅读(118)  评论(0)    收藏  举报