Skip to content

Instantly share code, notes, and snippets.

@samilkorkmaz
Last active February 25, 2020 15:55
Show Gist options
  • Save samilkorkmaz/4a809d1445081f131b85a71f9b133398 to your computer and use it in GitHub Desktop.
Save samilkorkmaz/4a809d1445081f131b85a71f9b133398 to your computer and use it in GitHub Desktop.
Arduino Nano: LED brightness with HC-SR04 ultrasonic distance sensor
//Reference: https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/
const int ledPin = 9;
const int trigPin = 8;
const int echoPin = 4;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW); //to make sure that the trigPin is clear
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW); //after this, 8 cycle sonic burst will be sent out
long duration_us = pulseIn(echoPin, HIGH);
int distanceRaw_cm = 0.034*duration_us/2;
int distance_cm = constrain(distanceRaw_cm, 0, 30);
Serial.print(distance_cm);
int brightness = map(distance_cm, 0, 30, 255, 0);
Serial.print(", ");
Serial.println(brightness);
analogWrite(ledPin, brightness);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment