This documentation is out of date.

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

CANNY 7, System Registers

From CANNY Wiki
Revision as of 07:24, 10 December 2015 by MEGA (Talk | contribs) (Hibernation)


Jump to: navigation, search

General description

System resources are divided into an address group of read registers and an address group of write registers. Referring to the given registers from the functional diagram, you can get demanding information for practical application about the current status of the controller, and control its operation mode. The list of system resources registers located in the "State of the controller" addresses directory CannyLab, which is available to the user via IO context menu "Address" type of the function blocks.

Reset controller

Reset controller occurs as a result of any of the three events: when power up the controller, with the soft reset from the functional diagram or on command by Watchdog. The controller is initialized after reset: the entire memory contents is cleared, input-output channels are resets to a neutral state, system software drivers are transferred to the initial state, power consumption is set to normal, a functional diagram execution starts from the beginning. The non-volatile memory content does not change at reset.

Information that reset occurred is available by accessing the address "Power On Detect Register"

Address Return Values
Power On Detect Register
1 = the current execution cycle is the first one, since a soft reset or restored power
0 = the current execution cycle is not the first one, since a soft reset or restored power

Forced reset of the controller is performed by writing a nonzero value to "Reset Register" address. In this case, the controller reset takes place immediately after the end of the execution cycle of functional diagram, in which there was such a record.

Address Expected values
Reset Register
1...65535 = start a forced controller reset
0 = value is ignored


Built-in LED

The controller has a built-in bi-color (green/red) LED. The functional diagram controls switching-on of which each color by writing specific values into the appropriate registers.

Address Expected values
Green LED On/Off Register
1...65535 = turn-on built-in Green LED
0 = turn-off built-in Green LED
Red LED On/Off Register
1...65535 = turn-on built-in Red LED
0 = turn-off built-in Red LED
Note: Turning the LED simultaneously in both colors is not designed, so if functional diagram set simultaneous switching on of Red and Green LEDs, the LED turns green only (green priority).

A functional diagram fragment, which turns-on built-in Red LED for one second after each controller reset.

6 5 3 1.png


Hibernation

After reset the controller starts working in normal power consumption, functional diagram is executed continuously. Transition to Hibernation Mode carried out by command of functional diagram, recording a non-zero value to "Sleep Mode Enable Register". Transition to the Sleep Mode takes place immediately after the end of functional diagram execution cycle, in which such recording was made, in the absence of conditions that impede this transition.

The duration of "sleep" phase can be set from the functional diagram by writing a value to the address "Sleep Mode Time Scale Register". By default, if the functional diagram has no entry in the corresponding register, the "sleep" phase of hibernation mode lasting 1000ms. This means that while controller in low power mode, in the absence of conditions for transition to the normal power, the controller makes a pause of 1 second after each execution cycle of functional diagram.


Address Expected values
Sleep Mode Enable Register
1...65535 = go into low power mode
0 = return to normal power mode
Sleep Mode Time Scale Register
0...65535 = duration of "sleep" phase in milliseconds after each execution cycle of functional diagrams

Return controller to normal power is either forced: immediately after the end of the execution cycle of functional diagrams, during which it was written "0" at "Sleep Mode Enable Register", either automatically by any of the following events:

  • with changing of the electric potential in any terminal with the appropriate controller channel, configured as an active input or pulse counter;
  • when enabled from the functional diagram of any of the drivers CAN, LIN, UART/RS232, IR or Elita GSW with changing of the electric potential on the corresponding drivers' terminal.

Information on the current power mode is available when accessing the address "Sleep Mode Control Register"

Address Return Values
Sleep Mode Control Register
1 = controller is in Sleep Mode
0 = controller is in Normal Mode
Note: When creating a functional diagram used low-power mode should be considered a side effect brought by the change in the time scale. The effect manifests itself in that functional blocks increment time: delay start, stop and PWM generators in a low power mode occurs in leaps and bounds according to the time actually spent in the phase of "sleep" (default 1000 ms increments).

A fragment of a functional diagram, with typical low-power mode control: transition to the low power mode in the absence within 10 seconds conditions preventing it and automatic return to normal mode doe to controller periphery activity or set ban to "sleep" from the diagram:

6 5 4 1.png
Note: Inversion of the output of the function block №4.

Сторожевой таймер

Для исключения вхождения контроллера в бесконечный цикл вне функциональной диаграммы, что может произойти в случае его неправильного подключения или ошибок в системном программном обеспечении, предусмотрен сторожевой таймер - Watch Dog Timer (WDT).

В интегрированной среде разработки CannyLab, до версии 1.4, пользователь мог управлять работой сторожевого таймера: включать или выключать его, устанавливать его период.

Начиная с CannyLab версии 1.4, пользователь не имеет доступа к управлению WDT. Сторожевой таймер включен постоянно и его период составляет 1...2 секунды.

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

Фактическое время выполнения функциональной диаграммы

Время, требующееся контроллеру для выполнения функциональной диаграммы в реальных условиях эксплуатации зависит от числа и типов функциональных блоков присутствующих на диаграмме, числа задействованных драйверов входящих в состав системного программного обеспечения и их активности. На практике, цикл выполнения диаграммы CANNY 7 содержащей около 400 функциональных блоков и активно взаимодействующей с драйвером CAN продолжается приблизительно 9 мс.

Примечание: При создании функциональной диаграммы, следует учитывать эффект привносимый продолжительностью её цикла. Эффект выражается в том, что приращение счетчиков времени функциональных блоков: задержек включения, выключения и генераторов ШИМ происходит скачкообразно. Так, при фактической длительности цикла в равной 6 мс, фактический период всех генераторов ШИМ на диаграмме будет кратен 6 мс.

Информация о продолжительности предыдущего цикла выполнения функциональной диаграммы контроллера доступна по адресу «Регистр контроля длительности программного цикла».

Адрес Возвращаемые значения
Регистр контроля длительности программного цикла, мс
0...65535 = продолжительность предыдущего полного цикла выполнения функциональной диаграммы в целых долях миллисекунд.
Примечание: Наиболее точным способом измерения общего времени работы контроллера, например при реализации часов, является суммирование с накоплением значений получаемых по адресу «Регистр контроля длительности программного цикла» в ходе каждого цикла выполнения функциональной диаграммы.

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

6 5 6 1.png

Идентификатор устройства

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

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

Адрес Возвращаемые значения
Регистр идентификатора устройства D1:D0
0...65535 = значение двух младших байт (D1 и D0) индивидуального идентификационного номера контроллера;
Регистр идентификатора устройства D3:D2
0...65535 = значение двух младших байт (D3 и D2) индивидуального идентификационного номера контроллера.


В процессе разработки пользовательской диаграммы, из CannyLab, идентификатор устройства можно узнать обратившись к информации об устройстве, доступной в пункте «Устройство» → «Информация» главного меню программы или по нажатию кнопки «Информация» панели инструментов, где он представлен в виде 4х байтового (32-битного) числа, с расположением старшего байта слева.

Например, идентификатор 0x563B8693 будет представлен так: регистр идентификатора устройства D1:D0 равен 0x8693, регистр идентификатора устройства D3:D2 равен 0x563B.

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

6 5 7 1.png

Смотри также

CANNY 7