Arduino Project #4: Arduino Nano and Ultrasonic Sensor HC-SR04, RB URF02


 Arduino Nano and Ultrasonic Sensor HC-SR04, RB URF02





// code is available to download - link below the video

/* HC-SR04 or RB URF02
 VCC to Arduino 5V
 GND to Arduino GND
 Echo (or OUTPUT) to Arduino pin 2
 Trig (or INPUT) to Arduino pin 3 */
#define echoPin 2 // Echo Pin (OUTPUT pin in RB URF02)
#define trigPin 3 // Trigger Pin (INPUT pin in RB URF02)

int led = 5;
int maximumRange = 350; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
int brightness;

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

void loop() {
// The following trigPin/echoPin cycle is used to determine the distance of the nearest object by bouncing soundwaves off of it.
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = duration/58.2; //Calculate the distance (in cm) based on the speed of sound.
 Serial.println(distance); // distance in cm
 brightness= map(distance,1,100,0,255);
 analogWrite(led, brightness);  
 delay(50); //Delay 50 ms
}

2 comments:

INSTAGRAM FEED

@soratemplates