步骤1:所需的电气组件
这是电气零件的列表一个人需要完成这个项目-br-Arduino板
-跳线
-RGB led(我使用的是公共阴极,但单个LED也可以工作)
-3电阻。
-面包板
-HC-SRO4。
所有这些都连接起来
步骤2:连接
从Arduino + 5v向面包板提供+ 5v并执行相同的操作为地面。
将HC-SR04安装在试验板上。请记住,在数字电子产品类别中,+规则垂直针脚在板上横档连接在一起,而水平针脚在电源横档上连接在一起。
将传感器连接到GND和+ 5v。
连接回波针将HC-SR04的引脚连接到Arduino的引脚5,并通过Trig引脚将其连接到Arduino板的引脚6。
安装面包板上的LED。将电阻连接到RGB引脚,分别将它们分别连接到Arduino的引脚7,8和9,并将阴极接地。
步骤3:代码
连接后,编写并上传以下代码。
************************* ************************************************** *************
#define trigpin 6
#define echopin 5
#define R 7
#define G 8
#define B 9
void setup()
{ //serial monitor and pin setup.
Serial.begin(9600);
pinMode(trigpin,OUTPUT); //set trigpin as output
pinMode(echopin,INPUT);//set echopin as input
pinMode(R,OUTPUT);// set R,G and B as outputs
pinMode(G,OUTPUT);
pinMode(B,OUTPUT);
// put your setup code here, to run once:
}
void loop()
{
//the trigpin sends out a signal, which bounces off an obstacle and comes back, the
//echopin recieves this signal and gives out +5v setting the arduino pin on which it is connected to high.
//distance= time*speed, but this distnce is divided by 2 because signal sent out returns
//so distance= (the time it takes for the signal to leave and return)/2.
//i.e if the time is 6s the distance = (6s/2) = 3m or cm.
int duration, distance;//declare distance and duration as integers
digitalWrite(trigpin,HIGH);// trigin send out signal
_delay_ms(1000);//coninously for 1000ms
digitalWrite(trigpin, LOW);// then goes low
duration=pulseIn(echopin,HIGH); // duration is the pulseIn to the echopin
distance=(duration/2)/29.1; // the 29.1 is used to convert the distnce to cm, the value varies for other units.
if(distance 》 0 && distance 《= 20){//distcance is greater than 0 and less than 20cm
digitalWrite(G,LOW);//green led is off
digitalWrite(B,LOW);//blue led is off
_delay_ms(500);//delay
digitalWrite(R,HIGH);//red led is on
_delay_ms(500);
}
else if(distance 》 20 && distance 《= 80){//distcance is greater than 20 and less than 80cm
digitalWrite(R,LOW);//red led is off
digitalWrite(G,LOW);//green led is off
_delay_ms(500);
digitalWrite(B,HIGH);//blue led is on
}
else if(distance 》 80 && distance 《= 120 ){//distcance is greater than 80 and less than 120cm
digitalWrite(R,LOW);//red led is off
digitalWrite(B,LOW);//blue led is off
_delay_ms(500);
digitalWrite(G,HIGH);//green led is on
}
Serial.print(“cm”);
Serial.println(distance);//print values on serial monitor
_delay_ms(100);
}
// put your main code here, to run repeatedly:
步骤4:测试
我公寓的地板上有瓷砖,您可以看到距我的橱柜和冰箱的距离。 LED呈绿色,当距离减半时变为蓝色,而当传感器确实靠近时变为红色。我希望你喜欢这个。我打算做类似的事情,但我将使用MQ-2烟雾传感器来更改LED的颜色。
-
超声波
+关注
关注
63文章
3014浏览量
138348 -
距离传感器
+关注
关注
3文章
75浏览量
15121
发布评论请先 登录
相关推荐
评论