Search code examples
windowslistbatch-filecmdmodbus

Batch script printing set command, not desired set list value


the code below is for printing a command line based on the 2 sets

@echo off

rem Define lists of register addresses and values to write
set MY_REG_ADDRESSES=3 22 28 29 31 32 21 51 94 97 104 105 77
set MY_REG_VALUES=4 12000 450 40 100 40 1440 100 450 10000 0 0 1000

rem Write values to Modbus registers using the lists
set i=0
for %%a in (%MY_REG_ADDRESSES%) do (
    set /a i=i+1
    echo modpoll -r %%a -t 4 -4 1  COM3 !MY_REG_VALUES:~%i%,1!
)

I would expect the code to output lines that look like:

modpoll -r 3 -t 4 -4 1  COM3 4

but rather I am getting:

modpoll -r 3 -t 4 -4 1  COM3 !MY_REG_VALUES:~0,1!

I have tried using list[i] also but that returned nothing??


Solution

  • Perhaps something like this is what you're trying to do!

    It may not be the most efficient way to do it, but as long as your lists aren't super long, it should work perfectly well for you.

    @Echo Off
    SetLocal EnableExtensions EnableDelayedExpansion
    
    Rem Define lists of register addresses and values to write
    Set "MY_REG_ADDRESSES=3 22 28 29 31 32 21 51 94 97 104 105 77"
    Set "MY_REG_VALUES=4 12000 450 40 100 40 1440 100 450 10000 0 0 1000"
    
    Rem Write values to Modbus registers using the lists
    Set "Acount=0"
    For %%G In (%MY_REG_ADDRESSES%) Do (
        Set /A Acount += 1, Vcount=0
        For %%H In (%MY_REG_VALUES%) Do (
            Set /A Vcount += 1
            If !Acount! Equ !Vcount! Echo modpoll -r %%G -t 4 -4 1  COM3 %%H
        )
    )
    
    Pause
    

    Obviously the last line is optional, (I just included it so you could see the results, if you double-clicked the script).