Motors — Esp32 Devkit C V4 simulation

An interactive Esp32 Devkit C V4 circuit simulation you can run free in your browser on Velxio, by alireza-cs94.

Components

Sketch code

#define TOTAL_MOTORS 14

const int PINS[14] =
{23, 22, 21, 19, 18, 17, 16,
 32, 33, 25, 26, 27, 14, 13};

byte MOTORS_STATE[14] =
{0, 0, 0, 0, 0, 0, 0,
 0, 0, 0, 0, 0, 0, 0};  // 0=off, 1=on

const int MOTOR_SPEED = 200;  // PWM value when motor is ON (0-255)

void setup() {
  // Initialize all pins as outputs and ensure motors are OFF
  for (int i = 0; i < TOTAL_MOTORS; i++) {
    pinMode(PINS[i], OUTPUT);
    analogWrite(PINS[i], 0);
  }

  Serial.begin(115200);
  Serial.println("ESP32 ready. Send 14 bits (e.g., 10101010101010):");
}

// Update physical motors based on MOTORS_STATE array
void updateMotors() {
  for (int i = 0; i < TOTAL_MOTORS; i++) {
    if (MOTORS_STATE[i]) {
      analogWrite(PINS[i], MOTOR_SPEED);  // Motor ON
    } else {
      analogWrite(PINS[i], 0);            // Motor OFF
    }
  }
}

// Parse input string and fill MOTORS_STATE array
// Returns true if valid, false if error (and prints error message)
bool parseInput(String input) {
  // Check length first!
  if (input.length() != TOTAL_MOTORS) {
    Serial.print("Error: Expected ");
    Serial.print(TOTAL_MOTORS);
    Serial.print(" digits, got ");
    Serial.println(input.length());
    return false;
  }

  // Validate and convert
  for (int i = 0; i < TOTAL_MOTORS; i++) {
    char c = input[i];
    if (c == '0') {
      MOTORS_STATE[i] = 0;
    } else if (c == '1') {
      MOTORS_STATE[i] = 1;
    } else {
      Serial.print("Error: Invalid char '");
      Serial.print(c);
      Serial.print("' at position ");
      Serial.print(i);
      Serial.print(". Your Input: ");
      Serial.println(input);
      return false;
    }
  }
  return true;
}

void loop() {
  if (Serial.available() > 0) {
    // Read until newline (or timeout)
    String input = Serial.readStringUntil('\n');
    input.trim();  // Remove \r, \n, and spaces

    // Ignore empty lines
    if (input.length() == 0) return;

    // Parse and update motors if valid
    if (parseInput(input)) {
      updateMotors();

      // Confirmation
      Serial.println("Motors set: ");
      for (int i = 0; i < TOTAL_MOTORS; i++) {
        // Serial.print(MOTORS_STATE[i]);
        Serial.print("Motor ");
        Serial.print(i+1);
        Serial.print(" (esp pin ");
        Serial.print(PINS[i]);
        Serial.print(") is ");
        Serial.println(MOTORS_STATE[i] ? "ON.":"OFF.");
      }
      Serial.println();
      Serial.println("Send 14 bits (e.g., 10101010101010):");
    }
  }
}

More projects by alireza-cs94