Overview of Integrated Counting on S7-300 Compact CPUs
The SIMATIC S7-300 Compact CPUs (CPU 312C, CPU 313C, CPU 313C-2 DP/PtP, and CPU 314C-2 DP/PtP) integrate technological functions directly on the module. These include high-speed counters, frequency measurement, and pulse-width modulation. Unlike standard digital inputs that are evaluated by the cyclic process image update, the integrated counter channels of the CPU 31xC are evaluated by a dedicated hardware block on the module and can therefore detect pulse edges that are far shorter than the OB1 cycle time of the CPU.
The reference document for these functions is the SIMATIC S7-300 Technology Functions manual (order number 6ES7390-1AF30-0AA0 / file S7300C_tf_e.pdf), Chapter 5. The hardware description and wiring details are covered in the S7-300 CPU 31xC and CPU 31x Manual (file HB_CPU31xC_und_CPU31x_e.pdf). The application of the counting function for general SIMATIC S7 CPUs is described in the Counting Function Manual (file GS_ZAEHLEN_E.PDF).
Why Counting Works Despite Slow OB1 Cycle
OB1 executes the user program cyclically. The cycle time of a CPU 314C with a fully loaded program is typically between 5 ms and 20 ms. A pulse train from a 10 kHz incremental encoder has a period of 100 µs - two orders of magnitude shorter than the OB1 cycle. Yet the CPU 31xC counts every pulse correctly. Three architectural details make this possible:
- Dedicated counter hardware on the compact CPU: The integrated counter channels are implemented in a hardware block (ASIC + counter register) that is clocked independently of the CPU's scan cycle. Each incoming pulse is latched into a 32-bit hardware counter register on the rising edge of the pulse.
- Direct hardware-to-memory mapping: The hardware counter value is mapped into a fixed address range in the I/O area of the CPU. The application can read this value at any time without first having to request it from the technology module.
- Hardware interrupt on comparator events: If the count value reaches a configured comparison value, a hardware interrupt (OB 40) can be triggered, bypassing OB1. The interrupt latency is in the microsecond range, not the cycle range.
The technology functions are therefore not executed in the OB1 cycle. They run in the background. The OB1 cycle only serves to coordinate the data exchange between the user program and the technology module via special system function blocks (SFBs). The SFBs do not start or stop the counter - the counter runs continuously as soon as it has been parameterized and enabled.
CPU 31xC Model Variants and Counter Performance
The number, maximum frequency, and operating modes of the integrated counter channels depend on the specific compact CPU in use. The following table summarizes the counter capabilities of the relevant CPU 31xC variants. Values are taken from the CPU 31xC Manual Collection and the S7-300 Module Data Manual.
| CPU | Order Number (MLFB) | Counter Inputs | Max. Frequency | Counting Modes | Outputs |
|---|---|---|---|---|---|
| CPU 312C | 6ES7312-5BF04-0AB0 | 2 (channels 0-1) | 10 kHz | Count, Frequency, PWM (1 ch) | 2 DO (24 V / 0.5 A) |
| CPU 313C | 6ES7313-5BG04-0AB0 | 3 (channels 0-2) | 30 kHz | Count, Frequency, PWM (2 ch) | 8 DO (24 V / 0.5 A) |
| CPU 313C-2 PtP | 6ES7313-6BG04-0AB0 | 3 (channels 0-2) | 30 kHz | Count, Frequency, PWM (2 ch) | 8 DO + serial interface |
| CPU 313C-2 DP | 6ES7313-6CG04-0AB0 | 3 (channels 0-2) | 30 kHz | Count, Frequency, PWM (2 ch) | 8 DO + PROFIBUS DP |
| CPU 314C-2 PtP | 6ES7314-6BH04-0AB0 | 4 (channels 0-3) | 60 kHz | Count, Frequency, PWM, A/B counter | 8 DO + serial interface |
| CPU 314C-2 DP | 6ES7314-6CH04-0AB0 | 4 (channels 0-3) | 60 kHz | Count, Frequency, PWM, A/B counter | 8 DO + PROFIBUS DP |
Supported Counting Modes
Each counter channel can be operated in one of three counting modes, configured via HW Config under the properties of the CPU in STEP 7. The same channel cannot be switched at runtime - the mode is fixed at configuration time.
| Mode | Signal Source | Range | Typical Use |
|---|---|---|---|
| Endless counter | One count input (pulse), optional gate input | 0 to 32 767 (or -32 768 to +32 767) | Position count, part count |
| Periodic counter | One count input, hardware gate | 0 to 999 (or user range) | Repeat-count with auto-reset |
| Frequency measurement | One count input | 0.1 Hz to max counter freq. | Speed monitoring |
The CPU 314C-2 also supports the A/B counter mode (SFB 38), which uses two pulse trains in quadrature (phase-shifted by 90°). The hardware decodes the direction of rotation and increments or decrements the count value accordingly. Multiplication by 4 (counting every edge of both channels) is also selectable. The maximum input frequency in A/B mode is reduced by a factor of 4 compared to single-channel counting (15 kHz on CPU 314C-2).
Hardware Wiring and Encoder Interface
The integrated counter inputs are located on the front connector X1 of the CPU. Pin-out (CPU 314C-2 example):
| Pin X1 | Signal | Function |
|---|---|---|
| 1 | 1L+ | 24 V encoder supply |
| 2 | DI+0.0 | Channel 0 count input A |
| 3 | DI+0.1 | Channel 0 direction / B input |
| 4 | DI+0.2 | Channel 0 hardware gate |
| 5 | DI+0.3 | Channel 1 count input A |
| 6 | DI+0.4 | Channel 1 direction / B input |
| 7 | DI+0.5 | Channel 1 hardware gate |
| 8 | DI+0.6 | Channel 2 count input |
| 9 | DI+0.7 | Channel 3 count input |
| 20 | 1M | Ground for inputs |
Encoder wiring notes:
- Use shielded twisted-pair cable for all encoder signals. Connect the shield to the grounded S7-300 mounting rail at both ends (low-impedance).
- Provide a separate 24 V supply for the encoder. Do not power the encoder from the CPU's 1L+ terminal if the encoder current exceeds 200 mA - use an external power supply.
- The hardware gate input must be tied to a defined level (24 V for "gate open", 0 V for "gate closed") if the hardware gate is not used. The CPU will not count without a defined gate level.
- Maximum cable length: 50 m for 24 V encoders at 10 kHz. For higher frequencies or longer runs, use encoders with line-driver outputs and an external signal converter.
Configuration in STEP 7 HW Config
The integrated technology is configured in HW Config in STEP 7 V5.x (the configuration tool for S7-300). The steps are:
- Open the SIMATIC 300 station and select the CPU 31xC.
- Double-click the CPU to open the properties dialog. Switch to the "Counting" tab.
- Activate the channels you want to use (Channel 0, Channel 1, ...).
- Select the counting mode (Endless, Periodic, or Frequency) and the operating mode (single-phase, two-phase with direction, A/B quadrature).
- Set the maximum count value (only relevant for periodic counting).
- Configure the hardware gate behavior (cancels count, interrupts, no effect).
- Assign the hardware interrupt (OB 40) sources if comparator events are needed.
- Set the input filter time (0.5 µs, 1 µs, 2 µs, 5 µs, 10 µs, 20 µs). The filter suppresses noise but reduces the maximum count frequency. For 60 kHz counting, use 2 µs or smaller.
- Compile and download the hardware configuration.
System Function Blocks for Counting
Once the channel is configured, the application exchanges data with the technology module through the SFBs listed below. The SFBs are part of the SIMATIC library and are called from OB1 or any other user program block.
| SFB | Name | Function | Supported CPUs |
|---|---|---|---|
| SFB 29 | HS_COUNTER | Counter control (start, stop, read, set comparison value) | All CPU 31xC |
| SFB 30 | FREQ_MES | Frequency measurement, integration time, limit values | All CPU 31xC |
| SFB 38 | HSC_A_B | A/B counter with hardware gate (CPU 314C-2 only) | CPU 314C-2 DP / PtP |
| SFB 39 | HSC_OR | OR combination of multiple counter channels (logical linking) | CPU 314C-2 DP / PtP |
Each SFB instance is a system data block (DB) that must be assigned a number. The instance DB holds the channel parameters, the current count, the status bits, and the comparison values. A separate instance DB is required per channel.
Programming Example: SFB 29 in Endless Counter Mode
The following STL snippet shows the minimal call sequence for an endless counter with a comparator. The comparator triggers a hardware interrupt (OB 40) when the count reaches the comparison value.
// Call SFB 29 for channel 0
// Instance DB: DB 30 (assigned in HW Config or inserted manually)
CALL SFB 29, DB 30
LADDR := W#16#100 // Logical address of channel 0 (configurable)
CHANNEL := 0 // Channel number on the CPU
SW_GATE := I0.0 // Software gate - 1 = counting enabled
CTRL_DO := // Direct control of digital output (optional)
SET_DO := // Set DO on comparator event
JOB_REQ := // 1 = execute a job (e.g. set count)
JOB_ID := // Job identifier
JOB_VAL := // Job value
STS_GATE: = // 1 = gate open
STS_STRT: = // 1 = counter has been started
STS_LTCH: = // Latch bit - comparator reached
STS_DONE: = // Job complete
STS_C_DN: = // Count downward active
STS_C_UP: = // Count upward active
COUNTVAL: MD100 // Current count value (DINT)
MEASVAL: // Measured frequency (DINT, in 0.1 Hz)
The hardware configuration in HW Config assigns the logical base address W#16#100 for channel 0 by default. The address is shown in the properties dialog of the CPU under the tab "Addresses". The instance DB must be created with the same number that is referenced in HW Config ("Counting" tab, "Instance DB for SFB 29").
Hardware Interrupt (OB 40) and Comparator Events
Each counter channel has two comparison values. When the count value crosses a comparison value (either upward or downward), the CPU can trigger a hardware interrupt OB 40 if this is configured in HW Config. The OB 40 contains the event identifier in the local data at OB40_POINT_ADDR (16 bits) and the channel number. The interrupt latency is in the order of 100-300 µs, which is sufficient for fast reaction on a count event without requiring OB1 polling.
Typical OB 40 implementation for a comparator event:
ORGANIZATION_BLOCK OB 40
TITLE = "Hardware Interrupt - Counter Event"
VAR_TEMP
OB40_EV_CLASS : BYTE; // 16 = interrupt activated
OB40_STRT_INF : BYTE; // 2 = OB was entered
OB40_POINT_AD : DWORD; // Address of event source
OB40_FLT_ID : BYTE; // Fault identifier
info : ARRAY[1..20] OF BYTE;
END_VAR
BEGIN
// Read event source: low byte = channel, high byte = event type
L #OB40_POINT_AD;
L DW#16#0000FFFF;
AW;
T MB 200; // MB 200 = channel number that caused the interrupt
// Custom reaction code:
SET ;
S M 101.0; // Set "comparator reached" flag for OB1
END_ORGANIZATION_BLOCK
Data Consistency and the Snapshot Mechanism
Because the counter value changes asynchronously to OB1, reading the count value during a long OB1 scan can result in an inconsistent value being read (e.g., a value that changes between the high word and the low word read). To prevent this, the CPU 31xC provides a snapshot mechanism: a dedicated I/O read operation on the counter channel's logical address latches the current 32-bit count value into an internal buffer, and the subsequent read of the two 16-bit words returns the latched value. The SFB 29 internally performs the snapshot read, so applications that use SFB 29 do not need to handle this manually.
L PIW ... or L PID ...) instead of the SFB, the snapshot must be triggered by writing a value to the control byte of the channel. The exact procedure is described in the S7-300 Technology Functions manual, Chapter 5.3. This is a common source of intermittent errors when porting legacy code.Comparison with S7-1200 High-Speed Counters
The S7-1200 family also provides integrated high-speed counters, but the architecture and configuration approach differ significantly from the CPU 31xC. The S7-1200 supports up to 6 high-speed counters on the CPU 1214C (CPU 1212C: 4, CPU 1211C: 3) with maximum frequencies of 100 kHz single-phase and 80 kHz in A/B mode. The HSC is configured in TIA Portal through a dedicated HSC configuration dialog, and the counting is controlled by the CTRL_HSC instruction in the program.
Key differences:
| Feature | S7-300 CPU 31xC | S7-1200 |
|---|---|---|
| Configuration tool | STEP 7 V5.x (HW Config) | TIA Portal |
| Control instruction | SFB 29 (HS_COUNTER) instance DB | CTRL_HSC / CTRL_HSC_EXT |
| Maximum frequency | 10-60 kHz (model-dependent) | 100 kHz single, 80 kHz A/B |
| Counting modes | Endless, Periodic, Frequency, A/B | Endless, Single, Periodic, A/B, A/B 4x |
| Hardware interrupt | OB 40 with event identifier | Hardware interrupt OB attached in HSC config |
| Data consistency | Snapshot via SFB 29 | Direct from HSC IDB (hardware latched) |
For projects migrating from CPU 31xC to S7-1200, the SFB 29 logic can be rewritten as a CTRL_HSC call. The HSC IDB of the S7-1200 contains the current count value at the COUNT symbol. Detailed configuration is documented at Configuring a high-speed counter on TIA Siemens Documentation and the general overview is provided at General information on high-speed counters (S7-1200) in the Siemens Industry Online Support.
Commissioning Checklist
- Verify that the CPU 31xC firmware version supports the desired counting mode. CPU 314C-2 with firmware V2.0 or higher is required for the A/B counter (SFB 38).
- In HW Config, set the input filter to a value appropriate for the maximum expected frequency. For 30 kHz: filter ≤ 2 µs. For 60 kHz: filter ≤ 1 µs.
- Connect the encoder supply and the signal lines. Tie the hardware gate input to a defined level (24 V for "gate open") if the hardware gate is not used.
- Download the hardware configuration. Verify in the CPU diagnostic buffer that no configuration errors are reported (event ID 16#4931, 16#4932).
- Insert the instance DB for the SFB 29 / SFB 30 / SFB 38 in the S7 program.
- Call the SFB in OB1 and set SW_GATE = TRUE.
- Force the count value via the SFB 29 JOB interface (JOB_ID = 1) to test the system before connecting the live encoder.
- Connect the encoder, run a slow-speed test, and verify the count increments in the VAT (Variable Table) when monitoring the instance DB.
- Verify the hardware interrupt path by setting a comparison value below the current count and confirming that OB 40 is entered.
Troubleshooting Matrix
| Symptom | Likely Cause | Diagnostic Step | Resolution |
|---|---|---|---|
| Counter does not increment | Software gate closed | Check SW_GATE bit on SFB 29 input | Set SW_GATE = TRUE in user program |
| Counter does not increment | Hardware gate open but level wrong | Measure voltage at hardware gate input (pin 4 / X1) | Wire 24 V to hardware gate or disable hardware gate in HW Config |
| Counter increments erratically | Encoder cable too long or unshielded | Check cable routing, ground shield | Use shielded cable, max 50 m, ground at both ends |
| Counter value inconsistent in OB1 | Direct I/O access without snapshot | Search for L PID / L PIW on counter address | Read via SFB 29 (handles snapshot internally) |
| OB 40 not entered on comparator event | Hardware interrupt not assigned | Check CPU properties, "Basic Interrupts" tab | Assign OB 40 to the channel and enable "Comparator event" |
| Diagnostic buffer event 16#4931 | Incorrect parameter assignment for the technology function | Open the diagnostic detail in STEP 7 | Re-check the counting mode selection in HW Config |
| Counter freezes at a value | JOB_ID = 4 (set counter) was sent with a value | Check JOB_REQ pulse in the user program | Do not set JOB_REQ every cycle; use a one-shot |
| CPU goes to STOP with SF LED on | OB 40 missing (required for hardware interrupt) | Read diagnostic buffer for "OB not loaded" | Insert OB 40 into the S7 program, even if it is empty |
Field-Proven Tips and Caveats
- The SFB 29 must be called in OB1 (or a higher-priority OB) at least once per cycle. Even if the application only wants to read the count value, the SFB must be called so that the instance DB is updated.
- The instance DB of SFB 29 / SFB 30 must be marked as non-optimized (classic DB) if the application reads its symbols from external sources. The S7-300 classic DBs do not support optimized block access.
- For A/B counting with a 24 V single-ended encoder, the phase shift of 90° must be guaranteed over the full frequency range. Open-collector encoders with slow rise times may not produce a clean 90° shift above 10 kHz. Use push-pull (PNP) encoders for A/B mode above 20 kHz.
- The maximum count frequency in the data sheet is a hardware limit. It assumes a 50% duty cycle. If the encoder produces short pulses (low duty cycle), the maximum usable frequency is lower because the input filter rejects pulses shorter than the filter time.
- Do not use the integrated DO of the CPU 31xC for switching inductive loads without external free-wheeling protection. The DO is rated 0.5 A but the internal protection is not designed for repetitive switching of contactors or solenoids.
- For applications requiring more than 4 counters, use the FM 350-1 or FM 350-2 counter modules in the S7-300 rack. These provide 1-8 counter channels with higher accuracy and additional functions such as measurement mode.
Why does the CPU 31xC count correctly even when OB1 cycle time is longer than the pulse period?
The integrated counter channels are evaluated by a dedicated hardware block on the CPU module that latches each pulse into a 32-bit hardware register on the rising edge. The hardware runs independently of the OB1 scan. The application reads the latched value from the I/O area at OB1 cycle boundaries, so the OB1 cycle time is irrelevant for pulse detection. Hardware interrupts (OB 40) can be triggered on comparator events with sub-millisecond latency.
Which SFB controls the integrated counter on a CPU 314C-2?
SFB 29 (HS_COUNTER) controls endless, periodic, and single-phase counting. SFB 30 (FREQ_MES) handles frequency measurement. SFB 38 (HSC_A_B) is used for A/B quadrature counting on the CPU 314C-2 only (firmware V2.0 or higher). SFB 39 (HSC_OR) is available on the CPU 314C-2 for logical OR combination of multiple counter channels. Each instance requires its own instance DB assigned in HW Config.
What is the maximum count frequency of the CPU 31xC integrated counters?
CPU 312C: 10 kHz. CPU 313C, 313C-2 DP/PtP: 30 kHz. CPU 314C-2 DP/PtP: 60 kHz. In A/B quadrature mode, the effective count rate is one quarter of the single-channel maximum because all four edges are counted. The input filter setting in HW Config must be 1 µs or smaller to achieve the rated maximum frequency; longer filter times reduce the maximum usable frequency proportionally.
How do I configure the hardware gate for a CPU 31xC counter channel?
The hardware gate input is a physical terminal on the CPU front connector. The input must be held at 24 V for the gate to be open and 0 V for the gate to be closed. If the hardware gate is not used, the configuration in HW Config must be set to "Hardware gate not assigned" or the input must be tied to 24 V externally. The software gate (SW_GATE bit of SFB 29) is in series with the hardware gate - both must be active for counting to occur.
Can the CPU 31xC counters be configured in TIA Portal?
The CPU 31xC is supported in TIA Portal as of V13 SP1, but the integrated technology functions (counting, frequency measurement, PWM) must be configured by calling the SFBs (SFB 29, SFB 30, SFB 38) directly. TIA Portal does not provide a graphical configuration dialog for the CPU 31xC integrated counters. For a fully graphical HSC configuration in TIA Portal, use the S7-1200 family, which has dedicated HSC configuration tools and the CTRL_HSC instruction.