Arduino Sonar和步进马达

Arduino Sonar and Stepper Motor

本文关键字:马达 步进 Sonar Arduino      更新时间:2023-10-16

我正在尝试创建一个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);
}

问题不在代码上。

事实证明,传感器很挑剔,需要几乎完全需要5 V来运行。使用伺服和传感器使用相同的电源,当伺服运行时,电压将降至5 V以下。

感谢所有帮助的人。

如果要捕获距离,则可以执行此过程以验证传感器没有问题(我想接线是正确的):

// 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);
}

为了生成超声波,您需要将触发器设置为高状态10 µs。这将发出8个周期的声音爆发,该爆发将以速度声音传播,并将在Echo Pin中接收。回声引脚将在微秒内输出声波传播的时间。

声音的速度为340 m/s或0.034 cm/µs,因此您除以2,以捕获距离