Code readingHow-to

PLC ladder logic to compare barcode strings and count three reads

Wire an RS-232 barcode reader to a PLC serial port, receive each string in ladder logic, compare it to two stored codes and latch an output after three reads.

LumaSpec Vision10 min read Share on LinkedIn

On this page 10 sections
  1. 01What you need on the bench
  2. 02Wire the reader to the PLC port
    1. One cable for trigger and serial
  3. 03Set the port and the reader to the same framing
  4. 04The ladder pattern: receive, strip, compare, count
  5. 05Timing arithmetic: how fast three reads really are
  6. 06Prove the logic before you hand the machine over
  7. 07Five mistakes that cost an afternoon
  8. 08When this ladder is the wrong tool
  9. 09Order and commissioning checklist
  10. 10Questions

A fixed barcode reader wired to the PLC's serial port can confirm every part before the machine accepts it: the reader scans the same code three times, and only the third identical read latches the acceptance output. This walkthrough builds that logic end to end on a controller whose built-in serial port offers a plain receive instruction and string comparison — no add-on serial communication module. You will cross-wire three conductors, configure one start character and one terminator, write six ladder rungs that strip, compare and count, and size the timeout from the real message time at 9600 baud. The pattern fits any compact controller whose built-in port carries receive and string-compare instructions.

What you need on the bench

  • A barcode reader with an RS-232 output and configurable framing: one start character and one terminator you can choose.
  • A PLC with a built-in serial port, or its serial option board, whose instruction set includes a receive instruction and string comparison.
  • The programming software and instruction manual for that controller family.
  • A 24 V DC supply for the reader and a spare transistor output for the trigger line.
  • A DB9 female-to-open cable for the serial run, plus the reader's power leads.

Before you strip a single wire, settle the electrical plan once: the barcode reader PLC communication guide works through the port, protocol and handshake decisions in order, and it is the checklist to finish before any of the rungs below.

A cable with a DB9 female connector on one end and open leads on the other covers both ends of the run: the plug mates with the reader's serial socket, and each lead lands on a screw terminal at the PLC.

CablesFrame Grabber I/O Cable, DB9F to Open, 7 m (LS-CBL-0224)LS-CBL-0224
Type
Frame grabber I/O cables
Length
6-8 m
$79.00View partBuild a system with it

Wire the reader to the PLC port

Three conductors carry the link. The reader's transmit lands on the PLC's receive, the reader's receive lands on the PLC's transmit, and the two signal grounds join at the PLC terminal — a serial port listens on its RX pin, so the crossover is not optional. Bond the cable shield to chassis at the panel end only, so the shield never becomes a current path.

The RS-232 standard's guideline of roughly 15 m at 20 kbit/s is the envelope to design inside. At 9600 baud a run inside that envelope is comfortable; longer runs often work, but treat one as proven only after a few thousand reads have passed through it.

Drive the reader's trigger input from a spare PLC transistor output, one pulse per read, at the minimum pulse width the reader's manual states. One trigger per read is what makes the counter mean three scans of the same part rather than three arbitrary auto-reads.

One cable for trigger and serial

Where the reader breaks out through an M8 8-pin socket, trigger and serial can share one drag-chain-rated cable:

CablesCamera Power and I/O Cable, M8 8-pin connector, Male to Open end (8-core), 7 m, drag-chain use (LS-CBL-0300)LS-CBL-0300
Type
Power and I/O cables
Length
6-8 m
$79.00View partBuild a system with it

The core split runs 3 serial (TX, RX, signal ground), 2 trigger, 3 spare. Keep that lead away from AC power cores in the shared drag chain so the serial bits arrive clean.

Set the port and the reader to the same framing

On the PLC side, open the controller's system or parameter settings, find the built-in serial port, and set it to its plain receive mode — many manuals call this no-protocol or free-format serial communication. Start at 9600 baud, 8 data bits, no parity, 1 stop bit, and enable the port in the program.

On the reader side, set the identical format, then build the message frame: one start character (STX), the payload, one terminator (CR). One start character fixes the payload offset at byte 1, which is what lets the strip rung copy an exact length. Switch off any preamble or suffix the reader offers by default — every extra character becomes a compare failure later. If the reader insists on CR plus LF, either select CR only or plan for two terminator characters in the arithmetic.

Set the receive instruction's end condition to the terminator, with the maximum count above the longest expected message — 32 characters covers both codes here with room for a longer code at changeover.

The ladder pattern: receive, strip, compare, count

The names below are examples — your programming software names its registers and bits its own way, so map each one to your address scheme.

Name Type and size Initial value Role
RX_BUF string buffer, 32 bytes cleared raw message: start char + payload + terminator
CMP_BUF string buffer, 32 bytes cleared stripped payload
CODE_A constant string, 12 characters family-A code, for example A12345678901 first compare target
CODE_B constant string, 9 characters family-B code, for example B98765432 second compare target
MATCH_A, MATCH_B bits 0 one-scan compare results
COUNT_A, COUNT_B up-counters, preset 3 0 consecutive matches per code
OUT_A, OUT_B retentive (latched) bits 0 acceptance outputs
T_TRIG on-delay timer, preset 0.5 s — per-read timeout

Then the six rungs:

  1. Trigger. On the rising edge of the read-request bit, pulse the trigger output and start T_TRIG.
  2. Receive. Call the serial receive instruction every scan while the port is enabled. When the terminator arrives, it fills RX_BUF and sets the receive-done flag.
  3. Strip. On the done flag, copy the payload into CMP_BUF from offset 1 with length = message length − 2 (start char + terminator). For code A that is 14 − 2 = 12 characters. Clear RX_BUF and the done flag so nothing leaks into the next read.
  4. Compare. CMP_BUF equal to CODE_A sets MATCH_A for one scan; CMP_BUF equal to CODE_B sets MATCH_B. If neither matches, set a reject bit and reset both counters — a different code mid-count means the wrong part is in the fixture.
  5. Count and latch. MATCH_A increments COUNT_A, MATCH_B increments COUNT_B, both preset to 3. COUNT_A done latches OUT_A; COUNT_B done latches OUT_B. Either latch also sets a port-lock bit so a fourth read cannot restart the count.
  6. Reset. A product-change command clears both counters, both latches, the reject bit and the buffers, and drops the port-lock bit.

Keep the compare strict: compare CMP_BUF at the stripped length, never the full 32-byte buffer — trailing bytes make two equal-looking strings unequal.

Timing arithmetic: how fast three reads really are

t_char = 10 bits / baud rate t_msg = message length × t_char margin = timeout / t_msg

Async serial at 8 data bits, no parity, 1 stop bit sends every character as 1 start + 8 data + 1 stop = 10 bits. At 9600 baud one character takes 10 / 9600 = 1.04 ms. A code A message is 1 + 12 + 1 = 14 characters, so it occupies the line for 14 × 1.04 ms = 14.6 ms. Code B is 1 + 9 + 1 = 11 characters, or 11.5 ms. At 19200 baud the same code A message halves to 7.3 ms.

A 0.5 s timeout against a 14.6 ms message is a margin of 500 / 14.6 ≈ 34×, which absorbs slow decodes and a busy scan without ever looking like a fault. Space the three triggers 250 ms apart and the count completes within 3 × 250 ms = 750 ms plus the reader's decode time — typically a few tens of milliseconds — so a 2 s machine window holds the whole confirmation with room to spare. The 32-byte buffer against a 14-character longest message leaves 18 bytes of margin.

Prove the logic before you hand the machine over

  1. Read code A three times on the bench: COUNT_A steps 1, 2, 3 and OUT_A latches on exactly the third read.
  2. Read A, A, then B: both counters reset and no output latches. This is the test that proves the consecutive-match rule.
  3. Read an unknown code: the reject bit sets and both counters stay at zero.
  4. After OUT_A latches, read A again: the port-lock bit holds and nothing increments.
  5. Pull the serial lead mid-count: T_TRIG times out in 0.5 s, a no-read fault sets, and the count clears.
  6. Watch CMP_BUF during a live read: exactly 12 characters for code A, no start character, no terminator.

Five mistakes that cost an afternoon

  • Comparing the raw message. STX and CR still in the buffer make the compare false forever — strip first, compare second.
  • Comparing the whole buffer at fixed length. Trailing bytes make equal strings unequal; compare at the stripped length.
  • Terminator mismatch. A reader sending CR plus LF against logic expecting one terminator leaves a stray character leading the next message — the classic cause of garbage characters from a barcode scanner.
  • The wrong receive instruction for the port. Add-on serial communication modules carry their own receive instruction set, and those instructions will not run on a built-in port; take the receive and string instructions from the manual's table for the port you actually wired.
  • Counting triggers instead of matches. A reader left in continuous mode auto-reads between pulses and phantom-counts; switch auto-read off.

If a bench copy still refuses to match, this walkthrough of string-compare mismatches in ladder programming software traces the usual register-level causes one by one. For how the stripped bytes actually sit in the controller's memory, see ASCII barcode strings in PLC memory: bytes, words and clears.

When this ladder is the wrong tool

Hard-coded CODE_A and CODE_B fit a two-part machine. When codes change per shift or come from a recipe system, read them over a fieldbus instead: the Modbus RTU route into a PLC or a network reader matched as a TCP client or listener both scale past two codes. The wider set of choices sits in barcode scanner input methods to a PLC: serial, USB and Ethernet.

A USB-only reader at a workstation belongs on an HMI, not on this ladder — HID keyboard mode versus a serial port covers that decision. If the three reads exist only because decodes are marginal, fix the read itself: date code print quality inspection shows what a readable code looks like. The mirror-image case — two readers whose strings must agree — is the two barcode readers into one PLC comparison.

Order and commissioning checklist

  • Reader output is RS-232, not USB-only — the built-in port speaks RS-232 levels and nothing else.
  • The built-in port's instruction table shows a receive instruction and string comparison — module instructions will not run there.
  • Both ends configurable to 9600 baud, 8 data bits, no parity, 1 stop bit, one start character, one terminator.
  • Cable ends match the hardware: DB9 female at the reader, open leads at the terminals; drag-chain grade if the reader rides a mover.
  • Trigger driven from a transistor output, one pulse per read, width per the reader's manual.
  • Counter semantics agreed with production: three consecutive matches, reset on a different code.
  • Total serial run inside the 15 m envelope.

More reader-integration patterns sit on the code-reading topic page.

Pick the cables and the accessories finder to filter the run by connector and length, and the configurator assembles the whole set for a station. If the port side of your controller is unclear, ask through the contact page and we will name the receive and compare instructions for that port.

Questions

How long can the RS-232 cable between reader and PLC be?

The RS-232 standard's own guideline is about 15 m of cable at 20 kbit/s. At 9600 baud with 14-character messages, a 7 m run sits well inside that envelope. Keep the total run at or under 15 m; for longer distances, choose a reader with RS-485 or Ethernet output rather than stretching an RS-232 link.

Do I need an add-on serial communication module for this?

Not if the controller's built-in port offers a plain receive instruction plus string-processing instructions. Add-on serial communication modules expose a different receive instruction set, and those instructions will not run on a built-in port. Take the receive and string instructions from the manual's table for the port you actually wired.

The string looks right in the monitor, but the compare never fires — why?

Usually leftover framing: a terminator still in the buffer, a second terminator character from a CR plus LF pair, or a stale tail from a longer previous message. Clear the receive buffer at the end of each compare and strip to an exact payload length, and the comparison lines up.

Should the counter need three consecutive matches or three matches in total?

For part acceptance, use consecutive: any string that is neither code A nor code B resets the running count and raises a reject bit, because a different code mid-count means the wrong part is in the fixture. Counting three matches in total only makes sense when one part legitimately carries the same code on several lanes.

Can trigger, serial and reader power share one cable?

Yes, on an 8-core to-open lead: 3 cores for TX, RX and signal ground, 2 for the trigger pair, and spares for a second input. Route that cable away from AC power cores in the same drag chain so the serial bits stay clean.