Bool to word tia

0 / 0 / 0

Регистрация: 08.06.2017

Сообщений: 2

1

08.06.2017, 13:28. Показов 4858. Ответов 2


Студворк — интернет-сервис помощи студентам

Доброго времени суток. Требуется преобразовать массив из 15и элементов bool в переменную типа word.



0



Почетный модератор

Эксперт по компьютерным сетямЭксперт Windows

28040 / 15771 / 981

Регистрация: 15.09.2009

Сообщений: 67,752

Записей в блоге: 78

08.06.2017, 20:39

2



0



0 / 0 / 0

Регистрация: 08.06.2017

Сообщений: 2

21.06.2017, 20:14

 [ТС]

3

Нашел решение, оказалось крайне просто:

Код

STATUS[0..15]:Bool
W1, W2:word

W1 := 0;
for I = 0 to 15 do  // Заполняем биты W1 в зависимости от значения элемента массива
if STATUS[I] = true then
W1 := W1 + 2 ^ I;
else
W1 := W1 + 0;
end_for;

W2 := W1; // Присваиваем результат переменной W2, для того что бы значение обновлялось, но не сбрасывалось



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

21.06.2017, 20:14

3

Помогите преобразовать

obok

Любитель
Сообщения: 53
Зарегистрирован: 10 апр 2018, 20:16

Помогите преобразовать

Помогите пожалуйста!
Имеется удаленный модуль с 4 входами, соединяется с контроллером по RS485 через modbus
О замкнутых контактах на входе модуль сообщает Битовой маской значений входов, он присылает число от 0 до 15

где 0 — нет замкнутых контактов, 15 замкнуты все поясняю:

Присылаемое число 1 — замкнут контакт номер 1 что соответствует (в двоичной системе) — 1
Присылаемое число 2 — замкнут контакт номер 2 что соответствует (в двоичной системе) — 10
Присылаемое число 3 — замкнут контакт номер 1 и 2 что соответствует (в двоичной системе) — 11
Присылаемое число 4 — замкнут контакт номер 1 что соответствует (в двоичной системе) -100
Присылаемое число 8 — замкнут контакт номер 1 что соответствует (в двоичной системе) — 1000
…..
Присылаемое число 15 замкнуты все контакты что соответствует (в двоичной системе) — 1111

т.е. кажый контакт соответствует 0 или 1 у входа контакта модуля, и это регистр у двоичного числа
Так вот ….
Помогите как мне из полученного числа «Х» (в десятичной системе) перевести его в двоичную и понять 1 или 0 стоит в соответствующем регистре?

Примерно это должно выглядеть как то так (в SCL):
Вход1:= Взять_регистр 1 ( Преобразовать_в_двоичный код (Х) )
Вход2:= Взять_регистр 2 ( Преобразовать_в_двоичный код (Х) )
Вход3:= Взять_регистр 3 ( Преобразовать_в_двоичный код (Х) )
Вход4:= Взять_регистр 4 ( Преобразовать_в_двоичный код (Х) )

где Вход тип (bool), а у X тип (int)

Пожалуйста помогите как это записать в SCL?


Аватара пользователя

Ka3ax

Специалист
Сообщения: 303
Зарегистрирован: 07 сен 2013, 10:09

Re: Помогите Перобразовать

Сообщение

Ka3ax » 25 сен 2018, 00:44

смутно задача описана.

Вход1:= Взять_регистр 1 ( Преобразовать_в_двоичный код (Х) )

входу присвоить?
и здесь не ясно

Присылаемое число 4 — замкнут контакт номер 1 что соответствует (в двоичной системе) -100
Присылаемое число 8 — замкнут контакт номер 1 что соответствует (в двоичной системе) — 1000

отчего «страдает» всегда первый контакт? ожидаемые контакты 4 и 8
исхожу из

где 0 — нет замкнутых контактов, 15 замкнуты все поясняю:

в scl имеются команды int_to_bool bool_to_word, SHR, SHl
можно двигать и маскировать

Код: Выделить всё

VAR_INPUT
    Input_word:           WORD;
    
END_VAR
VAR
    
    comp_1_in:              INT;
    comp_2_in:              INT;
    temp:       bool;
END_VAR

    BEGIN;
    
    comp_1_in     := Input_word AND w#16#ff;
    comp_2_in := Input_word AND w#16#00ff SHR(in:=Input_word, N:=8); 

или двигать и младший бит считывать

Код: Выделить всё

temp := int_to_bool( SHR(in:=Input_word, N:=8))

или слайс. в TIA

Код: Выделить всё

temp := Input_word.%x1 
temp12 := Input_word.%x11
 

все через case реализовать

ps
пока отвечал. понял, что входящяя переменная int тип.
тогда расскладываем по битам int_to_word и далее один из вышеприведенных принципов.
только вместо
temp := int_to_bool( SHR(in:=Input_word, N:=8))
temp := word_to_bool( SHR(in:=Input_word, N:=8))
извиняйте. засыпаю :)

Supervision of erection


Михайло

Администратор
Сообщения: 4073
Зарегистрирован: 19 сен 2012, 19:16

Re: Помогите преобразовать

Сообщение

Михайло » 25 сен 2018, 06:25

obok писал(а):где Вход тип (bool), а у X тип (int)

Вместо INT используйте тип WORD, INT — для хранения числовых значений, WORD — для наборов отдельных битов (как в вашем случае).

Ну и как написал Ка3ах:
Вход0:= Х.x0;
Вход1:= Х.x1;
Вход2:= Х.x2;
Вход3:= Х.x3;

Вход15:= Х.x15;


obok

Любитель
Сообщения: 53
Зарегистрирован: 10 апр 2018, 20:16

Re: Помогите преобразовать

Сообщение

obok » 25 сен 2018, 08:23

Михайло писал(а):

obok писал(а):где Вход тип (bool), а у X тип (int)

Вместо INT используйте тип WORD, INT — для хранения числовых значений, WORD — для наборов отдельных битов (как в вашем случае).

Ну и как написал Ка3ах:
Вход0:= Х.x0;
Вход1:= Х.x1;
Вход2:= Х.x2;
Вход3:= Х.x3;

Вход15:= Х.x15;

СПАСИБО! То что нужно!

Извините, что смутно описал проблему не знал как это объяснить.


obok

Любитель
Сообщения: 53
Зарегистрирован: 10 апр 2018, 20:16

Re: Помогите преобразовать

Сообщение

obok » 25 сен 2018, 08:38

Еще подскажите как правильно это записать в цикле, я записываю так но у меня компилятор ругается см. картинку

У вас нет необходимых прав для просмотра вложений в этом сообщении.


Аватара пользователя

Ka3ax

Специалист
Сообщения: 303
Зарегистрирован: 07 сен 2013, 10:09

Re: Помогите преобразовать

Сообщение

Ka3ax » 25 сен 2018, 09:00

а никак :D
слайст не работает в цикле, я недавно бегал, сам спрашивал как.
тупо 16 значений прописать и все, что сименс в своих примерах тоже делает.
или через оверлей AT и массив к битам обращаться.
но в Вашем случае проще 1 раз прописать 16 бит

Supervision of erection


obok

Любитель
Сообщения: 53
Зарегистрирован: 10 апр 2018, 20:16

Re: Помогите преобразовать

Сообщение

obok » 25 сен 2018, 12:13

Ka3ax писал(а):а никак :D
слайст не работает в цикле, я недавно бегал, сам спрашивал как.
тупо 16 значений прописать и все, что сименс в своих примерах тоже делает.
или через оверлей AT и массив к битам обращаться.
но в Вашем случае проще 1 раз прописать 16 бит

Спасибо, а то бился не мог понять, что же не правильно пишу и кавычки ставил и скобки, и фигурные скобки …. вобщем не мог я сдаться, а оказалось так просто нельзя))) :wall:


Table 7- 74

Data types for the parameters

Parameter

Data type

IN

Bit string

BCD16, BCD32

OUT

Bit string

BCD16, BCD32

The instruction does not allow you to select Bit strings (Byte, Word, DWord). To enter an operand of data type Byte,

1

Word, or DWord for a parameter of the instruction, select an unsigned integer with the same bit length. For example,

select USInt for a Byte, UInt for a Word, or UDInt for a DWord.

After you select the (convert from) data type, a list of possible conversions is shown in the

(convert to) dropdown list. Conversions from and to BCD16 are restricted to the Int data

type. Conversions from and to BCD32 are restricted to the DInt data type.

Table 7- 75

ENO status

ENO

Description

1

No error

0

IN is +/- INF or +/- NaN

0

Result exceeds valid range for OUT data type

7.7.2

Conversion instructions for SCL

Table 7- 76

Conversion from a Bool, Byte, Word, or DWord

Data type

Instruction

BOOL_TO_BYTE, BOOL_TO_WORD,

Bool

BOOL_TO_DWORD, BOOL_TO_INT,

BOOL_TO_DINT

BYTE_TO_BOOL

Byte

BYTE_TO_WORD, BYTE_TO_DWORD

BYTE_TO_SINT, BYTE_TO_USINT

BYTE_TO_INT, BYTE_TO_UINT,

BYTE_TO_DINT, BYTE_TO_UDINT

WORD_TO_BOOL

Word

WORD_TO_BYTE

WORD_TO_DWORD

S7-1200 Programmable controller

System Manual, 03/2014, A5E02486680-AG

, SInt, USInt, Int, UInt, DInt, UDInt, Real, LReal,

1

, SInt, USInt, Int, UInt, DInt, UDInt, Real, LReal,

1

Description

Input value

Input value converted to a new data type

Result OUT

Valid result

+/- INF or +/- NaN

OUT is set to the IN value

Result

The value is transferred to the least significant bit of the

target data type.

The least significant bit is transferred into the destination

data type.

The value is transferred to the least significant byte of the

target data type.

The value is transferred to the target data type.

The value is transferred to the least significant byte of the

target data type.

The least significant bit is transferred into the destination

data type.

The least significant byte of the source value is

transferred to the target data type

The value is transferred to the least significant word of

the target data type.

Basic instructions

7.7 Conversion operations

245

Old
September 7th, 2009, 02:22 AM

 
#1

Member

Australia

Boxy is offline

 

Boxy's Avatar

 

Join Date: Nov 2008

Location: Sydney

Posts: 56

s7-300 Bool into Word using Indirect Addressing


So far all the code i’ve written for PLC’s has been simple ladder logic and I’m sure this will be simple once i know how.

I have an s7-300 setup with Danfoss Drives connected via profibus. I am trying to construct a function block that i can use for all drives to move bool run/quickstop/ramp/etc to operate the control word.

So far i have tried creating an array of Word stored in the temp area and then within the code referencing the LX.X
then moving this arrayed word to a word stored in the Out area of the declaration.

I have also tried referencing the Out word bools.

Both these only kind of word. When i use the array i end up getting a SF with an error which says area length error when reading.

If i look at the Out word, in the Address info it says theres an error with the format.

Am i doing it all wrong??

 

Reply With Quote

Old
September 7th, 2009, 02:34 AM

 
#2

Member

Australia

Boxy is offline

 

Boxy's Avatar

 

Join Date: Nov 2008

Location: Sydney

Posts: 56

I apologise I have the SF was unrelated to the Array part.
I would still like to know if i have the right approach if i do it via the Array[0..0] of Word way?

 

Reply With Quote

Old
September 7th, 2009, 02:49 AM

 
#3

Lifetime Supporting Member + Moderator

Denmark

JesperMP is offline

 

JesperMP's Avatar

 

Join Date: Feb 2003

Location: ᚴᚬᛒᛅᚾᚼᚬᚠᚾ

Posts: 15,757

Can you describe a bit more how the data to the drive must be formatted, and how you want the data to be formatted in your own code.

__________________
Jesper
NOTICE:
JesperMP has passive-aggressive tendencies, can be impolite and may even use sarcasm !
Also: ᛁᚠ ᚢᚬᚢ ᚴᚬᚾ ᚱᛅᚬᛏ ᚦᛁᛋ ᚦᛅᚾ ᚢᚬᚢ ᚼᚬᚠᛅ ᚴᚬᛁᚾᛅᛏ ᛘᚢ ᚱᛅᛋᛒᛅᚴᛏ

 

Reply With Quote

Old
September 7th, 2009, 03:05 AM

 
#4

Lifetime Supporting Member

United Kingdom

L D[AR2,P#0.0] is offline

 

Join Date: Nov 2006

Location: UK

Posts: 6,512

 

Reply With Quote

Old
September 7th, 2009, 03:20 AM

 
#5

Member

Australia

Boxy is offline

 

Boxy's Avatar

 

Join Date: Nov 2008

Location: Sydney

Posts: 56

The data to the drive has to be sent as a word to the PQW address.

Each bit within that word is a bool function eg(bit 6 high=run low=stop, bit 9 high=ramp 1 selected low=ramp 2 selected, etc) so to run the drive i need to set bit 6 to true.

I was going to create a block with my bool bits coming into the block, and the out of the block be a word. I can do it if i make it all symbols but i thought it might be better to do it in a function block that way i can use it for all 15 drives, so exactly the opposite of what LD[AR2..] posted. Also I’m writing in Ladder as i’ve never had any formal training in STL SCL

 

Reply With Quote

Old
September 7th, 2009, 03:47 AM

 
#6

Lifetime Supporting Member

United Kingdom

L D[AR2,P#0.0] is offline

 

Join Date: Nov 2006

Location: UK

Posts: 6,512

Here’s the reverse function. Note remove the CAW if you do not wish to swap the bytes in the word.

Code:

FUNCTION FC 2 : VOID
TITLE =
VERSION : 0.1

VAR_INPUT
  bBit0 : BOOL ; 
  bBit1 : BOOL ; 
  bBit2 : BOOL ; 
  bBit3 : BOOL ; 
  bBit4 : BOOL ; 
  bBit5 : BOOL ; 
  bBit6 : BOOL ; 
  bBit7 : BOOL ; 
  bBit8 : BOOL ; 
  bBit9 : BOOL ; 
  bBit10 : BOOL ; 
  bBit11 : BOOL ; 
  bBit12 : BOOL ; 
  bBit13 : BOOL ; 
  bBit14 : BOOL ; 
  bBit15 : BOOL ; 
END_VAR
VAR_OUTPUT
  wWord : WORD ; 
END_VAR
VAR_TEMP
  bTempBit0 : BOOL ; 
  bTempBit1 : BOOL ; 
  bTempBit2 : BOOL ; 
  bTempBit3 : BOOL ; 
  bTempBit4 : BOOL ; 
  bTempBit5 : BOOL ; 
  bTempBit6 : BOOL ; 
  bTempBit7 : BOOL ; 
  bTempBit8 : BOOL ; 
  bTempBit9 : BOOL ; 
  bTempBit10 : BOOL ; 
  bTempBit11 : BOOL ; 
  bTempBit12 : BOOL ; 
  bTempBit13 : BOOL ; 
  bTempBit14 : BOOL ; 
  bTempBit15 : BOOL ; 
END_VAR
BEGIN
NETWORK
TITLE =bit to word mapper
      A     #bBit0; 
      =     #bTempBit0; 
      A     #bBit1; 
      =     #bTempBit1; 
      A     #bBit2; 
      =     #bTempBit2; 
      A     #bBit3; 
      =     #bTempBit3; 
      A     #bBit4; 
      =     #bTempBit4; 
      A     #bBit5; 
      =     #bTempBit5; 
      A     #bBit6; 
      =     #bTempBit6; 
      A     #bBit7; 
      =     #bTempBit7; 
      A     #bBit8; 
      =     #bTempBit8; 
      A     #bBit9; 
      =     #bTempBit9; 
      A     #bBit10; 
      =     #bTempBit10; 
      A     #bBit11; 
      =     #bTempBit11; 
      A     #bBit12; 
      =     #bTempBit12; 
      A     #bBit13; 
      =     #bTempBit13; 
      A     #bBit14; 
      =     #bTempBit14; 
      A     #bBit15; 
      =     #bTempBit15; 
      LAR1  P##bTempBit0; 
      L     W [AR1,P#0.0]; 
      CAW   ; 
      T     #wWord; 
      SET   ; 
      SAVE  ; 
END_FUNCTION

 

Reply With Quote

Old
September 7th, 2009, 03:52 AM

 
#7

Lifetime Supporting Member + Moderator

Denmark

JesperMP is offline

 

JesperMP's Avatar

 

Join Date: Feb 2003

Location: ᚴᚬᛒᛅᚾᚼᚬᚠᚾ

Posts: 15,757

With Q addresses it is blisfully simple, as you can assign symbols to the BOOLs as well as the WORDs (and BYTEs and DWORDs) for the same overlapping adresses.

However, you want to program a reusable block for all the drives, which is a reasonable idea, and then you no longer have direct access to the Q addresses.

There are several ways to solve it.
1. Program in SCL. In SCL you can use the AT declaration to access the same data in differing ways (i.e. BOOLs and WORDs at the same time).
2. Use indirect addressing.
3. Use intermediary Merker addresses. This looks not so ‘pretty’ but is very quick and easy. You can assign symbols to overlapping addresses with Merkers just as you can with I and Q addresses. Notice, do not use the Merkers to store the data, only to transfer to the final output pin of the FC or FB.

edit: The way you have done it (or attempted to do it), by accessing the Lx.x adresses, is not recommendable. It may work, but the slightest change of the declaration part will wreak havoc on the code. It is most difficult to maintain.

__________________
Jesper
NOTICE:
JesperMP has passive-aggressive tendencies, can be impolite and may even use sarcasm !
Also: ᛁᚠ ᚢᚬᚢ ᚴᚬᚾ ᚱᛅᚬᛏ ᚦᛁᛋ ᚦᛅᚾ ᚢᚬᚢ ᚼᚬᚠᛅ ᚴᚬᛁᚾᛅᛏ ᛘᚢ ᚱᛅᛋᛒᛅᚴᛏ


Last edited by JesperMP; September 7th, 2009 at 03:55 AM.

 

Reply With Quote

Old
September 7th, 2009, 05:43 AM

 
#8

Lifetime Supporting Member

Finland

TurpoUrpo is offline

 

Join Date: May 2008

Location: Switzerland

Posts: 1,570

Most likely your problem is endianess.

You have that control word you need to sent to danfoss drive, when you manipulate bits by bits you need to swap bytes.

this is from my memory

cw byte1

start1
start2
start3



cw byte2







when you load that 47f (run command yes?)

to lw 0, if you want to access bit start2

you need to write to l1.1 not l0.1

 

Reply With Quote

Old
September 7th, 2009, 11:28 PM

 
#9

Member

Australia

freddofrog is offline

 

Join Date: May 2009

Location: ANYWHERE BUT 4m3ri(4

Posts: 29

heres how i do it with a danfoss.

Mapping danfoss data in;

L #Address; // Grab address reference (start address of the VLT)
SLW 3;
LAR1 ;
L PIW [AR1,P#0.0]; //pass in status word
T #TEMP1;
L PIW [AR1,P#4.0]; //pass in PCD 3
T #TEMP2;

A L 0.3;
= #Running; //Set running status
A L 3.4; // check FC300 input status at terminal 29
= #Term_29;
A L 3.5; // check FC300 input status at terminal 27
= #Term_27;
A L 3.6; // check FC300 input status at terminal 19
= #Term_19;
A L 3.7; // check FC300 input status at terminal 18
= #Term_18;

Writing data to danfoss

NETWORK
TITLE = Write FCD Data

L W#16#43C; // prepare control word for stop mode
T #TEMP1; //(temp 1 is at mem position 0)
A #Relay01; //map in value
= L 0.3;
A #Reverse; //map in value
= L 0.7;
A #Go_Drive; //map in value
= L 1.6;
L #TEMP1;
T PQW [AR1,P#0.0]; //control word

L #Speed_out;
T PQW [AR1,P#2.0]; // Output speed

this can be set up in a FB or FC and via the declarations may be called for as many drives at once, ive hade 500 running in one PLC no probs, has a very low overhead.


Last edited by freddofrog; September 7th, 2009 at 11:31 PM.

 

Reply With Quote

Old
September 8th, 2009, 11:09 PM

 
#10

Member

Australia

Boxy is offline

 

Boxy's Avatar

 

Join Date: Nov 2008

Location: Sydney

Posts: 56

Hey thanks guys. I used the method shown by LD[AR2..]
It worked a treat.
I guess i should learn STL then.
Thanks again

 

Reply With Quote

бул ту ворд бай тиапортал13

  • Цитата

Сообщение

megavolt86 » 20 окт 2015, 21:29

Привет всем местным)
Друзья, может кто сталкивался с упаковкой битовых значений в слово в ТИПортал 13?
Возникла загвоздка не получается упаковать, в фбд такой инструкции вообще не знает, а в scl функция bool_to_word вызывается, но при компиляции ругается на синтаксис…
Вообще в чем отличие фб в языках fbd и scl?

:ext_secret:

Понравилась статья? Поделить с друзьями:
  • Bool to int excel
  • Books with two word text
  • Books with the at word family
  • Books use in a sentence for each word
  • Books that have word families