Mission 6 - Distance Sensor Sound Device
 DuinoKit Essentials   Started by Daniel Alich   2017-06-27 21:41:16 -04:00   Comments: 1    Viewed: 61

  1. Daniel Alich
    Daniel Alich Member Staff Member


    /*
    HC-SR04 Ping distance sensor]
    VCC to arduino 5v GND to arduino GND
    Echo to Arduino pin 3
    Trig to Arduino pin 2

    Buzzer
    + to Arduino pin 4
    - to Arduino GND

    This sketch will also display distance values in Serial Monitor

    */

    #define trigPin 2
    #define echoPin 3
    #define buzzer 4

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

    void loop() {
    // One process to calculating distance using HC-SR04 Ping distance sensor
    // There are numerous examples and explinations online on how the code works
    long duration, distance;
    digitalWrite(trigPin, LOW); // Added this line
    delayMicroseconds(2); // Added this line
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10); // Added this line
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

    // map the input range (in this case, 0 - 135cm from the Distance Sensor)
    // to the output pitch range (2500 - 50Hz)
    // change the minimum and maximum input numbers below
    // depending on the range your sensor's giving:
    int thisPitch = map(distance, 0, 135, 2500, 50);

    // play the pitch:
    tone(buzzer, thisPitch, 10);

    Serial.print(distance);
    Serial.print(" cm ");
    Serial.print(thisPitch);
    Serial.println("Hz");

    delay(50); // delay in between reads for stability

    }
    Daniel Alich, 2017-06-27 21:41:16 -04:00
  2. (You must log in or sign up to post here)

Report Post

Write your reason

Log in | Sign up
Terms & Conditions!
Help!