第3步代码时间
以下是编写的Arduino程序,上传到Arduino中.
如果你想让距离听得见,还可以在这个项目中添加蜂鸣器。
// Simple Proximity Sensor using Infrared // Description: 通过红外LED发过的光测量到障碍物的距离和读取红外线光电二极管的值。这个精确度不是很完美,但伟大的工作就是从小型的项目开始。 // Author: Ricardo Ouvina // Date: 01/10/2012 // Version: 1.0 int IRpin = A0; // IR photodiode on analog pin A0 int IRemitter = 2; // IR emitter LED on digital pin 2 int ambientIR; // variable to store the IR coming from the ambient int obstacleIR; // variable to store the IR coming from the object int value[10]; // variable to store the IR values int distance; // variable that will tell if there is an obstacle or not void setup(){ Serial.begin(9600); // initializing Serial monitor pinMode(IRemitter,OUTPUT); // IR emitter LED on digital pin 2 digitalWrite(IRemitter,LOW);// setup IR LED as off pinMode(11,OUTPUT); // buzzer in digital pin 11 } void loop(){ distance = readIR(5); // calling the function that will read the distance and passing the "accuracy" to it Serial.println(distance); // writing the read value on Serial monitor // buzzer(); // uncomment to activate the buzzer function } int readIR(int times){ for(int x=0;x<times;x++){ digitalWrite(IRemitter,LOW); // turning the IR LEDs off to read the IR coming from the ambient delay(1); // minimum delay necessary to read values ambientIR = analogRead(IRpin); // storing IR coming from the ambient digitalWrite(IRemitter,HIGH); // turning the IR LEDs on to read the IR coming from the obstacle delay(1); // minimum delay necessary to read values obstacleIR = analogRead(IRpin); // storing IR coming from the obstacle value[x] = ambientIR-obstacleIR; // calculating changes in IR values and storing it for future average } for(int x=0;x<times;x++){ // calculating the average based on the "accuracy" distance+=value[x]; } return(distance/times); // return the final value } //-- Function to sound a buzzer for audible measurements --// void buzzer(){ if (distance>1){ if(distance>100){ // continuous sound if the obstacle is too close digitalWrite(11,HIGH); } else{ // beeps faster when an obstacle approaches digitalWrite(11,HIGH); delay(150-distance); // adjust this value for your convenience digitalWrite(11,LOW); delay(150-distance); // adjust this value for your convenience } } else{ // off if there is no obstacle digitalWrite(11,LOW); } }
当然,你可以修改它以适应你自己的项目。例如,您可以让机器人从基于红外传感器上读到距离来改变方向或速度。只要是距离传感上的项目都可以试一哈。
猜你会喜欢
iPhone控制的简易物联网
这次我尝试制作一个简单的物联网系统,可以...
有爱的碗
该文是在Chinked-out工作室翻译...
TEM36温度传感器
非常容易解释什么是模拟温度传感器,它就是...
基于MK802的摄像头自动光源跟踪
基于MK802的摄像头自动光源跟踪,展示...
用Android和Arduino控制门锁
这次我制作一个简易的无线控制门锁,实现用...
评 论
选择昵称后请轻按空格键
请勿进行人身攻击,谩骂以及任何违法国家相关法律法规的言论。