#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128  // 定义屏幕宽度为128像素 Define the screen width to be 128 pixels
#define SCREEN_HEIGHT 64  // 定义屏幕高度为64像素 Define the screen height to be 64 pixels
#define OLED_RESET -1     // 定义 OLED 复位引脚为-1（如果不使用复位功能，则设置为-1） Define the OLED reset pin to -1 (or -1 if the reset function is not used)
// 创建 Adafruit_SSD1306 对象，用于控制 OLED 屏幕，指定屏幕宽度、高度、I2C 总线对象和复位引脚
// Create an Adafruit_SSD1306 object that controls the OLED screen, specifying the screen width, height, I2C bus object, and reset pin
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define Echo 6      //定义超声波Echo引脚 Define the ultrasonic Echo pin
#define Trig 5      //定义超声波Trig引脚 Define the ultrasonic Trig pin
int Udistance = 0;  //定义超声波距离变量 Define the ultrasonic distance variable

void setup() {
  Serial.begin(9600);
  pinMode(Echo, INPUT);   //定义引脚工作模式为输入 Define the pin operation mode as the input
  pinMode(Trig, OUTPUT);  //定义引脚工作模式为输出 Define the pin operation mode as output
  Wire.begin();           //初始化 I2C 总线 SDA引脚设置为A4，SCL引脚设置为A5 The initial I2C bus SDA pin is set to A4 and the SCL pin is set to A5

  // 初始化屏幕 Initializing the screen
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 initialization failed"));
    for (;;)
      ;
  }
}

void loop() {
  Udistance = GetDistance();  // 获取超声波距离 Obtaining ultrasonic distance
  display.clearDisplay();     // 清空屏幕缓冲区 Clear the screen buffer
  //显示超声波距离 Display ultrasonic distance
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(16, 8);
  display.println("Distance");
  display.setCursor(32, 40);
  display.print(Udistance);
  display.print(" cm");
  display.display();
  //delay(200);  // 延迟一段时间再进行下一次读取 Delay the next read for a while to adjust the update rate
  //Serial.print("Distance = ");
  //Serial.println(Udistance);
}

float GetDistance()  //获取超声波传感器数值 Get ultrasonic sensor values
{
  float distance;
  digitalWrite(Trig, LOW);  //发送一个低电平到Trig触发测距 Sending a low level to the Trig triggers ranging
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig, LOW);
  distance = pulseIn(Echo, HIGH) / 58.00;  //输出距离转换 Output distance conversion
  //delay(10);
  return distance;
}