Devices & Components
Arduino Leonardo with Headers
Ultrasonic Sensor - HC-SR04 (Generic)
Project description
Code
HC-SR04 Code
arduino
1#define echoPin 8 // echo pin connected to pin 8 2#define trigPin 9 // trig pin connected to pin 9 3#define RED 5 // red led connected to pwm pin 5 4#define GREEN 6 // green led connected to pwm pin 6 5 6int time; 7int dist; 8const int MAX_DIST = 400; // Anything over 20 cm (120us pulse) is "out of range" 9char outputValue; //8bit 0 to 255 10 11void setup() { 12 pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT 13 pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT 14 pinMode(RED, OUTPUT); 15 pinMode(GREEN, OUTPUT); 16 Serial.begin(9600);//start serial monitor 17} 18 19void loop() { 20 // trigger sensor for 10us pulse 21 digitalWrite(trigPin, LOW); //reset trig condition 22 delayMicroseconds(2); 23 digitalWrite(trigPin, HIGH); // set trig HIGH for 10 us 24 delayMicroseconds(10); 25 digitalWrite(trigPin, LOW); // return to LOW 26 27 // read echo pin, output in us 28 time = pulseIn(echoPin, HIGH); 29 30 // Calculate distance in cm 31 dist = time * 0.0343 / 2; // time * speed of sound through air, divided by 2 (pulse is there and back) 32 outputValue = map(dist, 0, MAX_DIST, 0, 255); //map int to 8 char 33 34 Serial.print("Distance: ");//Prints distance in serial monitor 35 Serial.print(dist); 36 Serial.println(" cm"); 37 38 if (dist < MAX_DIST){ 39 analogWrite(RED, outputValue); // more red when close 40 analogWrite(GREEN, 255 - outputValue); // more green when far away 41 } 42 43 else{ 44 analogWrite(RED, 255); 45 analogWrite(GREEN, 255); 46 } 47 48} 49
Downloadable files
HC-SR04 wiring diagram
HC-SR04 wiring diagram

HC-SR04 wiring diagram
HC-SR04 wiring diagram

Comments
Only logged in users can leave comments