analogWrite is not working - while trying to control DC motor speed
Well, 2M resistor to the base? If the motor is running with that, the transistor must be broken (shorted). Just try to check if the motor is running with disconnected base.

You can also check PWM output by connecting LED with resistor (no, not 2M ohms, just about 330 ohms). For the transistor 1k should be sufficient maybe little less (depends on motor current and h21e amplification coeficient).

Also there are some versions 2N2222 with emitter and collector swapped. And reversed transistor has much lower current amplification coeficient.

And I hope you are using external power supply, USB is not a good idea. Starting power is usually way too much for the overcurrent protections.

Anyways, this works for me:

void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  analogWrite(9, map(analogRead(A0), 0, 1023, 0, 255));
  delay(100);
}


2N2222A + 1k + PC FAN + 12V Fan Power supply.

Connections: E -> Gnd, C -> FAN-, FAN+ -> 12V, 12V GND -> Arduino GND, Pin 9 -> 1k -> B

On the Arduino side 47k trimmer and the USB