Thimble Learning Platform
Back to full view

Robotics Kit 3

Introduction

This is the third kit in the Robotics Series. In this kit you'll be adding on a servo and pen mount to turn your robot into a drawing bot.

Objectives

  • Learn about DC motors and H bridges.
  • Add drawing functionality to your robot with a servo and pen mount.
  • Have fun!
  • I've Never Used an Arduino

    Then this is a great place to start! If you're already familiar with setting up the Arduino and the IDE, you can skip to the next section.

    Terms 

    When we talk about Arduino, the Arduino IDE, and coding, there are a lot of words being thrown around. This section will clear all of those up and get you ready to start building!

    Arduino 

    The Arduino is a electronics prototyping platform. That means it's a flexible platform for building, testing, and, of course, prototyping electronics. That could be simple LEDs that light up at night, or advanced robots. When we talk about the Arduino we are talking about the physical board itself. The one that comes in this kit is red, but they come in many different shapes and colors. The Arduino brand and original board were created by arduino.cc and you can read more about the details of its history here.

    Arduino IDE 

    The Arduino IDE, or Integrated Development Environment, is not hardware, but a piece of software. If you wanted to write an essay, you might use Microsoft Word or Google Docs. If you wanted to edit pictures, you'd probably use Photoshop or Paint.net. If you want to program code for the Arduino, you'd use the Arduino IDE. Its a computer program (tool) that let's you develop and test out code. Once written, the code can be upload to the physical Arduino where it will stay until you upload new code.

    Download

    Since it is a program, you'll need to install it.

    For Windows computers use this link Windows Installer

    For Mac computers use this link Mac Installer

    After following each link, press the Just Download button to begin downloading the Arduino IDE. The Mac version has a few more steps and we have a video just for that.

    Mac Installation
    For Mac users

    Installation

    Open the executeable file you downloaded. You'll see a screen asking you to agree to their license. You can press I Agree.

    LicenseLicense

    Next up are the installation options. The Install USB Drivers lets the Arduino board communicate with the IDE. We definitely want this. The Associate .ino files makes any Arduino file on your computer open up to the Arduino IDE. Very helpful, so we'll keep that too. Press Next >.

    OptionsOptions

    Now you are being asked where you'd like the Arduino IDE program installed. I don't mind it in the standard Program Files so I just press Install. You can change where it will be installed, just remember what you chose. I recommend not changing it.

    FolderFolder

    Now the IDE is installing.

    InstallingInstalling

    Once completed proceed to the next section.

    CompletedCompleted

    Arduino IDE 101

    Open up the Arduino IDE for the first time. So, let's figure out what's what.

    Arduino IDEArduino IDE

    There is a mostly empty space in the middle that has this text:

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    8
    9
    void setup() {
      // put your setup code here, to run once:
    
    }
    
    void loop() {
      // put your main code here, to run repeatedly:
    
    }
    

    This is a simple Arduino Sketch. A Sketch is code you write that will later be uploaded to the Arduino board.

    There are few steps to go from code written in a sketch to code that runs on the Arduino board. Those are Verify > Compile > Upload.

    All of these you can get to by going under Sketch on the top bar of the program. Or using the Checkmark and Arrow icons right below that. The Checkmark verifies your code will compile, and the arrow button uploads the code to the Arduino.

    Sketch
    Icons

    Verify - looks at your code and makes sure it can actually run. It checks that there are no errors or things out of place. If your code will work, it goes to the Compile stage.

    Compile - The code you've written is great for human. It is readable and hopefully understandable. But this isn't great for a machine ie the Arduino. The Compile stage takes your written code and translates into something that the Arduino can understand and run, called machine code. It saves that compiled file and tried to Upload it to the board.

    Upload - This takes the compiled files and tries to send it to a plugged in Arduino. The IDE doesn't know where you've plugged in your Arduino or what kind it is. You have to tell it. I'll show you how to set that up in the next section.

    Arduino Board Setup

    For this section, make sure your Arduino Board that came with your kit is plugged in. Use the included micro USB cable to plug your Arduino into any free USB port on you computer.

    Navigate to the Tools section at the top of the Arduino IDE.

    You'll be greeted with a scary drop down. To setup your Arduino to accept uploads, do the following: Go to Board: and make sure Arduino/Genuino Uno is selected.

    BoardBoard

    Next is the Port. For Mac users refer to the video for these instructions. With your Arduino plugged in, you'll see some options. Mine says COM 15. This is the channel that the IDE will use to communicate with your Arduino. If you have a lot of COM # devices and don't know which is your Arduino, unplug your Arduino and take note of that numbers are there. Then plug it back in. Whichever is the new one in the list is your Arduino. Select that port.

    PortPort

    With the board and port selected and ready to go, let's upload our first sketch.

    Sketches

    We are going to upload a simple sketch to make an LED on the board blink. Head to File > Examples > Basics > Blink . You should see this sketch.

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    /*
      Blink
    
      Turns an LED on for one second, then off for one second, repeatedly.
    
      Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
      it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
      the correct LED pin independent of which board is used.
      If you want to know what pin the on-board LED is connected to on your Arduino
      model, check the Technical Specs of your board at:
      https://www.arduino.cc/en/Main/Products
    
      modified 8 May 2014
      by Scott Fitzgerald
      modified 2 Sep 2016
      by Arturo Guadalupi
      modified 8 Sep 2016
      by Colby Newman
    
      This example code is in the public domain.
    
      http://www.arduino.cc/en/Tutorial/Blink
    */
    
    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
    }
    
    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }
    

    Don't worry about the coding for now. Let's upload this sketch. You can press the Arrow icon, go to Sketch then Upload, or you can use the shortcut Ctrl+U in order to upload the code. Your sketch will auto-verify, compile, then upload to your Arduino board.

    Upload the SketchUpload the Sketch

    You will see the message Done uploading and your board should now have a blinking light.

    Uploading Sketches and Code From Thimble 

    We provide example code for all our projects. To use those you'll need to copy them from our website. Then, go into the Arduino IDE, File > New. It's best to then delete all the code already there in the sketch before you paste our code in, as that will avoid any errors from copying over the old code.

    Serial Plotter

    You'll be asked to use the Serial Plotter on some projects. This reads any information coming from the Arduino and displays it on a graph. It can only be accessed after you've uploaded your code. It is in the Tools menu. Once opened, make sure the Baud rate is set to 9600.

    Where to find the Serial Plotter
    Baud rate

    Troubleshooting 

    The most common issues are solved by double checking your Board and Port settings.

    Libraries

    What are Libraries? 

    Libraries are a collection of code that has already been written. We use them when we want to add functionality without have to write everything from scratch. The advantage of using a library is code re-use.

    Some of the projects in this set need libraries so this section will show you how to install those.

    Libraries to be downloaded 

    Our libraries come in the form of zip files that need to be downloaded but NOT unzipped.

    Library for I2C Servo Driver

    Adding Them to the Arduino IDE 

    Open up the Arduino IDE and go to Sketch > Include Library > Add .ZIP Library.... After that navigate to the zip files and add them one by one. And that's it!

    Add a LibraryAdd a Library

    What Should I Have Received?

    What 

    Here are all the parts that come with Robotics Kit 3

    Modules 

    Gather the following parts to complete this project.

    Parts

    All Parts x Qty
    Level 2 Chassis x 1
    Servo Holder x 1
    Pen Plate x 1
    Pen Holder x 2
    Servo x 1
    Servo Driver Board x 1
    20mm Nylon Standoff x 8
    M3 10mm Machine Screw x 6
    M3 Hex Nuts x 6
    M2 10mm Machine Screw x 8
    M2 Hex Nuts x 8
    Red Male-to-Male Jumper x 1
    Black Male-to-Male Jumper x 1
    Rubber bands x 2
    Cable x 1

    Additional parts

    You should also have received a sheet of 6 stickers and a postcard with instructions.

    Postcard
    Sticker Sheet
    Preparing the Level One Chassis

    Start 

    This is the Third Project in the Robotics Series. In this kit we'll be adding on a second level to your completed Robotics Kit 1. Before we can do that we must disassemble some of the first kit. There is a hole in the chassis were a pen, pencil, or marker must pass through. That hole is right below the I2C Motor Driver. The bad news is we have to remove the I2C Motor Drive to make room for the marker. The good news is that the level two chassis has more room and that's where we'll be attaching the driver.

    Modules 

    Gather the following parts to complete this project.

    Parts

    All Parts x Qty
    20mm Nylon Standoff x 8
    M3 Hex Nuts x 4

    Remove Cable to the I2C Motor Driver 

    Take the cable out of the I2C Motor Driver and its other side in the black base shield. You leave any cables going to the line finders or the WiFi module.

    Disconnecting this cable
    Unplug from I2C Motor Driver
    Unplug from black base shield
    Set to the side

    Unscrew Terminals 

    Unscrew the six screws found in the green terminal blocks of the I2C motor driver. The screws will not and should not come out of the terminal blocks. Remove all wires from the terminal blocks. This includes two coming from the battery holder, two from motor one, and two from motor two.

    Taking a look at the I2C Motor Driver
    Unscrew battery terminal
    Unscrew battery terminal
    Unscrew left motor
    Unscrew left motor
    Unscrew right motor
    Unscrew right motor
    Grab right motor wires
    Remove from terminal block
    Grab left motor wires
    Remove from terminal block
    Grab battery wires
    Remove from terminal block

    Unscrew the I2c Motor Driver 

    Unscrew the two M2 10mm screws holding the I2C motor driver in place. You will need to hold the nut on the other side as you undo the screws. With the screws removed, take off the I2C motor driver.

    Unscrew top screw
    Unscrew middle screw
    Remove both
    Grab board
    Remove and set aside

    Combining the Standoffs 

    Take all eight 20mm standoffs from the hardware bag. Using two as a time, combine them to create one 40mm. Repeat this three more times until you have a total of four 40mm standoffs.

    All the standoffs
    Grab two
    Thread together
    All the way
    Repeat for the rest
    Repeat
    Repeat
    Done

    Attaching the Standoffs 

    Place one of your newly made 40mm standoffs in one of the holes shown below. Attach and hand tighten a nut to the bottom of the chassis where the standoff pokes through. Repeat this three more times in the remaining holes.

    This is how your robot should look
    Standoffs go here
    And here
    Parts for one standoff
    Take standoff
    Place in hole
    It should stand up
    Take nut
    Thread to the bottom
    Screw down
    Done
    Side view
    Repeat for others
    Repeat for others
    Repeat for others
    Done

    Next Section 

    Our disassembly is complete and now we can start working on the Level Two chassis.

    Preparing the Level Two Chassis

    Start 

    In this section, we will be adding a couple of modules and the servo motor to the level two chassis. The servo motor will allow us to mount a pen and move it up and down.

    Modules 

    Gather the following parts to complete this project.

    Parts

    All Parts x Qty
    Level 2 Chassis x 1
    Servo Driver Board x 1
    M3 10mm Machine Screw x 1
    M3 Hex Nuts x 1
    M2 10mm Machine Screw x 8
    M2 Hex Nuts x 8
    Servo x 1
    Servo Holder x 1

    Add the I2C Motor Driver 

    Face the level two chassis with the arrows facing away from you. Place the I2C motor driver on the three mounting holes to the left. The white socket should be on the far side and the two green motor terminal blocks should be on the close side. Place a M2 10mm screw into each of the three mounting holes. Then attach a nut to the bottom of each and hand tighten. Not too tight as to bend the module.

    Level two chassis piece
    Backing removed
    This part should be on the top
    Servo board and parts
    Take the board
    Line up with the three mounting holes
    Zoom in
    Take a screw
    Place in mounting hole
    Take a nut
    Hand tighten
    Repeat for other screws
    Repeat for other screws

    Add the Servo Driver Board 

    Place the servo driver board on the three mounting holes to the right. Now the white socket should be on the close side and the blue push terminal block should on the far side. Place a M2 10mm screw into each of the three mounting holes. Then attach a nut to the bottom of each and hand tighten. Not too tight as to bend the module.

    The servo board and its mounting holes
    Take the board
    Place over mounting holes
    Get the hardware needed
    Take a screw
    Place in hole
    Place in hole
    Attach nut to other side
    Repeat with remaining screws
    Repeat with remaining screws
    Done

    Attach the Servo Horn 

    Take the blue Servo (not the one included with the Creator Set) out of its bag along with the servo horns and screws. Check out the picture below for the correct horn and screw to use. You'll want the horn to be able to go 90 degrees above and below where we are going to mount it. Place the servo horn on point away from the servo cable. Manually twist the horn and make sure it can do 90 degrees both up and down. If it can't, twist the horn to the middle of its actuation path, take off the horn, and reattach it so that it points away from the servo cable. Once you're sure it is on the right way, use the screw and tighten it and the servo horn down. Once the horn starts moving while tightening the screw, that is tight enough.

    Bag the servo came in
    Take out parts
    Bag of servo horns
    All horns and screws
    Use these two
    Servo and horn
    Cable out side to the left
    We want the horn this way
    Take horn
    Place on servo
    Get ready to test
    Pushing up this one is too far
    Pushing down this is not enough
    Find middle
    Take off horn
    Place back on facing right
    Pushing up this is good
    Pushing down this is also good
    Set back to middle and get the small screw
    Tighten down
    Ready for mount

    Completing the Servo Holder 

    Starting with the servo holder piece. The T-slot should be on the bottom right and the rectangular cutout should be to the left. First place the servo cable through the cutout. It should go from the top side of the servo holder piece through to the back. Once you get to the servo, you want the side the cable comes out of to the left in the cut out. Angle the servo to push it through. The servo horn should be pointing to the right.

    Servo Holder
    Removed backing
    Servo and holder
    T-slot to the right
    Take cable
    Feed through
    All the way
    Angle servo
    Place in
    Until flush with piece

    Take a M2 10mm screw and place it through each hole to the left and the right of the servo. Attach a M2 nut to the back of each screw and hand tighten.

    Hardware parts needed
    Take screw
    Place into mounting hole
    Take nut
    Hand tighten to back
    Take other screw
    Repeat

    Attaching the Servo Holder 

    Place the servo holder in the holes shown below. The circle hole is for the T-slot and the servo horn should be on the side facing the middle of the chassic. Side an M3 nut into the T-slot then from below screw in a M3 10mm screw. Becareful not to over tighten the screw.

    Servo and level two chassis
    Place into chassis as shown
    Another view
    Add nut to T-slot
    Add screw
    Tighten down
    All done

    Next Section 

    The level two chassis is ready to be attached to the level one so follow the instruction in the next section.

    Combining the Chassis

    Start 

    The plural of chassis is indeed Chassis. In this section, we will be attaching level two to level one.

    Modules 

    Gather the following parts to complete this project.

    Parts

    All Parts x Qty
    M3 10mm Machine Screw x 4
    Red Male-to-Male Jumper x 1
    Black Male-to-Male Jumper x 1
    Cable x 2

    Adding the Cables 

    Before we attach the level two chassis, we must place cables back into the black base shield. Plug in one side of a cable for the I2C motor driver and use another cable for the I2C servo driver. So that's two cables in two I2C sockets.

    All the cables we'll need
    Taking the free one
    One end into I2C
    Nice
    Grabbing the new one
    Magic unwrap
    One end into I2C
    Done

    Routing the Cables and Wires 

    Below are the recommended spots for routing all wires and cables coming from the level one chassis. Pulling the cables through and routing them this way makes sure that no wires or cables interfere with the drawing mechanism. Feel free to choose your own routing method as you add additional modules, or purely for aesthetics.

    Routing placesRouting places

    Screw Together 

    Line up the level two chassis with the standoffs. The arrows etched into the level two chassic should be on the same side as the battery pack on level one. Tighten a M3 10mm screw into each one.

    Levels one and two
    Take level two
    Place on top
    Route cables and wires
    Get the M3 screws
    Take a screw
    Place in mounting hole and into standoff
    Tighten
    Repeat
    Repeat
    Repeat
    Done

    Reattaching the Wires 

    Place the red wire from the battery holder into the VS terminal found on the same side as the socket on the I2C motor driver. Place the black wire from the battery holder into GND in the same terminal block. Tighten both terminal screws.

    Take battery wires
    Plug RED into VS
    Plug BLACK into GND
    Tighten
    Tighten
    Ready for next wires

    Place the red wire coming from the left motor into the M2+ on the I2C motor driver. Place the black wire from the left motor into the M2- in the same terminal block. Tighten both terminal screws.

    RED motor wire into M2+
    BLACK motor into M2-
    Tighten
    Tighten
    Ready for next wires

    Place the red wire coming from the right motor into the M1+ on the I2C motor driver. Place the black wire from the right motor into the M1- in the same terminal block. Tighten both terminal screws.

    RED motor wire into M1+
    BLACK motor into M1-
    Tighten
    Tighten
    Done

    Attaching the Cables 

    Place one cable coming from the I2C sockets into the I2C motor driver. Place the remaining one into the I2C servo board.

    Ready to plug in the cables
    One I2C
    Into Motor Driver
    Other I2C
    Into Servo Driver
    Ready for next step

    Jumping the Power 

    Grab the red and black male-to-male jumper wires. Unscrew the VS terminal screw just enough to fit one end of the red jumper inside. You should have both the jumper and wire inside the VS terminal. Re-tighten the terminal screw. Next, unscrew the GND terminal screw just enough to fit one end of the black jumper inside. You should have both the jumper and wire inside the GND terminal. Re-tighten the terminal screw.

    Parts for this section
    Unscrew VS a little
    Fit in jumper
    Re-tighten
    Next one
    Unscrew GND a little
    Fit in jumper
    Re-tighten
    Both jumpers in

    Hold the red jumper by the wire of the free end and not the black casing. Press down on the orange button on the 5V side of the blue terminal block on the I2C servo driver. Push the jumper inside then let go on the orange button. The wire should stay in even with a little tug. Hold the black jumper the same way. Press down the orange button on the GND side of the blue terminal block and push the jumper inside.

    Hold red jumper by wire
    Press down button
    Insert
    Release button and tug
    Hold black jumper by wire
    Press button
    Insert
    Release and tug to check
    Done

    Attach the Servo Cable 

    The servo cables goes to one of the headers on the I2C servo driver. It is going on the set of three headers closest to the GND terminal. Insert the cable into these three headers with the orange wire in the cable facing the middle of the chassis.

    Take servo cable
    These headers
    In slot one
    Orange wire
    Facing in
    Done

    Next Section 

    Level two is attached and wired up. The next section will cover making the pen mount.

    Assembling the Pen Mount

    Start 

    We will be putting the pen mount together and preparing everything for calibration of the pen holder.

    Modules 

    Gather the following parts to complete this project.

    Parts

    All Parts x Qty
    Pen Plate x 1
    Pen Holder x 2
    Rubber bands x 2

    Combining the Parts 

    Place the two pen holder peices into the slots on the pen plate. They should go in sideways with the cutouts in the holders pointing down towards the legs in the pen plate. Place a M3 10mm screw into the hole and through both pen holders. Attach a nut and hand tighten.

    Acrylic parts
    Movie magic
    No backing
    Take one of the holders
    Place into the plate so the cutout faces the legs
    Holder in
    Repeat
    Repeat
    Cutout down
    Shown here
    Now for the hardware
    Grab the screw
    Insert into the hole
    Like so
    Grab the nut
    Attach
    Tighten

    Adding a Pen 

    Use a pen, pencil or marker for this part. You will also need one of the rubber bands. Place the pen in the wedge created by the pen holders. Wrap the rubber band around the pen. Start with the notches in the pen plate then over the pen then to the other notches in the pen plate.

    All the parts
    I'm using a marker
    See the wedge
    Taking the marker
    Placed onto the holders
    Holding here for the next part
    Taking the rubber band
    Getting it on this notch
    And the other
    Across the pen
    In the other notches
    Top view

    The Other Rubber Band 

    Going back to the chassis. Take the other rubber band. It will be placed in the notch below the servo horn. The easiest way is to first loop it around the notch and pull it up and in fron of ther servo horn. With some tension on the rubber band, drop your pen pen through the center hole in the chassis. The legs in the pen plate will slide into the two slots in the chassis. Now pull the rubber band forward and over the pen holders but not the plate.

    Zoom in of the servo
    This is the notch
    Other rubber band
    Looping over notch
    Pulling a bit
    Pulling up
    Insert pen piece
    Pull over
    Done

    Next Section 

    The mechanical assembly is all done. Now we need to do some manual calibratation covered in the next section.

    Calibrating

    Start 

    There are two things to calibrate on the robot. One is the mechanical position of the pen in its holder. The other is the position in degrees of the servo.

    Modules 

    Gather the following parts to complete this project.

    Parts

    All Parts x Qty
    Potentiometer x 1
    Cable x 1

    Calibrate the Servo 

    We are going to find the minimum and maximum that the servo should move. Plug a cable into A0 and the other side into the potentiometer. Set the potentiometer to its middle position. This is done by rotating it so the groove in the dial points to the socket.

    All the parts
    Take cable
    Into potentiometer
    Into A0
    Ready

    Upload

    Upload the following code. You will need all 6 batteries in and powering the I2C boards

    Potentiometer must in middle positionPotentiometer must in middle position

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
                                                            
    
    //Libraries needed
    #include "ServoDriver.h"
    #include <Wire.h>
    
    //84 to 116
    
    //Creating the servo driver object
    ServoDriver servoDriver;
    
    //Variables for data
    int dialSocket = A0;  
    int val;
    
    void setup()
    {
        //Open I2C communication
        Wire.begin();
        //Begin Serial communication
        Serial.begin(9600);
        //Begin communication with driver
        servoDriver.init(0x7f);    
    }
    
    void loop()
    {
      //Read dial value
      val = analogRead(dialSocket);
      //Map value to a degree
      val = map(val, 0, 1023, 0, 180);
      //Send that mapped value to Serial Monitor
      Serial.println(val);
      //Set servo position in position 1 to the value
      servoDriver.setAngle(1, val);
      //Small delay for stability
      delay(15);
    }
    

    Observe

    Open up the Serial Motor. Your initial value should be pretty close to 90 degrees.

    Find the Minimum

    Slowly rotate the dial so the servo horn moves down. You are looking for the spot where the servo horn is just barely in the pen holder cutouts. I get a value of about 85. Write your number down.

    Starting at middle
    Turn
    Middle
    Down
    Middle
    Down

    Find the Maximum

    Slowly rotate the dial the other way so the servo horn moves up. You are looking for the spot where the pen assembly is slightly up and tilted. I get a value of about 120. Write your number down. These are your servo calibration numbers.

    From low
    Turn
    Down
    Up
    Down
    Up

    Calibrate the Pen 

    Set your servo to the minimum position. Roll the pen down in the pen mount (adjusting the rubber band if necessary) so that it just touches the surface of whatever your robot is on. I suggest you place a piece of paper under your robot. Especially if you are using a marker.

    Un-calibrated
    Touching the paper at minimum
    When servo is up

    Upload

    Change the minimum and maximum values then upload the following code.

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    
    //Libraries needed
    #include "ServoDriver.h"
    #include <Wire.h>
    
    //Creating the servo driver object
    ServoDriver servoDriver;
    
    //PUT YOUR VALUES HERE
    int minVal = 85;
    int maxVal = 120;
    
    void setup()
    {
      //Open I2C communication
      Wire.begin();
      //Begin communication with driver
      servoDriver.init(0x7f);
    }
    
    void loop()
    {
    
      //Set servo position to Max
      servoDriver.setAngle(1, maxVal);
      //Wait
      delay(2000);
      //Set servo position to Min
      servoDriver.setAngle(1, minVal);
      //Wait
      delay(2000);
    }
    

    Observe

    If you've calibrated everything correctly then the pen should be lifting up, waiting two seconds, then going down and making contact with the paper, and waiting two more seconds before looping.

    Next Section

    With everything calibrated you can remove the potentiometer and cable to move on to drawing some shapes in the next section.

    Draw Simple Shapes

    Start 

    This section will show off some code to get your robot to draw shapes. We are using timed instructions.

    Circle Square Spiral 

    Uncomment only the shape you want to draw. Make sure you're on fresh batteries or your results may vary.

    Upload

    Upload the following code.

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    
    //Libraries needed
    #include "ServoDriver.h"
    #include <Wire.h>
    #include "Grove_I2C_Motor_Driver.h"
    
    // default I2C address is 0x0f
    #define I2C_ADDRESS 0x0f
    
    //Creating the servo driver object
    ServoDriver servoDriver;
    
    //Motor names
    #define LEFTMOTOR MOTOR2
    #define RIGHTMOTOR MOTOR1
    
    //PUT YOUR VALUES HERE
    int minVal = 40;
    int maxVal = 80;
    
    //Shape to draw
    String shape = "circle";
    //String shape = "square";
    //String shape = "spiral";
    
    void setup() {
      //Open I2C communication
      Wire.begin();
    
      //Begin communication with driver
      servoDriver.init(0x7f);
    
      //Bring servo up to begin
      penUp();
    
      // start motor driver
      Motor.begin(I2C_ADDRESS);
      // correct pwm cycles
      Motor.frequence(F_490Hz);
    
    }
    
    void loop() {
      // put your main code here, to run repeatedly:
      //Wait to begin
      delay(10000);
    
      if (shape == "circle") {
        //Turn left motor on
        Motor.speed(LEFTMOTOR, 80);
        //Wait for Motor to hit speed
        delay(1000);
        //Put pen down
        penDown();
        //Draw circle
        delay(3300);
        //Stop motor
        Motor.stop(LEFTMOTOR);
        //Put pen up
        penUp();
      }
    
      if (shape == "square") {
        //One loop for each side
        for (int i = 0; i <= 3; i++) {
          //Put pen down
          penDown();
          //Set both motors forward
          Motor.speed(RIGHTMOTOR, -65);
          Motor.speed(LEFTMOTOR, 50);
          //Wait for distance
          delay(800);
          //Stop motors
          Motor.stop(RIGHTMOTOR);
          Motor.stop(LEFTMOTOR);
          //Wait
          delay(1000);
          // Lift up pen
          penUp();
          //Turn Right
          turnRight();
          //Set both motors Back
          Motor.speed(RIGHTMOTOR, 50);
          Motor.speed(LEFTMOTOR, -60);
          //Wait for distance
          delay(250);
          //Stop motors
          Motor.stop(RIGHTMOTOR);
          Motor.stop(LEFTMOTOR);
          //Wait
          delay(1000);
        }
        // Put pen up
        penUp();
      }
    
      if (shape == "spiral") {
        //Set right motor on
        Motor.speed(RIGHTMOTOR, 80);
        //Wait for motor to come up to speed
        delay(500);
        //n<=5 where 5 is the number of spirals
        for (int n = 0; n <= 2; n++) {
          // Put pen down
          penDown();
          //Wait for circle
          delay(3300);
          //Set left motor on
          Motor.speed(LEFTMOTOR, 50);
          //For a short time to nudge it
          delay(150);
          //Stop left motor
          Motor.stop(LEFTMOTOR);
        }
        //Stop right motor after spiral completed
        Motor.stop(RIGHTMOTOR);
        // Put pen up
        penUp();
      }
    
      //After shape is drawn stop forever
      while (1) {
    
      }
    }
    
    void penDown() {
      //Set servo to down position
      servoDriver.setAngle(1, minVal);
    }
    
    void penUp() {
      //Set servo to up position
      servoDriver.setAngle(1, maxVal);
    }
    void turnRight() {
      Motor.speed(LEFTMOTOR, 50);
      Motor.speed(RIGHTMOTOR, 50);
    
      delay(800);
    
      Motor.stop(LEFTMOTOR);
      Motor.stop(RIGHTMOTOR);
    }
    
    void turnLeft() {
      Motor.speed(LEFTMOTOR, -50);
      Motor.speed(RIGHTMOTOR, -50);
    
      delay(840);
    
      Motor.stop(LEFTMOTOR);
      Motor.stop(RIGHTMOTOR);
    }
    
    

    Observe

    After five seconds the robot will have drawn a circle if you haven't changed anything above.

    Common problems 

    Here are some common problems and how to fix them.

    The circle doesn't go fully around

    Increase the second delay in the circle drawing section. Up from 3300.

    The circle goes too much

    Decrease the second delay in the circle drawing section. Down from 3300.

    There is a weird mark when the pen goes down

    This is normal.

    The servo works but doesn't draw

    Make sure your calibration variables are correct and added to the code.

    The servo doesn't move

    Check that both jumpers are still connected.

    Drawing With the Controller

    Start 

    Now we will use the buttons on the controller to operate the pen wirelessly!

    Controller Code 

    If you are still using the example from Robotics Kit 2 with the two button then there is no need to reupload code. If not or just to be sure, upload the code below to the controller.

    Upload

    Upload the following code to the controller.

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    //All the libraries used
    #include <WiFiEsp.h>
    #include <WiFiEspUdp.h>
    #include "SoftwareSerial.h"
    
    //Button sockets
    #define leftSocket 5
    #define rightSocket 6
    //Create Serial communication Object
    SoftwareSerial Serial1(8, 9); // RX, TX
    
    
    WiFiEspUDP Udp;
    
    IPAddress apIP = IPAddress(192, 168, 111, 111);
    IPAddress stationIP = IPAddress(192, 168, 111, 112);
    IPAddress broadcastIP = IPAddress(0, 0, 0, 0);
    
    //Wifi settings
    char ssid[] = "My Wifi Robot";    // the name of your access point
    char pass[] = "password";        // the password for your access point
    int status = WL_IDLE_STATUS;     // the Wifi radio's status
    
    //Ports to be used
    unsigned int listeningPort = 10003;  // local port to listen on
    unsigned int sendingPort = 10002;  // local port to sent on
    
    //Message Variables
    #define arrayLength 8
    char data[arrayLength + 1];
    String dataAsString;
    
    // Vaiables
    int leftData;
    int rightData;
    int leftButton;
    int rightButton;
    
    void setup()
    {
      // Start Serial Communication with computer and WiFi module
      Serial.begin(9600);
      // initialize serial for ESP module
      Serial1.begin(9600);
      // initialize ESP module
      WiFi.init(&Serial1);
      WiFi.config(stationIP);
    
      // Connect to robot
      status = WiFi.begin(ssid, pass);
    
      // Set up UDP listener on port
      Udp.begin(listeningPort);
    
      // Print out which port
      Serial.print(F("Listening on port "));
      Serial.println(listeningPort);
    }
    
    void loop() {
      //Read the Joystick values
      leftData = analogRead(A0);
      rightData = analogRead(A2);
    
      //Read button values
      leftButton = digitalRead(leftSocket);
      rightButton = digitalRead(rightSocket);
    
      //Concatanate all the vlaues into one string
      dataAsString = String(leftData) + String(rightData) + String(leftButton)+ String(rightButton);
    
      //Convert String to char array
      dataAsString.toCharArray(data, arrayLength + 1);
    
      //Print out all values
      Serial.println(data);
    
      //Begin UDP sending
      Udp.beginPacket(apIP, sendingPort);
      //Send the data
      Udp.write(data);
      //Send ending packets
      Udp.endPacket();
    
      //Battery saving delay
      delay(10);
    }
    

    Robot With Pen Code 

    This code is very similar to the chainable LED example from Robotics Kit 2 except it uses the penUp() and penDown() functions.

    Upload

    Upload the following code. Use the toggle boolean to choose whether you want the buttons change pen state on a click, which would be true . Or if you'd like to hold down the button to draw, which would be false . Try both!

    Download file Copy to clipboard
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    //All the libraries used
    #include <WiFiEsp.h>
    #include <WiFiEspUdp.h>
    #include "SoftwareSerial.h"
    #include "Grove_I2C_Motor_Driver.h"
    #include "ServoDriver.h"
    #include <Wire.h>
    
    //Pen control
    bool toggle = true;
    bool previousPen = false;
    bool currentPen = false;
    
    //Your servo limits here
    int minVal = 40;
    int maxVal = 80;
    
    //Your servo limits here
    int leftUp  = 253;
    int leftDown = 769;
    int rightUp = 775;
    int rightDown = 247;
    
    // default I2C address is 0x0f
    #define I2C_ADDRESS 0x0f
    
    //Creating the servo driver object
    ServoDriver servoDriver;
    
    //Motor names
    #define LEFTMOTOR MOTOR2
    #define RIGHTMOTOR MOTOR1
    
    //Button Variables
    int leftButton = 0;
    int rightButton = 0;
    
    //Create Serial communication Object
    SoftwareSerial Serial1(8, 9); // RX, TX
    
    WiFiEspUDP Udp;
    
    IPAddress apIP = IPAddress(192, 168, 111, 111);
    IPAddress stationIP = IPAddress(192, 168, 111, 112);
    IPAddress broadcastIP = IPAddress(0, 0, 0, 0);
    
    //Wifi settings
    char ssid[] = "My Wifi Robot";    // the name of your access point
    char pass[] = "password";        // the password for your access point
    int status = WL_IDLE_STATUS;     // the Wifi radio's status
    
    //Ports to be used
    unsigned int listeningPort = 10002;  // local port to listen on
    unsigned int sendingPort = 10003;  // local port to sent on
    
    
    //Message Variables
    #define arrayLength 8
    char data[arrayLength + 1];
    String dataAsString;
    
    // Vaiables
    int leftData = 0;
    int rightData = 0;
    
    //Motor Variables
    int leftSpeed = 0;
    int rightSpeed = 0;
    
    void setup()
    {
      // Start Serial Communication with computer and WiFi module
      Serial.begin(9600);
      // initialize serial for ESP module
      Serial1.begin(9600);
      // initialize ESP module
      WiFi.init(&Serial1);
      WiFi.configAP(apIP);
    
      //Open I2C communication
      Wire.begin();
    
      //Begin communication with driver
      servoDriver.init(0x7f);
    
      // start motor driver
      Motor.begin(I2C_ADDRESS);
      // correct pwm cycles
      Motor.frequence(F_490Hz);
    
      // Print out debugging messages
      Serial.print("Attempting to start AP ");
      Serial.println(ssid);
    
      // start access point
      status =  WiFi.beginAP(ssid, 10, pass, ENC_TYPE_WPA2_PSK);
    
    
      // Set up UDP listener on port
      Udp.begin(listeningPort);
    
      // Print out which port
      Serial.print(F("Listening on port "));
      Serial.println(listeningPort);
    }
    
    void loop()
    {
    
      //Check for incoming packets
      int packetSize = Udp.parsePacket();
    
      // If there are packets
      if (packetSize) {
        //memset(data, 0, sizeof data);
        //Print out update
        //Serial.println("Packets Received");
        // read the packet into packetBufffer
        int len = Udp.read(data, arrayLength);
        if (len > 0) {
          data[len] = 0;
        }
        //Send received data to function
        dataTranslate(data);
    
        //Map values to speeds
        leftSpeed = map(leftData, leftDown, leftUp, -100, 100);
        rightSpeed = map(rightData, rightDown, rightUp, -100, 100);
      }
    
      //Check button values
      if (leftButton || rightButton) {
        currentPen = true;
        //Check to see if toggle is on
        if (toggle) {
          //If the button was just pressed
          if (currentPen && !previousPen) {
            //Put the pen down
            penDown();
          }
        } else {
          //If not just put the pen down
          penDown();
        }
        //No buttons pressed
      } else {
        currentPen = true;
        //Check to see if toggle is on
        if (toggle) {
          //If the button was just released
          if (!currentPen && previousPen) {
            //Bring pen up
            penUp();
          }
        } else {
          //If not just put the pen up
          penUp();
        }
      }
    
      //Check to see if joystick is in deadzone
      if (leftSpeed < 10 && leftSpeed > -10) {
        //Stop motor
        Motor.stop(LEFTMOTOR);
      } else {
        //Set motor to mapped speed
        Motor.speed(LEFTMOTOR, leftSpeed);
      }
    
      //Check to see if joystick is in deadzone
      if (rightSpeed < 10 && rightSpeed > -10) {
        //Stop motor
        Motor.stop(RIGHTMOTOR);
      } else {
        //Set motor to mapped speed
        Motor.speed(RIGHTMOTOR, rightSpeed);
      }
    
      //Print out all values
      Serial.println(String(leftSpeed) + "," + String(rightSpeed) + "," + String(leftButton) + "," + String(rightButton));
    }
    
    //Function that takes raw string and chops it into values
    void dataTranslate(char recData[]) {
      //Set passed array into a temp variable
      dataAsString = recData;
      //Write a section of the array to a value based on location
      leftData = dataAsString.substring(0, 3).toInt();
      rightData = dataAsString.substring(3, 6).toInt();
      leftButton = dataAsString.substring(6, 7).toInt();
      rightButton = dataAsString.substring(7, 8).toInt();
    }
    
    void penDown() {
      //Set servo to down position
      servoDriver.setAngle(1, minVal);
    }
    
    void penUp() {
      //Set servo to up position
      servoDriver.setAngle(1, maxVal);
    }
    

    Observe

    When you drive around the robot, you can press either button on the controller to put the pen down. Try out the toggle feature and see which you like best.

    Introduction to Motors

    Intro 

    Motors are everywhere - from toothbrushes to hard drives. Their ability to convert electrical energy to mechanical energy has revolutionized technology. Take a look at the motors used by your robot. How is it possible that supplying power through two wires can cause the tires to rotate? It all has to do with electromagnetism.

    What is electromagnetism? 

    If you've read the Infrared section from Robotics Kit 1, then you'll know that there is an electromagnetic spectrum made up of radiation of different wavelengths (some of which are visible to humans). Electromagnetism is a branch of physics revolving around the interaction between electrically charged particles. Visible light is electromagnetic radiation (radiation being the transmission of energy) and what allows motors to turn is called electromagnetic force.

    So how is this applied inside the motor? Well if you take a piece of iron, wrap it a couple hundred times in wire, and apply a voltage between the two ends of the wire you'll get whats called an electromagnet which is essentially a homemade magnet! If you increase the voltage, the magnet gets stronger. If you reverse the direction of current by swapping the terminals, the north and south ends of the magnet will switch.

    This is exactly what happens inside of a DC, or direct current, motor like you use in your robot. If you were to crack open one of your motors you'd see two magnets, a big winding of copper wire, two brushes (not like your hairbrush) and a commutator. The coil of wire is the electromagnet, and when you connect the two wires from your motors to an external power source (your battery holder) you're creating a magnetic field. This coil is wrapped around the axle of the motor. The magnets on the outside of the coil of wire create a magnetic field around the coil with one side being south and the other being north. When the motors are supplied with power, the electromagnet creates a magnetic field within this outer magnetic field. As the saying goes, "opposites attract and sames repel". This means that torque (a twisting force that causes rotation) is applied to the electromagnet by the outer magnets as the south ends of both magnets align and therefore repel causing the coil to spin, leading to the north ends of both magnets lining up and repelling one another, on and on. This causes the motor axle to turn, thus turning your tires.

    What are the commutator and brushes for? The commutator is a rotary electrical switch that prevents the current from reversing direction because this would cause the motor to slow down and spin in the opposite direction. The brushes are devices that allow the motor to spin while still allowing current to be conducted between the stationary parts of motor (the commutator) and the moving ones (the axle). Without the brushes the electromagnet would lose contact with the external power source and no longer be an electromagnet.

    Conceptual Question: From what you now know about motors can you figure out why reversing the terminals your motor wires are connected to also changes the direction the motor turns in?

    Servos 

    Another application of DC motors is inside of a servo. A servo is a rotary actuator that allows for precise control of its position. Basically, its a motor that you can control the rotation of instead of having it continuously spin like the motors on your robot. Servos are controlled with three wires: a black one for ground, a red one for power, and a third wire with which the servo's position is controlled with. Inside of the servo there is a DC motor, some gears, and a control circuit that monitors the position of the servo. The gears give the servo more torque than a regular motor because they take the force of the motor turning and spread it out over a longer distance. This increases the torque as seen in the formula Work = Force * Distance. This also slows down the motor, but allows the servo to hold its position even if you try and twist it's axle.

    The exact position of the servo is set through PWM or Pulse Width Modulation. Each servo has a minimum pulse width and a maximum pulse width; these values (plus every value between them) correspond to a specific degree. The minimum pulse width corresponds to 0 degrees while the maximum pulse width corresponds to 180 degrees.

    PWM Corresponding to Servo Degree ChangesPWM Corresponding to Servo Degree Changes

    So how do we set the width of these pulses? Well the pulses correspond to duty cycle. Duty cycle is represented in percentages with the percentage representing how long something is "on" versus how long it is "off". If you have a constant 5 volts flowing through a wire for 10 seconds it has a 100% duty cycle. If you then decide to to only supply 5 volts for 2.5 seconds then you're only turning the power on for 1/4th of the time and it now has a 25% duty cycle. This is how a servo is told how far to turn. If the minimum pulse width for a servo is 1 ms and the microcontroller supplies power to the servo in pulses of 1 ms then the servo turns to its 0 degree position. If that same servo has a maximum pulse width of 2 ms and it is supplied that, then it rotates to its 180 degree position. Any pulse width in between causes the servo to turn to the degree corresponding to that width.

    25%, 50%, and 75% Duty Cycles25%, 50%, and 75% Duty Cycles

    H Bridges 

    An important electrical component that allows for the control of motor is an H bridge. An H bridge is a component with an internal circuit consisting of four switches that allows for the control of the direction and flow of current to a load. On your motor driver you'll see an H bridge - it's the largest black component. The switches inside of a H bridge are in the shape of an H, hence the name.

    H BridgeH Bridge

    In the diagram below you'll see an H bridge and its configurations. The top end of the H bridge is connected to a power supply while the bottom is connected to ground. Diodes and transistors control whether an element is open or closed. When side 1 and 4 are on, then side 1 is connected to the power supply and side 4 is connected to ground. This completes the circuit and causes the motor to turn, for example, forward.

    If, on the other hand, side 2 and 3 are on then side 2 is connected to power and side 3 is connected to ground. This reverses the current going through the motor and it turns backwards.

    H BridgeH Bridge

    The H bridge used in your motor driver actually consists of two H bridges! This allows two motors can be controlled at once, each one being controlled by a different H bridge. When you make your robot drive forward and then backwards you are utilizing the H bridge by changing the direction of current and changing the status of the switches within the H bridge.

    The Different Switches in H BridgesThe Different Switches in H Bridges

    Continuing Onward!

    Now that you have an idea of how your motors work to move your robot, let's continue onto the main tutorial for this kit. If you'd like to learn more about H bridges or motors check out this link and this link.