最近在臉書上看到一篇文章:「原來超音波只要用echo腳位就好」。原作是在Microbit上使用,筆者就開始想在Arduino上試試看,底下為筆者搭配Arduino New Ping的成功做法。
- Arduino UNO R3 板子 x 1
- 杜邦線母對母 x 7
- 330歐姆電阻 x 1
- Arduino Sensor Shield x 1
- HC-SR04 x 1
- SSD1306 I2C 0.96 吋 OLED 顯示模組 x 1
- 麵包版 x 1
硬體電路:

接線方式:
將HC-SR04 接在麵包版上,使用330歐姆的電阻將HC-SR04的 Echo 與 Trig 給接在一起。
HC-SR04 的 Echo 接到 Arduino Sensor Shield Pin 12
OLED 的 SCL 接到 Arduino Sensor Shield SCL
OLED 的 SDA 接到 Arduino Sensor Shield SDA
安裝 Arduino New Ping 與 OLED的程式庫:
https://github.com/adafruit/Adafruit_SSD1306
https://github.com/adafruit/Adafruit-GFX-Library
Arduino IDE 程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <NewPing.h> | |
#include <SPI.h> | |
#include <Wire.h> | |
#include <Adafruit_GFX.h> | |
#include <Adafruit_SSD1306.h> | |
#define SCREEN_WIDTH 128 // OLED display width, in pixels | |
#define SCREEN_HEIGHT 64 // OLED display height, in pixels | |
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) | |
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin) | |
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); | |
#define NUMFLAKES 10 // Number of snowflakes in the animation example | |
#define LOGO_HEIGHT 16 | |
#define LOGO_WIDTH 16 | |
static const unsigned char PROGMEM logo_bmp[] = | |
{ B00000000, B11000000, | |
B00000001, B11000000, | |
B00000001, B11000000, | |
B00000011, B11100000, | |
B11110011, B11100000, | |
B11111110, B11111000, | |
B01111110, B11111111, | |
B00110011, B10011111, | |
B00011111, B11111100, | |
B00001101, B01110000, | |
B00011011, B10100000, | |
B00111111, B11100000, | |
B00111111, B11110000, | |
B01111100, B11110000, | |
B01110000, B01110000, | |
B00000000, B00110000 }; | |
#define PING_PIN 12 // Arduino pin for both trig and echo | |
NewPing sonar(PING_PIN, PING_PIN); | |
void setup() { | |
Serial.begin(9600); | |
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); | |
display.clearDisplay(); | |
display.setTextColor(WHITE); | |
display.setCursor(0,30); | |
display.setTextSize(4); | |
display.println("Hello World!"); | |
display.display(); | |
} | |
void loop() { | |
delay(500); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay | |
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS). | |
Serial.print("Ping: "); | |
unsigned int distanceCM = uS / US_ROUNDTRIP_CM; | |
Serial.print(distanceCM); // convert time into distance | |
Serial.println("cm"); | |
display.clearDisplay(); | |
display.setTextColor(WHITE); | |
display.setCursor(0,30); | |
display.print(distanceCM); | |
display.println("cm"); | |
display.display(); | |
} |
示範影片: