|
rt- #define echopin 5
- #define trigpin 4
- #define led 0
- void setup()
- {
- Serial.begin(115200);
- pinMode(echopin, INPUT);
- pinMode(trigpin, OUTPUT);
- pinMode(led, OUTPUT);
- }
- void loop()
- {
- digitalWrite(trigpin, LOW);
- delayMicroseconds(2);
- digitalWrite(trigpin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigpin, LOW);//发一个10ms的高脉冲去触发TrigPin
- float distance = pulseIn(echopin, HIGH);//接收高电平时间
- distance = distance/58.0;//计算距离
- if(1<distance && distance<450)
- {
- Serial.print("distance:");
- Serial.print(distance);//输出距离
- Serial.println("cm");//输出单位
- if(distance<10)// 距离小于10cm时灯亮---》报警
- {
- digitalWrite(led, LOW);
- }
- else
- {
- digitalWrite(led, HIGH);
- }
- }
- delay(60);//循环间隔60us
- }
复制代码
|
|