en:software:devices:modbus

This translation is older than the original page and might be outdated. See what has changed.

This is an old revision of the document!


DEVICE MODBUS

The MODBUS® protocol represents an industrial communication system distributed and developed by Gould-Modicon to integrate PLC’s, computers, terminals, inverter and other devices. MODBUS is a Master/Slave communication protocol where only one device can be Master and monitors all activities of the serial line or TCPIP. As for the serial line can be connected up to a maximum of 247 slave along the same lines. Each device is assigned an address that distinguishes it from all other connected devices.
The MODBUS device lets you choose which serial port use for connection. The features s of data transmission (number of device, baud rate, parity, stop bits) and the transmission mode must be selected on each station and cannot be changed during the operation.
With using a serial line, there are two modes of transmission used in the Modbus Protocol. Both ways allow the same communication skills. The mode is selected by the master and must be unique for all devices connected to the network. The modes are:

  • ASCII (American Standard Code for Information Interchange)
  • RTU, (Remote Terminal Unit.)

This manual is divided into two parts:
Part I - Operation as master
Part II - Operation as slave.

The modbus communication protocol standard defines 4 types of Exchange data:

  • INPUT STATUS = Digital Inputs
  • COIL STATUS = UDigital Outputs
  • INPUT REGISTER = Analog Inputs
  • HOLDING REGISTER. = Analog Outputs

Throughout the manual you have to take into account existing conventions.

Declaration of the used device (internal device): device name assigned, MODBUS, slot location and number of the device.

INTDEVICE
...
<device_name>      MODBUS    TCamp    channel
...

Where:

INTDEVICEis a keyword indicating the beginning of the definition of internal devices,
<device_name>is the device name,
MODBUSis the keyword that identifies the device described in this document,
TCampis the sampling time of the device,
channelis the definition of the type of communications channel connected (0 = Prog, 1 = User, for the other ports the ID number depends on the hardware and firmware of the instrument used, 43 = Ethernet port to a modbus TCPIP).

To declare the hardware used in the “BUS” section of the configuration unit you will have to refer to the firmware of the hardware itself.

Example

INTDEVICE
modbus             MODBUS     0002    1
1234567 8 910111213141516Index table
1514131211109 8 76546210Weight of the bits(2N)
Modbus
register
0001 iword1 216ilong1
0002 iword2 20
0003 iword3 216ilong2
0004 iword4 20
0005 iword5 216ilong3
0006 iword6 20
0007 iword7 216ilong4
0008 iword8 20
0009 iword9 216ilong5
0010 iword10 20
0011 iword11 216ilong6
0012 iword12 20
0013 iword13 216ilong7
0014 iword14 20
0015 iword15 216ilong8
0016 iword16 20
0017 iword17 216ilong9
0018 iword18 20
0019 iword19 216ilong10
0020 iword20 20
0021 iword21 216ilong11
0022 iword22 20
0023 iword23 216ilong12
0024 iword24 20
0025 iword25 216ilong13
0026 iword26 20
0027 iword27 216ilong14
0028 iword28 20
0029 iword29 216ilong15
0030 iword30 20
0031 iword31 216ilong16
0032 iword32 20

NOTE 1: the “ iword1 ” is the most significant word of the “ ilong1 ” (long = double word), the “iword3” is the most significant word of the “ ilong2 ”, …
NOTE 2: the “ st_ibit0 ” parameter less significant bit (with weight 0) of the “ iword1 ”, while the “ st_ibit15 ” bit is the most significant (with weight 15) of the “ iword1 ”.

1234567 8 910111213141516Index table
1514131211109 8 76546210Weight of the bits(2N)
Modbus
register
0001 oword1 216olong1
0002 oword2 20
0003 oword3 216olong2
0004 oword4 20
0005 oword5 216olong3
0006 oword6 20
0007 oword7 216olong4
0008 oword8 20
0009 oword9 216olong5
0010 oword10 20
0011 oword11 216olong6
0012 oword12 20
0013 oword13 216olong7
0014 oword14 20
0015 oword15 216olong8
0016 oword16 20
0017 oword17 216olong9
0018 oword18 20
0019 oword19 216olong10
0020 oword20 20
0021 oword21 216olong11
0022 oword22 20
0023 oword23 216olong12
0024 oword24 20
0025 oword25 216olong13
0026 oword26 20
0027 oword27 216olong14
0028 oword28 20
0029 oword29 216olong15
0030 oword30 20
0031 oword31 216olong16
0032 oword32 20

NOTE 1: the “ oword1 ” is the most significant word of the “ olong1 ” (long = double word), the “oword3” is the most significant word of the “ olong2 ”, …
NOTE 2: the “ st_obit0 ” parameter is the less significant bit (with weight 0) of the “ oword1 ”, while the “ st_obit15 ” bit is the most significant (with weight 15) of the “ oword1 ”.

The MODBUS device can use a serial port or TCPIP to communicate in master mode (parameter mode = 0). Allows (via parameters, states and commands) all instruments to be able to communicate with any equipment utilizing Modbus.
The device provides a data exchange area where the QCL can write or read values shared with the slaves on the network. This area is represented by a list of parameters of the device divided into two groups to differentiate the type of access of the data by the device. The first section is identified as INPUT the second as OUTPUT. The INPUT section, for master operation, is the storage area of reads data. It is used by all reader functions (parameter type = 1, 2, 3 o 4). The OUTPUT section, in the master operation, is the area of data storage that the master should transfer to the slaves. It is used by all writing functions (parameter type = 5, 6, 15 o 16). To facilitate the exchange of data between devices, the structure of the Exchange area includes data types commonly used in QCL namely WORD, LONG and FLAG. The “BYTE” type does not appear because the modbus usually uses the word size for each address registers. The modbus protocol selects data based on the number of access log register, while the QCL selects based on the parameter symbol, you create a reference table in which each QCL symbol find the corresponding number in the register of access in Modbus protocol. To obtain greater flexibility for addressing, the same area of Exchange data can be manipulated by the QCL with different dimension parameterized. All the symbols that appear in the same row of the table refer to the same memory locations.

The data input or coil type have in the modbus Protocol a bit size. To store this information in the table of data exchange is defined as follows mode: each register (and then every word parameter of the device) represents 16 elements that are numbered from left to right. For the Scriptures or multiple readings when bits read are higher than those contained in the register the operation continues in the next register.
The st_ibit0… and st_obit1… states are useful in order to facilitate access to information bit, only in the first table log.

The master mode is set with the mode parameter = 0. The card generates modbus messages only on QCL ordering and does not automatically. To “format” the modbus message string there are a number of parameters.
Using the two commands SEND or SENDSYC you send the read or write request to the slave, a number of States allow an audit on the operation being executed. We see in detail:

0.5.2.1 Parameters for formatting the message:

type = request type that you want to process (reading or writing word or bit).
idcard = address of the slave drive to which you want to send the request.
addr = the index from which to start reading or at which to start writing in the slave.
tabreg = for read operations (type = 1, 2, 3, 4), This parameter indicates the position in the “table of data read” where will store the read data on the slave. For write operations (type = 5, 6, 15, 16), this parameter indicates the position in the “table of data to be written” where is the data to be written on the slave. Are accepted values are between 1 and 512 for values of type parameter = 1, 2, 5, 15 (writing and reading of bits), while for type value = 3, 4, 6, 16 (writing and reading of word) the expected values are between 1 and 32.
num = number of values that are read or write (if the request type so provides). Are accepted values are between 1 and 128 for values of type parameter = 1, 2, (reading of bits), while for type value = 3, 4, 16 (multiple word reading and writing) the accepted value are between 1 and 32.

0.5.2.2 Commands to send the message:

SEND sends the request message to the slave.
SENDSYC sends the request message to a QEM slave of MODBUS type and reports the operation concluded (st_sended) only when the slave executes the RECEIVED command.

0.5.2.3 State variables for diagnostic operation:

When ended the message send operation, the status st_sended variable is set to 1. If you used the SEND command the state is set to 1 when the master receive the confirmation of the message being sent. If you have used the SENDSYC command in the master then this status will be set to 1 when the slave QEM will execute the RECEIVED command. In case of error, This status is still in set to 1 (After the toutsyc time) but the err parameter indicates the cause of the error (see the description of this parameter for details).
The SENDSYC coomand it becomes necessary when you want to synchronize master data packet writing by reading the same data from the slave (can be used when both master and slave are Qmove).

Read Coil

Bit read function. You want to read the bits of a slave (idcard). Sets the parameter type = 1.
You must set addr to indicate the address of the bit in the slave from which to start reading. The num parameter indicates the number of bits that are read. You must to set tabreg to indicate the index of the bit in the “data read table” the master from which you want to be written the read bits. The raedings value will be saved in the “data read table”. It is recommended to always meet the following two conditions:
(addr + num - 1) ⇐ 512 e (tabreg + num - 1) ⇐ 512 otherwise the request will fail (reporting by wcmd).

Read Input

Bit read function. To read the bits of a slave (idcard). The function is equal to the “Read Coil”. Sets the parameter type = 2.
The meaning of the two functions is distinguished at the level of MODBUS protocol. Some slave can make available different memory areas depending if the bits are Coil or Input. In the case of slave Qmove the two requests have the same effect.

Read Holding Register

Word read function. For reading the word of the slave (idcard). Sets the parameter type = 3.
You must to set addr to indicate the address of the word in the slave from which to start reading. The num parameter indicates the number of word to be read. You must set tabreg to indicate the index of the word in the “read data table” of the master from which you want are writes the read words. The read values will be saved in the “read data table”. It is recommended to always meet the following two conditions:
(addr + num - 1) ⇐ 32 e (tabreg + num - 1) ⇐ 32 otherwise the request will fail (reporting by wcmd).

Read Input Register

Word read function. For reading the bit of the slave (idcard). The function is equal to the “Read Holding Register”. sets the parameter type = 4.
The meaning of the two functions is distinguished at the level of MODBUS protocol. Some slave can make available different memory areas depending if the read word are Holding or Input. In the case of slave Qmove the two requests have the same effect.

Force coil

Bit write function. For writing (force) the bit of the slave (idcard). Sets the parameter type = 5.
You must set addr to indicate the address of the bit in the slave that you want to write. You must set tabreg to indicate the index of the bit in the “write data table” that contains the value to be written.

Force register

Word write function. For write (force) the word of a slave (idcard). Sets the parameter type = 6.
You must set addr to indicate the address of the word in the slave that you intend to write. You must set tabreg to indicate the index of the word in the “data write table” that contains the value to be written.

Force multiple coil

Multiples bit write function. For write (force) the bit of a slave (idcard). Sets the parameter type = 15.
You must set addr to indicate the address of the bit in the slave that you intend to write. You must set in num the number of bits to write. You must set tabreg to indicate the bit index of the “data write table” from which to begin the values to be written. It is recommended to always meet the following two conditions:
(addr + num - 1) ⇐ 512 e (tabreg + num - 1) ⇐ 512 otherwise the request will fail (reporting by wcmd).

Force multiple register

Multiples word write function. For write (forzare) the word of a slave (idcard). Sets the parameter type = 16.
You must set addr to indicate the address of the word in the slave that you intend to write. You must set in num the number of word to write. You must set tabreg to indicate the index of the word in the “write data table” da cui iniziano i valori da scrivere. Si raccomanda di soddisfare sempre le seguenti due condizioni:
(addr + num - 1) ⇐ 32 e (tabreg + num - 1) ⇐ 32 altrimenti la richiesta non potrà essere eseguita (segnalazione mediante wcmd).

1) Impostazioni modbus e apertura del canale di comunicazione di tipo seriale

modbus.mode = 0                             ; modbus master
modbus.prot = 1                             ; RTU
modbus.brate = 57600                        ; baudrate
modbus.stopb = 1                            ; stop bits
modbus.par = 0                              ; parity
modbus.tout = 100                           ; timeout
 
modbus.OPENCOM
tm_opencom = 200                            ; timeout for OPENCOM command
WAIT modbus.st_opencom OR tm_opencom
IF NOT modbus.st_opencom
    OpenComError = 1                        ; com not opened
ENDIF

2) Impostazioni modbus e apertura del canale di comunicazione di tipo TCPIP

modbus.mode = 0                             ; modbus master
modbus.prot = 2                             ; TCPIP
modbus.tout = 100                           ; timeout
 
tcpip_port= 502                             ; number of tcpip port (default 502)
modbus.stopb = (tcpip_port ANDB &H0000FF00) / 256
modbus.par = tcpip_port ANDB &H000000FF
 
modbus.OPENCOM
tm_opencom = 500                            ; waiting time to have a correct response
WAIT tm_opencom
IF NOT modbus.st_opencom
    OpenComError = 1                        ; com not opened
ENDIF

3) Lettura del registro input nr.7 dello slave id 67

modbus.idcard = 67
modbus.addr = 7
modbus.tabreg = 7
modbus.num = 1
modbus.type = 4
modbus.SEND
WAIT modbus.st_sended
IF (modbus.err)
    CALL ErroreModbus
ENDIF
slVelocita = modbus.iword7

4) Lettura dei holding register dal nr.600 al nr.606 dello slave id 8
Siccome l’area di scambio dati QCL non supporta l’indirizzo 600, si utilizza il parametro tabreg per salvare i dati letti all’indirizzo 10

modbus.idcard = 8
modbus.addr = 600
modbus.num = 6
modbus.tabreg = 10
modbus.type = 3
modbus.SEND
WAIT modbus.st_sended
IF (modbus.err)
    CALL ErroreModbus
ENDIF
 
swTemp1 = modbus.iword10
slVelocita = modbus.ilong6
slPosiz = modbus.ilong7
swTemp1 = modbus.iword15

Il Broadcast è un messaggio speciale che viene inviato dal Master e viene ricevuto contemporaneamente da tutti gli slave connessi. La funzionalitá broadcast (idcard = 0) è supportata solamente in modo master e se viene usato un messaggio con type = 5, 6, 15 e 16 (solo scrittura). In questa modalità lo stato st_sended viene attivato appena terminata la trasmissione e non alla ricezione della conferma dallo slave. Infatti non esiste nessuna risposta degli slave per questo tipo di messaggi. Non è possibile utilizzare il comando SENDSYC.

La scheda quando funziona in modalità Master permette, con un speciale comando, di riconoscere se lo slave collegato è di tipo QEM. In caso affermativo determina anche il modello di slave connesso. Questo permette di realizzare una diagnostica sulla corretta configurazione della rete. Non è possibile estendere questo controllo a tutti i tipi di slave esistenti perché il protocollo non prevede una modalità standard di riconoscimento slave.
Il comando READSTYPE eseguito dopo aver opportunamente selezionato lo slave (tramite parametro idcard) invia allo slave una richiesta modbus nr.17 per il riconoscimento. Lo slave risponderà con un suo valore predefinito e potrà essere letto nel parametro stype del master. Nel caso lo slave non sia prodotto da QEM srl, il parametro avrà valore –1 ad indicare che lo slave è connesso ma non è possibile identificarlo.
Per il device MODBUS lo slave ID è diverso a seconda dello slave QEM utilizzato. Per una codifica degli slave in questo senso vedere il manuale Firmware dello slave utilizzato.

Esempio d'identificazione dello slave nr.12:

modbus:idcard = 12
modbus.READSTYPE
WAIT modbus.st_sended
IF (modbus.err)
    sbConfig = 3             ; error: slave 12 not connected
ELSE
    IF (modbus.stype EQ 1)   ; Board CAM-AG-98
        sbConfig = 1         ; configuration OK
    ELSE
        sbConfig = 2         ; error in network configuration
    ENDIF
ENDIF

Il protocollo di comunicazione modbus standard definisce 4 tipi di dati di scambio:

  • INPUT STATUS,
  • COIL STATUS,
  • INPUT REGISTER,
  • HOLDING REGISTER.

Questi 4 tipi trattano i segnali tipo Digital Inputs, Digital Outputs, Analog Inputs, and Analog Outputs. I valori dei registri (sia INPUT REGISTERS che HOLDING REGISTERS), sono definiti come valori a 16 bit, ognuno con un unico indirizzo, (esempio INPUT REGISTER #1, INPUT REGISTER #2, INPUT REGISTER #3, ecc.).
Per permettere di suppportare tipi di dato di dimensione maggiore di 16 bit, è stata progettata una estensione al protocollo per trattare valori di dimensione long 32 bit. L’implementazione di questa funzionalitá mantiene la formattazione del messaggio standard modbus e utilizza il contenuto di due indirizzi consecutivi per rappresentare un valore 32 bit. Quando questa estensione è attiva (wider = 1), a seconda dell’indirizzo utilizzato lo slave risponderà con un valore a 16 bit o 32 bit per ogni richiesta di registro. Se l’indirizzo è superiore a 5000 verrà risposto con valore a 32 bit, se inferiore il protocollo rimane invariato con risposta a 16 bit.

0.5.10.1 Simbologia adottata

Il nome del parametro, stato o comando viene riportato alla sinistra della tabella.

R
Indica se il relativo parametro o stato è ritentivo (al momento dell’inizializzazione del device mantiene lo stato precedentemente definito), oppure lo stato che assume al momento dell’inizializzazione del device.
Se il device non necessita di inizializzazione il campo “R” indica il valore che il parametro o stato assume all’accensione della scheda.
R = Ritentivo
0 = Al momento dell’inizializzazione del device il valore viene forzato a zero.
1 = Al momento dell’inizializzazione del device il valore viene forzato a uno.
- = Al momento dell’inizializzazione del device viene presentato il valore significativo.

D
Indica la dimensione del parametro.
F = Flag
B = Byte
W = Word
L = Long
S = Single Float

Condizioni

Vengono descritte tutte le condizioni necessarie affinché il parametro sia considerato corretto o perché il comando venga accettato.
In alcuni casi vengono specificati dei valori limite per l’accettazione del parametro: se vengono introdotti dei valori esterni ai limiti impostati, il dato viene comunque accettato; pertanto devono essere previsti opportuni controlli dell’applicativo tali da garantire il corretto funzionamento.
Per l’esecuzione di un comando, tutte le relative condizioni devono necessariamente essere soddisfatte; in caso contrario il comando non viene eseguito.

A
Indica la modalità di accesso.
R = Read (lettura).
W = Write (scrittura).
RW = Read / Write.

0.5.10.2 Parametri

Nome D R A Condizioni Descrizione
mode B R R/W - Mode
(0 ÷ 2)
Definisce se la scheda deve funzionare come master o come slave.
0 = master.
prot B R R/W - Protocol
(0 ÷ 1)
Definisce il tipo di protocollo Modbus da utilizzare.
0 = ASCII,
1 = RTU,
2 = TCPIP
wider B R R/W - Wide Registers
(0 ÷ 1)
Indica se utilizzare l’estensione del protocollo per i registri a 32bit. Vedere capitolo “Estensione del protocollo” :
0 = normale,
1 = protocollo esteso.
idcard W R R/W - Identification Card
(0 ÷ 255)
Nel funzionamento come master è il numero del dispositivo al quale s'intende trasmettere. Nel modo master è valida anche l’impostazione zero per il funzionamento broadcast.
type B 1 R/W - Type
Definisce il tipo di richiesta che il master deve eseguire.
Valori ammessi: 1, 2, 3, 4, 5, 6, 15, 16
addr L 1 R/W - Address
(1 ÷ 65535)
Definisce l’indirizzo utilizzato dal master per definire quale sia il dato da leggere o scrivere.
tabreg W 1 R/W - Destination
(1 ÷ 512)
Definisce l’indirizzo nelle tabelle dei dati in cui scrivere il dato letto o in cui trovare il dato da scrivere.
num W 1 R/W - Number
(1 ÷ 512)
È il numero d'elementi da scrivere o leggere nella richiesta che compone il master.
brate L R R/W - Baud rate
Baud rate della seriale.
Valori validi: 4800, 9600, 19200, 38400, 57600, 115200.
stopb B R R/W - Stop bit
Valori validi: 1, 2.
par B R R/W - Parity
(0 ÷ 2)
0 = none (nessuna),
1 = odd (dispari),
2 = even (pari).
tout W R R/W - Timeout
(0 ÷ 9999 msec)
Per la modalitá master è il tempo massimo in cui lo slave deve rispondere.
Impostandolo a zero il Timeout è disabilitato.
toutsyc W R R/W - Time out synchronize
(0 ÷ 9999 msec)
Utilizzato solamente per la modalitá master è il tempo massimo che puó trascorrere tra l’invio del comando SENDSYC e l’esecuzione del comando RECEIVED nello slave QEM.
iword1÷32 W 0 R - Input Word nr. (1Input Long nr. (1÷16)32)
st_ibit0÷15 F 0 R - Input bit nel parametro iword1
ilong1÷16 L 0 R - Input Long nr. (1÷16)
oword1÷32 W 0 R/W - Output Word nr. (1÷32)
st_obit0÷15 F 0 R/W - Output bit nel parametro oword1
olong1÷16 L 0 R/W - Output Long nr. (1÷16)

La possibilità di comunicare con il protocollo TCPIP è stata sviluppata in un tempo successivo rispetto alla nascita del device MODBUS. Per questo modivo l'impostazione della porta e dell'indirizzo IP viene eseguita mediante alcuni parametri che hanno un significato diverso.

Per configurare il numero della porta TCPIP è necessario andare a scrivere sui parametri stopb e par. Rispettivamente :

  • stopb = tcpip_port / &H00000100
  • par = tcpip_port ANDB &H000000FF

Per impostare lo slave TCPIP a cui si vuole eseguire la richiesta è necessario andare a scrivere sul parametro brate.
Un indirizzo IP può essere espresso come TcpAddr3.TcpAddr2.TcpAddr1.TcpAddr0 (per esempio 192.168.0.1).

  • brate = (TcpAddr3 * &H01000000) + (TcpAddr2 * &H00010000) + (TcpAddr1 * &H00000100) + TcpAddr0

0.5.10.3 Variabili

Nome D R A Condizioni Descrizione
err B 0 R - Errors
Indica se sono stati riscontrati errori nel protocollo.
In modalità master il parametro viene aggiornato in coincidenza dell’attivazione dello stato st_sended. I valori da 1 a 49 sono quelli inviati dallo slave. I valori superiori a 50 sono generati internamente dal master. I primi 8 valori sono normalizzati nel protocollo e sono:
0 = comunicazione avvenuta senza errori,
1 = ILLEGAL FUNCTION,
2 = ILLEGAL DATA ADDRESS,
3 = ILLEGAL DATA VALUE,
4 = SLAVE DEVICE FAILURE,
5 = ACKNOWLEDGE,
6 = SLAVE DEVICE BUSY,
7 = NEGATIVE ACKNOWLEDGE,
8 = MEMORY PARITY ERROR,
50 = UNKNOWN RECEIVED ERROR lo slave ha risposto con un codice superiore a 49,
51 = TIMEOUT lo slave non ha risposto entro il tempo programmato nel parametro tout,
52 = INVALID ANSWER,
52 = INVALID FUNCTION ANSWER - Tipo funzione non supportata,
53 = CHECKSUM ANSWER - Il checksum ricavato non corrisponde,
54 = TRUNCATED ANSWER - Messaggio troppo corto,
55 = INVALID ID ANSWER - Id slave non corrispondente,
56 = INVALID_MBAP_TRANSACTION_ID - modbus TCPIP, transaction ID non corretto,
57 = INVALID_MBAP_PROTOCOL_ID - modbus TCPIP, protocol ID diverso da zero,
70 = TIMEOUT SYNCHRONIZED lo slave QEM non hanno eseguito il comando RECEIVED entro il tempo programmato nel parametro toutsyc.
In modalità slave il parametro non viene mai aggiornato.
serr B 0 R/W - Serial Errors
Indica se sono stati riscontrati errori nella comunicazione seriale. Il parametro viene aggiornato ad ogni errore rilevato. Il valore permane fino:
- ad un successivo errore;
- alla scrittura di uno dei seguenti parametri: mode, prot, wider, brate, stopb, par;
- ad una scrittura sullo stesso (qualsiasi valore lo azzera).
0 = nessun errore,
1 = parity error,
2 = framing error,
3 = overrun error.
stype W 0 R - Slave type
Indica il tipo di slave connesso. Il parametro viene aggiornato quando il parametro st_sended diventa 1 e se era stato eseguito un comando READSTYPE

0.5.10.4 Stati

NomeDRACondizioniDescrizione
st_sendedF0R-Sended
Stato utilizzato solo in modalità master. L’attivazione indica il completamento della trasmissione di un messaggio. Lo stato viene resettato con i comandi SEND o SENDSYC.
st_opencomF0R-Open communication port
L'attivazione indica che il device sta impegnando la porta di comunicazione seriale. Per settare questo stato usare il comando OPENCOM, per resettarlo CLOSECOM.
wdataF0R-Warning Data
Questo bit segnala che è stato tentato un inserimento di un valore non valido in un parametro.
wcmdF0R-Warning Command
Questo bit segnala che è non è stato eseguito un comando perché mancano le condizioni necessarie.

0.5.10.5 Comandi

I comandi a disposizione per gestire il device sono elencati sotto in ordine di priorità decrescente.
Il device esegue tutti i comandi ricevuti entro lo stesso tempo di campionamento iniziando da quello con la priorità maggiore.
Per esempio se il device riceve nello stesso tempo di campionamento i comandi CLOSECOM e OPENCOM, per primo esegue il comando OPENCOM e poi quello di CLOSECOM lasciando perciò la porta di comunicazione chiusa.

NomeDRACondizioniDescrizione
SEND---mode = 0
0 < num ⇐ 128
st_sended = 1
st_opencom = 1
Sended
Determina la trasmissione del messaggio verso lo slave selezionato.
SENDSYC---mode = 0
0 < num ⇐ 128
st_sended = 1
st_opencom = 1
Send synchronize
Utilizzabile solo in modo master determina la trasmissione del messaggio verso uno slave QEM con la sincronizzazione.
READSTYPE---mode = 0
st_sended = 1
st_opencom = 1
Read slave type
Richiesta lettura informazione type sullo slave specificato in idcard. La risposta verrá segnalata sul parametro stype quando lo stato st_sended diventa 1.
CLRWDATA----Clear Warning Data
Azzera la segnalazione del parametro wdata.
CLRWCMD----Clear Warning Command
Azzera la segnalazione del parametro wcmd.
OPENCOM---st_opencom = 0Open Serial communication\ Apre la comunicazione seriale (il device quindi impegna la porta di comunicazione ). Lo stato st_opencom diventa 1.
CLOSECOM----Close Serial communication
Chiude la comunicazione seriale (il device quindi non impegna piú la porta di comunicazione ). Lo stato st_opencom diventa 0.

La modalità slave viene impostata con il parametro mode = 1 o mode = 2. Bisogna introdurre nei parametri il codice dell’ID slave tramite il parametro idcard.

Impostazioni modbus e apertura del canale di comunicazione di tipo seriale

modbus.mode = 1                             ; modbus slave
modbus.prot = 1                             ; RTU
modbus.brate = 57600                        ; baudrate
modbus.stopb = 1                            ; stop bits
modbus.par = 0                              ; parity
modbus.idcard = 1                           ; slave id
 
modbus.OPENCOM
tm_opencom = 100                            ; timeout for OPENCOM command
WAIT modbus.st_opencom OR tm_opencom
IF NOT modbus.st_opencom
    OpenComError = 1                        ; com not opened
ENDIF

Impostazioni modbus e apertura del canale di comunicazione di tipo TCPIP

modbus.mode = 1                             ; modbus slave
modbus.prot = 2                             ; TCPIP
 
tcpip_port= 502                             ; number of tcpip port (default 502)
modbus.stopb = (tcpip_port ANDB &H0000FF00) / 256
modbus.par = tcpip_port ANDB &H000000FF
 
modbus.OPENCOM
tm_opencom = 100                            ; waiting time to have a correct response
WAIT (modbus.st_opencom OR timerOpencom)
IF NOT modbus.st_opencom
    OpenComError = 1                        ; com not opened
ENDIF

Le operazioni che spettano all’applicativo QCL sono essenzialmente due:

  • aggiornare i parametri tipo owordNN, olongNN (che verranno poi letti dal master)
  • processare i parametri tipo iwordNN, ilongNN (che sono stati scritti dal master)

0.6.1.1 Aggiornamento dei parametri tipo owordNN

Per aggiornare i parametri tipo owordNN il QCL deve scrivere i valori nei parametri quindi inviare il comando VALIDATE. L’utilizzo del comando si rende necessario per rendere disponibili alle letture del master i nuovi dati nello stesso istante, evitando così che possano venire letti solamente parte dei parametri aggiornati. Quindi l’assegnazione di un valore ad un parametro device NON SIGNIFICA che esso sia immediatamente disponibile per le letture del master. Sarà disponibile solamente dopo il comando VALIDATE.

Esempio

modbus.olong1 = anpos.speed
modbus.oword1 = npezzi
modbus.oword2 = npezzitot
modbus.oword3 = anpos.dir
modbus.olong2 = anpos.posit
modbus.VALIDATE

0.6.1.2 Processo dei parametri tipo iwordNN

Per processare i parametri tipo iwordNN, invece, il QCL deve attendere che lo stato st_msgrx venga attivato. Questo significa che un messaggio di scrittura è stato inviato dal master. Per i messaggi di lettura nessun segnale viene riferito ai parametri QCL. Il QCL poi deve prelevare i valori dall’area scambio dati e al termine deve inviare il comando RECEIVED, solo allora lo stato st_msgrx viene disattivato.

Esempio

WAIT modbus.st_msgrx
anpos.speed = modbus.ilong1
anpos:posit = modbus.ilong2
npezzi = modbus.iword1
RECEIVED modbus

Naturalmente non esiste nessun controllo per evitare che durante la lettura dei parametri iwordNN il master erroneamente esegua un’altra scrittura, prima che il codice del progetto presente nello slave finisca il processo.
Inoltre il codice per la manipolazione del device modbus nell’applicativo è consigliato che sia raccolto in un unico task in modo da non creare accessi contemporanei ai device che potrebbero generare delle condizioni non valide in ogni singolo contesto.

Tutte le richieste di lettura che arrivano dal master MODBUS fanno riferimento ai dati di tipo owordNN accedendo quindi alla stessa area dati. Lo slave mette a disposizione i valori che il master leggerà nei parametri di tipo owordNN.
Tutte le richieste di scrittura che arrivano dal master MODBUS fanno riferimento ai dati di tipo iwordNN accedendo quindi alla stessa area dati. Lo slave mette a disposizione i parametri iwordNN dove il master potrà scrivere i dati.

0.6.3.1 Simbologia adottata

Il nome del parametro, stato o comando è riportato alla sinistra della tabella.

R
Indica se il relativo parametro o stato è ritentivo (al momento dell’inizializzazione del device mantiene lo stato precedentemente definito), oppure lo stato che assume al momento dell’inizializzazione del device.
Se il device non necessita di inizializzazione il campo “R” indica il valore che il parametro o stato assume all’accensione della scheda.
R = Ritentivo
0 = Al momento dell’inizializzazione del device il valore è forzato a zero.
1 = Al momento dell’inizializzazione del device il valore è forzato ad uno.
- = Al momento dell’inizializzazione del device è presentato il valore significativo.

D
Indica la dimensione del parametro.
F = Flag
B = Byte
W = Word
L = Long
S = Single Float

Condizioni

Sono descritte tutte le condizioni necessarie affinché il parametro sia considerato corretto o perché il comando venga accettato.
In alcuni casi sono specificati dei valori limite per l’accettazione del parametro: se sono introdotti dei valori esterni ai limiti impostati, il dato è comunque accettato; pertanto devono essere previsti opportuni controlli dell’applicativo tali da garantire il corretto funzionamento.
Per l’esecuzione di un comando, tutte le relative condizioni devono necessariamente essere soddisfatte; in caso contrario il comando non è eseguito.

A
Indica la modalità d'accesso.
R = Read (lettura).
W = Write (scrittura).
RW = Read / Write.

0.6.3.2 Parametri

Nome D R A Condizioni Descrizione
mode B R R/W - Mode
(0 ÷ 2)
Definisce se la scheda deve funzionare come master o come slave.
1 = slave con area di scambio dati fissa;
2 = slave senza area di scambio dati fissa: ad ogni scrittura o lettura eseguita dal master viene messi a 1 il flag st_msgrx.
Contemporaneamente i parametri type, addr e num indicano le caratteristiche del messaggio ricevuto.
- Type indica il tipo di funzione che vuole fare ill master (lettura o scrittura),
- addr indica l'indirizzo dell'inizio del blocco di dati scritti o letti,
- num indica il numero di dati letti o scritti (a bit o a byte a seconda del valore di type).
Il device controllerà, in ricezione, solamente num (size di messaggio) che non sia superiore a 32word ma non più l'indirizzo che può essere ora qualsiasi.
Se è una scrittura (lo si capisce dal valore di type se è 5,6,15,16) vengono riportati i dati nelle variabili di scambio input (sempre a partire dalla prima word) ed il device attende il comando RECEIVED.
Se è una lettura il device attende che il QCL depositi i dati nelle word variabili di scambio output ed attende il comando VALIDATE.
prot B R R/W - Protocol
Definisce il tipo di protocollo Modbus da utilizzare.
0 = ASCII,
1 = RTU,
2 = TCPIP.
wider B R R/W - Wide Registers
Indica se utilizzare l’estensione del protocollo per i registri a 32bit. Vedere capitolo “Estensione del protocollo”.
0 = normale,
1 = protocollo esteso.
idcard W R R/W - Identification Card
( 1 ÷ 255 per slave)
Nel funzionamento come slave è il numero che identifica l’apparecchio nella rete.
brate L R R/W - Baud rate
Baud rate della seriale.
Valori validi: 4800, 9600, 19200, 38400, 57600, 115200.
stopb B R R/W - Stop bit
Valori validi: 1, 2.
par B R R/W - Parity
(0 ÷ 2)
0 = none,
1 = even,
2 = odd.
rdelay W R R/W - Reply delay
(0 ÷ 9999 msec)
E' il tempo di attesa prima di trasmettere la risposta.
iword1÷32 W 0 R - Input Word nr. (1Input Long nr. (1÷16)32)
st_ibit0÷15 F 0 R - Input bit nel parametro iword1
ilong1÷16 L 0 R - Input Long nr. (1÷16)
oword1÷32 W 0 R/W - Output Word nr. (1÷32)
st_obit0÷15 F 0 R/W - Output bit nel parametro oword1
olong1÷16 L 0 R/W - Output Long nr. (1÷16)

0.6.3.3 Variabili

NomeDRACondizioni Descrizione
serrB0R/W-Serial Errors
Indica se sono stati riscontrati errori nella comunicazione seriale.
Il parametro viene aggiornato ad ogni errore rilevato. Il valore permane fino ad un successivo errore o ad una scrittura sullo stesso con il QCL.
0 = nessun errore,
1 = parity error,
2 = framing error,
3 = overrun error.

0.6.3.4 Stati

NomeDRACondizioni Descrizione
st_msgrxF0R-Message received
Stato utilizzato solo in modalitá slave. Indica che un messagio del master ha eseguito una scrittura nell’area scambio dati QCL. Lo stato viene resettato con il comando RECEIVED.
st_opencomF0R-Open communication port
L'attivazione indica che il device sta impegnando la porta di comunicazione seriale. Per settare questo stato usare il comando OPENCOM, per resettarlo CLOSECOM.
wdataF0R-Warning Data
Questo bit segnala che è stato tentato un inserimento di un valore non valido in un parametro.
wcmdF0R-Warning Command
Questo bit segnala che è non è stato eseguito un comando perchè mancano le condizioni necessarie.

0.6.3.5 Comandi

I comandi a disposizione per gestire il device sono elencati sotto in ordine di priorità decrescente.
Il device esegue tutti i comandi ricevuti entro lo stesso tempo di campionamento iniziando da quello con la priorità maggiore.
Per esempio se il device riceve nello stesso tempo di campionamento i comandi CLOSECOM e OPENCOM, per primo esegue il comando OPENCOM e poi quello di CLOSECOM lasciando perciò la porta di comunicazione chiusa.

Nome D R A Condizioni Descrizione
RECEIVED - - - st_msgrx = 1
mode = 1, 2
st_opencom = 1
Received
Utilizzato solamente in modalitá slave. Indica che l’applicativo QCL ha processato le informazioni che il master ha inviato
VALIDATE - - - mode = 1, 2
st_opencom = 1
Validate
Indica che i parametri di scambio dati QCL diventano disponibili al master.
CLRWDATA - - - - Clear Warning Data
Azzera la segnalazione del parametro wdata
CLRWCMD - - - - Clear Warning Command
Azzera la segnalazione del parametro wcmd
OPENCOM - - - st_opencom = 0 Open Serial communication
Apre la comunicazione seriale (il device quindi impegna la porta di comunicazione). Lo stato st_opencom diventa 1.
CLOSECOM - - - - Close Serial communication
Chiude la comunicazione seriale (il device quindi non impegna piú la porta di comunicazione). Lo stato st_opencom diventa 0.

Il primo aspetto da tenere presente per la migrazione è il fatto che il device MODBUS01 è esterno mentre il MODBUS è interno. Questo implica che la dichiarazione del device deve essere eseguita nella sezione “INTDEVICE” dell’unità di configurazione del progetto. Inoltre, questo comporta la scelta, durante la definizione del device MODBUS, del tempo di campionamento. Il valore del tempo di campionamento che mantiene inalterate le prestazioni della comunicazione tra i due device è pari a 5 ms. Bisogna inoltre, in fase di definizione, selezionare la seriale da impegnare.
Il device MODBUS ha aumentato il numero di variabili di scambio (da 16 word a 32 word) ma questo non influenza il funzionamento per le impostazioni che utilizzano al massimo 16 word come sono quelle pensate per il device MODBUS01.
Il device MODBUS ha limitato la variabile “num” a 128, mentre per il device MODBUS01 il limite è 256. Questo si è reso necessario per permettere un’ottimizzazione del tempo di campionamento. La scelta è stata presa in considerazione del fatto che tali valori venivano impiegati unicamente per la gestione dei Coils, ma che perdeva di logica la lettura/scrittura di più di 128 coils consecutivi.
Il device MODBUS consente di controllare (mediante 2 nuovi comandi) l'impegno della seriale di comunicazione da parte del device. Questa nuova funzionalitá è interessante nell'eventualità che in un progetto Qview siano stati dichiarati altri devices che possono utilizzare la stessa seriale.
Se un applicativo era stato scritto per il device MODBUS01 bisogna aggiungere il comando OPENCOM (eseguito anche solo una volta) come mostrato nel seguente esempio.

; impostazione dei parametri di comunicazione
modbus.mode = 0
modbus.brate = 38400
...
modbus.OPENCOM
WAIT modbus.st_opencom
 
modbus.idcard = 8
modbus.addr = 600
modbus.num = 6
modbus.tabreg = 10
modbus.type = 3
modbus.SEND
WAIT modbus.st_sended
IF (modbus.err)
    CALL ErroreModbus
ENDIF
  • Last modified: 2019/08/29 17:18