This documentation is out of date.

The new version of the documentation is here: https://cannylogic.com/docs

Difference between revisions of "CFD Language"

From CANNY Wiki
Jump to: navigation, search
[unchecked revision][unchecked revision]
(Сеть)
(Network)
Line 40: Line 40:
  
 
In programming languages terms, the network is "variable", data storage place. The function block at the end of the calculations, writes its output value in the network, then  functional blocks whose inputs connected to this network after it are read from the network stored in it value and use it in their calculations as input values.
 
In programming languages terms, the network is "variable", data storage place. The function block at the end of the calculations, writes its output value in the network, then  functional blocks whose inputs connected to this network after it are read from the network stored in it value and use it in their calculations as input values.
Along with the use of anonymous networks, in CannyLab, networks can assign names to be displayed on the diagram.Logically unified network, for which a name is assigned, it is possible to separate into several visually unrelated segments for easier composition. For example, two segments of "Tyre pressure, kPa" in the figure below represent the same network, and have the same value at each point in time, though not visually connected.
+
Along with the use of anonymous networks, in CannyLab, networks can assign names to be displayed on the diagram.Logically unified network, for which a name is assigned, it is possible to separate into several visually unrelated segments for easier composition. For example, two segments of "Tyre pressure, kPa" (on the figure below) represent the same network, and have the same value at each point in time, though not visually connected.
  
 
[[File:3_3_1.png]]
 
[[File:3_3_1.png]]

Revision as of 06:01, 15 February 2016

In Canny Lab IDE used programming language-Canny Function Diagram (CFD), to program Canny 7 controller. During its development, the goal was set to create a tool which best suits the capabilities of the controller, and at the same time close enough to the industry standard. Function Block Diagram (FBD) Language is taken as the basis for the development of the CFD. It is perhaps one of the most balanced among the five languages approved by the International Electrotechnical Commission to create user programs for PLC within IEC 61131-3 standard.

As a graphical programming language, CFD has a high clarity comparable to wiring diagrams, but is at a higher level of abstraction, which allows to hide irrelevant implementation details.

Functional Diagram

The program in CFD language , represents as a draught (scheme), depicting the functional blocks, linking to one another with connecting lines (network), and support elements, called functional diagram.

The program implementation in CFD language can be described as successively, usually from the left to the right, calculation of each functional block, with the result transferring to the next associated function block. Such algorithms will be called a thread of execution.

3 1 1.png

Presentation of the program in this way makes it easy to trace the process of its implementation, just looking at the picture, moving eyes from block to block on the trunk.

In CFD language, the relative position of the blocks in the acyclic diagram does not affect their execution order. Functional blocks order of execution of such a diagram is automatically calculated by the following rule: each functional block is executed when all its inputs are calculated.

In determining the order of execution of the cyclic, that is, having a feedback diagram, functional blocks involved in the feedback loop executed in such order, that latest is executed the function block located to the right of all other blocks involved in the cycle.

3 1 2.png

Functional Block

The function block is a graphical element in the functional diagram indicating the function, algorithm or mathematical expression,produces calculation of its output data depending on the input data received from the outside. On the function block image, its inputs disposed on the left and outputs on the right .

3 2 1.png

Стандартная библиотека функциональных блоков языка CFD includes both simple blocks that perform basic logic transformation on their input data - such AND, OR, NOT, and more complex function: triggers, generators, switches.

Function block depending on its type, may have several inputs and several outputs, for computing can use its own memory as well as access the controller operating system resources, such as timers and use the data in its calculations of output values.

3 2 2.png

In CannyLab environment, sources of input data for a function block can be functional blocks of whose output is bound with connecting lines (networks), numeric constants entered by the user or selected from the directory or date from controller service memory registers.

Any function block input or output can be inverted. In the case of an input inversion, as input data to function block will be given a value that results from the operation of "Logical NOT" on actual input data. In case of output inversion, "Logical NOT" operation will be applied to the data before sending the calculation result of the function block to its "out".

Network

The line connecting data source to one or more recipients of the data on the functional diagram, is called a network. In CFD language, the data source is usually the output of a function block, a recipient is an input of another function block. In CFD language any network can have only one data source.

In programming languages terms, the network is "variable", data storage place. The function block at the end of the calculations, writes its output value in the network, then functional blocks whose inputs connected to this network after it are read from the network stored in it value and use it in their calculations as input values. Along with the use of anonymous networks, in CannyLab, networks can assign names to be displayed on the diagram.Logically unified network, for which a name is assigned, it is possible to separate into several visually unrelated segments for easier composition. For example, two segments of "Tyre pressure, kPa" (on the figure below) represent the same network, and have the same value at each point in time, though not visually connected.

3 3 1.png

Data

В языке CFD, все использующиеся данные являются 16-битными целыми неотрицательными числами в диапазоне от 0 до 65535. Результатом арифметических операций будет числовое значение из указанного диапазона, а результаты логических операций представляются значениями «1» (истина) и «0» (ложь).

При выполнении функциональной диаграммы, там где это необходимо, преобразование данных от логического типа к числовым данным и обратно выполняется автоматически по следующим правилам:

  • При преобразовании числа к логическому значению, ноль преобразуется в значение «ложь», любое число отличное от нуля – в значение «истина».
  • В арифметических операциях логические значения «ложь» и «истина» представляются как числа 0 и 1 соответственно.
  • Инверсия на входе или выходе любого блока, автоматически преобразует его данные к логическому типу.

3 4 1.png

Результаты арифметических операций берутся по модулю 65535. Это означает, что если результат операции превысил 65535, то из него автоматически вычитается 65536. А если результат оказался меньше нуля, то к нему прибавляется 65535 и еще единица.

Например: 65535 + 1 = 0   1 – 2 = 65535
65535 + 2 = 1   1 – 3 = 65534
65500 + 122 = 86   117 – 259 = 65294

Управление ресурсами контроллера

Для того, чтобы разработанная пользователем функциональная диаграмма могла использовать данные физических входов контроллера и изменять состояние его физических выходов, получать и передавать данные по интерфейсам передачи данных, или хотя бы просто изменять состояние встроенного светодиода контроллера, диаграмму и ресурсы контроллера необходимо связать между собой.

В контроллере CANNY7 доступ к аппаратным ресурсам из пользовательского приложения, реализован в форме чтения и записи данных по определенным адресам (регистрам) отображающим состояние этих ресурсов.

Ресурсы контроллера требуют определенного порядка доступа. Например, в самом простом случае, чтобы включить встроенный светодиод контроллера, достаточно передать по определенному адресу «1», а чтобы выключить «0». Но уже для того, чтобы использовать универсальный внешний канал контроллера для управления реле, его необходимо предварительно его инициализировать, записав значение требуемого режима его работы в адрес его конфигурации. Лишь после этого появляется возможность, устанавливая «1», или «0» в адрес выходного значения канала, управлять электрическим потенциалом данного канала контроллера.

Так будет выглядеть приведенная ранее диаграмма управления светофором железнодорожного переезда, после привязки к ресурсам контроллера. Такая диаграмма уже полностью пригодна для записи в ПЛК и управления реальным оборудованием.

3 5 1.png

Список адресов всех доступных пользователю ресурсов контроллера находится в справочнике адресов CannyLab, который доступен пользователю через контекстное меню при назначении входов и выходов типа «Адрес» функциональных блоков.

Конфигурация определенных ресурсов контроллера требует использования специальных констант, все они поименованы и собраны в списке констант CannyLab, который доступен пользователю при назначении входов типа «Константа» функциональных блоков.

Подробное описание ресурсов CANNY 7 и порядка доступа к ним, рассматривается в справочном руководстве по контроллеру.