Arduino Masterclass Part 4: Build a mini robot

Arduino Masterclass Part 4: Build a mini robot

 

Meet Rolly APC's first autonomous microbot
Meet Rolly our first autonomous microbot based on an Arduino Uno microcontroller and our own ‘special sauce’ software.

The Arduino Uno might be an aging 8-bit microcontroller board but when it comes to interacting with the outside world it’s much easier to use than an Intel Core or AMD FX CPU. The Uno’s cache of analogue and digital inputs and outputs are perfect for many real-world tasks and so far in this series that’s what we’ve been doing: lighting LEDs using temperature/humidity sensors and even creating a simple composite TV output.

However this time we’re ramping things up pulling in parts from eBay Bunnings Jaycar and the local $2 shop to create a microcontroller-powered robot (microbot) called Rolly. This isn’t a remote-controlled bot – Rolly thinks for himself avoiding obstacles and determining his own direction.

We’ll be looking at how to build Rolly in a two-part project introducing lots of new components and features looking at some new theory and as we’ve done in this series showing you how to put it all into practice.

 

Getting the parts

The first thing you’ll want to do is get the parts together. The goal in designing Rolly was to make a robot that was as cheap as possible to build and run yet still capable of showing personality. Depending on how many of the parts you have already the cost can come down to as little as $40 so it won’t break the bank. See the table below for the detailed parts list. Just be prepared – you may need to wait a few weeks for those eBay parts to arrive. We haven’t included other items such as a soldering iron (yes there’s some soldering required) needle-nose pliers miniature flat-blade screwdriver and the like so we’ll leave that for you to sort out (check out our Tech Corner on ‘Soldering 101′ towards the end of this article).

Microbot Parts List

Part Cost per unit Quantity Where you can get this:
Arduino Uno R3 US$13.20 1 eBay
L293D Motor Drive Shield US$5.16 1 eBay
HC-SR04 ultrasonic sensor US$1.91 1 eBay
TowerPro SG90 servo motor US$2.45 1 eBay
1:120 geared DC motor & wheel (pair) US$8.95 1 eBay (ask seller for 1:120 model)
4 x AA battery holder with switch $2.95 1 Jaycar
4 x 2000mAh AA-size NiMH batteries $15 1 Bunnings Jaycar or supermarket
900mL plastic food container $2.50 1 Local discount shop or supermarket
4 x male-to-female dupont wires US$2.88 1 eBay
30mm caster wheel $4 1 Bunnings (Ambassador brand comes as a pair)
15mm x 4mm machine screws $2 2 Bunnings (you need a minimum of two along with nuts and washers)
Scotch double-sided padded tape $6.50 1 Bunnings (10mm wide and about a metre in length should be enough)
16m hookup wire pack $4.95 1 Jaycar
0.1uF/50VW ceramic capacitors $0.32 1 Jaycar (comes as a pack of two – you’ll need both)
Approximate total cost $74.77  

You’ll also need the microbot.zip source code for the Arduino Uno board. You can grab that for free from our website at apcmag.com/arduino.htm and find ‘Project 4: Mini Robot’. The source code also contains the library files needed to run the external devices.

 

Block diagram

We’ll talk more about how Rolly does what he does in the next series but the block diagram will give you a good idea of what’s going on. The microbot combines a number of real-world devices that we’re controlling all at the same time. It starts with the Motor Drive Shield (‘shield’ is the Arduino name for expansion boards) to provide extra grunt to handle the two DC traction motors plus the ‘neck’ servo motor on which the ultrasonic sensor ‘eyes’ sit.

Rolly's block diagram
Rolly’s block diagram.

The ultrasonic sensor provides accurate distance information down to the nearest centimetre and it’s used to determine whether Rolly needs to stop and back up or simply veer away from the object blocking his path. Although it’s connected to the Motor Drive Shield data from the ultrasonic sensor feeds directly into the Arduino microcontroller board. Steering the microbot is as simple as controlling the spin direction of the DC traction motors – if the left motor drives forward and the right motor backwards the bot will turn right and vice versa. With both motors driving forward the bot will obviously move forward and vice versa. It’s all controlled via the source code. But that’s enough of the theory – let’s start building!

 

Step 1: The base

Yes we’re using the lid of the food container as the base for our microbot. If you’re sniggering stop it – you can build yours out of whatever you want. Just make sure it’s approximately 15 x 10cm and fairly stiff (don’t use takeaway containers). You may need to cut away a flange at the edge on either side of the lid to allow the shaft of the motor wheel to move freely. Carefully use a box knife and make sure you have all your fingers afterwards. Next drill two holes diagonally for the caster wheel at the opposite end of the base to your flange cuts. Use the caster wheel mount plate as a template mark the holes and drill them.

Tip: When drilling into plastic set your drill to the lowest speed start with a 2mm drill bit and work up to a 4mm bit. If you drill at high speed all at once you’ll rip the plastic to shreds.

APC Arduino Microbot project Step 1: The base
Yes that really is a food container lid as our base – it’s cheap and see-through.

 

Step 2: Solder the capacitors & wires

The 0.1uF capacitors have to be soldered across the motor connections and help reduce electrical noise in the circuit otherwise the Arduino gets a bit cranky. Provided you use ceramic or Mylar capacitors they have no polarity so just solder one leg to each motor connection tag and do so on both motors. Try to lay the capacitors flat against the yellow gearbox body to keep things neat.

You also need to solder onto the connection tags the wires that go to the Motor Drive Shield. Try attaching them to the capacitor leads if you’re not confident to get everything soldered at the motor connection points. These motors have a D-shaft and wheels that simply press onto the shaft. Use just enough pressure to get the wheel on. After that cut a small strip of double-sided padded tape peel back one layer and press it against the motor gearbox which will mate with the base.

Tip: The motor connection tabs are quite weak so don’t bend or force them. And take no more than five seconds to solder the capacitors or you might cause the motor connection to break.

APC Arduino Microbot project Step 2: Solder the capacitors & wires
The 0.1uF capacitors help reduce RF noise on the supply rail.

 

Step 3: Install the DC motors

Install the two DC motors to opposite sides of the base using the double-sided tape. Get the motors as close to the edge as possible to allow the wheel free movement.

3: Install the DC motors
Use double-sided padded tape to attach the motors to the base.

 

Step 4: Add the horn to the motor

The little SG90 servo motor gives our microbot a neck so it can spin the ultrasonic sensor on its axis. The servo motor itself should come with an accessory pack of attachments called horns. Use the two-sided arm and press it onto the servo motor shaft. You’ll probably need to use a bit of force to get it on the first time but try not to use too much.

Step 4: Add the horn to the motor
Use the two-sided horn on the servo motor.

 

Step 5: Solder the wires to the shield

The Motor Drive Shield provides the extra drive power to control the DC motors. It also provides connection for the servo motor and the ultrasonic sensor for which you’ll need four male-to-female DuPont wires. If you bought a bag of 40 moulded wires peel four of them off and carefully solder the male ends to the Motor Drive Shield. Solder one wire to the +5V rail one to the GND pin and one each to analogue pins A4 and A5 down in the bottom right-hand corner. Check the block diagram for pin assignments.

Step 5: Solder the wires to the shield
Solder four male-to-female DuPont wires to the Motor Drive Shield

 

Step 6: Add the shield to the Arduino

The Motor Drive Shield has a series of pin headers on the bottom of the board – these align with the headers on the top of the Arduino. Align the pins and press the shield onto the Arduino board.

Step 6: Add the shield to the Arduino
Align the pin headers and press the shield down into the Arduino Uno board.

 

Step 7: Install the Arduino & battery

Grab some more double-sided padded tape and add it to the bottom of the Arduino board and the battery box. Note that you want the bottom of the battery box stuck to the base so you can easily remove the top of the box and get at the batteries. Make sure you orient the battery box so the slide switch hangs over the back edge to make it easier to operate. Stick the battery box down first ensuring the switch overhangs at the back and align the Arduino/shield stack next to it. Depending on the size of the lip of your food container you may need two layers of padded tape to get the height right.

Step 7: Install the Arduino & battery
Make sure the power switch is overhanging the back.

 

Step 8: Install the sensor & motor

Next add some double-sided padded tape to the top of the ultrasonic sensor – use enough to wrap around the sides of the sensors for added stick. Make sure the four header pins are pointing up and press the sensor against the servo horn. Add some more tape to the bottom of the servo motor and install it at the front of the base near the caster wheel mounting holes. Connect the servo motor power cable to the ‘SERVO_2′ port at the top-left of the Motor Drive Shield. The orange wire should go to the ‘s’ header pin.

Step 8: Install the sensor & motor
Use more double-sided tape to attach the sensor to the servo motor horn.

 

Step 9: Connect the DuPont wires

Next connect the female ends of the DuPont wires to the ultrasonic sensor pins. The A5 wire should go to the ‘echo’ pin and A4 to the ‘trigger’ pin. I used a loosely wrapped rubber band to keep the wiring neat and allow enough play to move freely.

Tip: The HC-SR04 ultrasonic sensor is connected to the Arduino’s analogue inputs although we first program them into digital inputs in our source code.

Step 9: Connect the DuPont wires
Attach the DuPont wires to the sensor pin header (check the block diagram).

 

Step 10: Wire up the motors & battery

Connect the battery to the EXT_PWR screwblock but make absolutely sure you get the polarity right or you’ll blow up everything before you start. One of the screw terminals in that block should be labelled +M or +; the other GND. Whichever battery holder you choose the red wire goes to the +M screw terminal and the black wire to the GND terminal.

The DC motor wires connect to the M1 and M2 screwblocks. The left-side motor wires go to the M1 terminals; the right-side motor goes to the M2 block (you should be able to make this out looking at the silk screening on the top of the Motor Drive Shield.) Don’t worry too much about polarity at this stage – wait until you get to the test run stage and we’ll sort out any polarity issues then.

Step 10: Wire up the motors & battery
Add the DC motor wires to the motor drive shield M1 and M2 screwblocks.

 

Step 11: Pre-flight check

Before you install any batteries check recheck and triple-check your wiring now. The servo motor header the ultrasonic sensor and battery box connections must be correct. The DC motor wires are less important.

compile the microbot source code into the Arduino board
Use the Arduino IDE to compile the microbot source code into the Arduino board.

 

Step 12: Program the Arduino

Grab the ‘microbot.zip’ source code. Unzip it and copy the contents of the ‘libraries’ folder to the Arduino-1.0.2libraries folder on your PC. Copy the microbot folder to your sketchbook folder. Launch the Arduino IDE and you should be able to test-compile the source code. Plug in the USB cable to your Arduino board and in the IDE go to ‘Tools > Serial Port’ and check you’re using the correct COM port. Compile and upload the code to your Arduino board. When it’s completed you’re done. Not that there’s a problem with the Arduino USB driver on 64-bit Windows 8 systems. We suggest you use a Windows 7 or 32-bit Windows 8 system for now.

The sensor will need realigning once when you first power it up
The sensor will need realigning once when you first power it up.

 

Step 13: Align the ultrasonic sensor

When you’re positively sure you have the major wiring correct install four freshly charged 2000mAh or better NiMH AA batteries into the battery box (leave the cover off for the time being) and flick the switch count two seconds and turn it off. The servo motor should move briefly the LED should light up on the Motor Drive Shield but the ultrasonic sensor will probably no longer point directly ahead. Don’t worry – this is completely normal. Carefully pull the servo motor horn with the sensor still attached off the servo motor (the padded tape will come with it) and realign the horn so that the ultrasonic sensor is facing directly ahead. When you’re happy with the new alignment press the servo motor back into position at the front of the microbot base.

 

First Test Run

You’re ready for your first test run. Put the microbot on open ground flick the switch on the battery box and watch what happens. After a short stutter the servo motor should swing the ultrasonic sensor in both directions and Rolly should start moving forward. If it’s spinning around on itself you probably have the DC motor wires incorrectly connected. If it’s turning right the right-side motor is back to front; if it’s turning left the left-side motor is wrong.

Once you’ve fixed that try putting some objects in front of the microbot. If it baulks at them and turns to a different direction congratulations – it’s working!

 

What’s next?

If you’re feeling adventurous try modding the source code. I’ve annotated it all over the place so you should be able to get an understanding of what’s going on but take your time because there’s a fair bit of code there. We’re actually creating a very crude form of artificial intelligence for our microbot – it’s the code that determines its ‘personality’ or how it responds to its surroundings. Provided you don’t change pin assignments in the source code try changing other parts of the code to see what happens.

 

Give it a go!

The best tip I can give is be ready to improvise. As I said right at the start we’re not building a kit we’re creating something from scratch so you may need to adapt the design to fit the parts you have. And that’s perfectly fine because you’re not just learning problem-solving you’re learning about electronics microcontrollers and the rest which will help you with other designs and maybe even spawn a whole new career!

In the 2nd part of this project we’ll look at enhancing Rolly and how to use it to capture mobile video. So watch this space!

 

Tech corner:

Soldering 101

Our microbot needs a small amount of soldering. If you’re not confident with this try to find a mate who knows how or learn. There are plenty of tutorials on the web that will show you how to solder. Just remember soldering irons get damn hot (over 300°C) so treat them with respect or they’ll bite hard. Jaycar has a beginner’s soldering kit for $25 that would be a great way to start.

Troubleshooting

We’ll look more at troubleshooting in the next article but here are some brief tips:

Charge the batteries. The Motor Drive Shield needs 4.5V minimum to work and we’re pushing it using just four AA NiMH cells (4.8V) so make sure you freshly charge the batteries to get best results. If the bot seems to continually stutter you could add a fifth NiMH battery but we’ve avoided that as five batteries aren’t as convenient to charge as four.

Motor polarity. If the bot seems to go backwards all the time you may have the motor wires reversed. Just swap them over in the screwblocks.

Look at the code. You’re getting version 4 of my microbot code. Read the comments and learn how it works. You can set the speed and correct for motor speed differences if the bot doesn’t roll in a straight line.

 

 

  • Kennan Trevyn Zenjaya

    where can i download the code?

  • Raquib Buksh

    I am facing issues with this project… my servo attached with HC-SR04 ultrasonic sensor, seems to work fine when the power supply is via USB….it detects obstacles…..but when it is connected via external source, in this case 4.8v battery…..the servo stutters, although I connected a new battery…….moreover, my motors ain’t moving….but when I open the servo connection only the left motor periodically moves clockwise and anticlockwise…..there is yet no movement in the right motor…..what I am doing wrong??? Is it because the motor I am using is 12v DC and it’s overloading ??? or there is some other fault….help and guide me…THANKS

    • http://darrenyates.com.au Darren Yates

      Use motor output M4 instead of M2.

      • Raquib Buksh

        I have been using M4 only….but I have doubt in the coding, the subroutine checkpath(), has an if statement curDist>curDist (i have doubt here) maxAngle=pos…..but curDist=readPing(), so how does the checking works??…so I was wondering if you could explain me the programming, help me…..

  • MaroonR

    Hi. Really like the masterclass series! It’s a great resource for people like me who want to get into this. Hopefully someone with more knowledge will see this – I started working through this to edit the code for my robot car build (it has a couple extra wheels and a few other sensors I’m using), and I just noticed a few things that might cause problems. I’ve been programming for a while, so I understand basic things well enough, but maybe there are a few arduino specific things I’ve missed out on. Firstly, if an object is too far away, the ultrasonic sensor will return a ‘0’ for distance, which may be the cause of a lot of stuttering. I verified that through real world testing and through the serial monitor, though I haven’t tried fixing it yet. Secondly, the car seems to not like to turn left. I’m still not sure quite what the problem is, but line 67 (if (curDist > curDist) {maxAngle = pos;}) doesn’t make sense. The conditional statement there should NEVER be true, unless arduino does weird things with local variables like that.

    • Raquib Buksh

      exactly, I did mention Darren that here….and I had some discussion with him on his website where he said he is going to publish a new code in the next edition of the mag. But, may I ask did u try building this rolly?? I am working on this for approximately a month now…..it’s frustrating when its not working like some other object avoiding robot I see on youtube :/ is the motor for your car a 6V DC??

      • MaroonR

        The motors I’m using are all 6V. The arduino operates at 5V and can handle up to almost 20. Currently I’m using a voltage divider I made with a 500 ohm resistor and a trimpot so that a 9V battery will feed variable power to the external power on the motor shield (I have it set at 5V, currently). You might want to try adding more power, and see if that fixes your problem – but not too much. Don’t break your arduino.

        Darren’s code works well enough, though I’m trying to improve it a bit to make things smoother – namely, the car stuttered a lot, and it tends to get stuck when it reaches a tight corner. I did finish building it, and it does work quite well. Like I said though, I want to work on improving it.

        I see your post from 22 days ago. You might try testing each part individually to make sure they all work (I made several really basic programs for this). If you’ve already assembled your car, you can just rewrite the setup and loop portions, and change them back after you finish. It’s not too hard to do if you look at the example code (which is included in the download for the robot car source code).

        • soufiane maakouk

          hey how are you?
          need your help on something if you dont mind.
          i made the robot its working perfect.
          im powering the motorshield with 9.6v nicad battery and the arduino get the power from the motor shield what i want to do is power the shield with 9.6v and power arduino with separate battery but when i did it and i took of the power pin from the shield the robot wont move or aything.
          whats the problem with it?

          • http://darrenyates.com.au Darren Yates

            Does it still work if you swap back to your original mode? I’m just wondering if it’s blown up. That said, if you want to power the Arduino separately, you have to remove the pin header jumper marked ‘PWR’ on the shield.
            Cheers,
            Darren.

          • soufiane maakouk

            Arduino is powered by 9v the shield by 9.6v once I take the pwr pin out in the shield the motors stop running, servo and ultrasonic when I put back everything works fine
            I don’t know if its hardware problem or something else
            Can you try it if you made the same robot?
            Do you have any idea about that ?

          • http://darrenyates.com.au Darren Yates

            Okay, sounds like your 9V battery to the Arduino isn’t working. The PWR pin routes power from the shield power source to the Arduino. You remove the pin jumper to use separate power sources for both – that means your Arduino is getting no power, so that’s where to look.
            Cheers,
            Darren.

    • http://www.dwumasowki.pl Łukasz Ż

      Please tell me where I must put this “&& !=0″ ?
      Maybe you could give me a proper code?

      • MaroonR

        Hi, sorry if this ends up being a double post. Every time i make a post it gets removed somehow, but the second post seems to work (unless APC hates me?). Anyway, on Line 60 of the code, you’ll see an IF statement. Just change that line to look like this:

        if (curDist < COLL_DIST && != 0) { // if the current distance to object is less than the collision distance

        that should stop some stuttering, though you may find your robot getting stuck in more corners than it was previously since its moving a lot faster than the sensor can keep up (you can play with the speed settings some if you want to)

        • http://www.dwumasowki.pl Łukasz Ż

          I have this error:

          APC_4_ROBOT.ino: In function ‘void checkPath()':

          APC_4_ROBOT:60: error: expected primary-expression before ‘!=’ token

          and ScreenShot not working :(

        • http://www.dwumasowki.pl Łukasz Ż

          I have this error:

          APC_4_ROBOT.ino: In function ‘void checkPath()':

          APC_4_ROBOT:60: error: expected primary-expression before ‘!=’ token

          My code:

          if (curDist < COLL_DIST && != 0) {

          • MaroonR

            Oh I’m sorry. It needs to say:

            if (curDist < COLL_DIST && curDist != 0) {

            sorry about that

          • http://www.dwumasowki.pl Łukasz Ż

            Thanks a lot for solving my problem. I am beginner and Im still learning.
            My robot really work better with you fix.

            Keep in touch.

  • AMC

    we are following the same steps as above but our ping sensor is not picking anything and the car is just spinning around. What is wrong ?

  • http://www.dwumasowki.pl Łukasz Ż

    Maby add a ir controll?

  • Tyler

    Having issue with the HC-SR04 sensor returning zeros. How do I fix this?

  • Thomas Hawkin

    I’m lacking time badly and need help? what is the code you used in this project

  • Ian Gorman

    Hi I have a problem I have built the robot and I have tried to use the sketch however there is a slight problem it won’t allow me to Verify it as it says that there is an error with this line:

    NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE); // sets up sensor library to use the correct pins to measure distance.

    Please help I am new to this stuff so I am trying to get through this but I cant figure out why

  • Fares Ahmed Ali

    hi how can i get the code. I didn’t find it on the page

  • Daniel Castaño

    Hi, Greetings. I connected the Rolly as indicated by the first version (APC_4_ROBOT). The servo sensor starts working but only begins to spin in a circle with one servomotor, it seems that the other work (right). Use the version for rolly mk ii (APC_17_RollyMkII_v3) and the sensor shakes only and does not rotate. Please help.

  • Daniel Castaño

    Hello again, I have problems with the project are that rotates one side (right) and the obstacles seem to place him not detected. Help please!

  • Daniel Castaño

    Hi, i’ve tried the new code for rolly mk ii and the rolly seems not run. Just shake and no move anywhere. Help!

  • Daniel

    can someone give me the code? please!!