Arduino:超声波与执行器协同工作

时间:2018-10-08 20:45:11

标签: arduino

我正在研究将超声波传感器和执行器连接到Arduino板的挑战。我需要做的是使超声波传感器检测到10厘米范围内的东西时,将执行器伸出,然后仅 1秒钟缩回它。

但是,我的代码现在正在做什么,完全缩回执行器。我不确定为什么我的代码会导致这种现象。 如何修改我的代码,使执行器仅缩回1秒钟?

代码:

/*
Actuator -->> PIN 32,34; ultrasonic -->> PIN Trig = 3, Echo = 7
*/

// defines pins numbers
const int trigPin = 3;
const int echoPin = 7;
const int relay1 = 32;    // Arduino pin that triggers relay #1
const int relay2 = 34;    // Arduino pin that triggers relay #2
const int threshold = 10; // An arbitrary threshold level that's in the 
                          // range of the digital input

// defines variables
long duration;
int distance;

void setup() {
    pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin, INPUT);  // Sets the echoPin as an Input
    pinMode(relay1, OUTPUT);  // Set pinMode to OUTPUT for the relay pin
    pinMode(relay2, OUTPUT);  // Set pinMode to OUTPUT for the relay pin
    Serial.begin(9600);       // Starts the serial communication
}

void loop() {
    // Clears the trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);

    // Calculating the distance
    distance= duration*0.034/2;

    if (distance > threshold) {
        digitalWrite(relay1, LOW);  // retractActuator
        digitalWrite(relay2, HIGH); // retractActuator 
    }     
    else {
        digitalWrite(relay1, HIGH); // extend actuator
        digitalWrite(relay2, LOW);  // extend actuator
    }

    // Prints the distance on the Serial Monitor
    Serial.print("Distance: ");
    Serial.println(distance);
}

0 个答案:

没有答案