Web Hosting

This post may contain affiliate links. See the affiliate disclosure for more information.

If you’ve ever tried to build a mobile robot, then you’ll need to learn how to program motor controllers. In our Beginner Bots tutorials, we use the L298N motor controller with the Arduino Uno to drive four motors. You can pick up a Smart Robot Car and follow along with this article if you’d like!

For this tutorial, I’m going to show you how to translate motor controller specifications into Arduino code.

First, we will take a look at the L298N Motor Controller Specifications. Typically the manufacturer will include a truth table outlining key functionality. I’ve moved a copy of the L298N truth table below, for your reference.

L298N Motor Controller Truth Table

Next, we will create global variables for each of the motor pins. There are three pins per motor, so we will map each pin to a global variable. In the setup() method, we’ll declare each pin as an OUTPUT using the built-in pinMode(...) method.

Arduino L298N motor code

Now, we’ll use the truth table to map out motor functionality for the robot. We want to create methods for forward, backward, left, right, and stop.

Here’s what the forward(...) method looks like.

We can use digitalWrite(...) to set the pin to a 1 or 0 (HIGH or LOW), respectively. To control the speed, we’ll use the analogWrite(...) command on the enable pin for each motor. Use a value of 0-255 because digital pins support 8-bit PWM control.

Also, the stop() method will set the Enable pin to 1 and Input 1 and 2 to 0. Then, you can repeat the translations for left, right, and backward moves using the remaining rows in the truth table.

When you’re finished, call the methods in loop() so that they execute on the robot. Be sure to test out your code on the floor and make modifications to the speed and/or direction, as necessary.

If you have any questions about how to program your robot using a motor controller, be sure to comment below. You can also follow Learn Robotics on Facebook and Instagram for insider tips, robotics news, and updates!

Join our Newsletter, and Gain Robotics Skills FAST!


Become a better programmer. Build Electronics. Create Robots. FREE Tips for LR Subscribers!

Success! You're in! Check your inbox for an awesome subscriber-only message! ;)

global robotics competition online

Get Notified of the Next Competition


Be the first to know when we launch our next online robotics competition. Plus gain FREE robotics tips to your inbox.

You have Successfully Subscribed!

liz miller learn robotics


Gain Access to FREE robotics projects.

You have Successfully Subscribed!

Pin It on Pinterest

Is this content Share-Worthy?

Tell a Friend about it!