Hackster is hosting Hackster Holidays, Ep. 7: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Friday!Stream Hackster Holidays, Ep. 7 on Friday!
James Peter Perrone Jefferies
Published © GPL3+

How to connect the Ultrasonic and LDR Sensors with NodeMcu

Have you ever wondered how to make use of an Ultrasonic Sensor, LDR Sensor or LED? Then this guide is made especially with you in mind!

BeginnerProtip30 minutes9,516
How to connect the Ultrasonic and LDR Sensors with NodeMcu

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
Jumper wires (generic)
Jumper wires (generic)
×9
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Photo resistor
Photo resistor
×1
Resistor 10k ohm
Resistor 10k ohm
×1
LED (generic)
LED (generic)
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

Completed Project

Arduino
const int ldr = A0;
const int trigPin = D1;
const int echoPin = D2;
int ldrVal = 0;
long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(D3, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;
  ldrVal = analogRead(ldr);
  Serial.println(ldrVal);
  Serial.println(distance);
  if (distance > 35)
  {
    digitalWrite(D3, HIGH);
    delay(500);
    digitalWrite(D3, LOW);
    delay(500);
  }
  else
  {
    digitalWrite(D3, LOW);
    delay(1000);
  }
 }

Credits

James Peter Perrone Jefferies

James Peter Perrone Jefferies

2 projects • 3 followers

Comments