EspMotors — ESP32 simulation

An interactive ESP32 circuit simulation you can run free in your browser on Velxio, by alireza-cs94.

Components

Sketch code

// 4-Channel 130 DC Motor Controller - ESP32 (hardware PWM via LEDC)
const uint8_t BTN[1] = {27};
const uint8_t PWM_PIN[1] = {33};   // Motor 1..4
const uint8_t POT_PIN = 34;                    // ADC1, input only

const uint32_t PWM_FREQ = 20000;   // 20 kHz (inaudible)
const uint8_t  PWM_BITS = 8;
const int PWM_MIN = 51;            // 20% of 255
const int PWM_MAX = 255;

static void pwmWrite(uint8_t i, int duty) {
#if defined(ESP_ARDUINO_VERSION_MAJOR) && ESP_ARDUINO_VERSION_MAJOR >= 3
  ledcWrite(PWM_PIN[i], duty);        // core 3.x: channel is bound to pin
#else
  ledcWrite(i, duty);                 // core 2.x: channel index
#endif
}

void setup() {
  analogReadResolution(12);
  for (uint8_t i = 0; i < 1; i++) {
    pinMode(BTN[i], INPUT_PULLUP);
#if defined(ESP_ARDUINO_VERSION_MAJOR) && ESP_ARDUINO_VERSION_MAJOR >= 3
    ledcAttach(PWM_PIN[i], PWM_FREQ, PWM_BITS);
#else
    ledcSetup(i, PWM_FREQ, PWM_BITS);
    ledcAttachPin(PWM_PIN[i], i);
#endif
    pwmWrite(i, 0);                   // all motors OFF at startup
  }
}

void loop() {
  int adc = analogRead(POT_PIN);                       // 0..4095
  int duty = map(adc, 0, 4095, PWM_MIN, PWM_MAX);      // 20%..100%
  for (uint8_t i = 0; i < 1; i++) {
    bool pressed = (digitalRead(BTN[i]) == LOW);
    pwmWrite(i, pressed ? duty : 0);
  }
}

More projects by alireza-cs94