繁体   English   中英

Arduino伺服和直流电机工作不正常

[英]Arduino servo and DC motor not working properly

我对 Arduino 世界很陌生,但我有一些其他语言的编程经验。

我正在尝试制作我的第一辆机器人汽车,我有 2 个直流电机连接到 L298N 模块,全部连接到 9V 电池和 Arduino Uno。

直流电机连接到电机 1 的端口 5、6、7 和电机 2 的端口 8、9、10。

该代码在 go 前后工作正常。

在这个阶段,我想将连接到端口 13 的直流伺服器连接到 5 伏和接地,这是问题所在:

使用以下代码,只有一个直流电机和伺服器在移动,但第二个直流电机卡住了!

我注意到如果我从void setup()中删除命令servo_motor.attach(13); 两台直流电机都在运行。

它应该移动伺服和两个直流电机......

有什么理由吗?

感谢帮助。

#include <Arduino.h>
#include <Servo.h>

const int mot2 = 10;
const int ava2 = 9;
const int ind2 = 8;
const int mot1 = 5;
const int ava1 = 6;
const int ind1 = 7;
Servo servo_motor;  // create servo object to control a servo
int pos = 0;

void moveForward() {
  Serial.print("Going Forward\n");

  // turn on motor A
  digitalWrite(ava1, HIGH);
  digitalWrite(ind1, LOW);

  // set speed to 200 out of possible range 0~255
  analogWrite(mot1, 100);

  // turn on motor B
  digitalWrite(ava2, LOW);
  digitalWrite(ind2, HIGH);

  // set speed to 200 out of possible range 0~255
  analogWrite(mot2, 100);

  delay(2000);
}

void moveBack() {
  Serial.print("Going BACK\n");

  // turn on motor A
  digitalWrite(ava1, LOW);
  digitalWrite(ind1, HIGH);

  // set speed to 200 out of possible range 0~255
  analogWrite(mot1, 250);

  // turn on motor B
  digitalWrite(ava2, HIGH);
  digitalWrite(ind2, LOW);

  // set speed to 200 out of possible range 0~255
  analogWrite(mot2, 250);
 
  delay(2000);
}

void moveServo() {
  for (pos = 0; pos <= 180; pos += 1) {
    servo_motor.write(pos);             
    delay(15);                       
  }
  for (pos = 180; pos >= 0; pos -= 1) {
    servo_motor.write(pos);             
    delay(15);                       
  }
}


void setup() {
  Serial.begin(9600);
  servo_motor.attach(13); //  why if i remove this both DC motor work and if i put only one DC motor work??
  pinMode(mot2, OUTPUT);
  pinMode(ava2, OUTPUT);
  pinMode(ind2, OUTPUT);
  pinMode(mot1, OUTPUT);
  pinMode(ava1, OUTPUT);
  pinMode(ind1, OUTPUT);
}

void loop() {
  moveServo();
  delay(2000);
  moveForward();
  delay(2000);
  moveBack();
}

您是否尝试过使用另一个引脚而不是引脚 13 来控制伺服? 不建议使用引脚 13 来控制伺服,因为有一个 LED 连接到引脚 13。尝试引脚 3,因为它有 PWM 并且没有连接上拉电阻。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM