Ultrasonic Sensors – How far is it?

This diagram shows how to wire up a distance sensor on an Arduino.

 

2wire_bb

#include <Wire.h>    // these are all the libraries we need for working with our screen.
#include <SPI.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>

#include <NewPing.h>

#define TRIGGER_PIN  9
#define ECHO_PIN     8
#define MAX_DISTANCE 10000

#define OLED_RESET 4                  // here we get the screen ready for sending instructions to using the libraries above
Adafruit_SSD1306 display(OLED_RESET); 

int x = 0;  // this is an important new step - here we are making a container called X to put a number in.
//this is a container that can only fit integers inside of it - an integer is a whole number (the ones we count with)
//this container is called a variable. Variables are central to maths and computing.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
 
   display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // tell the Arduino that our little OLED screen is 128 x 64 pixels
    display.clearDisplay(); 
    display.setTextColor(WHITE);
}

void loop() {
  display.clearDisplay();
  display.setCursor(0,0);
  delay(50);
  int uS = sonar.ping();
  display.print("Ping: ");
  display.println(uS / US_ROUNDTRIP_CM);
  int pitch = (uS / US_ROUNDTRIP_CM)*15;
  display.println(pitch);
  tone(11,pitch);
  display.println("cm");
  display.display();
}