0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ESP32-WROOM-32Eで距離を測るよ

0
Posted at

ESP32-WROOM-32Eで超音波センサUS-015を使って距離を得たいな。
US-015とHC-SR04は互換があるので差替えれば同じコードで動作するんだって。便利だね。

コードはこんな感じ。

#include <Arduino.h>

const int trigPin = 13;
const int echoPin = 12;

void setup() {
  Serial.begin(115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH);

  // 距離を計算(音速 340m/s = 0.34mm/us)
  float distance = duration * 0.34 / 2;

  if (distance > 400 || distance < 2) {
    Serial.println("Out of range"); // 測れない距離
  } else {
    Serial.print("Distance: ");
    Serial.print(distance);
    Serial.println(" mm");
  }

  delay(2000); // 2秒おきに測定
}

そんで回路図はこうなったよ。
ESP32US15.png

結果はこう。

Out of range
Out of range
Out of range
Out of range
Distance: 242.08 mm
Distance: 239.36 mm
Distance: 233.58 mm
Distance: 242.08 mm
Distance: 281.18 mm
Distance: 294.10 mm
Distance: 283.90 mm
Distance: 283.73 mm

PXL_20260126_144700830.jpg
ん-。妥当な距離じゃない?
いいと思うよ!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?