I would like to ask if there is a code that detects if a sensor is connected to the arduino automatically.
For example, I have a DS18B20 that gives a reading of -127.00 if it's not connected, so I placed an if statement saying if it's equal to this, then it's obviously not connected.
Seems simple enough, right? But for a PIR Motion Sensor, I placed an if statement saying if digitalRead equals 1, then it is definitely on. However, I may look silly waving my hand every time the arduino gets reset just for that message of saying it is on.
Probably no way without getting the sensor to change state (wave to it), but who can say for sure cause we do not know what exact PIR Motion Sensor that you have. Does it have a data sheet?
I have some of those and there is no way to query them that I know of. But, of course, that does not mean that it is impossible. There may be a member that has a clever way to do it.
Edit: I just thought of something to try. Give me a minute to wire up a IR LED and one of my sensors. Maybe turning on (flashing) an IR LED that it can see will get it to change state.
I didn't think that it would work and it does not, but we are allowed to experiment, aren't we?
Probably the IR wavelength of the IR LED and human body are that much different. I had no luck finding to what wavelength that the HC-SR501is sensitive. I am pretty sure that my IR LED is 940nm.
Maybe connect a high value pull-down resistor like 470K to the Arduino pin. Start with the pin in INPUT mode. If the pin reads HIGH, the sensor must be connected. Otherwise change the input mode to INPUT_PULLUP. If the input changes from LOW to HIGH, the sensor not connected. Obviously this is not fool proof. All it ready does is detect if the pin is floating. But that might be good enough for this project.
The PIR on the data sheet that was linked to, shows an onboard MCU driving the output through a 1k series resistor.
You could attach it to an analog input and bias it with a high value voltage divider. It would read half scale (or something) when not connected, and some digital level when connected. You don't need the bandwidth of digital for this.
Not certain about that, I admit, and my suggestion relies on the sensor actively pulling HIGH/LOW. The data sheet may say something about that in its original Chinese version, but the English translation reads like it was written by a drunken idiot.