Example Code for Arduino-Switch Output
Last revision 2025/12/17
Hardware Preparation
- DFRduino UNO R3 (or similar) x 1
- Water-proof Ultrasonic Sensor (ULS) x1
- Connectors
Software Preparation
Wiring Diagram
Other Preparation Work
The internal probe surface is regarded as the detecting starting point by default. If you take the plane of the bell-mouth as starting point, then the distance will be the detected distance minus 40mm.
Sample Code
* ****************************************************
* @brief Water-proof Ultrasonic Sensor (ULS)
* @copyright [DFRobot](https://www.dfrobot.com), 2016
* @copyright GNU Lesser General Public License
* @author [Xiaoyu]([email protected])
* @version V1.0
* @date 2019-03-11
* GNU Lesser General Public License.
* All above must be included in any redistribution
* ****************************************************/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
unsigned char buffer_RTT[7] = {};
unsigned long duration;
int datapin = 9;
void setup() {
Serial.begin(57600); // Enable serial port and set band rate to 57600 bps
mySerial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(datapin, INPUT);
digitalWrite(LED_BUILTIN, HIGH);
}
void loop() {
digitalWrite(LED_BUILTIN, LOW);//give low level
duration = digitalRead(datapin);//read pin state
delay(3);
switch(duration){
case 0 :Serial.println("LOW"); break;//the distance to the object is less than the preset distance, set the defalut to 1m
case 1 :Serial.println("HIGH"); break;//the distance to the object is more than the preset distance
}
}
Result
Was this article helpful?
