No title

// BTS7960 Pins

#define RPWM 5

#define LPWM 6

#define R_EN 7

#define L_EN 8


// Buttons

#define BTN_CW 2

#define BTN_CCW 3


// Potentiometer

#define POT A0


int speedValue = 0;

int direction = 0; // 1 = CW, -1 = CCW, 0 = Stop


// Button states (for edge detection)

bool lastCWState = HIGH;

bool lastCCWState = HIGH;


void setup() {

  Serial.begin(9600);


  pinMode(RPWM, OUTPUT);

  pinMode(LPWM, OUTPUT);

  pinMode(R_EN, OUTPUT);

  pinMode(L_EN, OUTPUT);


  pinMode(BTN_CW, INPUT_PULLUP);

  pinMode(BTN_CCW, INPUT_PULLUP);


  digitalWrite(R_EN, HIGH);

  digitalWrite(L_EN, HIGH);


  Serial.println("=== Toggle Motor Control Started ===");

}


void loop() {


  // Read potentiometer

  int potValue = analogRead(POT);

  speedValue = map(potValue, 0, 1023, 0, 255);


  // Read buttons

  bool currentCW = digitalRead(BTN_CW);

  bool currentCCW = digitalRead(BTN_CCW);


  // Detect press (HIGH → LOW)

  if (lastCWState == HIGH && currentCW == LOW) {

    direction = 1; // CW

    Serial.println("Button Pressed: CW");

  }


  if (lastCCWState == HIGH && currentCCW == LOW) {

    direction = -1; // CCW

    Serial.println("Button Pressed: CCW");

  }


  lastCWState = currentCW;

  lastCCWState = currentCCW;


  // Motor Control

  if (direction == 1) {

    analogWrite(RPWM, speedValue);

    analogWrite(LPWM, 0);

    Serial.print("Direction: CW | Speed: ");

    Serial.println(speedValue);

  }

  else if (direction == -1) {

    analogWrite(RPWM, 0);

    analogWrite(LPWM, speedValue);

    Serial.print("Direction: CCW | Speed: ");

    Serial.println(speedValue);

  }

  else {

    analogWrite(RPWM, 0);

    analogWrite(LPWM, 0);

    Serial.println("Stopped");

  }


  delay(100);

}

Post a Comment

Previous Post Next Post

Contact Form