How to turn off PWM

Hi There,

I’m trying to modify a program that generates PWM. First off its a motor speed controller for a DC motor and I want to be able to switch the rotation of the motor shaft with this circuit I’m building and in doing so I want to be able to stop the motor first before allowing the switching to occur. I tried writing code to shut it off but couldn’t get it to work because I don’t have very much savvy of the inner workings of PWM. I’m hoping it’s possible. I came up with a way to do it using another relay. I got it working with a SPDT relay by wiring pin 9 of my Mega 2560 to the common of the relay and then from the normally closed contact of the relay to my mosfet then I just powered up the relay when I wanted to stop the motor.

It would work OK but it’s added parts. Does anyone here have any ideas on how to do it in the code rather than adding more hardware? I uploaded the schematics for the circuit I’m going to use below. The schematics doesn’t show the second relay to stop the motor and hopefully I won’t need it. Any help will be very much appreciated…


//This is the code for the PWM Motor Speed Controller
//This is the URL where I got the code:

int potPin = A0;
int motorPin = 9;
int potValue = 0;
int motorValue = 0;
void setup() 

void loop() 
 potValue = analogRead(potPin);  
 motorValue = map(potValue, 0, 1023, 0, 255);
 analogWrite(motorPin, motorValue);  
 Serial.print("potentiometer = " );     
 Serial.print("\t motor = ");

To stop sending the pwm signal just analogWrite the pin to 0.

analogWrite(motorPin, 0);

Or, use digitalWrite(motorPin, LOW);. That will turn off PWM timers, too.

Hi Paul & Delta,

it works great! Very much appreciated.