PWM Pins with same different analogWrite values not working

The Problem: I have students building an Arduino Car with two motors using an H-Bridge. We should be able to adjust the speed of each motor individually, but it seems that recently when we upload the code it is only allowing the following two scenarios:

  • One pin is set to 255 and the other pin can be whatever value we set it to
  • Both pins are set to exactly the same value

If both motors are a different value (one of which is not 255) then one or both show 0 voltage. Here is the code we are uploading:

//Motor 1
const int EN1 = 2;
const int MC1A = 3;
const int MC2A = 4;
//Motor 2
const int EN2 = 11;
const int MC3A = 9;
const int MC4A = 8;

void setup()
  {
    pinMode(EN1, OUTPUT);
    pinMode(MC1A, OUTPUT);
    pinMode(MC2A, OUTPUT);
    pinMode(EN2, OUTPUT);
    pinMode(MC3A, OUTPUT);
    pinMode(MC4A, OUTPUT);
    brake();
  }

void loop()
  {
    forward();
    delay(5000);
    brake();
    delay(1000);
    reverse();
    delay(5000);
    brake();
    delay(1000);
  }

void forward ()
  {
    digitalWrite(MC1A, HIGH);
    digitalWrite(MC2A, LOW);
    analogWrite(EN1, 255);
    
    digitalWrite(MC3A, HIGH);
    digitalWrite(MC4A, LOW);
    analogWrite(EN2, 255);
  }

void reverse ()
  {
    digitalWrite(MC1A, LOW);
    digitalWrite(MC2A, HIGH);
    analogWrite(EN1, 255);
    
    digitalWrite(MC3A, LOW);
    digitalWrite(MC4A, HIGH);
    analogWrite(EN2, 255);
  }

void brake ()
  {
    digitalWrite(EN1, LOW);
    digitalWrite(MC1A, LOW);
    digitalWrite(MC2A, LOW);
    
    digitalWrite(EN2, LOW);
    digitalWrite(MC3A, LOW);
    digitalWrite(MC4A, LOW);
  }

We have tried this on an Arduion MEGA 2560, on an UNO, and on some generic boards like a Keyestudio Mega.
Any help would be appreciated.

Like I said in my original post, I can PWM both pins at the same time if they are the same values. One is going into enable pin 1 and the other is going into enable pin 2. I know which pins are PWM enabled for all of my boards. That doesn't seem to be the issue...

Board PWM Pins PWM Frequency
Uno, Nano, Mini 3, 5, 6, 9, 10, 11 490 Hz (pins 5 and 6: 980 Hz)
Mega 2 - 13, 44 - 46 490 Hz (pins 4 and 13: 980 Hz)
Leonardo, Micro, Yún 3, 5, 6, 9, 10, 11, 13 490 Hz (pins 3 and 11: 980 Hz)
Uno WiFi Rev2, Nano Every 3, 5, 6, 9, 10 976 Hz

which board are you using?

Pin2 is not a PWM pin on an Uno, but it is on a Mega.

Some pins have different default PWM frequencies, which can result in different motor behaviour.
Leo..

I've seen where too high of a freq. will saturate the motor and it acts like its only on/off. Possibly this is an issue?

-jim lee

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.