繁体   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