A wiper motor connected to a motor driver module to control with an Arduino Uno.

Control DC Motors with Arduino: Wiring & Code Examples

Welcome to the world of creative engineering! In this comprehensive Arduino motor control guide, we’re delving into the exciting process of controlling DC motors, even 12V wiper motors, using an Arduino and a motor driver module. Whether you’re crafting an intricate animatronic, building a custom robot, or designing dynamic motorized props, mastering the art of motor control is crucial. We’ll start from the basics, exploring how to wire your Arduino to a 12V DC motor with the help of a motor driver module, while explaining every connection. Then, we’ll journey into the realm of programming, where I’ll show you how to write Arduino motor control code that breathes life into your projects with custom motor movements beyond what a motor speed controller can do.

New to coding? No problem! This Arduino motor control tutorial is designed for makers of all skill levels, aiming to equip you with the knowledge to bring your mechanical creations to life in an interactive and controlled manner. We’ll start with some easy Arduino code examples and work our way to precise and randomized motor control. So, grab your motor, Arduino microcontroller and compatible motor driver module and let’s start turning those imaginative ideas into moving, whirring realities!

In this Arduino Motor Control Tutorial:

Learning how to code and using an Arduino microcontroller for the first time may seem intimidating at first but it’s not that big a jump if you’ve already been incorporating motors into your prop and controlling the speed with a motor speed controller. But if you want to go further than just setting a speed and watching your prop perform the same movement over and over again, then learning how to program motor direction, speed and timing can unlock another level of realism for future projects.

What is Arduino?

Arduino is a popular open-source electronics platform that has revolutionized the world of DIY electronics and prototyping. It consists of both a physical programmable circuit board (often referred to as a microcontroller) and a piece of software, or Integrated Development Environment (IDE), that runs on your computer. The Arduino IDE is free and allows you to write and upload code to the physical board.

If you’re just starting out, the Arduino Uno is the easiest microcontroller board to learn on. Since Arduino is open source, you’ll find various clones (copies) from different manufacturers, usually at lower price points. But all Unos pretty much look and function the same. I recommend starting with an official Arduino Uno microcontroller and then trying other clones once you’re more familiar with its features.

Arduino Uno microcontroller for controlling motors with Arduino code.
The Arduino Uno is the most popular microcontroller for beginners.

As for the coding part, Arduino has a vast ecosystem of libraries to make working with different components easier with examples to help get you started. This, combined with a vibrant community, make it an excellent choice for various electronics projects, including robotics, animatronics, and in our case, programming prop motor movements to bring your character to life!

Can I Connect a DC Motor Directly to an Arduino Microcontroller?

Unless you’re going for a smoke effect, I highly advise against connecting your DC or 12V motor directly to any Arduino microcontroller. There are several reasons for why this is a bad idea:

  • Voltage Limitations: Arduino pins are designed to operate at 5V. If you connect a 12V motor directly to an Arduino pin, the motor won’t get enough voltage to rotate at its normal speed, if at all.
  • Current Limitions: Arduino pins can typically provide around 20 to 40 milliamperes (mA) of current which is no where near what a 12V motor needs. Motors often require much more current to operate, especially during startup or under load. Connecting a 12V motor directly to an Arduino pin will result in the motor trying to draw too much current and at best, frying the pin. But there’s also a good chance it will damage the Arduino microcontroller too.
  • Lack of Control: Connecting a motor directly to an Arduino pin provides no way to control the motor’s speed or direction. To have full control over the motor, you need a motor driver or an H-bridge circuit.

How Do You Control a DC Motor with Arduino?

If you can’t connect a motor directly to an Arduino microcontroller, then how are you supposed to control the motor? One of the main advantages of using an Arduino board is that it’s compatible with a nearly endless amount of components that can act as intermediaries that pass along the code instructions we write and upload to the Arduino microcontroller to the motor along with the correct power requirements to drive it.

There are several components you can use with the Arduino for controlling a 12V motor:

  • Motor Driver Modules (recommended): This is the most common method for controlling motors with Arduino. Motor driver modules are specifically designed to interface between microcontrollers and motors, providing easy control over the motor’s speed and direction.
  • Relays: Relays are switches that can be controlled by an Arduino. You can use a relay to turn a motor on and off, but you won’t have control over the motor’s speed or direction. For controlling direction, you would need to use two relays.
  • Transistors: Transistors can be used as switches to control a motor. You can use a transistor to turn a motor on and off, and by using PWM, you can control the motor’s speed. For controlling direction, you would need two transistors.

For this Arduino motor control tutorial, we’ll be using a motor driver module because it has all the control features you’d want packaged in a single inexpensive component.

What is a Motor Driver Module?

A motor driver module is a device that acts as an interface between a microcontroller (such as an Arduino) and a motor, allowing the microcontroller to control the motor’s speed, direction, and sometimes other features like braking. The motor driver module handles the higher current and voltage requirements of the motor while executing the instructions coming from the Arduino microcontroller.

Examples of motor driver controllers that can be used with Arduino including the L293D IC chip pictured on the left and L298N motor driver module on the right.

Motor driver modules come in different varieties, the most common being either an IC (chip) like the L293D motor driver or module circuit board like the popular L298N motor driver. While they all pretty much work the same, some can control one motor while others can control two. No matter which one you choose, you can rest assured that at minimum it will handle these important functions:

  • Handle Higher Voltage & Current: Motors typically require more voltage and current than a microcontroller can provide. The motor driver module can handle higher power levels and provide the motor with the required current and voltage, protecting the microcontroller from damage.
  • Control Motor Speed: A motor driver allows you to control the speed of a motor by using Pulse Width Modulation (PWM). By varying the duty cycle of the PWM signal, you can control how much power is delivered to the motor, thereby controlling its speed.
  • Control Motor Direction: A motor driver can change the direction of the motor by reversing the polarity of the voltage applied to the motor terminals.
  • Provide Isolation & Protection: Motor driver modules can provide isolation between the microcontroller and the motor. They often include protection features such as overcurrent protection, thermal shutdown, and under-voltage lockout to prevent damage to the motor and the driver itself.

The main decision-making factor when choosing a motor driver module for your project is the power requirements of the motor(s) you plan to use, especially current output.

For instance, the L293D IC can only output 600mA per channel (per motor). This won’t be nearly enough to run a 12V motor like a wiper motor. The L298N is a bit better and can output 2A per channel so it can control small to medium-sized motors that draw up to 2A. That’s still not beefy enough for a 12V motor that will need at least 5A.

Types of Motor Driver Modules for Controlling 12V Motors

When it comes to driving 12V high-current motors, there are several motor driver modules and controllers that can handle the job. Here are two that I use most frequently to control 12V motors (like wiper motors) with Arduino for my motorized prop projects that need at least 5A.

XY-160D Motor Driver

The XY-160D motor control module is a versatile and user-friendly option for controlling DC motors in your Arduino projects. Based on the popular L298N H-bridge driver, it can handle two DC motors or one stepper motor, with an input voltage range from 7V to 27V and a continuous operating current of 7A per channel (per motor). The module features input pins for connecting to an Arduino or other microcontroller, enabling precise control over the motor’s speed and direction using Pulse Width Modulation (PWM) signals. Additionally, it often includes protection features such as overcurrent protection and thermal shutdown. This makes the XY-160D a reliable and efficient choice for your motor-driven projects.

The XY-160D motor driver module to control larger DC motors with the Arduino.

Since the XY-160D motor driver module most closely meets the needs of many of my 12V motor projects, I’ll be featuring it in the motor wiring and Arduino coding examples below. But if you need a motor driver module that can handle even more current, check out the IBT-2. It wires up very similarly to the XY-160D so you can still follow the rest of this tutorial with ease.

IBT-2 BTS7960 Motor Driver

The IBT-2 BTS7960 motor control module is a robust and powerful solution for controlling high-current DC motors, ideal for applications where motors need to move heavy loads. Built around the BTS7960 high-power H-bridge driver, the IBT-2 is capable of driving motors with currents up to 43A, making it suitable for even the most demanding projects. The module operates at voltages from 6V to 27V, accommodating a wide range of motors. It features an onboard heat sink to dissipate heat effectively, ensuring reliable performance even under heavy load.

The IBT-2 motor driver module to control larger DC motors with the Arduino.

The module’s interface is user-friendly, with input pins for PWM and direction control, making it easy to integrate with microcontroller platforms like Arduino. With its high-current handling capabilities, efficient heat management, and easy-to-use interface, the IBT-2 BTS7960 is an excellent choice for those looking to control powerful motors in their projects.

Pinout of a XY-160D Motor Driver Module

Although the surface of the XY-160D control module may look a bit crowded, the connection points are easy to see. Like many board-based driver modules, you’ll find two types of connections: male pins to connect to the Arduino microcontroller and screw terminals for the power supply and connecting your motor(s).

Pinout of a XY-160D motor control module with male pins to connect to the Arduino and screw terminals to connect a power supply and motors.

The XY-160D motor driver module has the following pinout:

  • IN1, IN2, IN3 & IN4 Pins: These are the input pins used to control the direction of the motors. IN1 and IN2 control the first motor, and IN3 and IN4 control the second motor.
  • ENA Pins: On this module, there are two ENA pins, one for each motor. You’ll often see them labeled as ENA and ENB on other models. These are the enable pins for the motors. They can be connected to the PWM pins on your Arduino to control the speed of the motors.
  • +5V Pins: Either of these pins supply power for the switching logic circuitry inside the module. I often use the 5V pin from the Arduino for this.
  • GND: This is the ground pin of the module that gets connected to a GND pin on the Arduino microcontroller. All components you use with the Arduino have to share a common ground. Some other models don’t have this pin so you normally have to run an extra ground wire from the power supply GND screw terminal of the motor module to the GND pin of the Arduino to make the circuit work. Having this additional GND pin makes wiring easier because it establishes a common ground through the module.
  • OUT1, OUT2, OUT3 & OUT4 Screw Terminals: These are the outputs that connect to the positive and negative wires of the motors. OUT1 and OUT2 connect to the first motor, and OUT3 and OUT4 connect to the second motor.
  • 9-24V & PGND Screw Terminals: This pair of screw terminals (green) is where you connect your power supply for the motors. Insert the positive wire of your power supply into the 9-24V slot and the ground wire into PGND (power ground) slot. Although the module can tolerate voltages of 7V to 27V, it operates best between 9V and 24V. If you’re using a 12V motor, connect a 12V power supply here with enough Amps to run your motors. Large motors and wiper motors work well with 5A.

How to Wire a 12V Motor to an Arduino Uno and Motor Control Module

Wiring the three components together is pretty straightforward. At the center of it all is the motor driver module so we’ll work on each section of it at a time, starting with the Arduino side.

1. Connect the Motor Driver Module to the Arduino Uno

In order to make these connections you’ll need female-to-male breadboard jumper wires. They usually come in a package with all the combinations you typically use for electronics projects like male-male, female-female and female-male.

  • Ground Wire: Connect the motor driver’s ground (GND) pin to the Arduino’s ground (GND) pin.
  • 5V Power Wire: Connect the motor driver’s 5V pin to the Arduino’s 5V pin.

An Arduino Uno and XY-160 motor control module showing how to wire 5V and GND connections.

  • Direction Control Wires: Connect the IN1 and IN2 pins of the motor driver to any of the digital pins on the Arduino. These will be used to control the direction of the motor.
  • Speed Control Wire: Connect the ENA pin of the motor driver to a PWM-capable pin on the Arduino. These pins have a “~” next to the pin number. This will allow you to control the speed of the motor.

An Arduino Uno and XY-160 motor driver module showing how to wire the direction pins (IN1 & IN2) and speed pin (ENA) to control the motor.

2. Connect the 12V Motor to the Motor Driver Module

  • Positive Wire: Connect the positive wire from the motor to the OUT1 screw terminal of the motor driver. If you’re working with a wiper motor, then select either the high or low speed wires as the positive wire. I normally choose the high speed wire to give me a wider range of speeds to choose from.
  • Ground Wire: Connect the ground wire from the motor to the OUT2 screw terminal of the motor driver.

DC motors typically have two wires and if you’re having trouble figuring out which wire is positive and which one is negative, don’t worry. Even though I specified which wire to connect to what OUT terminal above, the reality is that it doesn’t matter. It won’t hurt anything if you hook it up backwards. We’ll soon be able to figure it out once we start programming some movements with the Arduino later on in this Arduino motor control tutorial.

A 12V motor wired to a XY-160D motor driver module to be controlled by an Arduino.

But if you’re using a wiper motor like I am, then you may have anywhere from three to five wires. I like to use the high speed wire (yellow in my case) as my positive connection so you get a wider range of speeds. If you’re not sure which wire is which on your wiper motor, I have a wiper motor wiring tutorial that will walk you through the process of how to identify your wiper motor wires.

3. Power Your Motor via the Motor Driver Module

The Arduino Uno will provide power to the XY-160D motor control module through the 5V and GND connections you made earlier for it to do its job. But the motor needs power too.

The green power supply screw terminals on the XY-160D motor driver module is where you connect the wall adapter you use to power your motor. Mine is a 12V 8A adapter. Rather than cut the male end off, I prefer to use a female DC power jack adapter. That way, once you’re done with your prop for the season, you can use your power adapter for other projects.

A 12V power supply wired to a XY-160D motor driver module to power a 12V motor that's controlled by an Arduino Uno.

Unlike connecting your motor, polarity for this connection matters. Make sure to double check that the orientation of the positive and negative wires coming out of the female jack adapter going into the screw terminals of the motor control module are correct.

Sometimes, trying to follow a mess of wires in a photo can be tricky so I put together a cleaner wiring diagram showing every connection we made.

Wiring diagram showing how to connect a 12v motor to a motor driver module and wire the module to an Arduino Uno so it could control the motor via the motor control module.

Here are the connections I made from the motor driver module to the Arduino Uno:

  • 5V to Arduino 5V
  • ENA pin to Arduino pin ~9 (PWM-enabled)
  • IN1 pin to Arduino pin 8
  • IN2 pin to Arduino pin 7
  • GND to Arduino GND

How to Write Arduino Code to Program Motor Movements

The Arduino Integrated Development Environment (IDE) is a software application that provides an easy-to-use interface for writing, compiling, and uploading code to Arduino boards. It supports the C and C++ programming languages and includes a variety of libraries and examples that make it easier to develop Arduino projects.

How to Install the Arduino IDE and Configure your Board

If you’ve never coded anything before, don’t worry. I’ll take you through a variety of Arduino code examples for controlling motors with line-by-line code explanations. You can use my code examples in your own motorized prop projects as is, or modify them to better suit your needs.

Go ahead and connect the Arduino Uno to your computer with a USB cord. Don’t plug in your power supply just yet (the one that plugs into the female adapter). We’ll do that when we’re ready to upload the code.

Download the Arduino IDE

If you haven’t already, download the Arduino IDE from the official Arduino website and follow the installation instructions for your operating system.

When you launch the Arduino IDE software, a new blank sketch (coding window) will appear. You’ll notice some code already on there but ignore it for now.

Select the Correct Board & Port

Before we can start writing any code, double check that the correct board is selected in Tools -> Board. In my case, I’d select the Arduino Uno because that’s what I’m using. If you’re using a clone of the Uno, then you still select Arduino Uno.

Then select the Port on your computer that your Arduino board is connected to. Go to Tools -> Port and select the one that has the board name next to it.

If this is your first time working with an Arduino microcontroller or coding anything, check out my introduction to the Arduino IDE guide where I take you step-by-step through the software download, board/port configuration steps and familiarize you with different parts of an Arduino sketch.

If you prefer to just go for it (like me most of the time), then let’s start writing our first sketch!

Define Arduino Pin Connections and Variables

The first thing I like to do, is tell the Arduino what pins we’re connected to. The best way to do this is using variables. This means we’re going to give each pin we’re using a name and associate it with an Arduino pin number.

Any code that appears in gray are my personal notes for you. In an Arduino sketch, they are called comments. The microcontroller will ignore anything that appears after // and is grayed out. You don’t have to include any of my comments in your code for it to work.

We have three wires coming from the motor driver and connecting to the Arduino IN1, IN2 and ENA. The power and ground wires don’t count because we won’t be using them to control anything. You can name the pins whatever you want but it’s best to use descriptive names that you’ll remember what they refer to months later. Do not include spaces in your variable names.

Let’s start with the first line:

int IN1pin = 7;

The int tells the Arduino that our variable is an integer (whole number). Since the IN1 pin from the motor driver is connected to Arduino pin 7, I named the pin IN1pin and set it equal to to 7.

Do the same for the other two wires:

int IN2pin = 8;

int ENApin = 9;

The variable names I used are pretty self-explanatory and I’ll remember what they refer to if I ever come back to this sketch at a later date. If you ever need to change your connections and move to a different pin on the Arduino microcontroller, remember to update the pin numbers in this area.

Configure Arduino Pins as Outputs

Next, let’s move on to the void setup() section. Any code you put within the curly brackets gets executed one time by the Arduino as soon as you power it up. There are certain instructions that you only have to tell the Arduino once and it will use it for the rest of the program.

Arduino pins can either be used as inputs or outputs so we have to tell the Arduino how we want the pins to function. It’s important to use the correct capitalization for your code to work. Arduino uses certain keywords that turn different colors when you type them in correctly.

Since the Arduino will be sending out instructions to the motor driver, which will then control the motor, it makes sense to set each of our three Arduino pins to outputs.

In order to do this, we use the pinMode function. This will set the “mode” of our Arduino pins to either an output or an input. The structure of this function is:

pinMode(pin, OUTPUT or INPUT);

Be sure to enter your pin name exactly as you typed it earlier at the top of the sketch and that OUTPUT is in all capital letters. Because the pin name is something we made up, it won’t turn any colors.

Now that we’ve set everything up, let’s get this motor moving with a few examples.

Code Examples: Motor Control with Arduino

Most of the code we’re going to be writing will take place in the void loop() section. Unlike the void setup() section that contains instructions that’s only read and executed one time, anything we put within the curly brackets of the void loop() section will be executed one line at a time until the program reaches the bottom. It will then “loop” back to the top of this section and start again. This process repeats itself until you either turn off your microcontroller or write other code to exit the loop section.

We’ll start with the basics to learn how to control motor direction, speed and timing with the Arduino. Then we’ll progress together to more randomized movements.

Example Code 1: Turn the Motor Clockwise (Direction 1)

If we want to do anything cool with our motor, we’re going to have to get it to move. We do that by sending 5V signals to the IN1 and IN2 pins of the XY-160D via the Arduino. The XY-160D then takes these signals and moves the motor using the 12V power supply you connected.

One of the functions you can use to send 5V signals from an Arduino pin to the motor driver is called digitalWrite(). Here’s how it’s structured:

digitalWrite(pin, HIGH or LOW);

If you write an Arduino pin HIGH, it will send 5V out. If you write it LOW, it will send 0V out. Those are the only two options when using the digitalWrite() function.

In the first line of code inside the void loop() section, I’m telling the Arduino to send out 5V to the IN1 pin of the motor driver.

digitalWrite(IN1pin, HIGH);

I must also tell the Arduino to send 0V (LOW) to the IN2 pin of the motor driver so only one direction is getting power. A motor can’t turn in two directions at once. You should always include instructions for both directions so there’s no misunderstanding which direction you want the motor to turn.

That’s why in the second line, I wrote:

digitalWrite(IN2pin, LOW);

So we’ve set the direction we want, but unless you step on the gas the motor won’t move. That’s where the PWM functionality of the Arduino pin comes in. Unlike digitalWrite() where you only have two options, HIGH or LOW (basically on or off), speed needs to have values in between rather than just no speed or max speed.

Because we connected the ENA pin of the motor driver to pin 9 of the Arduino, which has PWM capabilities, we’ll be able to choose from a range of PWM values. This will determine the speed, like an accelerator pedal of a car.

In order to work with PWM values, we’ll use the analogWrite() function. It looks like this:

analogWrite(pin, PWM value);

The PWM value can be any whole number from 0 (always off) to 255 (always on).

How does PWM work?

Pulse Width Modulation (PWM) is a technique used to simulate an analog output using digital means. Since Arduino can’t directly output analog voltages, it uses PWM to create a similar effect. It achieves this by rapidly turning a digital signal on and off. The key factor in PWM is the duty cycle – the percentage of time the signal is on versus the time it is off in each cycle. This produces an average voltage per cycle.

As the motor driver receives these 5V pulses from the Arduino, it translates them to 12V pulses to the motor using the 12V power supply you connected.

Why 0 to 255?

This range is due to the 8-bit resolution of the PWM output in Arduino. An 8-bit value can represent any number between 0 and 2^8 – 1, which is 0 to 255. Each number in this range corresponds to a specific duty cycle, providing fine control over the simulated analog output.

Now that you know how PWM works let’s get back to the code!

Let’s put the pedal to the metal and set our speed to max at 255. To do that, the third line of code looks like:

analogWrite(ENApin, 255);

We’re done! If this is your first Arduino sketch – congratulations, you’re now a programmer!

Plug in your power supply and upload the code. If there aren’t any errors, the Arduino IDE will upload the code to your Arduino Uno microcontroller.

The motor should start spinning and it’s usually in a clockwise direction. If yours is spinning counter-clockwise, don’t worry. You can leave it as is if it doesn’t bother you.

If you want IN1 to spin clockwise, there’s two ways to accomplish that. The first is in the code. Simply swap the HIGH and LOW values in the digitalWrite() functions. Upload the code again, and it should be spinning clockwise.

The second way to do it is simply swap your positive and negative motor wires at the output terminal block of the motor driver and leave the code alone.

Try Different Motor Speeds

See how slowly you can get your motor to spin by entering in progressively lower PWM values in your analogWrite() function. Interestingly, your motor will stop spinning before you even reach a PWM value of 0.

Why does my motor stop turning below a certain PWM value?

As you lower your PWM value, it will translate to a shorter and shorter duty cycle, the percentage of time your motor is getting power per cycle. You eventually hit an average voltage that’s not enough for the motor to operate and it will stop turning.

This “bottom” value is different for every motor so it’s important to find your motor’s bottom before writing a custom animation, only to discover your prop, robot or animatronic stops moving unexpectedly because you used PWM values that are too low.

The bottom for my wiper motor was a PWM value of 70. Keep your bottom value in mind to use for the next code examples.

Example Code 2: Turn the Motor Counter-Clockwise (Direction 2)

Now that we have the motor turning clockwise, let’s change direction.

All you have to do is switch your digitalWrite() values:

digitalWrite(IN1pin, LOW);
digitalWrite(IN2pin, HIGH);

The IN1 pin which turns the motor clockwise is set to LOW and will get 0V while the IN2 pin which turns the motor counter-clockwise is set to HIGH so it will get 5V.

Upload the code and see if your motor starts turning the opposite way than it did with the previous code.

Example Code 3: Turn the Motor in Each Direction

We’ve spun the motor in both the clockwise and counter-clockwise directions separately and picked a speed. But this is no different than just using a motor speed controller where you turn the knob to set the speed you want and watch your prop make the same movement over and over again.

With the Arduino, you can do so much more! Being able to have your motor switch directions within the same program opens up a world of animation possibilities. Here are just a few ideas:

  • Jump Scare Mechanisms: Use the motor to suddenly move a scary prop in one direction, like a ghost or skeleton, out from a hidden spot and then retract it back by reversing the direction of the motor. The sudden forward and backward movement can add some unexpected surprises for visitors.
  • Haunted Swinging Object: Create a pendulum-like effect with a motor. A prop such as a hanging ghost or lantern can swing back and forth, first moving in one direction and then reversing.
  • Rising and Descending Spider: A spider can drop from above to scare visitors and then climb back up. The motor lowers the spider on a string and then winds it back up.

I’m sure you’re already thinking of the mechanisms you can build to create these and other movements so let’s take a look at this next example where we turn the motor a certain direction, pause it, and then reverse the direction.

First, I start by picking a direction for the motor and setting a speed of 255:

digitalWrite(IN1pin, HIGH);
digitalWrite(IN2pin, LOW);
analogWrite(ENApin, 255);

Next, we have to choose how long we want the motor to turn in this direction. Let’s keep it spinning for 3 seconds.

The Arduino executes each line of code faster than a blink of an eye until it gets to the bottom of the sketch and then loops back to the top of the void loop() section and starts again. This means that the motor will switch directions back and forth so quickly, we’ll barely be able to see the switch. We need to pause the code each time we want the motor to turn for longer than a fraction of a second.

There’s an easy function we can use for just this purpose:

delay(time in milliseconds);

There are 1000 milliseconds in each second so if we want to pause the code to allow our motor to spin at a PWM value of 255 that we specified on line 17 for three seconds, we would put the following code right after that line:

delay(3000);

This will pause the code execution process for three seconds right after your instructions to spin the motor at max speed (255) in the previous line of code.

After three seconds have passed, the Arduino will pick up where it left off and continue executing lines of code as usual.

If this code was for a jump scare effect or for a spider that drops and retracts back into the ceiling, we would want the prop to hang out in its current location for a bit so visitors could get a good look at it before it retreats back into the hidden starting position. This is also an opportunity to fire off additional effects like blinking LEDs and sound FX while the prop is prominently visible.

In order to hold the prop at its current position after appearing, whether it’s a spider at the end of its drop or a prop that pops out from a hidden spot, we need to stop the motor and pause the code again at this position for a bit.

First, let’s turn off all the output to the motor driver:

digitalWrite(IN1pin, LOW);
digitalWrite(IN2pin, LOW);

Then, let’s keep them turned off for five seconds.

delay(5000);

You can make this pause for how ever long you need to suit any other effects you want to set off during this time.

After the five seconds are done, it’s time to return the prop to its starting position by turning the motor in the opposite direction. Don’t forget to set a speed!

digitalWrite(IN1pin, LOW);
digitalWrite(IN2pin, HIGH);
analogWrite(ENApin, 175);

I’m having the prop move back into position a bit slower than it came in with a PWM value of 175 instead of 255. That being the case, I’ll give it more time to spin by adding an extra second to the delay() function:

delay(4000);

The speed and delay numbers would have to be fine-tuned until you get the movement you want but this code example gives you a good framework to tweak and build upon.

Once the motor has spun for four seconds and your prop is back at it’s starting point, let’s hold it there for two seconds before the program loops back to the beginning and the motor animation starts all over again.

digitalWrite(IN1pin, LOW);
digitalWrite(IN2pin, LOW);

delay(2000);

The Arduino will continue executing this entire motor sequence repeatedly until you power off your prop. In a future Arduino tutorial, we’ll add a motion sensor and write a program that triggers the motor animation sequence once, only whenever motion is detected.

Example Code 4: Increase and Decrease Speed Incrementally

Up until now, we’ve been choosing a direction and selecting a single speed that runs for a specified period of time. What if you want the motor to accelerate and/or slow down in specific increments of speed and time?

You could always use the analogWrite() function over and over again putting in values from 70 to 255 with a delay() for each, but that’s over one hundred lines of code to do something so simple!

Luckily, Arduino has a function that makes incrementing anything up or down easy with just a few lines of code.

for Loops

A for loop is a control structure that allows you to repeat a block of code a certain number of times. This loop is incredibly useful in many programming scenarios, especially when you need to perform a repetitive action or iterate over a range of values.

It has the following structure:

for (initialization; condition; increment/decrement) {
CODE YOU WANT EXECUTED SO LONG AS THE CONDITION IS TRUE
}

We’ll take a look at these parameters shortly, but first let’s create another variable to use in our for loops.

Looking at the top of this code example where you defined your Arduino pin connections, you’ll notice a new variable. I called it motorSpeed and didn’t assign it any value. In other words, I didn’t set it to any number.

We can’t hard code any PWM values for speed because it’s going to be constantly changing, so we need a container (variable) to store whatever the current speed is and send it to the ENApin.

The first two lines of code in the loop() section are familiar. I picked a direction:

digitalWrite(IN1pin, HIGH);
digitalWrite(IN2pin, LOW);

After that, you see our first for loop that we’re going to use to increase the speed by 1 PWM value at a time until it reaches max speed (255).

for (motorSpeed = 70; motorSpeed <= 255; motorSpeed ++) {

Let’s dissect the different parts within this line of code.

The first thing in the for loop parenthesis is our starting number or initial state. The slowest my motor will spin is at a PWM value of 70 so I set that as my starting point:

motorSpeed = 70;

Next, the Arduino will check the current motorSpeed against the condition you specified every time this for loop repeats itself to see if it’s true or false. My condition is that so long as the motorSpeed is less than or equal to 255, then proceed with the speed modification.

motorSpeed <= 255;

If the condition is true, it will modify the speed by incrementing the motorSpeed by 1:

motorSpeed++

The ++ is shorthand for:

motorSpeed = motorSpeed + 1

If you’re only adding 1 to whatever you’re incrementing, then most programmers use ++ rather than writing out the entire math equation.

You’ll notice that for loops have their own set of curly brackets. Anything you put inside those curly brackets will get executed over and over again so long as the condition you set up earlier is true. If it becomes false, then the Arduino will jump out of the curly brackets and proceed with the rest of your code.

Now that we’ve set up our parameters for our for loop, we next have to specify what happens inside the curly brackets. We’ve indicated how we want the speed to move but haven’t written anything to the ENApin yet.

That’s the first thing I do within the for loop’s curly brackets:

analogWrite(ENApin, motorSpeed);

This will tell the motor driver to spin the motor at whatever the PWM value for motorSpeed happens to be in your acceleration sequence.

Because the Arduino executes lines of code so fast, you’ll get to 255 before seeing any acceleration effect at all. It will look almost as if the motor starts spinning at full speed. To control the rate of acceleration, we’ll need to pause at each PWM value.

That’s why the very next line of code within the for loop’s curly brackets is a delay:

delay(100);

The larger the number (in milliseconds) that you use, the slower the acceleration effect will be. I wanted mine to be quick, so I chose to run the motor at each PWM value for 100 milliseconds.

Our first for loop is complete!

for (motorSpeed = 70; motorSpeed <= 255; motorSpeed++) {
analogWrite(ENApin, motorSpeed);
delay(100);
}

We’ll start the motorSpeed at 70, write it to the ENApin and hold it for 100 ms. Then the Arduino will go back to the beginning of the for loop, skip the initial value and look at the condition. Is a motorSpeed of 70 less than 255? Yes, so modify the motorSpeed by adding 1 to it. The new motorSpeed is now 71.

With this new value, it will then execute what’s inside the curly brackets. So the new motorSpeed of 71 gets written to the ENApin for 100 ms. This process continues until you reach a motorSpeed of 255. When it adds 1 to the motorSpeed, it becomes 256 and 256 is not less than or equal to 255 so the Arduino will jump out of the entire for loop.

At this point, your motor is spinning at a PWM value of 255 so let’s hold this max motorSpeed for 1 second (1000ms):

delay(1000);

After spinning at 255 for 1 second, let’s write another for loop to decelerate the motorSpeed back down in increments of 1 PWM value. This should look pretty familiar now:

for (motorSpeed = 255; motorSpeed >= 70; motorSpeed--) {
analogWrite(ENApin, motorSpeed);
delay(100);
}

Since the motor is spinning at a PWM value of 255, that’s what I use as my initial state for the motorSpeed. Then for the condition, as long as the motorSpeed is greater than or equal to 70, then proceed with decreasing the motorSpeed.

motorSpeed--

As you may have guessed, the above code is shorthand for subtracting 1 from the current motorSpeed, or:

motorSpeed = motorSpeed - 1

The Arduino will keep executing the code within the curly brackets of this for loop until the condition is no longer true, writing each motorSpeed for 100 ms. Eventually, the motorSpeed will reach 70 and once you subtract 1 from that, you’ll have 69. Since 69 is no longer greater than or equal to 70, the Arduino will jump out of this for loop.

Since the motor is now spinning at a PWM value of 70, I’d like to keep it spinning at that motorSpeed for another second:

delay(1000);

Upload the sketch to your Arduino Uno and watch your 12V motor start to accelerate, hold the max speed for 1 second and then begin to decelerate before holding the minimum speed for a second. This sequence will repeat over and over again.

Try Different Motor Speed Increments

The math equations you use to increment or decrement the motor speed don’t have to be complicated. For instance, try swapping motorSpeed++ for motorSpeed = motorSpeed + 10. You’ll notice that the acceleration happens much more quickly because you’re adding 10 to the PWM value each time rather than just incrementing by 1.

You’ve come a long way from not knowing much about Arduino or how to code! Now you’re ready to write Arduino code for your custom motor animation sequences by picking direction of rotation, setting speeds and timing out how long each part of your animation should last. You have full control over your prop’s movements and can even orchestrate a timed storyline with precise actions.

But I’m not ready to quit just yet, and I hope you’re not either!

Example Code 5: Change Speed Randomly

While precisely timed movements can enhance the realism of a prominently featured prop, robot or animatronic, it may be overkill for those that are used as background visuals or for supporting roles. Adding a bit of randomness to popular motorized props like zombie ground breakers, coffin door openers and tombstone peepers can add interest to otherwise predictable movements.

Let’s start by randomizing the motor speed.

The first thing I do is specify a direction of rotation:

digitalWrite(IN1pin, HIGH);
digitalWrite(IN2pin, LOW);

Now, let’s tackle how to write a random speed to the ENApin. Normally we’d write a speed like this:

analogWrite(pin, PWM value);

But rather than hard-coding a PWM value, we want a random number to pop in there like:

analogWrite(pin, random PWM value);

Luckily, Arduino has another function to save the day! It’s called the random() function and looks like this:

random(low value, high value + 1);

The random() function will pick a number between the low value and high value every time the line of code is executed. The slowest my 12V wiper motor will go is a PWM value of 70 so I’ll set that as my low value. For the high value, I’ll use 256.

Why 256? The random() function will randomly pick a number from the low value up to but not including the high value so always remember to add 1 to your high value. Mine would look like this:

random(70, 256);

Now, the trick is to nest this function inside our analogWrite() function where we would normally put in a PWM value:

analogWrite(ENApin, random(70, 256));

Note the double closing parenthesis )) towards the end. Double check that you close every open parenthesis on that line. A common error you’ll get is if you forget one of the closing parenthesis!

Finally, how long do we want each random speed to last? I picked 500 ms or half a second:

delay(500);

This means that the Arduino will randomly pick a new speed from 70 up to (but not including) 256 every 500 ms.

Example Code 6: Change Speed & Direction Randomly

Let’s add a bit more unpredictability to our prop’s motor movements by randomizing both motor speed and direction of rotation.

As you may have guessed by now, we need to nest a random() function within the digitalWrite() we’ve been using where you’d normally choose HIGH or LOW.

But wait a minute! The digitalWrite() function only takes HIGH or LOW but we need to pick actual numbers for the random() function to work. Well, it turns out that when you look at the source code of Arduino, HIGH is defined as 1 and LOW is defined as 0. We can use these numerical values instead so our code to randomize a motor’s direction of rotation would look like:

digitalWrite(IN1pin, random(0,2));
digitalWrite(IN2pin, random(0,2));

Remember to always add 1 to the high value. That’s why you see a 2. The random() function will randomly select either a 0 or a 1 to insert in the place of LOW or HIGH to write to the IN1 and IN2 pins.

Sometimes the motor will turn clockwise, and other times it will turn counter-clockwise. But because it can also generate a 0 or a 1 for both direction pins, either of these instances will cause the motor to stop. So you’ll actually have three motor rotation options chosen at random.

The rest of the code should look familiar. We ask the Arduino to pick a random PWM value from 70 to 255.

analogWrite(ENApin, random(0, 256));

Finally, we tell the Arduino to run our random direction of rotation and motor speed for 500 ms before looping back to the beginning and choosing another set of random numbers.

delay(500);

Play around with these numbers to see what kind of different motor movements you can generate.

Example Code 7: Change Speed, Direction and Timing Randomly

We’ve randomized the motor speed and picked random directions but there’s still one more element to randomize for the ultimate in unpredictability! That would be the timing in the delay() function.

As expected, I nested a random() function inside the delay() function where you’d normally set a time in milliseconds:

delay(random(250, 3001));

Each time the Arduino loops through our code it will pick a direction at random, a speed from 70 to 255 and hold all those selections for a random period of time between 250 ms to 3 seconds.

From Wiring to Coding: Moving Forward with Your Arduino Motor-Controlled Projects

Controlling a motor with an Arduino and a motor driver module opens a door to endless possibilities with your robotics, animatronics and custom-built prop projects. Now that you’ve wired up one motor driver module, you’ll find the other board-based ones just as easy to wire to an Arduino and use it to control just about any motor.

Use these Arduino motor control code examples as a foundation for programming more complex motor movements to make your props truly unique. In the future, we’ll explore other components we can add to mix like motion sensors that trigger specific motor animation sequences to make your props more interactive and able to respond to the environment around it. As you continue on your journey of building and programming, let your imagination lead the way, and watch your creations come to life with every line of code and wire you connect.