You fix it by completely re-designing and then re-writing the code. If you want precision you will use peripheral hardware and a timer. Even then there will be tiny variations as the rising and falling times of pins with respect to the CPU clock aren't perfect (close, subcycle errors only, but not perfect.) You may also write crafted assembly code where you count cycles across branch edges and ensure that the exact same number of cycles occur for a 0 as for a 1 output. But that takes sit-down time on paper. What you did makes the least possible sense (almost.)
↧