After observing the discussions about bit operations in the group over the past few days, it’s hard to express my feelings! Some of the bit operation codes written by people made my eyes hurt. If the fundamentals of these bit operations are not solid, you could end up in serious trouble on-site! Not to mention anything else, just two years ago at that paper mill, a few young people’s chaotic bit operations caused the equipment to stop for three days, resulting in losses of over a million. I had to go in and fix it.
In fact, bit operations seem simple, but they can easily go wrong. What’s the reason? Simply put, it’s because of weak fundamentals and bad habits. I’ve seen too many engineers who just write code without thinking, and debug only when problems arise. This reckless approach will eventually lead to failure.
1
Common Pitfalls in Bit Operations
Let’s start with the most common issues. Many people like to use AND and OR directly between bits without considering precedence or adding parentheses. Writing code without parentheses shows a lack of understanding of data structures! Especially when mixing Siemens STL and SCL, the pitfalls are deeper than you might think. Last year, a young man argued with me that he could run code without parentheses. I just laughed; try running it on an old S7-300 without parentheses and see if it works!
Look at the following code:
// Incorrect Example IF Input_1 AND Input_2 OR Input_3 AND Input_4 THEN Output_1 := TRUE; END_IF;
Can you determine the execution order? Different PLC brands or even different firmware versions may interpret it differently. Remember this iron rule: whenever there are two or more logical operators, parentheses must be added! Although most modern PLCs will prioritize AND before OR, this rule is not universal, and if someone else has to maintain your code later, they might not understand it at all!
The correct way to write it is as follows:
// Correct Example IF ((Input_1 AND Input_2) OR (Input_3 AND Input_4)) THEN Output_1 := TRUE; END_IF;
By the way, speaking of this, I remember that in 2018, on the automotive production line using AB ControlLogix, the project leader reversed all the bit operations in the control word, writing the DINT to BOOL positions incorrectly, which caused a control delay of several tens of milliseconds, disrupting the entire production line’s rhythm. On the debugging day, everyone stayed up until 3 AM just because of this stupid mistake.
2
Masking Operations are Essential
Many PLC programmers come from electrical backgrounds and are not familiar with the computer thinking behind bit masking. To be honest, PLC engineers who cannot use masks are not qualified. Especially when processing data from HMIs or communicating with upper-level machines, using masks effectively can save a lot of code.
For example, if a machine needs to control four valves based on four independent buttons, but sometimes needs to open or close all at once. Those who have never used masks would typically write:
// Ordinary Method Valve_1 := Button_1 OR MasterControl; Valve_2 := Button_2 OR MasterControl; Valve_3 := Button_3 OR MasterControl; Valve_4 := Button_4 OR MasterControl;
Looks fine, right? But what if you have 16 valves? Or 32? Moreover, boolean variables actually take up a lot of space in memory, especially since some domestic PLCs handle bit addressing poorly. In this case, using word operations with masks is much more efficient:
On Siemens S7-1500, I usually do it like this:
// Bit Mask Processing, handling multiple bits at once ValveWord := (ButtonWord OR (MasterControl * 16#000F));
By the way, the mask 16#000F here represents hexadecimal F in the S7 series, which is binary 0000 0000 0000 1111, perfectly covering the low 4 bits. Practicing with bit masks will greatly improve your efficiency, and I have seen the worst case where a project had over 200 I/O points, writing thousands of lines for single bit processing, causing a performance bottleneck with CPU usage over 70%. After switching to bit mask processing, CPU usage dropped to below 30%.
Speaking of bit masks, it frustrates me that some domestic PLCs can’t even handle basic bit operations well… This is not aimed at anyone, but anyone who has used Siemens and AB will really complain. Siemens’ bit logic is truly the industrial standard, yet some PLCs insist on doing things differently, even getting the bit shift operators wrong, which is just painful to look at.
3
Examples of Misleading Practices
Last year, I took on a project at a food factory where the previous programmer wrote something like this:
// Negative Example tmp := INT_TO_BOOL(WORD_TO_INT(StatusWord AND 16#0004)); IF tmp THEN // Processing Code END_IF;
Do you see it? This kind of back-and-forth conversion is bound to cause errors! The result of bit operations should be compared directly to 0, why complicate it?
// Correct Approach IF (StatusWord AND 16#0004) <> 0 THEN // Processing Code END_IF;
This code is simple and efficient, requiring fewer CPU instruction cycles and is more readable. The previous convoluted conversions made my head hurt just looking at it.
Also! Beginners often make the mistake of mixing bit operations with arithmetic operations, for example:
// Incorrect Example Result := (Value1 + Value2) AND 16#00FF;
Can you guess which one it calculates first? Different PLCs may have different rules! Some will calculate addition first and then AND, while others will throw an error. Programming is not a guessing game, does adding parentheses hurt??
// Correct Example Result := ((Value1 + Value2) AND 16#00FF);
Ah, I digress. Back to the topic of performance bottlenecks. In PLC cyclic scanning programs, if bit operations are poorly written, they can consume all CPU resources. I remember that two years ago at the paper mill in Northeast China, the scanning time was originally 5ms, but after adding hundreds of unit reads and writes, the scanning time skyrocketed to over 30ms, causing communication timeout alarms to go off continuously. Later, I went in and merged all single-point operations into word operations in one afternoon, and the problem was solved.
Another common issue is jitter compensation, which can be simplified using bit operations. For example, in the past, unstable wiring would cause signal jitter, and some engineers would use TON/TOF timers for filtering, but a few lines of bit operations and shifts can also do the trick:
// Using shifts for simple filtering FilterReg := FilterReg SHL 1; IF Input_Signal THEN FilterReg := FilterReg OR 16#0001; END_IF; // If 8 consecutive times are 1, consider the signal stable as ON IF FilterReg AND 16#00FF = 16#00FF THEN Stable_Signal := TRUE; // If 8 consecutive times are 0, consider the signal stable as OFF ELSIF FilterReg AND 16#00FF = 16#0000 THEN Stable_Signal := FALSE; END_IF;
This bit shift register approach is particularly useful for on-site modifications, allowing for simple filtering without needing extra variables. Those who love to use ladder diagrams for this end up writing seven or eight networks, which is exhausting to look at.
4
Final Thoughts
As I write this, some may wonder, is it really worth discussing such basic things as bit operations? Weak fundamentals can lead to major issues! I’ve seen countless so-called “senior engineers” who can’t even grasp the most basic bit logic, struggling during debugging. When problems arise, they call, “Electrician, come quick, the equipment is malfunctioning,” only to find a multitude of issues once they get on-site.
If you are a beginner, remember these points:
1. Develop the habit of adding parentheses; it’s better to write a few extra characters than to be unclear.
2. Familiarize yourself with the bit operation characteristics of the PLC you are using; they may differ between brands.
3. Use word operations whenever possible instead of a large number of single-point operations to improve efficiency and readability.
4. Bit masking combined with shifting operations is powerful; practice this area more.
5. Test, test, and test again! Don’t rush to upload and run.
By the way, I am currently working on a set of automated tools for PLC programming that can automatically check for these common bit operation errors. If you’re interested, feel free to message me. Next time, I plan to discuss control delays in PLCs; if anyone has thoughts, please feel free to leave comments for discussion.
Before you go, remember to click “Looking”~