Dan*_*oop 5 robot arduino arduino-uno
我正在为学校项目建造机器人。我目前正在使用Arduino Uno,两个直流电动机和一个超声波传感器。这两个电机是通过Arduino Motor Shield v3控制的。我希望该机器人具有自主性,因此它必须能够使用超声波传感器自行移动。
这是我的源代码的最新版本:
#include <Servo.h> // include Servo library
#include <AFMotor.h> // include DC motor Library
#define trigPin 12 // define the pins of your sensor
#define echoPin 13
AF_DCMotor motor2(7); // set up motors.
AF_DCMotor motor1(6);
void setup() {
Serial.begin(9600); // begin serial communication
Serial.println("Motor test!");
pinMode(trigPin, OUTPUT); // set the trig pin to output to send sound waves
pinMode(echoPin, INPUT); // set the echo pin to input to receive sound waves
motor1.setSpeed(105); // set the speed of the motors, between 0-255
motor2.setSpeed (105);
}
void loop() {
long duration, distance; // start the scan
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // delays are required for a successful sensor operation.
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // this delay is required as well!
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1; // convert the distance to centimetres.
// if there's an obstacle ahead at less than 25 centimetres, do the following:
if (distance < 25) {
Serial.println("Close Obstacle detected!" );
Serial.println("Obstacle Details:");
Serial.print("Distance From Robot is " );
Serial.print(distance);
Serial.print(" CM!"); // print out the distance in centimeters.
Serial.println (" The obstacle is declared a threat due to close distance. ");
Serial.println (" Turning !");
motor1.run(FORWARD); // Turn as long as there's an obstacle ahead.
motor2.run (BACKWARD);
} else {
Serial.println("No obstacle detected. going forward");
delay(15);
motor1.run(FORWARD); // if there's no obstacle ahead, Go Forward!
motor2.run(FORWARD);
}
}
Run Code Online (Sandbox Code Playgroud)
当前的问题是车轮按预期旋转,但转了几圈后便停了下来。
我怀疑问题与软件有关,但我不确定。此外,我相信电机已正确连接到电机护罩,但是我可能无法在代码中正确处理它们。
谁能帮我解决这个问题?
简单的答案 - 消除循环中的延迟
delay(15);
Run Code Online (Sandbox Code Playgroud)
与使用的库结合使用,这会导致一段时间后根本没有任何运动。延迟会停止处理所有内容,因此请使用非阻塞时间测量来为电机例程提供处理时间,而不是阻塞所有内容。请参阅ArduinoIDE中的blinkwithoutdelay示例,了解如何实现这种例程。
使用机器人时,如果作者使用delay(),请务必查看库(=开源的优势),如果是,则重写该函数或放弃库。特别是在 Arduino 环境中,存在很多非常糟糕的库 - 它们在桌面上的简单测试用例中工作,但不能在机器人等复杂的接近实时的环境中工作。
归档时间: |
|
查看次数: |
344 次 |
最近记录: |