机器人不动

时间:2017-02-17 17:33:57

标签: arduino arduino-uno robot

我正在为学校项目建造机器人。我使用的是Arduino Uno,2直流电机和Ultra Sonic测距模块。我希望机器人是自主的,它必须能够使用Ultra Sonic传感器自行移动。重要的是我不使用MotorShield来控制我的直流电机。这是我最新的源代码版本:

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

问题:我添加了一个 ARDUINO MOTOR SHIELD REV3 来控制我的直流电机,车轮实际上正在旋转,但经过几转后它们会停止。

我认为这个问题与软件有关,但我对此并不完全确定。此外,我认为电机正确连接到电机屏蔽,但我可能无法在代码中正确处理它们。

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

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

  delay(15);

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

答案 1 :(得分:0)

我认为您必须将 PWM 引脚用于电动机。由于 AFMotor 库具有用于设置速度的选项。因此,请将motor2的引脚7 更改为引脚5 并进行检查。