モジュールとなっているこのセンサーはトリガー・ピンへパルス信号を送り、反射して帰ってくる超音波をエコーから取得します。
取得した値から距離を計算します。
計算してみるとなかなか正確な距離が出ています。
ここでは近づくとブザーで警告するよう設定してみました。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// distanceSensor.ino -- Beeps if an object within 5cm is detected | |
// Copyright (c) 2016 easai | |
// Author: easai | |
// Created: Mon Jan 11 23:14:55 2016 | |
// Keywords: | |
// Commentary: | |
// Trigger: Pin 7 | |
// Echo: Pin 8 | |
// Buzzer: Pin 5 | |
// Code: | |
long duration, distance; | |
int trig = 7; | |
int echo = 8; | |
int buzzer = 5; | |
void setup() { | |
pinMode(echo, INPUT); | |
pinMode(trig, OUTPUT); | |
pinMode(buzzer, OUTPUT); | |
} | |
void loop() { | |
digitalWrite(trig, LOW); | |
delay(5); | |
digitalWrite(trig, HIGH); | |
delay(10); | |
digitalWrite(trig, LOW); | |
duration = pulseIn(echo, HIGH); | |
distance = duration / 58.2; | |
if (distance < 5) | |
digitalWrite(buzzer, HIGH); | |
else | |
digitalWrite(buzzer, LOW); | |
delay(50); | |
} | |
// distanceSensor.ino ends here |