上次买arduino的时候,顺带买了个HC-SR04,一直没玩,今年翻出来了,仅仅测距多没意思。想想可以做点什么呢?来做个倒车雷达吧。
在论坛上没有看到HC-SR04的库文件,我就找了找,放在后面了。
辛苦卷纸了。代码很简单。{:soso_e121:}
- #include <Ultrasonic.h>
- #define TRIGGER_PIN 12
- #define ECHO_PIN 13
- #define NUMBER_BUFFERS 3
- #define BUFFER_SIZE 3
- #define BUFFER_01 0
- #define BUFFER_02 1
- #define BUFFER_03 2
- Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);
- bool disableSD = false;
- size_t count = 0;
- void setup()
- {
- Serial.begin(9600);
- Serial.println("Starting Ultasonic Test using standard deviation ...");
- pinMode(3,OUTPUT);
- pinMode(4,INPUT);
- /*
- * If NUMBER_BUFFERS is 2 then it must be followed by two size variables
- * one for each buffer to be created. The size variables do not need to be
- * the same value.
- *
- * Example: ultrasonic.sampleCreate(3, 20, 10, 3) is valid.
- *
- * Note: The minimum size for any buffer is 2. Using less than 2 will waist
- * resources and the buffer will be ignored.
- */
- if(!ultrasonic.sampleCreate(NUMBER_BUFFERS, BUFFER_SIZE, BUFFER_SIZE,
- BUFFER_SIZE))
- {
- disableSD = true;
- Serial.println("Could not allocate memory.");
- }
- }
- void loop()
- {
- float cmMsec, inMsec;
- float msStdDev, cmStdDev, inStdDev;
- long microsec = ultrasonic.timing();
- cmMsec = ultrasonic.convert(microsec, Ultrasonic::CM);
- inMsec = ultrasonic.convert(microsec, Ultrasonic::IN);
- if(disableSD)
- {
- Serial.print("CM: ");
- Serial.print(cmMsec);
- Serial.print(", IN: ");
- Serial.println(inMsec);
- }
- else
- {
- msStdDev = ultrasonic.unbiasedStdDev((float) microsec, BUFFER_01);
- cmStdDev = ultrasonic.unbiasedStdDev(cmMsec, BUFFER_02);
- inStdDev = ultrasonic.unbiasedStdDev(inMsec, BUFFER_03);
- Serial.print(", CM: ");
- Serial.print(cmMsec);
- }
- if(cmMsec<=200)
- {
- Serial.println("in if") ;
- digitalWrite(3,HIGH);
- delay(cmMsec*3);
- digitalWrite(3,LOW);
- tone(4,1000);
- delay(cmMsec*6);
- noTone(4);
- }
- delay(100);
- }
-
复制代码
|