c++ 无法更改L293D的速度

wgx48brx  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(137)

我不知道为什么我不能把analogWrite(motor_enA, 255);的值从255改成一个更小的数字,因为马达刚刚停止工作。

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Servo.h>

RF24 radio(7, 8); // CE, CSN

const byte address[6] = "00001";
Servo myservo; 

struct InputData  // define stuct
{
   int x;
   int y;
};

InputData data;

// Motor A connections
int motor_enA = 9;
int motor_in1 = 10;
int motor_in2 = 6;

int encoder1 = 2;
int encoder2 = 3;

volatile int counter = 0;
int angle = 0;

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(1, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();

  // Set all the motor control pins to outputs
  pinMode(motor_enA, OUTPUT);
  pinMode(motor_in1, OUTPUT);
  pinMode(motor_in2, OUTPUT);

  // Turn off motors - Initial state
  digitalWrite(motor_in1, LOW);
  digitalWrite(motor_in2, LOW);
  analogWrite(motor_enA, 255);

  pinMode (encoder1, INPUT);
  pinMode (encoder2, INPUT);

  myservo.attach(5);
}

void loop() {
  if (radio.available()) {
    radio.read(&data, sizeof(data));
    myservo.write(data.x);  
    Serial.println(data.y);
    if (data.y > 15) {
      digitalWrite(motor_in1, HIGH);
      digitalWrite(motor_in2, LOW);
    }
    else if (data.y < -15) {
      digitalWrite(motor_in1, LOW);
      digitalWrite(motor_in2, HIGH);
    }
    else {
      digitalWrite(motor_in1, LOW);
      digitalWrite(motor_in2, LOW);
    }
  }
  
}

我尝试将数字255更改为254,但电机不转。

taor4pac

taor4pac1#

正如注解中所指出的,您必须从最小草图开始,然后逐渐添加库和代码行。例如,SPI使用引脚10作为从机选择,无线电库可能会干扰Arduino的定时器,这可能涉及模拟写入。
请尝试以下代码:如果它仍然不起作用,那么就有硬件问题。

int motor_enA = 9;
int motor_in1 = 10;
int motor_in2 = 6;
int speed=255;

void setup() {
  Serial.begin(9600);
  // Set all the motor control pins to outputs
  pinMode(motor_enA, OUTPUT);
  pinMode(motor_in1, OUTPUT);
  pinMode(motor_in2, OUTPUT);

  digitalWrite(motor_in1, HIGH);
  digitalWrite(motor_in2, LOW);
}

void loop() {
     delay(500);
     analogWrite(motor_enA, speed); 
     speed=speed-10;
     if (speed < 10) speed=255; 
}

相关问题