我正在尝试创建一个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引脚中接收。 Echo引脚将输出声波传播的时间,以微秒为单位。
声速为340 m / s或0.034 cm /μs,因此除以2以捕捉距离
问题不在于代码。
事实证明,传感器非常挑剔,几乎需要5 V才能运行。伺服和传感器使用相同的电源时,伺服运行时电压会降至5 V以下。
感谢所有帮助过的人。