코드 검색

아두이노 코드 및 HC-SR04 초음파 거리 센서와 SSD1306 OLED 디스플레이용 영상

아두이노 코드 및 HC-SR04 초음파 거리 센서와 SSD1306 OLED 디스플레이용 영상

이 튜토리얼에서는 HC-SR04 초음파 거리 센서와 SSD1306 OLED 디스플레이를 함께 사용하여 거리 측정값을 시각화하는 방법을 시연합니다. 이 프로젝트를 통해 컴퓨터 없이도 거리를 측정할 수 있어 로봇 공학을 포함한 다양한 응용 분야에 이상적입니다. 이 프로젝트가 끝나면 OLED 화면에 거리 측정값을 직접 표시하는 기능적인 설정을 갖추게 됩니다.

How HC-SR04 ulrasonic sensor work
SSD1306 OLED display

진행하면서 두 구성 요소에 필요한 배선 연결을 설명하고 이러한 구성 요소를 통합하는 Arduino 코드를 안내하겠습니다. 이를 통해 센서가 거리를 측정하는 방법과 해당 데이터를 OLED 디스플레이에 출력하는 방법을 이해하는 데 도움이 될 것입니다. 더 자세한 설명이 필요하면 이 튜토리얼과 관련된 비디오(비디오 00:00)를 참조할 수 있습니다.

하드웨어 설명

이 프로젝트의 주요 구성 요소는 HC-SR04 초음파 거리 센서와 SSD1306 OLED 디스플레이입니다. HC-SR04는 초음파를 사용하여 작동합니다. 트리거 핀을 통해 음파 펄스를 방출하고 에코 핀에서 반향을 수신합니다. 소리가 돌아오는 데 걸린 시간을 계산하여 물체까지의 거리를 결정할 수 있습니다. 이 센서는 일반적으로 최대 400-500cm의 단거리 측정에 매우 효과적입니다.

SSD1306 OLED 디스플레이는 텍스트와 그래픽을 표시할 수 있는 I2C 인터페이스 디스플레이입니다. SDA(데이터 라인)와 SCL(클록 라인)의 두 핀을 통해 통신합니다. 우리 설정에서 이러한 핀은 특정 Arduino 핀에 연결되어 쉽게 통합하고 제어할 수 있습니다.

데이터시트 세부 정보

제조업체다양함
부품 번호HC-SR04
로직/IO 전압5V
공급 전압5V
출력 전류(채널당)15mA
피크 전류(채널당)20mA
PWM 주파수 안내해당 없음
입력 로직 임계값0.3*Vcc ~ 0.7*Vcc
전압 강하 / RDS(on) / 포화해당 없음
열 제한0-70°C
패키지4핀 모듈
참고 사항 / 변형표준 모듈

  • 두 구성 요소 모두에 적절한 전원 공급(5V)을 확인하십시오.
  • I2C 통신이 필요한 경우 풀업 저항을 사용하십시오.
  • 간섭을 피하기 위해 트리거 및 에코 라인을 짧게 유지하십시오.
  • 정확한 측정을 위해 초음파 센서의 방향을 확인하십시오.
  • 기계적 진동을 피하기 위해 디스플레이에 안정적인 표면을 사용하십시오.

배선 지침

Arduino wiring for HC-SR04 ultrasonic SSD1306 128x64 OLED
Arduino wiring for HC-SR04 ultrasonic SSD1306 128x64 OLED

HC-SR04 초음파 센서를 연결하려면 먼저 VCC 핀(보통 빨간색)을 Arduino의 5V 핀에 연결하십시오. 다음으로 GND 핀(일반적으로 검은색 또는 노란색)을 Arduino의 GND 핀 중 하나에 연결하십시오. 트리거 핀(종종 파란색)은 Arduino의 디지털 핀 12에 연결하고, 에코 핀(보통 녹색)은 디지털 핀 11에 연결해야 합니다.

SSD1306 OLED 디스플레이의 경우 VCC 핀을 Arduino의 5V 핀에 연결하고 GND 핀을 GND에 연결하십시오. SCL 핀은 Arduino의 A5 핀에, SDA 핀은 A4 핀에 연결해야 합니다. 전용 I2C 핀이 있는 다른 Arduino 모델을 사용하는 경우 디스플레이를 해당 핀에 직접 연결하십시오.

코드 예제 및 설명

설정 함수에서 디스플레이와 직렬 통신을 초기화합니다. 다음 발췌문은 디스플레이가 설정되는 방법을 보여줍니다:

void setup() {
   Serial.begin(9600);// 9600 보드로 직렬 모니터 설정
   display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // I2C 주소 0x3D로 초기화
}

여기서 디스플레이는 I2C 주소로 초기화되어 Arduino와 통신할 수 있습니다. 직렬 모니터도 거리 값을 출력하도록 설정됩니다.

메인 루프에서 디스플레이를 지우고 거리를 측정한 다음 출력합니다. 다음 코드 스니펫은 거리 측정을 처리하는 방법을 보여줍니다:

void loop() {
   display.clearDisplay();
   String distance  = String(sonar.ping_cm());// 거리를 가져와 디스플레이용 문자열로 변환
   robojaxText(distance +"cm", 3, 20, 3, false);
   display.display();
   delay(50); // 핑 사이에 50ms 대기
}

이 루프는 지속적으로 거리를 측정하고 현재 측정값으로 디스플레이를 업데이트합니다. `robojaxText` 함수는 OLED 화면에 텍스트를 표시하는 데 사용됩니다.

시연 / 기대 효과

설정이 완료되고 코드가 업로드되면 OLED 화면에 거리가 센티미터 단위로 표시되는 것을 볼 수 있습니다. 물체를 센서에 가까이 또는 멀리 이동하면 표시된 값이 그에 따라 변경되어야 합니다. 센서가 올바르게 방향이 지정되고 방해받지 않는지 확인하십시오(비디오 02:30).

비디오 타임스탬프

  • 00:00 - 프로젝트 소개
  • 01:15 - 배선 지침
  • 02:30 - 코드 설명
  • 04:00 - 센서 시연

이미지

HC-SR04 ulrasonic sensor
HC-SR04 ulrasonic sensor
How HC-SR04 ulrasonic sensor work
How HC-SR04 ulrasonic sensor work
Arduino wiring for HC-SR04 ultrasonic SSD1306 128x64 OLED
Arduino wiring for HC-SR04 ultrasonic SSD1306 128x64 OLED
SSD1306 OLED display
SSD1306 OLED display
SSD1306 OLED display-dimensions
SSD1306 OLED display-dimensions
SSD1306_128x64_OLDE-4
SSD1306_128x64_OLDE-4
SSD1306 OLED display-back
SSD1306 OLED display-back
44-This is the Arduino code for an HC-SR04 ultrasonic distance sensor with an SSD1306 display.
언어: C++
/*
 * This is the Arduino code for the HC-SR04 Ultrasonic Distance Sensor with SSD1306 Display
 * to measure the distance using Arduino for a robotic car and other applications
 * Watch the video https://youtu.be/Pgx5fNF4Q6M
 * 
 * Written by Ahmad Shamshiri for Robojax Video
 * Date: December 21, 2017, in Ajax, Ontario, Canada
 * Permission granted to share this code given that this
 * note is kept with the code.
 * Disclaimer: this code is "AS IS" and for educational purposes only.
 * 
 */

/* Original Code 
   from https://github.com/adafruit/Adafruit_SSD1306
// https://playground.arduino.cc/Code/NewPing
 * Modified for Robojax video on December 21, 2017
// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------
*/
//// start of SSD1306 display 
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

#define NUMFLAKES 10
#define XPOS 0
#define YPOS 1
#define DELTAY 2


#define LOGO16_GLCD_HEIGHT 64 
#define LOGO16_GLCD_WIDTH  128 
static const unsigned char PROGMEM logo16_glcd_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 };

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
//// end of SSD1306 display 

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.



void setup() {
   Serial.begin(9600);// set serial monitor with 9600 baud
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
  
}// setup end


void loop() {
   display.clearDisplay();
  robojaxText("Distance", 3, 0, 2, false);
  String distance  = String(sonar.ping_cm());// get distance and convert it to string for display
  robojaxText(distance +"cm", 3, 20, 3, false);
    display.display();

  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");

}// loop end


/*
 * robojaxText(String text, int x, int y,int size, boolean d)
 * text is the text string to be printed
 * x is the integer x position of text
 * y is the integer y position of text
 * size is the text size, 1, 2, 3 etc
 * d is either true or false.  Use true to display.
 */
void robojaxText(String text, int x, int y,int size, boolean d) {

  display.setTextSize(size);
  display.setTextColor(WHITE);
  display.setCursor(x,y);
  display.println(text);
  if(d){
    display.display();
  }

}

자원 및 참고자료

파일📁

데이터시트 (pdf)

  • SSD1306 display datasheet
    SSD1306 is a single-chip CMOS OLED/PLED driver with controller for organic / polymer light emitting diode dot-matrix graphic display system. It consists of 128 segments and 64commons. This IC is designed for Common Cathode type OLED panel. The SSD1306 embeds with contrast control, display RAM and oscillator, which reduces the number of external components and power consumption. It has 256-step brightness control. Data/Commands are sent from general MCU through the hardware selectable 6800/8000 series compatible Parallel Interface, I2C interface or Serial Peripheral Interface. It is suitable for many compact portable applications, such as mobile phone sub-display, MP3 player and calculator, etc.
    SSD1306_display_datasheet.pdf 1.79 MB