Skip to content

Instantly share code, notes, and snippets.

@mwafa
Last active October 21, 2019 04:20
Show Gist options
  • Select an option

  • Save mwafa/7b3c6dd64b9fb31384e084f138578b3f to your computer and use it in GitHub Desktop.

Select an option

Save mwafa/7b3c6dd64b9fb31384e084f138578b3f to your computer and use it in GitHub Desktop.
/*
* Ultrasonic Sensor HC-SR04 and Arduino Tutorial
*
* by Dejan Nedelkovski,
* www.HowToMechatronics.com
*
*/
// defines output pin
#define LED1 2
#define LED2 3
#define LED3 4
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
pinMode(LED1, OUTPUT)
pinMode(LED2, OUTPUT)
pinMode(LED3, OUTPUT)
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
if(distance>10){
digitalWrite(LED1, HIGH)
}else{
digitalWrite(LED1, LOW)
}
if(distance>20){
digitalWrite(LED2, HIGH)
}else{
digitalWrite(LED2, LOW)
}
if(distance>30){
digitalWrite(LED3, HIGH)
}else{
digitalWrite(LED3, LOW)
}
}
@mwafa

mwafa commented Oct 21, 2019

Copy link
Copy Markdown
Author

itu yang rangkaian nya R1 yang 1K bisa diganti sesuai kebutuhan, misalkan ganti 47k

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment