controlling two dc motors and servo with arduino code

霸气de小男生 提交于 2019-12-13 01:26:03

问题


The code does not seem to be working but I have also just started learning how to code arduino. I'm trying to run two dc motors and one servo as steering for a robot car. How should I wright it so it works. All I'm trying to do is use two motors to drive the car forward and the servo to provide direction for the car. How can I improve this code?

    #include <Servo.h>


    int servoRightPin = 2;
    int servoLeftPin = 3;
    int servoDirPin = 4;
    Servo servoRight;
    Servo servoLeft;
    Servo servoDir;


    void turnLeft()
    {
    servoDir.write(0.6);
    delay(300000);
    servoLeft.write(180);
    servoRight.write(0);
    }

    void moveForward()
    {
    servoDir.write(0);
    delay(240000);
    servoLeft.write(180);
    servoRight(0);
    }

    void turnLeft()
    {
    servoDir.write(0.6);
    delay(300000);
    servoLeft.write(180);
    servoRight.write(0);
    }

    void moveForward()
    {
    servoDir.write(0);
    delay(240000);
    servoLeft.write(180);
    servoRight(0);
    }




    june_4_car.ino: In function 'void moveForward()':
    june_4_car.ino:25:15: error: no match for call to '(Servo) (int)'
    june_4_car.ino: In function 'void turnLeft()':
    june_4_car.ino:28:6: error: redefinition of 'void turnLeft()'
    june_4_car.ino:12:6: error: 'void turnLeft()' previously defined here
    june_4_car.ino: In function 'void moveForward()':
    june_4_car.ino:36:6: error: redefinition of 'void moveForward()'
    june_4_car.ino:20:6: error: 'void moveForward()' previously defined here
    june_4_car.ino:41:15: error: no match for call to '(Servo) (int)'
    Error compiling.

回答1:


Several problems there.

Let's start with the compilation errors:

  1. You have two functions turnLeft and two functions moveForward. I assume the second pair should be turnRight and moveBackwards.
  2. In the moveForward function you call servoRight(0) this should probably be servoRight.write(0).

Fixing this should allow your code to compile, but it will still not work:

  1. You have defined pins but they are not attached to servos (no call to attach).
  2. You mentioned one servo and two dc motors so why does your code have three servos? (only one of the servo three pins is connected to a digital port the other two are for power).
  3. What's with the delay, write(180) and write(0) what are you trying to do there?
  4. write(0.6) is not going to increase the angle by 0.6 degrees. You need to either keep track of the current angle or read() it from the servo.

In short read some tutorials (like this), experiment and have fun.



来源:https://stackoverflow.com/questions/30657312/controlling-two-dc-motors-and-servo-with-arduino-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!