In this video lesson we create a portable distance measuring prototype, using an Arduino Uno R4 WiFi. This project incorporates a HC-SR04 Ultrasonic Sensor, a ‘Go’ button, and the SSD1306 OLED Display. The project is powered by the Sunfounder Breadboard power bank. The arduino is powered by the power bank as well, so the project can operate totally portable. When the device is turned on, the OLED prompts the user to position the device. When the ‘Go’ button is pushed, the device measures the distance to the target, then displays the distance on the OLED display.
The video above gives all the details of the project, with step-by-step instructions.
For your convenience, the code developed in the video is presented below. Enjoy!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
#include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> int butPin = 2; int butVal = 1; int butValOld = 1; int trigPin = 4; int echoPin = 3; int pingTime; float targDist; int ft; float in; int screenWidth = 128; int screenHeight = 64; int oledReset = -1; #define SCREEN_ADDRESS 0x3C Adafruit_SSD1306 oled(screenWidth, screenHeight, &Wire, oledReset); void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(butPin, INPUT_PULLUP); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); oled.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS); oled.clearDisplay(); oled.display(); } void loop() { // put your main code here, to run repeatedly: oled.setCursor(0, 12); oled.setTextColor(WHITE); oled.setTextSize(1); oled.println("Point the "); oled.println("DistoMatic at"); oled.println("Target and Press"); oled.println("Go"); oled.display(); butVal = digitalRead(butPin); if (butValOld == 0 && butVal == 1) { targDist = findDistance(); ft = targDist/12; in = targDist - ft*12; oled.clearDisplay(); oled.setCursor(0, 0); oled.setTextColor(WHITE); oled.setTextSize(2); Serial.println(targDist); Serial.println(ft); Serial.println(in); oled.println(String(ft)+" Ft."); oled.println(String(in)+" In."); oled.display(); delay(5000); oled.clearDisplay(); oled.display(); } butValOld = butVal; } float findDistance() { float d; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); d = pulseIn(echoPin, HIGH) / 2. * .0135; return d; } |