Config.h file settings for NC Limit Switches

I have built a CNC Router using an Arduino Uno with a Protoneer CNC Shield ver 3.0 attached. It has 4 DRV8825 Stepper Drivers driving NEMA17 motors drawing 1.7A max. 1 motor each for X and Z axis and 2 motors for Y. These are operating correctly.I am using Arduino version 1.8.12, grbl version 0.9 and CNCjs software for the g code.
My problem is that I cannot get the switches to shut off any axis operation. I have wired up Limit Sw in NC at each end stop for all 3 axis, through optocouplers to eliminate EM interference. I am getting 5V when a switch is activated - 0.2V when not. They are connected to X+, Y+ and Z+ with the ground wire on the Gnd pin adjacent to the 5V pin. I have set $5=1. The only time I can get the switch to cutoff the axis operation is when I set $21=1 and then the Alarm sets and I then have to Reset or disconnect and restart the program. I have also tried setting $22=1, but an error message comes up stating I do not have Homing enabled.
Any help would be greatly appreciated.

Here is the guide I use for limit switches

Be aware of NOISE on limit switch cables and counter it accordingly with shielded cables and capacitors.

Thank you - yes I have built and using the "OK" circuit at the bottom of that guide.

In my case shielded cables were most of the fix along with some small ferrite rings close to the switches and a single loop through the ring.

Were you using optocouplers to isolate? Or just shielded cables on the switch wiring? I have the optocouplers working and their output doesn't appear to false trigger. I'm concerned that the Homing function is not working and hence won't allow the Limit Switches to function correctly. Please see my original post.

Just shielded cables on the switch wiring

See this post for some tips starting at post #38

Thanks again - as I am using optocouplers to isolate the switches from the CNC Shield, I don't think that is my problem. I triggered the switches manually multiple times, and didn't get any spurious output from the optocouplers. The problem was getting grbl to recognise the triggers. I am now awaiting the latest version of the CNC Shield, which I believe is version 3.51, which I will try to configure and see how I get on. Again many thanks for your input.

Not sure another shield will fix the issues but they are always great to have on hand for a swap out and I keep a few different ones about.