Arduinoで距離測定

 トリガーをD8
 エコーをD9に接続
 スイッチサイエンスのHPを参照にソース
 
 pulseIn関数が使えるのでラズパイよりはずっとスマート
 ピンがHIGHになるのを待ち、時間計測を開始する。
 その後、ピンがLOWになるのを待ち、時間計測を終了する
 結果はマイクロ秒

int Trig = 8;
int Echo = 9;
int Duration;
float Distance;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(Trig,OUTPUT);
  pinMode(Echo,INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  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;  
    Serial.print(Distance);
    Serial.println(" cm");
  }
  delay(500);
 
}

raspberypiでは不安定だったがこちらは安定稼働

・シャープの距離センサーはもっと簡単

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}
void loop() {
  // put your main code here, to run repeatedly:
  int val;
  val=analogRead(0);
  Serial.println(val);
  delay(500);
}

後は、電圧と距離補正を組み込めば完成

この測距方法だが、三角測量の原理だそうで、赤外線LEDからの反射を
PSD(光位置検出素子)で見ているので、反射光に左右されない
ようです。

カテゴリー iot