秋月で手に入る距離センサー (SHARP GP2Y0A21YK) を使って距離を測ります。
[参考]
http://yutapon.hatenablog.com/entry/2014/02/09/192603
気を付けるのは、analogRead の値が 4096 段階なところ。
上記ページのような Arduino のサンプルで出ている式に突っ込む場合は、analogRead が 1024 段階なのを考慮して 4 で割ってから。
実際に取ってみましたが、大体あってる気がする。
たまに外れ値というか、デカすぎる値が帰ってくるので、適宜丸めたりは必要かも。
データシートとかを見ると、これの測定範囲は 10 – 80 cm だそうなので、それ以外は丸めればおkかな?
// Main.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "arduino.h"
int _tmain(int argc, _TCHAR* argv[])
{
return RunArduinoSketch();
}
int tmp;
int distance;
void setup()
{
}
// the loop routine runs over and over again forever:
void loop()
{
tmp = analogRead(0)/4;
if (tmp < 4) tmp = 4;
// 距離を計算(cm)
distance = (6787 / (tmp - 3)) - 4;
Log(L"distance : %dn", distance);
delay(100);
}
</pre>