Мо
дуль ультразвукового датчика расстояния (HC-SR04) может измерять расстояния от 2 сантиметров до 5 метров (если вам повезет).
Вы могли бы, например, использовать его для проверки уровня воды в баке или в качестве датчика парковки в вашем гараже.
Он работает методом отправки коротких ультразвуковых звуковых импульсов, которые не слышны человеку, и ждет, пока импульсы вернутся в микрофон. Затем HC-SR04 вычисляет расстояние, измеряя время задержки для каждого импульса.
Подключение
Начните с подключения радиомодуля.
Датчик | Arduino | Коментарии |
VCC | VCC | Красный |
TRIG | D6 | Синий |
ECHO | D5 | Зелёный |
GND | GND | Чёрный |
Пример
В этом примере используется внешняя библиотека NewPing, найденная здесь. Пожалуйста, установите его и перезапустите среду разработки Arduino перед тем, как компилировать.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
/** * The MySensors Arduino library handles the wireless radio link and protocol * between your home built sensors/actuators and HA controller of choice. * The sensors forms a self healing radio network with optional repeaters. Each * repeater and gateway builds a routing tables in EEPROM which keeps track of the * network topology allowing messages to be routed to nodes. * * Created by Henrik Ekblad <henrik.ekblad@mysensors.org> * Copyright (C) 2013-2015 Sensnology AB * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors * * Documentation: http://www.mysensors.org * Support Forum: http://forum.mysensors.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * ******************************* * * REVISION HISTORY * Version 1.0 - Henrik EKblad * * DESCRIPTION * This sketch provides an example how to implement a distance sensor using HC-SR04 * http://www.mysensors.org/build/distance */ // Enable debug prints #define MY_DEBUG // Enable and select radio type attached #define MY_RADIO_RF24 //#define MY_RADIO_RFM69 #include <MySensors.h> #include <NewPing.h> #define CHILD_ID 1 #define TRIGGER_PIN 6 // Arduino pin tied to trigger pin on the ultrasonic sensor. #define ECHO_PIN 5 // Arduino pin tied to echo pin on the ultrasonic sensor. #define MAX_DISTANCE 300 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. unsigned long SLEEP_TIME = 5000; // Sleep time between reads (in milliseconds) NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. MyMessage msg(CHILD_ID, V_DISTANCE); int lastDist; bool metric = true; void setup() { metric = getControllerConfig().isMetric; } void presentation() { // Send the sketch version information to the gateway and Controller sendSketchInfo("Distance Sensor", "1.0"); // Register all sensors to gw (they will be created as child devices) present(CHILD_ID, S_DISTANCE); } void loop() { int dist = metric?sonar.ping_cm():sonar.ping_in(); Serial.print("Ping: "); Serial.print(dist); // Convert ping time to distance in cm and print result (0 = outside set distance range) Serial.println(metric?" cm":" in"); if (dist != lastDist) { send(msg.set(dist)); lastDist = dist; } sleep(SLEEP_TIME); } |