gpt4 book ai didi

arduino - 转几圈后机器人不再移动

转载 作者:行者123 更新时间:2023-12-03 17:38:31 29 4
gpt4 key购买 nike

我正在为一个学校项目 build 一个机器人。我目前正在使用一个 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);
}
}

当前的问题是车轮按预期旋转,但转几圈后就停止了。

我怀疑这个问题与软件有关,但我不完全确定。此外,我相信电机已正确连接到电机护罩,但我可能无法在代码中正确处理它们。

谁能帮我解决这个问题?

最佳答案

简单的答案 - 摆脱循环中的延迟

  delay(15);

结合使用的库,这会在一段时间后导致根本没有 Action 。延迟停止处理所有内容,因此使用非阻塞时间测量来为电机例程提供处理时间,而不是阻塞所有内容。请参阅 ArduinoIDE 中的 blinkwithoutdelay 示例如何实现这种例程。使用机器人时,如果作者使用 delay(),请始终查看库(= 开源的优势)如果是,则重写函数或放弃库。尤其是在 Arduino 环境中,周围有很多非常糟糕的库——它们在桌面上的简单测试用例中工作,但在机器人等复杂的接近实时的环境中却不行。

关于arduino - 转几圈后机器人不再移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42304119/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com