Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
Rayan kiwan
Published © CERN-OHL

Arduino Distance sensor and OLED

Short and easy, read distance 2 - 400 cm and plot it in I2C OLED screen.

BeginnerFull instructions provided8,751
Arduino Distance sensor and OLED

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Graphic OLED, 128 x 64
Graphic OLED, 128 x 64
×1
Jumper wires (generic)
Jumper wires (generic)
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

circuit diagram

Code

distance sensor oled

Arduino
//rayan kiwan
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define CommonSenseMetricSystem
//#define ImperialNonsenseSystem

#define trigPin 13
#define echoPin 12

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //initialize with the I2C addr 0x3C (128x64)
  display.clearDisplay();

}

void loop() {
  long duration, distance;
  
  digitalWrite(trigPin, LOW);  //PULSE ___|---|___
  delayMicroseconds(2); 
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); 
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
  
  #ifdef CommonSenseMetricSystem
  distance = (duration/2) / 29.1;
  #endif
  #ifdef ImperialNonsenseSystem
  distance = (duration/2) / 73.914;
  #endif

  display.setCursor(22,20);  //oled display
  display.setTextSize(3);
  display.setTextColor(WHITE);
  display.println(distance);
  display.setCursor(85,20);
  display.setTextSize(3);
  
  #ifdef CommonSenseMetricSystem
  display.println("cm");
  #endif
  #ifdef ImperialNonsenseSystem
  display.println("in");
  #endif
  
  display.display();

  delay(500);
  display.clearDisplay();
 
  Serial.println(distance);//debug
  
 

}

Credits

Rayan kiwan

Rayan kiwan

36 projects • 2 followers

Comments