之前学了RGB灯,今天学了超声波测距,于是想将两者结合,简单将之前发的两段代码融合如下
int TrgPin = A0;
int EcoPin = A1;
int sw = 5;
int red = 4;
int blue = 3;
int green = 2;
float dist;
void setup()
{
Serial.begin(9600);
pinMode(TrgPin, OUTPUT);
pinMode(EcoPin, INPUT);
pinMode(sw, OUTPUT);
pinMode(red, OUTPUT);
pinMode(blue, OUTPUT);
pinMode(green, OUTPUT);
}
void loop()
{
digitalWrite(red, HIGH);
digitalWrite(blue, HIGH);
digitalWrite(green, HIGH);
digitalWrite(sw, HIGH);
digitalWrite(TrgPin, LOW);
delayMicroseconds(10);
digitalWrite(TrgPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrgPin, LOW);
dist = pulseIn(EcoPin, HIGH) / 58.00;
if (dist > 0)
{
Serial.print("Distance:");
Serial.print(dist);
Serial.println("cm");
if (dist<40)
{
digitalWrite(red, LOW);
}
if (dist>=40 & dist <=50)
{
digitalWrite(blue,LOW);
}
if (dist>50)
{
digitalWrite(green, LOW);
}
}
delay(1000);
}
代码很简单,效果也很好,唯一问题是这个RGB灯亮瞎眼,一点都不护眼,只好盖了张纸,哈哈哈。
远距离
中距离
近距离
|