Hi everyone, I've spent all day trying to control a DC motor with the serial monitor and despite how many codes I try and how many tutorials I look at, nothing seems to work. My arduino uno works for other things like controlling a servo motor using the serial monitor but i cant turn the motor on at all regardless what I try. I am using only things that came with the arduino starter pack. The following is the code I am using
int motorPin = 3;
void setup()
{
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
while (! Serial);
Serial.println("Speed 0 to 255");
}
void loop()
{
if (Serial.available())
{
int speed = Serial.parseInt();
if (speed >= 0 && speed <= 255)
{
analogWrite(motorPin, speed);
}
}
}
If you want to use an N-MOSFET to control a motor, wire it up like this with the gate of the MOSFET being driven by the Arduino directly (no resistor), and with a flyback diode in parallel with the motor (facing the positive side). The pull-down resistor is so that the motor is normally OFF. This is sometimes particularly useful to prevent a quick "jump" in the motor when you first power your Arduino on or if you forget to initialize the control pin properly, since the motor will only turn on if you set the pin to HIGH.