1
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?

More than 5 years have passed since last update.

距離センサを使ってみた

Posted at

概要

距離センサを購入したので試してみました。

部品

距離センサ:HC-SR04
83円
image.png
※参考にしたSwitchScienceによるとこれには一部欠陥があるようで、そちらのほうが良いかもしれません。

表示機:TM1637が組み込まれた7セグLED
73円
image.png

コンピュータ:Arduino UNO互換機
699円
img.png

配線

スクリーンショット 2020-03-22 7.46.02.png

Triggerを10マイクロ秒以上 UPさせると、40kHzで8回距離を測り、その結果をEchoに周波数で返す仕様らしいです。

ソースコード


# include <Arduino.h>
# include <TM1637Display.h>
# include <Wire.h>

# define SERIAL_BAUD 115200
# define CLK 2
# define DIO 3
TM1637Display display(CLK, DIO);
int Trig = 5;
int Echo = 4;

void setup() {
  Serial.begin(SERIAL_BAUD);
  while(!Serial) {}
   pinMode(Trig,OUTPUT);
   pinMode(Echo,INPUT);

  Wire.begin();
  uint8_t data[] = { 0xff, 0xff, 0xff, 0xff };
  display.setBrightness(0x0f);
  display.setSegments(data);
  delay(1000);
}

void loop() {
  int Duration;
  float Distance;
    digitalWrite(Trig,LOW);
    delayMicroseconds(1);
    digitalWrite(Trig,HIGH);
    delayMicroseconds(11);
    digitalWrite(Trig,LOW);
    Duration = pulseIn(Echo,HIGH);
    if (Duration>0) {
      Distance = Duration/2;
      Distance = Distance*340*100/1000000; // 340m/s = 34000cm/s = 0.034cm/us 
      Serial.print(Distance);
      Serial.println(" cm");
      display.showNumberDec((unsigned int)(Distance*100), false);
//      analogWrite(11, (unsigned int)(100-Distance));//ビープ音
    }
  delay(100);
}

github

動作確認

gif動画で上げても分かりにくかったので、Youtubeにて確認いただけると幸いです。
IMAGE ALT TEXT HERE

1
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
1
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?