概要
赤外線距離センサを購入したので試してみました。
物体からの距離を計測するセンサーです。
部品
距離センサー:赤外線距離センサモジュール
43円
表示機:TM1637が組み込まれた7セグLED
73円
コンピュータ:Arduino UNO互換機
699円
配線

ソースコード
アナログ信号を受け取り、10回の平均を表示するようにしています。
# include <Arduino.h>
# include <Wire.h>
# include <TM1637Display.h>
# define SERIAL_BAUD 115200
# define CLK 2
# define DIO 3
TM1637Display display(CLK, DIO);
# define IR_LEN 10
int IRs[IR_LEN] = {0,0,0,0,0,0,0,0,0,0};
int IRs_idx = 0;
void setup() {
Serial.begin(SERIAL_BAUD);
while(!Serial) {}
uint8_t data[] = { 0xff, 0xff, 0xff, 0xff };
display.setBrightness(0x0f);
display.setSegments(data);
delay(1000);
}
void loop() {
int ave = 0;
int IR;
IRs_idx++;
if(! (IR_LEN > IRs_idx) )
IRs_idx = 0;
IRs[IRs_idx] = analogRead(A0);
for(int i=0 ; i<IR_LEN;i++){
ave+=IRs[i];
}
IR = ave/IR_LEN;
display.showNumberDec(IR, false);
Serial.print("IR: ");
Serial.print(IR);
delay(100);
}
少し感想
初期設定だと5cm
から6cm
程度の範囲で検知できます。
その範囲以外だとある1000
や25
などの最大/最小値になってしまうため、検知できません。
上部にある可変抵抗をまわすことにより調整が可能です。