Posted on by & filed under Arduino Tutorials, How To Make a Robot, Software and Apps.

How to make a robot: lesson 10

Lessons Menu:

Programming is usually the final step involved in building a robot. If you followed the lessons, so far you have chosen the actuators, electronics, sensors and more, and have assembled the robot so it hopefully looks something like what you had initially set out to build. Without programming though, the robot is a very nice looking and expensive paperweight.

It would take much more than one lesson to teach you how to program a robot, so instead, this lesson will help you with how to get started and where (and what) to learn. The practical example will use “Processing”, a popular hobbyist programming language intended to be used with the Arduino microcontroller chosen in previous lessons. We will also assume that you will be programming a microcontroller rather than software for a full-fledged computer.

What Language to Choose?

Programming Robot from syraweb.orgThere are many programming languages which can be used to program microcontrollers, the most common of which are:

  • Assembly; its just one step away from machine code and as such it is very tedious to use. Assembly should only be used when you need absolute instruction-level control of your code.
  • Basic; one of the first widely used programming languages, it is still used by some microcontrollers (Basic Micro, BasicX, Parallax) for educational robots.
  • C/C++; one of the most popular languages, C provides high-level functionality while keeping a good low-level control.
  • Java; it is more modern than C and provides lots of safety features to the detriment of low-level control. Some manufacturers like Parallax make microcontrollers specifically for use with Java.
  • .NET/C#; Microsoft’s proprietary language used to develop applications in Visual Studio. Examples include Netduino, FEZ Rhino and others).
  • Processing (Arduino); a variant of C++ that includes some simplifications in order to make the programming for easier.
  • Python, one of the most popular scripting languages. It is very simple to learn and can be used to put programs together very fast and efficiently.

In lesson 4, you chose a microcontroller based on the features you needed (number of I/O, user community, special features, etc). Often times, a microcontroller is intended to be programmed in a specific language. For example:

If you have chosen a hobbyist microcontroller from a known or popular manufacturer, there is likely a large book available so you can learn to program in their chosen programming language. If you instead chose a microcontroller from a smaller, lesser known manufacturer (e.g. since it had many features which you thought would be useful for your project), it’s important to see what language the controller is intended to be programmed in (C in many cases) and what development tools are there available (usually from the chip manufacturer).

Getting Started

Hello World PSPThe first program you will likely write is  “Hello World” (referred to as such for historic reasons). This is one of the simplest programs that can be made in a computer and is intended to print a line of text (e.g. “Hello World”) on the computer monitor or LCD screen. In the case of a microcontroller, another very basic program you can do that has an effect on the outside world (rather than just on-board computations) is toggling an IO pin. Connecting an LED to and I/O pin then setting the I/O pin to ON and OFF will make the LED blink. Although the simple act of turning on an LED may seem basic, the function can allow for some complex programs (you can use it to light up multi-segment LEDs, to display text and numbers, operate relays, servos and more).

Step 1: Ensure you have all components needed to program the microcontroller

Not all microcontrollers come with everything you need to program them, and most microcontrollers need to be connected to a computer via USB plug. If your microcontroller does not have a USB or DB9 connector, then you will need a separate USB to serial adapter, and wire it correctly. Fortunately many hobbyist microcontrollers are programmable either via an RS-232 port or by USB, and include the USB connector on-board which is used not only for two-way communication, but also to power the microcontroller board.

Step 2: Connect the microcontroller to the computer and verify which COM port it is connected to. Not all microcontrollers will be picked up by the computer and you should read the “getting started” guide in the manual to know exactly what to do to have your computer recognize it and be able to communicate with it. You often need to download “drivers” (specific to each operating system) to allow your computer to understand how to communicate with the microcontroller and/or the USB to serial converter chip.

Step 3: Check product’s user guide for sample code and communication method / protocol

Don’t reinvent the wheel if you don’t have to. Most manufacturers provide some code (or pseudo code) explaining how to get their product working. The sample code may not be in the programming language of your choice, but don’t despair; do a search on the Internet to see if other people have created the necessary code.

  • Check product manuals / user guides
  • Check the manufacturer’s forum
  • Check the internet for the product + code
  • Read the manual to understand how to write the code

Useful Tips

  1. Create manageable chunks of functional code: By creating segments of code specific to each product, you gradually build up a library. Develop a file system on your computer to easily look up the necessary code.
  2. Document everything within the code using comments: Documenting everything is necessary in almost all jobs, especially robotics. As you become more and more advanced, you may add comments to general sections of code, though as you start, you should add a comment to (almost) every line.
  3. Save different versions of the code – do not always overwrite the same file: if you find one day that your 200+ lines of code do not compile, you won’t be stuck going through it line by line; instead you can revert to a previously saved (and functional) version and add / modify it as needed. Code does not take up much space o a hard drive, so you should not feel pressured to only save a few copies.
  4. Raise the robot off the table or floor when debugging (so its wheels/legs/tracks don’t accidentally launch it off the edge), and have the power switch close by in case the robot tries to destroy itself. An example of this is if you try to send a servo motor to a 400us signal when it only accepts a 500 (corresponding to 0 degrees) to 2500us (corresponding to 180 degrees) signal. The servo would try to move to a location which it cannot physically go to (-9 degrees) and ultimately burn out.
  5. If code does something that does not seem to be working correctly after a few seconds, turn off the power – it’s highly unlikely the problem will “fix itself” and in the meantime, you may be destroying part of the mechanics.
  6. Subroutines may be a bit difficult to understand at first, but they greatly simplify your code. If a segment of code is repeated many times within the code, it is a good candidate to be replaced with a subroutine.

Practical Example

Arduino UnoWe have chosen an Arduino microcontroller to be the “brain” of our robot. To get started, we can take a look at the Arduino 5 Minute Tutorials. These tutorials will help you use and understand the basic functionality of the Arduino programming language. Once you have finished these tutorials, take a look at the example below.

For the robot we have made, we will create code to have it move around (left, right, forward, reverse), move the two servos (pan/tilt) and communicate with the distance sensor. We chose Arduino because of the large user community, abundance of sample code and ease of integration with other products.

Sharp GP2D120 IR Range Finder
Distance sensor

Fortunately in the Arduino code, there is an example for getting values from an analog sensor. For this, we go to File -> Examples -> Analog -> AnalogInOutSerial (so we can see the values)


Again, we are fortunate to have sample code to operate servos from an Arduino. File -> Examples ->  Servo -> Sweep

Servocity Pan and TiltNote that text after two slashes // are comments and not part of the compiled code

#include <Servo.h>            // This loads the servo script, allowing you to use specific functions below

Servo myservo;                      // create servo object to control a servo
int pos = 0;                             // variable to store the servo position

void setup()                           // required in all Arduino code
myservo.attach(9);             // attaches the servo on pin 9 to the servo object

void loop()                               // required in all Arduino code
for(pos = 0; pos < 180; pos += 1)  // variable ‘pos’ goes from 0 degrees to 180 degrees in steps of 1 degree
myservo.write(pos);              // tell servo to go to position in variable ‘pos’
delay(15);                                 // waits 15ms for the servo to reach the position
for(pos = 180; pos>=1; pos-=1)     // variable ‘pos’ goes from 180 degrees to 0 degrees
myservo.write(pos);              // tell servo to go to position in variable ‘pos’
delay(15);                               // waits 15ms at each degree

Motor Controller

Pololu Serial Motor ControllerHere is where it gets a bit harder, since no sample code is available specifically for the Arduino. The controller is connected to the Tx (serial) pin of the Arduino and waits for a specific “start byte” before taking any action. The manual does indicate the communication protocol required; a string with specific structure:

  • 0x80 (start byte)
  • 0x00 (specific to this motor controller; if it receives anything else it will not take action)
  • motor # and direction (motor one or two and direction explained in the manual)
  • motor speed (hexadecimal from 0 to 127)

In order to do this, we create a character with each of these as bytes within the character:

unsigned char buff[6];

buff[0]=0x80; //start byte specific to Pololu motor controller
buff[1]=0; //Device type byte specific to this Pololu controller
buff[2]=1; //Motor number and direction byte; motor one =00,01
buff[3]=127; //Motor speed “0 to 128″ (ex 100 is 64 in hex)


Therefore when this is sent via the serial pin, it will be sent in the correct order.

Putting all the code together makes the robot move forward and sweep the servo while reading distance values.

You can see the full robot and the user manual.



77 Responses to “How to Make a Robot – Lesson 10: Programming Your Robot”

  1. Aghil.ts

    thanks …….
    its realy gr8 ……….
    i like it ,
    i want to study more……
    and how i find this materials ?

  2. cbenson

    You can either learn as part of a school or robotics club, start working with kits or read books. We are trying to put as much information in this blog as we can.

  3. sagy

    very usefull posts.. thank you very much … it has enlarged the picture of robot functioning. very beautifully sequenced explanations and hints .. really appreciate the knowledge and huge thanks for sharing it :)

  4. cbenson

    You are welcome. This is a preliminary set of lessons and we plan to improve and add to it.

  5. Rahul P

    Do you give any classes, Sir. These lessons have been really useful to me.

  6. cbenson

    Since we are an online company, we don’t have any locations open to the general public, and as such, cannot give in-person lessons. We may entertain the idea of online classes, but not at this time.

  7. Rahul P

    Is there any source to ask you any questions directly or personally, can i have you email id sir?

    Please dont take it in any bad side or something.

  8. cbenson

    Private questions regarding product selection and support can be asked via the RobotShop Support Center. More public or design related questions can be added to the RobotShop Forum.

  9. Ibukun

    Hi please for my final year project we are building a walking robot. We built the microcontroller from scratch and we wrote our code using mikroc for PIC. The problem now is we have done everything and we re testing the servomotors using a 9V battery that produces a 0.98Amps current. We are making a foru legged robot with 2 limbs each so we are making use of 8 servomotors. The problem is that the actuators have refused to drive the robot. One leg only works when we press the reset button but whenit reaches the 18.5ms pulse width it stops but the motion refuses to move to the next actuator. Please what can we do?

  10. cbenson

    Please contact us via the RobotShop Forum – the Blog is not the best place to do troubleshooting.

  11. Reisangdar

    I don’t hav any projects but m interested in robots…
    dat ws soooooooooooo… AWESOME:-))

  12. Reisangdar

    I don’t hav any projects but m interested in robots…
    dat ws soooooooooooo… AWESOME. :-))

  13. Anurag Verma

    Great Post …..I just have begun learning more and more about robotics and I think it is the best place to help me ….for now

  14. juzz

    it is really a big help for my self to know to a simple robot program thanks

  15. arjun

    it is not understand to all human so please write simple language and sent one copy to my email

  16. buzz

    hey its really cool but how do you start coding I cant open the transcript or anything the terminal on my computer is horrible because when I open its all like “need help sir” jeez plz help I also have rhino 3d and how do you design a robot on that thanks for the great blog

    • Coleman Benson

      The programming language is normally related to the choice of microcontroller, though if you have a single board computer, you have much more leeway. In regard to the 3D CAD program Rhinoceros, it’s really up to you as to what you want to design; the difficulty comes in materializing what you drew.


    What types of project i make for future for world,those are much required for this world please suggest me. I want to developed my own kit.

    • Coleman Benson

      If you are looking to develop / create a consumer product, it’s really up to you to research where there is the greatest need / market potential.

  18. Nagarjun me to bulid a small robot using c coding for my exibition sir.

    • Coleman Benson

      It’s best to create a new topic on the RobotShop Forum. Please explain what you have, your budget and what you want the robot to be able to do.

  19. ken

    I hope that there is a personal tutorial for robotics here in our country…. but thanks for this I learned a lot :)

  20. Joseph

    Thank for this website.. may send me a pdf sample of creating robots, please?

  21. ffdgdlgkj1

    sir i really want to learn robot programming please suggest any idea to learn robot programming using .net technology

  22. ALWAR

    sir your lessons are very interesting and great .iam from india i have an project in real time. ofcourse i am contractor for tamarind grading and packing . our customers are noticing me that tamarind seeds in packing ,so i want to rectify this problem . kindly give an suggestion which robot is suitable to my work and is it possible in low cost .
    give me reply to my mail id :

  23. Uzyer Razin

    I bookmarked this web. I will come back to continue next posts.Thank You very much for these posts. Have a good day.It’s very useful for everyone for sure.

  24. Classnikz

    I bookmarked this web. I will come back to continue next posts.Thank You very much for these posts. Have a good day.It’s very useful for everyone for sure.

  25. Nick Halterman

    Im having troubles installing the software. Help please?

    • Coleman Benson

      For technical support, it’s best to contact us via the RobotShop Forum with additional details such as which microcontroller you are using, which software you are trying to install, and any errors you get.

  26. Ronald Candil

    I love to study robotic even though i have no robotics materials.

  27. Aditya Gupta

    I love the information you share it really help me a lot but i want to study more about robot programming in more details so that i can explore more about it

  28. chandan

    hey sir please give me programing of temperature based speed of the fan controolled using avr

    • Coleman Benson

      @chandan For troubleshooting and technical support, please create a new topic o the RobotShop Forum and we would be happy to help.

  29. denish patel

    What basic thing to study for robotics progrmming? i know programming.


    sir,please tell me the best robotic programming book name in c language

  31. Joriza Mae

    Nice day Sir!,I was very interested when I read this online article about robotics since I am a Computer science student..but what programming language would i choose so that my robot can talk ?is C++ a useful language and how?

    • Coleman Benson

      @Joriza Mae Do you mean “communicate” as in send data, or actually “speak”? If you mean “speak”, you can use C++, but voice synthesis is really not easy if you start from scratch, and we suggest using a computer, or voice synthesizing module.

    • Coleman Benson

      @lisa “logic” normally refers to the main processor, but the word “logic” is simply a noun, and you need to add context.

  32. lisa

    what are some problems programmers face when programming a robot?

    • Coleman Benson

      @lisa Anything and everything, from not knowing how to begin or lacking knowledge, to the program not working at all or doing something which it was not supposed to do.

  33. happy verma

    iam confusing and want to know that which language is best to do and go with for robotics and also for advanced robotics including some ai techniques

  34. Omkar More

    Please, Suggest for beginner like me, Want to participate in ROBOCON Compilation Of Robotic programming .

  35. KKK

    hi ,want to learn robot programming using c# plz guide me how to go on this way

  36. rushikesh dhuve

    HIIII i want to create a robot using c language plz help me …….

  37. fahad

    It was a very important guide shall I can download this guide as PDF file

  38. Parag Kulkarni

    Hi Benson Sir, Firstly thanks for knowledge sharing approach. I am new in robotics but familiar with C language & created basic gui, game programs etc. Not having microcontroller knowledge. How can I obtain the required knowledge which help in my project. But I need to create my own unit and C program to control fan operations. I would request you to pls guide me from where should I start and what links or material will help me in achieving this complete project pls pls. thanks in advance. Looking for your seriius help as I am really passionate to do that. pls help. thanks.

    • Coleman Benson

      @Parag You need to create your own microcontroller breakout board and then program it in C? If this is the case, you’ll need to choose a C-compatible chip, learn how to create electronics and printed circuit boards (or use a breadboard for prototyping), and learn how to code in C (eiting teaching yourself from a book or online lessons).

  39. shreyas

    I want to create a human detection robot with raspberry pie and I want your help plz guide me I want this robot in the for of spider …..plz tell me which equipments will be needd for this and which language should I prefer

    • Coleman Benson

      shreyas Do you mean in the form of a spider? You should separate your robot into many sub-projects, such as the platform itself, the walking algorithm, and the “human detection” part. We don’t have a complete kit which meets all of your criteria, so what you are doing is building a custom robot.

  40. Pranali

    Hello Sir, these posts were really helpful. Do you know any books that I can refer to for learning more about Robotics ? I am a complete novice and except these articles I know pretty much nothing about the subject.

  41. csan

    sir i want to be robotics engineer and i have keen interest in do you have any idea. i want to develop robots too.

    • Coleman Benson

      @csan The best approach is to follow engineering at university, but theknowledge you gain from simply working on and building your own robots will be most important.

Leave a Reply

  • (will not be published)