|
|
发表于 2015-11-10 15:48:39
|
显示全部楼层
- int LedPin=8; //定义8接口为灯闪烁
- int Echo_Pin=3;
- int Trig_Pin=2; //定义超声波Echo接口和Trig接口
- float cm; //定义cm为超声波距离,浮点类型
- void setup()
- {
- Serial.begin(9600); //波特率为9600
- pinMode(Trig_Pin, OUTPUT);
- pinMode(Echo_Pin, INPUT);
- pinMode(LedPin,OUTPUT); //定义LED8口为输出
- }
- void loop() {
- digitalWrite(Trig_Pin, LOW); //低高低电平发一个短时间脉冲去TrigPin
- delayMicroseconds(2);
- digitalWrite(Trig_Pin, HIGH);
- delayMicroseconds(10);
- digitalWrite(Trig_Pin, LOW);
- cm = pulseIn(Echo_Pin, HIGH) / 58.0; //将回波时间换算成cm
- cm = (int(cm * 100.0)) / 100.0; //保留两位小数
- Serial.print(cm);
- Serial.print("cm");
- Serial.println();
- delay(1000);
- if(cm>30)
- {
- digitalWrite(LedPin,HIGH);
- }
- if(cm>15&&cm<=30)
- {
- digitalWrite(LedPin,HIGH);
- delay(1500);
- digitalWrite(LedPin,LOW);
- delay(1500);
- }
- if(cm>5&&cm<=15)
- {
- digitalWrite(LedPin,HIGH);
- delay(1000);
- digitalWrite(LedPin,LOW);
- delay(1000);
- }
- if(cm<=5)
- {
- digitalWrite(LedPin,HIGH);
- delay(500);
- digitalWrite(LedPin,LOW);
- delay(500);
- }
- }
复制代码 这个再看不懂我也没办法了。我也是初学者,大神勿喷 |
|