Printing to serial fixes digital reading

So, something really strange... I am working on a small project where I am reading pin values from the MCP23017 IO Expander. I then spin a motor, depending on the values of these digital inputs - if input A is high, then the motor may spin, otherwise it may not.

Now, for some reason, the program works perfectly when I read the values, then print them to serial, and then control the motors. But, for some reason beyond me, the code refuses to work when I remove the single line that prints the variable to serial. It just states that the pins are low, and therefore the motors may not spin. Then when I add just that single line:

Serial.println(Inhibits, BIN);

then it works again... and it works perfectly...

Has anyone had an issue like this before? I had thought it may be the compiler that is optimizing the variable away, but it doesn't help to add a line of arithmetic... The variable is also used multiple times later on and is a global...

Could it be a timing thing? Serial is pretty slow, and maybe that breather allowed something else to complete correctly?

Please read

Especially the bit about posting code. No one can help you with code they cannot see.

Another common problem that is affected by slight changes like this is writing outside the bounds of an array. Adding/removing a print can cause the compiler to rearrange things in memory, which changes what is being overwritten by the array write.

post the code using "</>"

Post. The. Code.

I thought it may have been, so I added a 1000ms delay to test the theory - but no luck...

Its a couple hundred lines. The only line of interest is included in the question

OK, here is my answer : well a couple of characters as I assume these are the only ones of interest :

nd the

Do you see why you need to post the full code?

A couple of hundred lines is nothing for most of us here to scan through.

So: for those following, I got it working without needing to print to serial. What did work was to subtract 1, and then add 1. When I had tested earlier doing some math, I had added 0b0 - which I assume the compiler chucked. It worked to sub 1 in one line, and add 1 in the next. I just need to check margin cases that could cause overflow in the ALU and that that is handled properly... Perhaps I should say (if byte>1, sub 1 then add 1, else add 1, then sub 1)

really? Man are you lucky that you made such a pickle run. This is neither programming nor debugging, this is just botch and it can and will cause you problems again at any time. This is the only place where you can be absolutely sure of your secret code with this botched alleged bug fix.

Lol. My car won't start... here is a picture of the car key - tell me why it won't start.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.