아두이노 드론 모터 제어 테스트

const int MOTOR_A = 23;
const int MOTOR_B = 19;
const int MOTOR_C = 18;
const int MOTOR_D = 26;
const int CHANNEL_A = 1;
const int CHANNEL_B = 2;
const int CHANNEL_C = 3;
const int CHANNEL_D = 4;
const int MOTOR_FREQ = 5000;
const int MOTOR_RESOLUTION = 10;

int selectedMotor = 0;
int previousMotor = 0;

void setup() {
  ledcSetupChannels();
  ledcAttachPins();
  ledcWriteChannels(0);
  Serial.begin(115200);
}

void loop() {
  if (Serial.available()) {
    String userInput = Serial.readString();
    userInput.trim();

    if (isNumeric(userInput)) {
      int speed = userInput.toInt();
      spinMotor(speed);
    } else {
      selectMotor(userInput);
    }
  }
}

void ledcSetupChannels() {
  ledcSetup(CHANNEL_A, MOTOR_FREQ, MOTOR_RESOLUTION);
  ledcSetup(CHANNEL_B, MOTOR_FREQ, MOTOR_RESOLUTION);
  ledcSetup(CHANNEL_C, MOTOR_FREQ, MOTOR_RESOLUTION);
  ledcSetup(CHANNEL_D, MOTOR_FREQ, MOTOR_RESOLUTION);
}

void ledcAttachPins() {
  ledcAttachPin(MOTOR_A, CHANNEL_A);
  ledcAttachPin(MOTOR_B, CHANNEL_B);
  ledcAttachPin(MOTOR_C, CHANNEL_C);
  ledcAttachPin(MOTOR_D, CHANNEL_D);
}

void ledcWriteChannels(int value) {
  ledcWrite(CHANNEL_A, value);
  ledcWrite(CHANNEL_B, value);
  ledcWrite(CHANNEL_C, value);
  ledcWrite(CHANNEL_D, value);
}

void selectMotor(String input) {
  if (input == "m1" || input == "m2" || input == "m3" || input == "m4" || input == "all") {
    previousMotor = selectedMotor;  // Store the previous selected motor

   
    selectedMotor = (input == "all") ? 100 : input.substring(1).toInt();

    if (previousMotor != 0 && previousMotor != selectedMotor) {
      stopMotor(previousMotor);  // Stop the previous motor if it was spinning
    }

    Serial.println("Motor " + input + " selected");
  } else {
    Serial.println("Invalid motor selection. Please enter 'm1', 'm2', 'm3', 'm4', or 'all'");
  }
}

void spinMotor(int speed) {
  speed = constrain(speed, 0, 1000);

  if (selectedMotor != 0) {
    ledcWriteChannels(0);
    if (selectedMotor != 100) {
      ledcWrite(selectedMotor, speed);
    } else {
      ledcWriteChannels(speed);
    }
  } else {
    Serial.println("Please select a motor before setting the speed");
  }
}

void stopMotor(int motor) {
  if (motor != 100) {
    ledcWrite(motor, 0);
  } else {
    ledcWriteChannels(0);
  }
}

bool isNumeric(String input) {
  for (size_t i = 0; i < input.length(); i++) {
    if (!isdigit(input.charAt(i))) {
      return false;
    }
  }
  return true;
}

모터 제어 테스트 소스

'Electronic Craft' 카테고리의 다른 글

ESP32 블루투스 연동 코드  (0) 2023.08.31
투싼ix 뒷문 USB 충전포트 DIY  (0) 2020.04.07