gioblu / PJON

PJON (Padded Jittering Operative Network) is an experimental, arduino-compatible, multi-master, multi-media network protocol.
Other
2.73k stars 239 forks source link

Document behaviour of set_random_seed() and role of A0 pin during begin() #387

Closed alastaira closed 3 years ago

alastaira commented 3 years ago

I spent some time today debugging a strange issue with my device, which I eventually managed to track down to (what I think is) undocumented behaviour in the PJON begin() method. Even though I've now fixed the problem, I thought I'd write it up here for the benefit of anyone else in the future!

Short version

PJON expects pin "A0" to be an unconnected Analog Input pin, so that it can be sampled to set a random seed on startup. This pin can be set to a different value using set_random_seed(), but I don't think either the default behaviour nor that function are documented or demonstrated in any example code.

Long version

I'm using an ESP32, and I have a button connected to Pin 36 which kept falsely triggering on startup. I initially thought this was a hardware fault, but after checking all the connections several times and swapping in a different button, the issue remained. So I figured it must be a problem in software. I stripped down my code line-by-line and removed every library, and eventually realised it was being caused by the PJON bus.begin() line (which, typically, was about the last place I looked!) The only pin I thought PJON used was the communication pin (or pins, if using separate input/output), which was set to 25. I scanned the code for occurrences of "36", just in case it had been hardcoded somewhere for some reason. And then I noticed that the begin() function starts by setting a random seed by sampling the "A0" pin (a fairly common practice). On an ESP32, Pin A0 corresponds to Pin 36, which I was using as a digital input (with an external pull-up resistor). The effect of the analogRead() in the begin() method caused this to read LOW on the first iteration of loop(), but HIGH on all subsequent passes - thus behaving as if the button had been pressed! The solution is quite straightforward - to call set_random_seed() prior to begin(), but I just thought it would be helpful to highlight that requirement if you were planning using pin A0 for anything! ;)

gioblu commented 3 years ago

Ciao @alastaira thank you very much for your support, I will add the missing documentation as soon as possible.

gioblu commented 3 years ago

Ciao @alastaira thank you very much for your report. I am sorry you lost some time figuring this out. I have added the required section in the documentation. Feel free to open a pull-request if you think that should be stated differently.

Happy tinkering :)