Controlling a DC motor using PWM and a potentiometer

matt9522:
what is the syntax for constraining a pwm signal reading? analogWrite(pot) I'm not sure this is correct.

int getpot()

{
  analogRead(pot) = constrain(pot, 90, 255)
}

No, that's not right. analogRead returns a value equal to the sensor reading, which means you have to assign it to a variable or use it as a variable directly. The point of the constrain function is to limit what values a variable can be. Anything above 255 will be 255, and anything below 90 will be 90. The actual analogRead function will return a value of 0 to 1023, and the PWM can only take a value between 0 and 255. So, you constrain it. There is also the map() function which you could use. How these are used is detailed in the "reference" section of this website.

So:

int val = analogRead(pot);
constrain(val,90,255);

would work, or:

constrain(analogRead(pot),90,255);

But doing it the first way is best.

matt9522:
the value string was supposed to set the motor to stop when the signal was between 100 and 140.

Then in your getpot() routine, check if the val is between 100 and 140 (but this would mean the motor would run at values from 90 to 99, and 141 to 255 and only stop while it is in between 100 and 140. I think the original code was supposed to run forward for values above 140 and backwards for values below 100. So centering the pot is what stopped it. Since you are going in only one direction, change the getpot routine in my code to this:

void getPot() {
  val = analogRead(pot);
  constrain(val,90,255); //this restricts the analog value to between 90 and 255
  if(val=<90){
    val = 0
  }

}

That will stop the motor for values of 90 (or below). Since we constrained the value, 0 (potentiometer all the way to one side) becomes 90. So, your actual variable speed is now 91-255. And the motor will completely stop when you move the pot completely to one side.

Since you are not using the relay, change the run() routine to this:

void run() {

  analogWrite(motorPin, val); //this will run the motor at the speed set by the pot value

}

Or just put that one line in your loop in place of run();