Here you have my previous tutorial about it:
#includes
and#defines
, before runsetup():
#include <SPI.h> //we need all those nasty libraries for OLED
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4 // this is the reset pin, IM NOT USING IT
Adafruit_SSD1306 display(OLED_RESET);
- In the
setup()
function:
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
//initialize with the I2C addr 0x3C (128x64)
display.clearDisplay(); // clear the display before start
- In
loop()
function:
display.setCursor(22,20); //x,y coordinates
display.setTextSize(3); //size of the text
display.setTextColor(WHITE); //if you write BLACK it erases things
display.println(distance); //print our variable
display.setCursor(85,20); //set size,print the units (cm/in)
display.setTextSize(3);
#ifdef CommonSenseMetricSystem//if theres#define CommonSenseMetricSystem
display.println("cm"); //print "cm" in oled
#endif
#ifdef ImperialNonsenseSystem//if there´s#define ImperialNonsenseSystem
display.println("in"); //print "in" in oled
#endif
display.display(); //you need to actually display all that data
delay(500); //wait!, human speed
display.clearDisplay(); //clear black the display
How to use HC-SR04 ultrasonic rangeHere you have the datasheet, the HC module sends a burst of pulses and then measures the time that the ultrasound´s echo takes to return to its original place.
- Make a pulse for HC trigger, the HC will do a pulse burst:
long duration, distance; //our beloved variables
digitalWrite(trigPin, LOW); //PULSE ___|---|___
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
- PulseIn() is a rare used function, detects the length of the step high (__----__) or low (----___---)
We use #ifdef
for only compiling the parts that we need.
duration = pulseIn(echoPin, HIGH); //
#ifdef CommonSenseMetricSystem
distance = (duration/2) / 29.1;
#endif
#ifdef ImperialNonsenseSystem
distance = (duration/2) / 73.914;
#endif
- And this for debugging in case your Oled is not working:
Serial.println(distance);//debug
javier muñoz sáez
13 projects • 84 followers
Electronic engineer and sparky person.
I make tutorials so my future self doesnt need to remember how he did the thing
Comments