Moving I/O Across PLCs at Four Positions Without Changing Machine Logic
An I/O relocation that looks like a programming rewrite is really an address change, once you see that the existing logic does not care which card a bit comes from. It only cares about the tag name.
1-minute summary
- Symptom / problem
- Four I/O points sit on the wrong PLC, and rewriting the FCs on both sides went nowhere.
- Who should read
- Anyone moving sensors and valves between PLCs without touching the machine logic.
- Fix in short
- Re-address the existing tags to %M and add a pair of OBs that swap bits over the existing TCP link. One mapping table generates every location.
I had a job from a factory whose project owner wanted to move a set of I/O from the line's central PLC to the PLCs at individual stations. These were workpiece sensors and Up/Down pneumatic cylinder valves at 4 work positions. For the first attempt, I handled one station by rewriting the FCs on both sides, passed compilation and testing, and delivered 2 files. Only when I started on the other 3 positions did I realize this approach could not scale. I went back and rethought the whole approach. This article explains where the first approach went wrong and what the final version looks like. All PLC names, tag names, and addresses in this article are fictitious.
This work changes the signal paths that control actual valve outputs. Every result in this article comes from testing one PLC at a time in a simulator using project copies. Nothing was ever loaded onto the machine. The numbers and fail-safe positions are specific to one machine. Before actual use, the engineer responsible for the machine must review the program, check the wiring, and confirm that the position on link loss is safe for people and workpieces at every point.
The task: I/O at four positions is on the wrong PLC
The system has one central PLC, which I call Main PLC, and 3 station PLCs. Some handle 2 work positions, making 4 positions in total. All are S7-1500 units running on TIA Portal V15.1, and they already communicate through TSEND_C and TRCV_C.
Originally, each station calculated when to lower its cylinder, then sent the command to Main PLC through a send DB. Main PLC had its own valve-control FB and sent workpiece status back to the station. All valves and sensors were wired to Main PLC. The project owner wanted this I/O moved to the PLC of the station it served.
First attempt: rewriting both FCs worked but could not scale
I started with one station using the most direct approach. I deleted the output and input tags from Main PLC, rewrote its cylinder FC from LAD to SCL so it would send commands instead of driving valves, and added a network to the station's FC to receive those commands and drive the outputs. Compilation passed, testing passed, and I delivered 2 files.
The problems appeared when I started on the other 3 positions. There were two, and neither could be solved by simply putting in more work.
First, each station's FC was different. I had to read and manually rewrite every one. Nothing from the first position could be reused for the second. The second, more serious problem was that I had changed the machine builder's logic. An FC that used to be LAD was now SCL written by me. The acceptance reviewer would have to reread the entire block to make sure all the original behavior was still there. Multiply that by four positions, and reviewing the work would be a bigger job than making the changes.
Rewrite the FCs on both sides
Delete existing tags, convert the FC from LAD to SCL, and add a network at the station. It works for one position, but each position needs another manual rewrite, and the machine's original logic changes. The reviewer has to reread everything.
remote I/O pattern
Leave the original logic untouched, point the same tag names to %M, and add one new OB on each side to copy bits over the existing link. Every position uses the same pattern and can be generated from a table. The reviewer only reads the new OBs.
The remote I/O pattern: move addresses, not logic
What I missed in the first attempt was that I assumed moving I/O meant moving the program that used it too. That is not true. Main PLC's logic references tag names, not addresses. If the same tag names remain, the original program can compile and every line behaves as before. The only thing that needs to change is where each tag's bit ends up.
The final approach works like this. A relocated tag, such as Valve_Down, originally at %Q10.0, is re-addressed to memory bit %M100.0 on the same Main PLC. The valve-control FB still writes to Valve_Down as before. The value now goes into memory instead of out through the card. A new OB then reads that %M bit and sends it over the link to the station PLC, which drives the actual output. Sensors work in the opposite direction. The station reads the physical inputs and sends them back. The OB on Main PLC writes them to the %M bits of the original sensor tags, and the existing logic reads those tags as usual.
This is possible because PlcTag.LogicalAddress can be written directly through Openness V15.1, without deleting and recreating the tag. The name stays the same, the data type stays the same, and every reference to the tag in the program remains unaffected. I have already covered connecting scripts to TIA and the import pitfalls in the article on editing LAD through SimaticML.
This pattern has four principles.
- Main PLC's original logic stays completely untouched. Relocated tags are re-addressed from %Q or %I to %M while keeping their names.
- Add one new OB on each side. The central side copies the Up/Down command bits from %M into the send DB and writes received sensor bits to the %M bits of the original sensor tags. The station copies commands to physical outputs and sends physical sensor states back.
- Rename existing spare members in the communication DB to keep its length unchanged. If there are not enough, append members at matching offsets on both sides.
- Use a 1 Hz heartbeat in both directions. The link is considered healthy only after a heartbeat has been seen and has not gone silent for more than 3 seconds. If the link is lost, the station forces the cylinder UP and blocks DOWN, while the central side assumes a workpiece is present at that position.
Point 3 matters more than it might seem. The communication DBs on both sides must match bit for bit in structure. The machine already uses this link for other data too. Using existing spare members leaves the DB length completely unchanged. When appending members is necessary, the generator always enforces the same offsets on both sides.
The pair of OBs that exchange bits over the existing link
All the added code lives in these two new OBs. The Main PLC side does four things: generate the outgoing heartbeat, monitor the incoming heartbeat, send commands, and receive sensor states.
// OB_IOLink_A ฝั่ง Main PLC (SCL) - ชื่อ DB และ tag เป็นชื่อสมมติ
// 1) heartbeat ขาออก: สลับทุก 500 ms = 1 Hz
"DB_IOLink_A".HbOsc.TON(IN := TRUE, PT := T#500MS);
IF "DB_IOLink_A".HbOsc.Q THEN
"DB_IOLink_A".HbTx := NOT "DB_IOLink_A".HbTx;
"DB_IOLink_A".HbOsc.TON(IN := FALSE, PT := T#500MS);
END_IF;
"DB_ToStation_A".Hb := "DB_IOLink_A".HbTx;
// 2) watchdog ขาเข้า: ต้องเคยเห็น heartbeat ก่อน และห้ามนิ่งเกิน 3 วินาที
IF "DB_FromStation_A".Hb <> "DB_IOLink_A".HbPrev THEN
"DB_IOLink_A".HbRcvd := TRUE;
END_IF;
"DB_IOLink_A".HbTimer.TON(IN := ("DB_FromStation_A".Hb = "DB_IOLink_A".HbPrev), PT := T#3S);
"DB_IOLink_A".HbPrev := "DB_FromStation_A".Hb;
"DB_IOLink_A".PeerOK := "DB_IOLink_A".HbRcvd AND NOT "DB_IOLink_A".HbTimer.Q;
// 3) คำสั่ง: tag เดิม (ตอนนี้ชี้ %M100.0 / %M100.1) -> DB ส่ง
"DB_ToStation_A".DownCmd := "Valve_A_Down";
"DB_ToStation_A".UpCmd := "Valve_A_Up";
// 4) เซนเซอร์: DB รับ -> tag เดิม (ตอนนี้ชี้ %M100.2) ลิงก์หาย = ถือว่ามีชิ้นงาน
"Prox_A_InPos" := "DB_FromStation_A".Prox OR NOT "DB_IOLink_A".PeerOK;
The station side mirrors it. The heartbeat and watchdog sections are identical line for line; the difference is in the second half.
// OB_IOLink ฝั่ง Station PLC (SCL) - ส่วนที่ต่างจากฝั่งกลาง
// คำสั่งจากฝั่งกลาง -> เอาต์พุตจริง ลิงก์หาย: บังคับ UP ห้าม DOWN
"Valve_Down_Q" := "DB_FromMain".DownCmd AND "DB_IOLink".PeerOK;
"Valve_Up_Q" := "DB_FromMain".UpCmd OR NOT "DB_IOLink".PeerOK;
// เซนเซอร์จริง -> DB ส่งกลับฝั่งกลาง
"DB_ToMain".Prox := "Prox_InPos_I";
The acceptance reviewer can see everything I added by reading just these two blocks. The rest of the program is the original, which can be compared against the source to confirm there are no differences. The HbRcvd line came from a hole I left in the first version: the watchdog reported a healthy link even though it had never received a heartbeat. That story is long enough for its own article, which you can read in the article on the watchdog and the first 3 seconds after power-on.
One mapping table generates every position
Once every position used the same pattern, the only differences were data: the original tag names, the new station-side addresses, and which bits to use in the communication DB. I put all of it into one table in a single Python file, 380 lines long, and had it generate change set folders for each position and each side. Below is an abridged version showing the structure.
# gen.py - สร้าง change set ต่อตำแหน่ง ต่อฝั่ง จากตาราง mapping เดียว (ตัวอย่างย่อ ชื่อและ address สมมติ)
import os
OUT = 'changeset'
MAP = {
'Station_A': dict(mbyte=100, valve_down='Valve_A_Down', valve_up='Valve_A_Up',
prox=['Prox_A_InPos'], st_dq=('%Q4.0', '%Q4.1'), st_di=['%I4.0'],
cmd_bits=('Spare_1', 'Spare_2', 'Spare_3')),
'Station_B': dict(mbyte=101, valve_down='Valve_B_Down', valve_up='Valve_B_Up',
prox=['Prox_B_InPos_1', 'Prox_B_InPos_2'], st_dq=('%Q6.0', '%Q6.1'),
st_di=['%I6.0', '%I6.1'], cmd_bits=None), # ไม่มี member สำรอง -> append
}
def write(path, text): # TIA ต้องการ CRLF + BOM
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w', encoding='utf-8-sig', newline='\r\n') as f:
f.write(text)
def main_readdress(pos, c): # tag ชื่อเดิม -> %M บน PLC กลาง
mb, note = c['mbyte'], 'IO-Move %s' % pos
rows = ['%s|%%M%d.0|%s: valve moved to station PLC' % (c['valve_down'], mb, note),
'%s|%%M%d.1|%s: valve moved to station PLC' % (c['valve_up'], mb, note)]
rows += ['%s|%%M%d.%d|%s: prox moved to station PLC' % (p, mb, 2 + i, note)
for i, p in enumerate(c['prox'])]
return '\n'.join(rows) + '\n'
def link_members(c): # บิตที่ต้องมีใน DB สื่อสาร
want = ['Link_Up_Cmd', 'Link_Down_Cmd', 'Link_Heartbeat']
if c['cmd_bits']: # มี member สำรองพอ -> เปลี่ยนชื่อ ไม่เปลี่ยนความยาว DB
return [('rename', old, new) for old, new in zip(c['cmd_bits'], want)]
return [('append', None, new) for new in want] # ไม่พอ -> ต่อท้ายที่ offset เท่ากันสองฝั่ง
for pos, c in MAP.items():
assert len(c['prox']) == len(c['st_di']), (pos, 'จำนวนเซนเซอร์กับช่อง DI ไม่เท่ากัน')
write(os.path.join(OUT, pos, 'main', '10_tags_readdress.txt'), main_readdress(pos, c))
plan = '\n'.join('%s|%s|%s' % m for m in link_members(c)) + '\n'
write(os.path.join(OUT, pos, 'main', '19_link_members.txt'), plan)
write(os.path.join(OUT, pos, 'station', '19_link_members.txt'), plan)
print('[OK] %s: readdress %d tag, link %s' % (pos, 2 + len(c['prox']), link_members(c)[0][0]))
$ python gen.py
[OK] Station_A: readdress 3 tag, link rename
[OK] Station_B: readdress 4 tag, link append
$ cat changeset/Station_B/main/10_tags_readdress.txt
Valve_B_Down|%M101.0|IO-Move Station_B: valve moved to station PLC
Valve_B_Up|%M101.1|IO-Move Station_B: valve moved to station PLC
Prox_B_InPos_1|%M101.2|IO-Move Station_B: prox moved to station PLC
Prox_B_InPos_2|%M101.3|IO-Move Station_B: prox moved to station PLC
The actual version generates more files than this. Each folder contains a *_tags_readdress.txt file in the format name|new address|comment, followed by .udt, .db, and .scl files for the new OBs and DBs, plus another set for self-tests on the simulator. Filenames start with numbers because the apply script processes them in filename order: tags must come first, followed by UDTs, then DBs, and finally code.
The apply script and the resulting 12 files
The script that applies a change set to a project is 98 lines of PowerShell. It works in five steps: copy the original project, process the folder's files in filename order, compile, save, and archive. The part that handles re-addressing looks like this.
# ส่วนหนึ่งของ apply.ps1: ไฟล์ *_tags_readdress.txt บรรทัดละ name|newaddress|comment
foreach ($line in Get-Content $f.FullName -Encoding UTF8) {
if (-not $line.Trim()) { continue }
$nm, $addr, $cmt = $line.Split('|')
$r = FindTag $nm # คืน @(tag table, tag)
if (-not $r) { L " tag $nm not found"; continue }
$old = $r[1].LogicalAddress
$r[1].LogicalAddress = $addr # ชื่อเดิม ชนิดเดิม เปลี่ยนแค่ address
if ($cmt) {
foreach ($it in $r[1].Comment.Items) {
if ($it.Language.Culture.Name -eq 'en-US') { $it.Text = $cmt }
}
}
L " tag $nm $old -> $($r[1].LogicalAddress) in $($r[0].Name)"
}
The apply script accepts multiple folders in sequence in a single command. This is what made the combined set possible without writing anything extra. The delivery included both individual sets for each position and one combined set for all positions. I assembled the combined set from the same individual change sets.
# ชุดเดี่ยว: ฝั่ง Main PLC ของตำแหน่งเดียว
powershell.exe -NoProfile -File apply.ps1 -Src C:\Projects\Main -Work C:\Projects\WORK_A `
-Dir C:\Projects\changeset\Station_A\main -ArchiveDir C:\Projects\out -ArchiveTag A
# ชุดรวม: change set เดี่ยวทุกตำแหน่งต่อกันตามลำดับ
powershell.exe -NoProfile -File apply.ps1 -Src C:\Projects\Main -Work C:\Projects\WORK_ALL `
-Dir C:\Projects\changeset\Station_A\main,C:\Projects\changeset\Station_B\main `
-ArchiveDir C:\Projects\out -ArchiveTag ALL
| Item | Result |
|---|---|
| Number of sets | 5 sets (4 individual position sets, 1 combined set for all positions) |
| Resulting project files | 12 files |
| Compilation results | 0 errors in every file |
| Simulator self-tests | T0 through T5 passed on all 4 PLCs |
| Full package size | 470 MB |
| Combined set only | 165 MB |
Mistakes along the way
I made three mistakes on this job, and all three were fixed through process rather than code.
The first involved spare output channels at the station. I chose one based on a tag named SPARE, assuming the name meant it was free. It turned out another FC was using that tag. The name had not been updated to reflect its actual use. Since then, I do not trust names. Before claiming a channel, I must search for its tag name in the XML of every exported block and get 0 hits.
# ช่องที่จะยึดต้องไม่มีบล็อกไหนอ้างชื่อ tag นั้นเลย
$ grep -rl 'Name="Spare_Q4_0"' export/Station_PLC_1/xml | wc -l
0
The second was a compilation warning: 1 warning said the program used I/O that did not exist in the configured hardware. The question was whether my re-addressing had caused it. To prove that, I compiled an untouched copy of the original project. It produced the same warning, which meant it had been there from the start and was not mine. Without this control, I would have spent time fixing something that was not broken, or worse, fixing an existing machine warning that nobody had asked me to fix.
The third was that, along the way, I manually edited files in some position folders. As a result, the files in the folders began to diverge from the table. I set a rule: never edit the generated output. Make changes in the table or generator, then regenerate every folder together.
The whole benefit of the generator is that every position has the same structure. A reviewer can read one position and trust all four. The moment even one file is edited manually, that benefit disappears, and every position has to be reviewed individually again, just like the first attempt.
What has not been tested yet
The 0-error result and passing self-tests only prove that the logic is correct in the simulator, one PLC at a time. There are still four things I have not tested, and I stated them plainly in the handover documentation.
| Item | Why it has not been tested | Who must confirm it |
|---|---|---|
| Actual TCP links between PLCs | The simulator used cannot test the links between PLCs in this project | Check during commissioning |
| New wiring | It is on-site work, outside the program | On-site electricians and engineers |
| UP position on link loss | I do not know whether it is safe at every point on the machine | The engineer responsible for the machine |
| Whether spare I/O channels are actually free | I can only check the program, not the physical wiring | The on-site team must inspect the cabinet |
TCP links in the simulator have their own details. My measurements showed that a link through the CPU's second interface connected, but no data flowed. I covered that in the article on PLCSIM and the second interface.
Handover documentation that lists only passing checks leads the recipient to assume everything has passed. Untested items must be documented just as clearly as passing ones, along with when they need to be checked and who will check them.
To sum up, when moving I/O across PLCs while the existing logic belongs to someone else, do not start by rewriting the logic. First ask whether the existing tag names can stay. If they can, the job comes down to re-addressing and one OB on each side to copy bits. Every position follows the same pattern and can be generated from one table, while the reviewer only needs to read a few dozen lines of new code. I do regret some of the time spent on the first attempt, but without doing the manual rewrite first, I probably would not have seen where it stopped scaling.
This pattern comes at a cost: I/O that used to be wired directly now depends on a link between PLCs, with both latency and the possibility of disconnection. It suits signals that can tolerate this, and it needs a fail-safe position accepted by the on-site team. It is not suitable for safety signals, which must use hardwired connections or an F-CPU only. Feel free to adapt it to whatever machine you are working on. If I have left gaps in the explanation or have more findings from the site, I will come back and update it later.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first