Skip to content

Instantly share code, notes, and snippets.

@Anas-jaf
Created November 1, 2023 22:02
Show Gist options
  • Save Anas-jaf/8247b460a4038ac962e0fcb76661867d to your computer and use it in GitHub Desktop.
Save Anas-jaf/8247b460a4038ac962e0fcb76661867d to your computer and use it in GitHub Desktop.
/*
JSN-SR04T-V3.0 Ultrasonic Sensor - Mode 0 Demo
srt04-mode0.ino
Uses JSN-SR04T-V3.0 Ultrasonic Sensor
Displays on Serial Monitor
Mode 0 is default mode with no jumpers or resistors (emulates HC-SR04)
DroneBot Workshop 2021
https://dronebotworkshop.com
*/
// Define connections to sensor
#define TRIGPIN 12
#define ECHOPIN 11
// Floats to calculate distance
float duration, distance;
void setup() {
// Set up serial monitor
Serial.begin(115200);
// Set pinmodes for sensor connections
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
}
void loop() {
// Set the trigger pin LOW for 2uS
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
// Set the trigger pin HIGH for 20us to send pulse
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(20);
// Return the trigger pin to LOW
digitalWrite(TRIGPIN, LOW);
// Measure the width of the incoming pulse
duration = pulseIn(ECHOPIN, HIGH);
// Determine distance from duration
// Use 343 metres per second as speed of sound
// Divide by 1000 as we want millimeters
distance = (duration / 2) * 0.343;
distance = distance/10;
// Print result to serial monitor
Serial.print("distance: ");
Serial.print(distance);
Serial.println(" cm");
// Delay before repeating measurement
delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment