Is it possible to write code in the sketch that checks the functioning of the ultrasonic sensor? Say if the sensor stopped working then the arduino will alert the user in the serial monitor.
closed as too broad by VE7JRO♦, sempaiscuba, Juraj, Greenonline, jose can u c Aug 27 '18 at 18:16
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.
First of all, this question is hard to answer because you don't provided a name of ultrasonic sensor that you are using. Also as @Majenko pointed out, the key here is to determine the state that you think sensor is not working correctly.
But if assume that you're using standard trig/echo ultrasonic sensor (HC-SR04 or similar) interface - the only possible solution here is to monitor the output(echo) signal of the sensor. Broken sensor will not respond on trigger pulses, so you'll not get the echo pulses. However, these sensors also do not send a signal if the object is out of range of the sensor.
Thus, it is possible to determine the breakdown by monitoring the output signal from the sensor only if you know that the object will always be in range. Otherwise - you can not determine for certain because of what you did not receive a signal, whether it is a sensor failure, or the object is too far from the sensor.
Detecting OUTPUT trigger failure - grounded. Add INPUT pin connected via small signal diode ( 1N914 / 1n4148) to TRIGGER pin. Read its value every time you set the TRIGGER HIGH and it should read HIGH when working correctly and LOW when the device TRIGGER pin is faulty AKA grounded by the device.
Detecting INPUT - echo pin failure - grounded. Connect delay circuit (RC) between TRIGGER and ECHO pins. (I would put diode in into it too just to make sure you do not ground TRIGGER from faulty ECHO pin)
Calculate the RC delay to emulate value lower than your minimal expected distance. Every time you send "ping" you should get TWO echoes - one from the "delay circuit" and one for real. If you get NONE - your ECHO pin is faulty AKA grounded.
Perhaps adding current monitoring to device supply could also be used as failure indicator. The device current draw MAY be different when "pi9nging" or when idle / not operational.