簡體   English   中英

Arduino聲納和步進電機

[英]Arduino Sonar and Stepper Motor

我正在嘗試創建一個由Arduino驅動的聲納/雷達。 我目前將聲納傳感器連接到電動機上並正在處理代碼。 問題出在下面的for循環中。 傳感器將發出ping聲,然后電動機將移動,重復正確的次數。 但是,無論距離多遠,聲納傳感器返回的值都是0或1。 在確定問題上的任何幫助將不勝感激。

/*
   Nathan Verdonk
   3/15/2019
*/

#include <NewPing.h>
#include <Stepper.h>

const int stepsPerRevolution = 2048;                      // Steps per revolution
const int rotSpeed = 10;                                  // Speed of rotation in RPM
const int triggerPin = 7;                                 // Trigger pin on sonar sensor
const int echoPin = 6;                                    // Echo pin on sonar sensor
const int maxDistance = 300;                              // Max distance expected from sensor in cm; do not exceed 400

int val;


Stepper stepper1(stepsPerRevolution, 8, 10, 9, 11);           // initialize the stepper library on pins 8 through 11:
NewPing sonar1(triggerPin, echoPin, maxDistance);             // initialize the new ping library with predefined values

void setup() {

  stepper1.setSpeed(rotSpeed);

  Serial.begin(115200);

}

void loop() {

  for(int i = 0; i < 50; i++){
    delay(50);

    val = sonar1.ping_cm();
    Serial.println(val);

    stepper1.step(1);
  }

  delay(3000);

}

如果您想捕獲距離,可以執行以下過程來驗證傳感器沒有問題(我認為接線正確):

// defines pins numbers
const int triggerPin = 7;
const int echoPin = 6;
// defines variables
long duration;
int distance;
void setup() {
    pinMode(triggerPin, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin, INPUT); // Sets the echoPin as an Input
    Serial.begin(115200); // Starts the serial communication
}

void loop() {
    delay(50);
    // Clears the triggerPin
    digitalWrite(triggerPin, LOW);
    delayMicroseconds(2);
    // Sets the triggerPin on HIGH state for 10 micro seconds
    digitalWrite(triggerPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(triggerPin, LOW);
    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
    // Calculating the distance
    distance= duration*0.034/2;
    // Prints the distance on the Serial Monitor
    Serial.print("Distance: ");
    Serial.println(distance);
}

為了產生超聲波,您需要將Trig置於高態10 s。 這將發出一個8周期的聲音脈沖,將以速度聲音行進,並且將在回音針中接收。 Echo引腳將輸出聲波傳播的時間(以微秒為單位)。

聲音的速度為340 m / s或0.034 cm / µs,因此您將其除以2以獲取距離

問題不在於代碼。

事實證明,該傳感器對需要幾乎恰好5 V的運行十分挑剔。 在伺服和傳感器使用相同電源的情況下,當伺服運行時,電壓將降至5 V以下。

謝謝所有幫助的人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM