如何使Arduino超声波传感器导致电机旋转?

时间:2019-07-04 19:40:08

标签: arduino

setup() runs only once while loop() is the repeating piece of 
code. There are 2 HC-SR sensors connected with 2 relays which are 
based on the measurement of motion between the sensor and the surroundings.

上下文:当前,引脚12,10用于输入,而引脚13,11,9,8是输出引脚。当trigpin测量距离小于5cm时,它将继电器状态更改为“高”,然后根据if else语句

    #include <math.h> 
    int trig1= 13;
    int echo1= 12;
    int trig2= 11;
    int echo2= 10;
    int motor1= 9;
    int motor2= 8;

    void setup() {
      pinMode(9, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(13, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(12, INPUT);
      pinMode(10, INPUT);
      Serial.begin(9600);
    }

    void loop() {
    digitalWrite(trig1, LOW);
    digitalWrite(trig2, LOW);
    delayMicroseconds(2);
    digitalWrite(trig1, HIGH);
    digitalWrite(trig2, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig1, LOW);
    digitalWrite(trig2, LOW);
    long duration1 = pulseIn(echo1, HIGH);
    long duration2 = pulseIn(echo2, HIGH);
    long distance1= duration1*0.034/2;
    long distance2= duration2*0.034/2;

      if(distance1 < 5)
      {
        digitalWrite(motor1, HIGH);
        delay (15000);

      }
      else if(distance2 < 5)
      {
        digitalWrite(motor2, HIGH);
        delay (15000);
      }
      else
      {
        loop();
      }
      }

0 个答案:

没有答案