Problem with DC motor software, newby

Hello, i am having troubles with my DC motor. I was trying to make it so it can vary speed, the arduino starter book suggested me to try and do so. Here is my problem : No matter what, my arduino keeps spinning the same MAX speed.

const int switchPin = 2;
const int motorPin = 9;
const int potPin = A0;
int switchState = 0;
int potVal = 0; //Potentiometer value
int motorOut = 0; //The to be speed mapped from 0-1023 to 0-255

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(switchPin, INPUT);
  pinMode(motorPin, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  switchState = digitalRead(switchPin);
  int potVal = analogRead(potPin);
  Serial.print("Etat du switch = ");
  Serial.println(switchState);
  Serial.print("potVal = ");
  Serial.println(potVal); 
  motorOut = map(potVal, 0, 1023, 0, 255);
  Serial.print("Valeur de MotorOut = "); 
  Serial.println(motorOut); //it actually works : printing value from 0-255
  float motorOut2 = motorOut/255*5; // Unused troubleshoot tries (overall useless)



  if (switchState == 1) { 
    
    digitalWrite(motorPin, motorOut); //Same motor speed no matter WHAT !
    delay(50);
  }

  else {
    digitalWrite(motorPin, LOW); //thankfully, it stops
    delay(50);
  }
  delay(5);
}

digitalWrite(motorPin, motorOut); //Same motor speed no matter WHAT !

You need to use an analog PWM pin, and analogWrite().

Please post a wiring diagram, and a link to the motor driver. Don't try to connect a motor directly to a digital pin, or power it from the Arduino 5V (even if the "starter book" tells you to do so).

Tutorial

What is printed out for "potVal"?

Thanks your for your fast answer :slight_smile:

I am litteraly using project 09 of the starter kit :

potVal prints value map from 0-1023 (pot) to 0-255. It works and shows as i move it.

I don't know what the motor driver is but on it is written as follow :

TT MOTOR
20210703

The motor driver is the black object with 3 pins on the breadboard, which should be a MOSFET transistor.

What are the markings on it? Post a close up, focused picture of your setup, clearly showing all the wiring.


the dual potentiometer doesnt really change much, it's only connected to the left one, that has white turning green wire connected to A0.

I MADE IT ! but i can't understand how it works :slightly_frowning_face: :

I just changed my
digitalWrite(motorPin, motorOut);

to

analogWrite(motorPin, motorOut);

Why does it work if my motorPin is acutally not on any analog, why is it analog write, and why does it works that way ?

The tutorial linked above explains that, or tries to. Read it, disregarding the difference in the driver used.