当前位置:网站首页>C # use Siemens S7 protocol to read and write PLC DB block
C # use Siemens S7 protocol to read and write PLC DB block
2022-07-07 04:21:00 【Little girl】
- Teach people to use C# How to read and write Siemens conveniently and quickly DB The value of the block , Realize the upper computer and plc The process of communication
- Siemens used PLC model ,S7 1200
1.Nuget install s7 Drive pack

2. Siemens plc Define a db block , This is what our upper computer needs to read and write DB

3. According to Siemens S7 Protocol documentation
Read DB There are many ways to block , Directly according to the DB It is also OK to read and write with an offset of , But reading or writing data requires corresponding data type conversion to finally get the value or write it , I think it's too much trouble . But documentation also provides a simpler way , Is the way of reading and writing .
3.1 The principle of reading and writing class , It is processed by reflection , But we don't need to care about how it reflects , We only care about how we use .
3.2 First , You need to create a class , With Siemens DB block Entity classes with the same name
Siemens plc The establishment of a DB Block name

C# Establish corresponding db Class attribute of block name

4. Class creation is complete , We read and write data through interfaces
There are two kinds of interface definitions , Common interfaces and generic interfaces . The differences and benefits of using generic interfaces and common interfaces will be introduced later
4.1 Implementation of common interface
according to s7 file , Provides ReadClass Read method . There are many ways to provide reading , We only introduce one way , Is to pass in the established entity class . Other self research and implementation .
public void ReadClass(object sourceClass, int db, int startByteAdr = 0)
- sourceClass Class instances of assigned values
- db Data blocks
- startByteAdr Read the starting address of the font
4.2 After we know the passed in parameters of this method , Next, you need to define the methods of the interface .

Why should we define to return an entity , Because when we read data , You need to pass in an entity , After reading ,Plc Of Db The value of the block will be reflected in this entity , We get the latest read value through this entity . Next, we implement this interface method .

1. The above implementation , It is equivalent to the following way of writing .
CathodeEntity testClass = new CathodeEntity(); plc.ReadClass(testClass, 5);It's just , In order to prevent every call, I will re new One CathodeEntity class . I'll just put this CathodeEntity Class is designed into singleton mode . Only instantiate once forever , All we need to change is the attribute value of this class . hinder 5, The meaning is what we want to read DB block 5
2. Single column instance class CathodeEntity
public class CathodeEntity { public bool CathodeUp { get; set; } public bool EntryAllowed { get; set; } public bool LeaveAllowed { get; set; } // Define a static variable to hold an instance of the class private static CathodeEntity uniqueInstance; // Define an identity to ensure thread synchronization private static readonly object locker = new object(); // Define private constructors , Make it impossible for the outside world to create such an instance private CathodeEntity() { } /// <summary> /// Defining a public method provides a global access point , You can also define public properties to provide global access points /// </summary> /// <returns></returns> public static CathodeEntity GetInstance() { // When the first thread runs here , It will be right at this time locker object " Lock ", // When the second thread runs the method , First detected locker The object is " Lock " state , The thread will hang waiting for the first thread to unlock // lock After the statement runs ( After the thread runs ) To the object " Unlock " if (uniqueInstance == null) { lock (locker) { // If an instance of the class does not exist, create , Otherwise go straight back to if (uniqueInstance == null) { uniqueInstance = new CathodeEntity(); } } } return uniqueInstance; } }3. Singleton design pattern Reference resources
4.3 Next , Call the interface , You can get plc The value of the .

The read value is similar to Siemens PLC DB5 The value of is the same 
5. The above is the implementation of ordinary interfaces , But if we are multiple db block , According to the routine, do you have to write N Implementation methods , This is not easy to maintain , A lot of code . So we design the interface as a generic implementation .
Why can we design generics , According to this s7 agreement , Methods of reading classes , The first parameter is object type , It can also be a specific instance type .
5.1 We need to set the interface constraint type . Why do this , The class that we want to implement this interface , Stipulate this T type , You can't pass int or string etc. , You must pass a class to it . This prevents , When the interface is implemented , You passed the wrong parameter .
5.2 next , We implement this generic interface , So this t, We can change it to , We follow Plc Defined data block , Establish the corresponding entity class .
for example , At present Plc There is one db block 5, We establish the corresponding entity attribute class name is CathodeEntity, When we call, we pass CathodeEntity Entities come in . If plc There are many. db block , We also need to have multiple corresponding entity classes . At this time, we can pass in different entity classes , Coming back is plc Specifically db The value of the block .
Implementation interface

5.3 Call interface . Instantiate first CathodeEntity Entity class , hold CathodeEntity Pass in , What you get is the corresponding Db block 5 Value . If it's something else Db block , We need to establish a relationship with plc db The entity class corresponding to the block name , And then again CathodeEntity Instead, create a new class to read . In this way, the interface method reuse is realized .

6. Interface call specific implementation .

6.1 Plc Connection class , Because I only need to instantiate it once , So we should also design it into a singleton mode
/// <summary>
/// Positive buffer rack plc
/// </summary>
internal class CathodeBufferRack
{
// Define static variables to save instances
public static volatile Plc CathodePlc;
// Define an identity to ensure thread synchronization
private static object lockHelper = new object();
// Define private variables , So that the external cannot create instances of this class
private CathodeBufferRack()
{
}
public static Plc Instance(string DeviceIp)
{
if(CathodePlc == null)
{
lock (lockHelper)
{
if (CathodePlc == null)
{
CathodePlc = new Plc(CpuType.S71200, DeviceIp, 0,1);
CathodePlc.Open();
if (!CathodePlc.IsConnected)
{
CathodePlc.Close();
CathodePlc = null;
}
}
}
}
return CathodePlc;
}
}7. Write plc db The same is true .
7.1 Define the interface method written

7.2 Implementation interface method
7.3 Program call

7.4 LeaveAllowed The entity is changed to true after , Pass in .plc The driver automatically reflects , Put the corresponding entity plc db The value of the block is updated directly . In this way, there is no need to operate reading and writing through offset db Block. .

If db There are different types of blocks , for example byte ,Int ,DInt , etc. , Same thing , Just create the corresponding data type .
7.5 PLC And C# Common data type conversion
| PLC | C# |
| Bool | Bool |
| Word | ushort |
| Int | ushort |
| Dword | uint32 |
| Dint | uint |
| byte | byte |
| Real | bouble |
Refer to Official website
8. Comparison between ordinary interface and generic interface .
8.1 As shown in the following example , After the ordinary interface is fixed and the entity parameters are passed in , It can only stipulate that you transfer CathodeEntity Entity class object .
Common interface methods :
But if , We are going to read the same plc, Different db block , Is this method not applicable . Then we have to redefine an interface method , Only the class parameters are different .
but plc.WriteClass() This method is suitable for writing different db The block , It is determined by the passed in parameters that it wants to write db block . So repeat the interface implementation like this , Increase the amount of code and it is not easy to maintain .
therefore , We should learn to analyze and conceive code .
1. First , Have to analyze this plc.WriteClass() What types of parameters can be accepted . Its first parameter is object type , Is any kind of data type .( Yes, of course , Any type of this is limited , Because it is plc The method of writing classes provided by the driver , Its arbitrary data type can only be limited to classes ), That is to say, you can pass different classes to it
2. Then we know that it accepts data types , Next, whether to test the design and implementation of the filter interface . Because it stipulates , Only any class type , That is , It can't accept int or string Type . So we define a generic interface to constrain this generic interface type . Implementation of generic interface , Only class objects can be passed in , It can't be anything else .
3. So generic interface implementation , Pass in a obj
4. Then when the interface is called , What to pass on , What is the corresponding generic
summary : This reduces the amount of code , Easy to maintain .
Let's do it first , Understand the likes collection , In case you can't find it that day .
边栏推荐
- 使用Thread类和Runnable接口实现多线程的区别
- Dab-detr: dynamic anchor boxes are better queries for Detr translation
- Enter the rough outline of the URL question (continuously updated)
- Golang calculates constellations and signs based on birthdays
- True global ventures' newly established $146million follow-up fund was closed, of which the general partner subscribed $62million to invest in Web3 winners in the later stage
- [team learning] [34 sessions] Alibaba cloud Tianchi online programming training camp
- Highly paid programmers & interview questions. Are you familiar with the redis cluster principle of series 120? How to ensure the high availability of redis (Part 1)?
- Allow public connections to local Ruby on Rails Development Server
- Leetcode: interview question 17.24 Maximum cumulative sum of submatrix (to be studied)
- SSM+JSP实现企业管理系统(OA管理系统源码+数据库+文档+PPT)
猜你喜欢

机械臂速成小指南(十):可达工作空间

C#使用西门子S7 协议读写PLC DB块

DAB-DETR: DYNAMIC ANCHOR BOXES ARE BETTER QUERIES FOR DETR翻译

【自动化经验谈】自动化测试成长之路

idea gradle lombok 报错集锦

Antd Comment 递归循环评论

ABAP 动态内表分组循环

硬件开发笔记(十): 硬件开发基本流程,制作一个USB转RS232的模块(九):创建CH340G/MAX232封装库sop-16并关联原理图元器件

Mysql-数据丢失,分析binlog日志文件

Operational amplifier application summary 1
随机推荐
【编码字体系列】OpenDyslexic字体
Mongo shell, the most complete mongodb in history
True Global Ventures新成立的1.46亿美元后续基金关账,其中普通合伙人认缴6,200万美元以对后期阶段的Web3赢家进行投资
使用 TiDB Lightning 恢复 GCS 上的备份数据
使用 BR 恢复 GCS 上的备份数据
[record of question brushing] 2 Add two numbers
Win11远程桌面连接怎么打开?Win11远程桌面连接的五种方法
什么是 CGI,什么是 IIS,什么是VPS「建议收藏」
[ArcGIS tutorial] thematic map production - population density distribution map - population density analysis
cuda编程
【knife-4j 快速搭建swagger】
Implementation of map and set
别样肉客联手德克士在全国部分门店推出别样汉堡
【OA】Excel 文档生成器: Openpyxl 模块
[multi threading exercise] write a multi threading example of the producer consumer model.
Tflite model transformation and quantification
PHP implements lottery according to probability
Binary, octal, hexadecimal
Some thoughts on cross end development of kbone and applet
leetcode 53. Maximum Subarray 最大子数组和(中等)

But if , We are going to read the same plc, Different db block , Is this method not applicable . Then we have to redefine an interface method , Only the class parameters are different .



summary : This reduces the amount of code , Easy to maintain .