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
|
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() { pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT);
Serial.begin(9600); if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Serial.println(F("OLED init failed")); for(;;); } display.clearDisplay(); display.display(); }
float getDistance() { digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); long duration = pulseIn(ECHO_PIN, HIGH); return duration * 0.034 / 2; // 距离(厘米) }
int posX = 0; // 用来在横向慢慢移动
void loop() {
// 绘制两边的参考线 display.drawLine(0, 0, 0, SCREEN_HEIGHT, WHITE); // 左边的距离线 display.drawLine(SCREEN_WIDTH - 1, 0, SCREEN_WIDTH - 1, SCREEN_HEIGHT, WHITE); // 右边的距离线 display.display();
float distance = getDistance(); // 单位 cm Serial.print("Distance: "); Serial.println(distance);
// 归一化距离(最多显示到60cm) int r = map(min(distance, 60.0), 0, 60, SCREEN_HEIGHT - 1, 0); // 越远越上
display.drawPixel(posX, r, WHITE); posX++; if (posX >= SCREEN_WIDTH) { posX = 0; display.clearDisplay(); // 清除屏幕从头来 } display.display(); delay(100); // 每秒10个点 }
|