Building an Arduino compatible robot from scratch
This tutorial will explain the basics of hobby robot design and covers many subjects. I have includes numerous links to explain various subjects in greater detail. I have attached several datasheets and other files to help. Topics covered in this tutorial are:
1. What motors will you need? - A short explanation of 3 commonly used motors in hobby robots.
- DC brushed motors
- Stepper motors
- RC hobby servos
2. Motor drivers - A brief description of a few commonly available types.
- Breakout boards and IC's
3. What sensors will you need? - A short explanation of commonly used sensors in hobby robots.
- Analog Vs. Digital
- Light sensors
- Gyro sensors
- Pressure sensor
4. Choosing a controller - A description of several readily available controllers and their unique features.
- Common Arduino boards
- Compatible alternatives
5. Types of batteries - not all batteries are suitable for all robots.
- Alkaline batteries
- Super capacitors
- Battery size
6. Regulating power - Good regulation will save a lot of frustration!
7. Planning your wiring - which pins can do what?
- What is PWM?
- External Interrupts
- Series communications
- I²C communications
8. Designing the chassis - some mechanical considerations.
- Power to weight ratio
- Center of gravity
- Torque calculations
- Acceleration and torque
9. Programming tips and tricks.
- Organizing your code
- Commenting your code
- Including a wiring diagram in your code
- Local Vs. Global variables
- Naming variables
- Avoiding delays
- Setting servo limits
- Using timeout options
- Internal pullup resistors
- Beyond D13 (digital pins D14-D21)
- Port manipulation
- Converting data to bytes for storage or transmission
If you have little or no experience with making robots then even a simple robot can be seem like an impossible task. With a little bit of knowledge and planning your robotic project can be designed, built and programmed much easier. A lot of the electronics needed has been packed into small PCBs so that you really only need to know some very basic electrical knowledge about voltage and current.
There are many controllers available including Picaxe, Propeller, Raspberry Pi, Beagle Bone and FEZ to name a few. This tutorial focuses on Arduino because I personally believe this is the best system for beginners. however a lot of information in this tutorial applies to any small hobby robot no matter what processor is used.
Frits, the founder of LMR has a great tutorial for a "Start Here" robot using picaxe. You can find this tutorial by clicking on "Start Here" at the top of the page.
If you have never programmed before then DON'T PANIC! You do not need to learn an entire language overnight. When you build a robot you will find it is really a group of small, simple systems that all work together. Each of those small systems needs to have some code written and tested (debugged). So really you only need to learn a small bit of the language every time you complete part of the robot.
When I was first learning the Arduino I found the attached file "Arduino Notebook" to be a fantastic help. In just a few pages it explained the basics well enough that I could then understand and use the online Reference Guide much easier.
The simplified C language used by the Arduino IDE is very easy to learn but as your skills improve you can add C / C++ commands and even machine code into your sketch. The open source nature of Arduino means that there are lots of librariesbeing written as new hardware becomes available.
A library is a group of related functions that make it easier to perform a certain task or use a certain piece of hardware. For example the Micro Magician mentioned in this tutorial has a library written for it that simplifies the use of it's built in hardware. One function included in the library make it easy for you to use a TV remote to control your robot.
Free books! As well as the online manuals for the Arduino language that is constantly improving and growing there are now also a number of books that you can download for free. Below are links to just a few.
- Beginning Arduino Programming
- Getting Started with Arduino
- Make Arduino Bots and Gadgets
- Arduino and LEGO Projects
Decide what you want your robot to do but try to keep the idea as simple as possible. A good beginner robot can move about on wheels and avoid crashing into things. Once you have mastered this then you can start experimenting with arms, legs etc. Do not attempt to build a full humanoid robot that can wash the dishes as your first robot. You will just get frustrated.
I suggest that absolute beginers experiment with various parts of a robot before trying to build an entire robot on your first attempt. Once you can control a Servo, a DC motor and use simple sensors like an ultrasonic range finder then you will be ready to combine them into a complete robot. Try using the output of a range finder to control a servo so that you can control the servo by moving your hand in front of the range finder.
Building material is not really important, a robot can be built with anything. If you need some inspiration then check out these robots.
- Rubik's cube solver made from cardboard by Dipanjan: http://letsmakerobots.com/node/35316
- A quadruped made from bamboo chopsticks by Lumi: http://letsmakerobots.com/robot/project/chopstick-junior-10
- A Tic-Tac-Toe robot made from K'nex by me: http://letsmakerobots.com/node/35933
This tutorial will guide you through all the steps required to build your first robot and explain about the different motors, sensors, controllers and batteries that you need to consider when planning your robot.
1. What motors will you will need?
Almost all robots move in some way so first we will look at the 3 most commonly used motor types. Different types of motors have different advantages and disadvantages. With the exception of servos, a control circuit is needed to interface your micro controller to a motor.
Servos have a control circuit built into them which is why they are generally more expensive than the other motor types. Below is a brief explanation of each type of motor and how it is controlled.
DC brushed motors
The type of motor most commonly used to drive the wheels for hobby robots is a DC brushed motor. These motors only have 2 wires and use an internal switch mechanism (commutator and brushes) to switch power to the windings. To control the direction we change the polarity of the voltage across the motor (swap the positive and the negative).
To control the speed of the motor we adjust how much power we give the motor. In most robots this is done digitally by pusing the power on and then off very quickly. This is called Pulse Width Modulation (PWM). For some analog robots such asBEAM robots speed is controlled by limiting the voltage / current to the motor with a variable resistor or a transistor that is only partially "ON". The analog method is less efficient but still suitable for small motors.
DC brushed motors usually spin too quickly and do not have enough torque (strength) for robotic applications so they usually require a gearbox. When you hear people talk about "geared motors" they are refering to a motor that comes with a gearbox mounted to it.
When you are buying a DC motor you need to look at it's specifications. The most important ones are:
- Rated voltage - this will help you determine what voltage is required from your power source.
- Peak (stall) current - we use it to determine what motor controller and power source your robot will need.
- Nominal current - we use this to help determine what size batteries we will need.
These motors cannot be driven directly from the logic circuitry. They need a motor driver circuit called a "H" bridge to control their speed and direction. The Arduino then sends control signals to the motor driver to control the motor.
ADVANTAGE: Cheap and easy to find in a wide range of voltages and sizes (bigger = more power).
DISADVANTAGES: Needs gear box, "H" bridge circuit to control it and possibly encoders / current sensors.
CONTROL: Requires 1 PWM output to control speed and 1 digital output for controlling direction.
A stepper motor can rotate in small increments and is normally used when precise positioning is required. To do this the motor does not use a commutator and brushes like a DC brushed motor. Instead an external circuit, controlled by your software must control power to the motor windings. As a result these motors will have at least 4 wires depending on how they have been wound.
A small bipolar motor can be driven by a dual "H" bridge motor controller IC such as an SN754410, L293D or L298N. A small unipolar motor can be driven using a dual "H" bridge or 4 individual darlinton transistors such as the BD681 (includesflyback diode) or an IC such as the ULN2804 which contains 8 darlington transistors and flyback diodes.
Some control circuits have additional control circuitry so that only 2 control pins are required. These controllers only need 1 pin for direction and another to pulse when the motor must step to it's next position.
A limit switch is often used with a stepper motor so than when the robot is first turned on it can determine a "home position" for the motor by driving it in one direction until the switch is hit. Once the home position is known, the software will know the position of the motor by the number of steps sent to the motor. The disadvantage of this system is that if the motor / mechanism is jammed then the computer will not know what position the motor is in until the home switch is hit again.
ADVANTAGES: Can move in precise increments. Available in many sizes.
DISADVANTAGES: Requires limit switch to know initial position. Requires more complex motor control circuit.
CONTROL: Depending on motor and control circuit may need as many as 4 IO pins plus digital input for limit switch.
RC hobby servos
The servos used for radio controlled models are perfect for hobby robotics. The servo contains a small DC brushed motor and gearbox. The output shaft of the servo is connected to a variable resistor called a potentiometer (pot) which tells a small control circuit what position the servo output shaft is in. The control circuit then drives the motor forward or backward to go to the desired position.
Most servos can only rotate from 0° to 120° although it is becoming more common to get servos that can rotate a full 180°. You can also get a continuous rotation servo. A continuous rotation servo can rotate continuously in either direction. The control signal determines speed and direction instead of position.
Servos have 3 wires, a signal wire which is usually white, yellow or orange. A red wire in the middle which is positive (+V) and a black or brown wire which is your ground (-V).
To control a servo we generate a positive pulse on the signal wire which is repeated typically every 20mS. The position of the servo is determined by the width of the pulse. Normally the center position is acheived with a pulse width of 1.5mS. Fortunately most micro controllers have a servo library that does this for you in the software.
Analog VS Digital - originally all hobby servos used an analog circuit to control the motor in the servo. Now if you are willing to pay more money you can buy a digital servo. A digital servo has a micro controller built into it that is programmed to control the motor. The advantage is that the micro controller can drive the motor harder and use software techniques such as PID to prevent the motor overshooting it's position.
In most cases I recommend using the cheaper analog servos. Unless you need the best possible speed and power then digital servos will just cost you more money.
ADVANTAGES: Easy to use, control circuit built in.
DISADVANTAGES: More expensive.
CONTROL: 1 digital IO pin.
For a typical beginners robot that can move about and avoid crashing into things you will need 2 geared motors or 2 continuous rotation servos to move about and either a stepper motor with a limit switch or a servo to turn the head left and right.
If you are on a tight budget then pull apart some old office equipment such as printers, fax machines, flat bed scanners etc. You can often find DC brushed motors and stepper motors in these devices.
2. Motor Drivers
As mentioned at the start of the motor section, if you are using DC brushed motors or stepper motors you will need a suitable motor controller. When choosing a motor controller there are several factors you need to consider.
- Voltage rating - The motor driver should have a voltage rating equal to or higher than the motor voltage rating.
- Current rating - The motor driver should be able to handle the "stall current" of your motors.
- Current sensing - Does the controller allow your program to monitor the current drawn by the motors?
- FET or BJT transistor output - FET motor controllers deliver more power to your motors.
- Logic voltage - Can the motor controller accept control signals from your processor.
- Control method - Some motor controllers will use I2C or Serial communications.
Shields below is a photo of the Arduino Motor Shield, this plugs directly into a Uno or clone such as the SparkFun RedBoard. The advantage of a shield is that no wiring is required. The shield simply plugs in on top of the Arduino controller.
The disadvantages are that they are usually expensive and you cannot select which pins are used. In the case of this shield, you cannot stack more shields to drive more motors. This shield can drive 2 DC brushed motors or 1 stepper motor.
The Adafruit Motor / Stepper / Servo shield is a better option if you can solder the header pins. It is I2C controlled with a selectable address. This allows you to stack multiple shields without conflicting with other shields. This shield can drive 2 stepper motors or 4 DC brushed motors with currents up to 1.2A continuous, 3A peak. The disadvantage is that I2C is a little bit harder for a beginner to learn (but well worth the trouble).
The ComMotion Shield from DAGU is another I2C controlled shield that can control up to 4 DC motors. Each FET "H" bridge is rated for 2.5A continuous and 4A peak. This shield offers the advantage of built in encoder feedback. The two onboard ATmega328P processors monitor the encoders for you and automatically adjust the motor speed making it easy to get your robot moving in a straight line.
Breakout boards and IC's
Some Arduino compatible controllers have a motor driver built in (see the controller section) but regardless of what controller you use, dedicated motor controllers (non - shield) can be easily connected with a few jumper wires and offer options such as higher current ratings for bigger motors. The Rover 5, 4ch motor controller shown below can drive up to 4 DC motors or 2 Stepper motors at up to 4A per motor and includes some encoder mixing circuitry.
Here is a short list of motor drivers from various suppliers.
Dawn Robotics: http://www.dawnrobotics.co.uk/search.php?search_query=motor+drivers&x=0&y=0
3. What sensors will you need?
There are a wide range of sensors available that can detect everything from light and sound to the earths magnetic field. Some sensors are very cheap and simple but may require some additional circuitry. Some sensors are expensive and complex. You will need to be able to read a datasheet to understand how to use them.
Do not be put off by the appearance of a datasheet. Although they usually contain a flood of information, quite often you only need to have a quick look to find 1 or 2 relevant pieces of information. As you gain experience you will appreciate how useful datasheets can be.
Analog VS Digital - Sensors can be either analog or digital. An analog sensor will generate an output voltage proportional to what it senses and will need to be connected to an analog input on your processor. The processor uses it's analog input to measure the voltage and give you a number between 0 and 1023 (Most Arduino boards have 10 bit analog / digital converters).
Digital sensors have one or more outputs that are either high or low. These sensors can connect to the digital inputs on your processor. Some digital sensors transmit complex data using serial or I2C. Other sensors might be a simple switch.
Below I've listed a few common types of sensors used in hobby robots.
For a beginners robot, infrared or ultrasonic range finders are essential. These sensors measure distance and can be digital or analog. They are relatively low cost and easy to use with no additional circuitry required. I suggest you experiment with both types as each has advantages and disadvantages.
The ultrasonic range finder on the left uses high frequency sound and is very good at detecting hard objects at a distance from a few centimeters to more than 3 meters depending on the size and shape of the object being detected. This sensor will work indoors or outdoors without any problem. One disadvantage is that soft objects such as curtains may not reflect the sound very well.
The HC-SR04 shown in the photo is a digital sensor (see the attached datasheet). A digital pulse from the processor to the "trig" pin causes the sensor to emit a short burst of ultrasound. Your program then measures the time until a digital pulse is received on the "echo" pin.
The IR (infrared) range finder on the right is available in several different types depending on the distances you want to detect. These sensors do not work outdoors during the day because the sunlight blinds them however they can detect soft objects that ultrasonic sensors cannot.
The Sharp GP2D12 shown in the photo is an analog sensor (see the attached datasheet) that can measure distance from 10cm to 80cm. The output voltage will vary depending on the distance of the object. The datasheet also shows a GP2D15 that has a digital output which changes when a preset distance is detected.
Ultrasonic and IR rangefinders work best when facing directly towards the object you want to detect. For this reason most hobby robots will scan the sensor left and right using a servo or in some cases a stepper motor. This helps make sure that all objects are detected.
LDR (Light Dependent Resistor) - these are a low cost sensor that detects light. These are analog sensors that have a very high resistance in the dark and a relatively low resistance in bright light. They are very easy to use with the Arduino as they only need one additional resistor connected in series to form a voltage divider.
Below are two almost indentical circuits. The circuit on the left will cause the output voltage to increase as more light shines on the LDR. The circuit on the right will cause the output voltage to decrease as more light shines on the LDR.
With both circuits I have shown a 10K pot which can be used to adjust the sensitivity of the circuit. Depending on the LDR used and typical opperating conditions this pot may need to be increased to 100K.
Photo transistor - a photo transistor is a transistor that is sensitive to light (usually infrared). In hobby robotics these transistors are often combined with an IR LED to form a simple object detection sensor. The diagram below shows a typical application as used in the Mr. General robot kit. The output can be connected directly to an analog input or digital input of your Arduino as long as you use the same supply voltage (Vcc) that the processor uses (5V for most controllers, 3.3V for Micro Magician, Lilly Pad and a few others).
I have written a short tutorial on making an IR compound eye here: http://letsmakerobots.com/content/cheap-home-made-ir-compound-eye
IR Receiver - an IR receiver is basically a photo diode combined with an amplifier, filter and detection circuitry designed specifically for detecting modulated IR signals from an IR remote control like those used for TV's and Stereos. Unlike a phototransistor they have a digital output that goes low when they detect IR light modulated at a certain frequency (typically 36kHz to 40kHz).
There is a great tutorial on IR protocols here: http://www.sbprojects.com/knowledge/ir/index.php
Sound sensor - essentially a microphone is the only sound sensor you are likely to use. There are some breakout PCB's available from various online stores that are pretty cheap. They include an amplifier and other required electronics. Key ring voice recorders are an ideal way to record 1 or more sounds and then play them back.
Accelerometer - an accelerometer detects acceleration. In hobby robotics it is often used to detect which way is "up" as the force of gravity is mass * acceleration. The range of the sensor is often measured in G's with one G equal to the acceleration generated by the earth which is typically 9.8m/s/s.
Many accelerometers can measure acceleration on 3 axes, front to back, left to right and top to bottom. This can be used to determine if the robot has fallen over or is about to tip over.
Gyro sensors are used to detect rotation rather than acceleration. These sensors are essential for robots that need to maintain their ballance and are used in conjunction with accelerometers for flying robots such as quadcopters.
When deciding which one to use you need to pay careful attention to the datasheets, especially if the sensor has an I²C or SPI interface because you will need to understand how to configure the sensor using it's internal registers.
First you need to decide how many axes you need. If you are making a simple ballancing robot on two wheels then you only need a single axis or maybe two axis if the robot can lean left and right. For more complex designs such as quadcopters then you will need a 3-axis sensor.
Next you need to consider the range / sensitivity. This is usually given in degrees / second and is the maximum rotation speed the sensor can monitor. For a simple balancing robot on 2 wheels, a sensor with lower range will usually have better sensitivity. For something like a quadcopter with fast maneuverability then a bigger range is more important than sensitivity. Sensitivity will depend on resolution as well as range.
You will also need to consider the required supply voltage (3.3V or 5V) and the type of interface. Many gyros have an analog output that can be connected directly to the processors analog inputs. Some sensors will have an ISP or I²C interface.
These days there is not such a big difference in price between single, dual and tri-axis sensors. Some of them have a selectable range. If you plan to do a lot of experimenting then look for a 3-axis gyro with a selectable range.
Some typical gyro sensors can be found here:
Pressure sensors - the most commonly available pressure sensor is an FSR (Force Sensing Resistor). These are sensors that change resistance when pressure is applied. They come in various shapes and sizes with different sensitivities.
If your on a budget you can make your own using conductive foam. This is the black, anti-static foam that microchips are packed in. I have written a tutorial about making your own here: http://letsmakerobots.com/content/simple-analog-pressure-sensor
4. Choosing a controller
There is a huge selection of official Arduino boards and their clones available all around the world. In most cases an Arduino UNO or a clone such as the SparkFun RedBoard will be all you need. These boards use the ATmega328 and have 32K of FLASH memory to store your program. The standard boards have 14 digital IO pins (D0 - D13) and 6 analog inputs (A0 - A5). The SMD version of the ATmega328 actually has 8 analog inputs so on some boards you will also find an A6 and A7.
Note: The larger USB socket on the UNO can short out some shields. This is a common design flaw in official Arduino boards and their clones. I suggest trying to find a board that uses the Mini USB socket such as the SparkFun RedBoard.
For those beginners with some electronics experience under their belt then an Arduino Nano is a good alternative. The Nano has all the basic features of the full sized boards except for the DC jack and it fits perfectly on a breadboard. This makes it ideal for experimenting with electronic circuits made from discrete components such as the LDR sensor circuit shown above.
Although probably not the best board for absolute beginners, If you are planning on building a robot with a lot of servos, motors or sensors then you may need more IO pins and memory. In that case an Arduino Mega2560 should do the job. The Mega has 256K of memory and 70 IO pins that include 13 PWM pins, 16 analog inputs and 4 serial ports. All the boards have an I2C interface.
There are some other Arduino boards such as the Leonardo and Due but for the beginner I do not suggest using them as their internal hardware is different from the standard Arduinos and will not be discussed in this tutorial.
As you will probably want to control a couple of motors and servos you will need to consider the additional circuits required to control them. If you buy an Arduino board then there are a number of "Shields" available. The Shields are circuit boards that plug into your Arduino board to give you extra hardware such as motor drivers, LCD displays etc.
If you are planning on using more than one shield then you will need to check what pins each shield uses. You may find that some shields want to use the same pins in which case they cannot both be used at the same time.
While the Arduino system offers a huge number of boards and shields they can be expensive and the standard arduino footprint may be too big if you want to make a small robot. I've designed some small boards especially for beginner robotics that are software compatible with the Arduino but have built in motor drivers and servo headers that can be powered directly from the battery.
Mini Driver - the DAGU mini driver is a small (60mm x 30mm), very low cost board (about $16 USD) that has reverse polarity protection, a dual "H" bridge and servo headers built in.
Micro Magician V2 - the Micro Magician is also a very small board (60mm x 30mm) but it has more hardware packed into it and is designed to work with lower voltages. This allows you to creat robots that can work from a single lithium cell. A library has been written for the Micro Magician that makes it easy for beginners to use the additional hardware features.
The DAGU Spider controller is essentially an Arduino Mega 2560 with a 3A switchmode regulator. This provides enough power to run a number of small servos directly from the controller. The Spider has the IO pins broken out into 3 pin male servo headers as well as the female headers. The pin spacing is not compatible with Arduino shields but it is compatible with prototype PCB. This allows you to make your own shields cheaply from discrete components.
5. Types of batteries - not all batteries are suitable for all robots
As most robots move about they need batteries but choosing the wrong battery can cause frustrating problems when testing and debugging your code because your controller or other components may not work reliably if the power "Browns out". A great source of information on all the different battery types and how to recharge them is the Battery University.
Alkaline batteries unless your robot is extremely low powered (no motors) then do not use alkaline batteries. Alkaline batteries are great for TV remotes and torches (flashlights) which may site for long periods of time without being used. However Alkaline batteries (even the really expensive ones) are virtually useless for robots. Their internal resistance is too high. This causes their voltage to drop drastically under heavy load which can be a common occurance in a robot. Another problem with alkaline batteries is that their storage capacity drops dramatically under heavy load so they don't last long before you need to buy new ones.
The most obvious result is that the processor will reset because the voltage dropped. Less common but more frustrating side affects include corrupting the bootloader (or your code) within the FLASH memory.
Li-ion batteries are commonly used in laptops and mobile phones. These batteries are great if you need light weight and good capacity. They can deliver the high currents needed for robots although some battery packs (particularly for mobile phones) will have a current limiting circuit built in.
You need to use the correct charger to charge these batteries otherwise they can catch fire. The output voltage will drop as the battery discharges which can cause problems such as poor efficiency and make it harder to maintain a set motor speed. The advantage is that a voltage monitoring circuit can be used to warn when the battery is getting flat.
NiMh batteries are the battery I prefer for small hobby robots. They can deliver far more current than the alkaline batteries and maintain a relatively steady voltage output for most of the discharge cycle. NiMh batteries have been on the market for a long time so the batteries and chargers are cheap and easy to find. They are safer than the Lithium batteries however they will self discharge (go flat) much quicker when not used.
SLA (Sealed Lead Acid) batteries are very heavy and not normally used for small hobby robots. In larger robots these batteries are a much cheaper alternative and offer good reliability when properly charged.
Super capacitors are starting to become more readily available and in larger capacities. They are still relatively expensive but are ideal for very small robots that must recharge very quickly and only need to run for a short period of time.
Battery size is measured in mAh for small batteries and Ah for large batteries. If for example you have a AA NiMh battery with 2700mAh on the side then in theory it can deliver 270mA for 10 hours or 2.7A for 1 hour.
In practice, if you draw 2.7A continuously then the battery will probably go flat a lot quicker depending on the type and quality of the battery. Most battery types only deliver their full capacity at low currents (less than 1C) Higher currents cause higher temperatures and other inefficiencies to occur within the battery.
To simplify things I suggest you make the assumption that the battery has about 80% of the rated capacity. This allows for many factors and should ensure that your robot runs for at least the desired period of time. Worse case scenario it might run for longer.
To choose the correct battery size you need some idea of how much current your robot will draw and how long you want it to run for before it needs recharging. If time is not an important factor then just use batteries that are readily available. For most hobby robots, 2700mAh AA NiMh batteries or a 2500mAh Li-Ion battery will be fine. If your robot is very small and does not use a lot of motors then 900mAh AAA batteries can be used.
If time is important then battery size can be difficult to determine since your robot will not draw a steady current. When the robot is still or moving slowly then the current draw will be very low. When the robot accelerates or moves at high speed then the current will be much higher. Under heavy load, especially if motors stall then the current can be several Amps.
To calculate your power requirements, you need to know how much current your controller and sensors need. Most Arduino controllers need less than 150mA however more powerful processors such as the Raspberry Pi might need as much as 2 Amps. You should assume this current to be constant.
Most sensors do not draw much current, if they do it is usually only for short bursts. LEDs, particularly High current LEDs can draw 20mA or more each. An Arduino Uno with an IR range finder should not draw more than 200mA peak.
Now add the nominal current draw of your motors under load. If you do not have this information then it is best if you can connect your motor to a battery of aproximately the correct voltage and use a multimeter to measure the current when you load the motor with your fingers until the pitch of the motor drops noticeably but the motor can still spin quickly. If you have no idea then allow 400mA for small motors and servos such as the servo to pan your sensor left and right. Allow 800mA for bigger m