Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IoT / Arduino

Arduino Unleashed

4.90/5 (19 votes)
18 Sep 2010CPOL8 min read 176.9K   679  
This article is all about empowering you with more powerful tools that let you unleash your creativity without being limited by the default IDE.

What is this Arduino Thing?

Straight from the horse’s mouth

Arduino is an open-source electronics prototyping platform based on flexible, easy-to-use hardware and software. It's intended for artists, designers, hobbyists, and anyone interested in creating interactive objects or environments.

Actually Arduino is a lot of things. Given a specific context, it may mean any of the following…

  1. Arduino – The hardware platform (“the board”)
  2. Arduino – The abstraction library over WinAVR. WinAVR is the GNU tool chain (Compiler + C Runtime library etc.) for the AVR microcontroller used in the Arduino boards (“the software”)
  3. Arduino – “The IDE” (We’re using Arduino 19)

Here is a picture of the specific variant of Arduino I am using (It’s called the Freeduino serial board):

http://www.freeduino.org/bf-analyze/images/freeduino_maxserial_500.jpg

Figure 1 Freeduino-serial board (with ATMega328)

Show Me Something Interesting

Here you go, but remember to come back!

  1. Makezine Arduino archive
  2. Electronics lab Arduino archive

My Hands Are All Itchy, Where Do I Start?

First of all, you need to familiarize yourself with the Arduino platform and play with the Arduino IDE which is freely downloadable from the Arduino website.

Being the expert programmer that you are, you’ll soon realize that your hands are itchier but the Arduino IDE is getting in your way of alleviating that itch. What you need is a more powerful set of tools. I recommend using the combination of WinAVR + Arduino Library + Eclipse and this is what we will explore in the rest of this article.

So What’s This Article About, Again?

This article is all about empowering you, the expert programmer (for almost any definition of expert ;)), with more powerful tools that let you unleash your creativity without being limited by the default IDE.

With Eclipse, you will have code completion, better code navigation, syntax highlighting and the whole shebang!

So from here onwards I am assuming that you have already familiarized yourself with regular Arduino development. If not, then go ahead and do it (should not take too long) then come back for a better deal or just stay the course if you don’t mind a little suspense.

Show Me the Way

Alright then, here are the steps to Arduino nirvana…

  1. Download Eclipse (about 90 MBs). Unzip it to C:\Misc\Eclipse
  2. Download the Arduino IDE. Unzip to C:\Misc\arduino-0019
  3. Download the latest version of WinAVR. Unzip to C:\Misc\WinAVR
  4. Download the AVR Eclipse plug-in and install it (follow the instructions on their website)

Starting Eclipse and Trying on a Sample Program for Size…

  1. Start Eclipse

    Image 2

  2. Dismiss the welcome page by clicking the cross on the tab to reveal the actual work environment…

    Image 3

  3. Start a new project by clicking on “File->New->C++ Project”. Choose the “AVR Cross Target Static Library” project type and set the project name to Arduino. We are now going to compile the Arduino source files into a static Library for later use. Finally click on finish.

    Image 4

  4. Use Windows Explorer to go to C:\Misc\arduino-0019\hardware\arduino\cores\arduino, select all the code files and drag them onto the Arduino project already open in Eclipse. Note only include files with the extensions .c, .cpp and .h

    sshot1.jpg

  5. Next click ok on the following dialog (accept the default copy option)…

    Image 6

  6. Now build the project by right clicking on it and choosing “Build” from the context menu. Horror of horrors we have 10 build errors…

    Image 7

  7. But don’t worry, we’ll fix them in a moment. Right click on the project and choose “Properties” and go to the “C/C++ Build -> Settings->AVR Compiler” option. Click on the “+” icon (after selecting the “Directories” option).

    Image 8

  8. Click on the “Workspace…” button and add the project directory “${workspace_loc:/${ProjName}}” as an include directory once for the “AVR Compiler” and again for the “AVR C++ Compiler”

    Image 9

  9. Right click on the project and choose “Properties”, then go to “AVR->Target Hardware” and then set the MCU Type option to the Microprocessor being used on your Arduino board along with the frequency of the crystal supplied with it. For me, it’s ATmega328P and 16,000,000 respectively. Then click on ok.

    Image 10

  10. Now build your project again and the build should succeed this time. Though you might get a bunch of warnings (21 in my case), just ignore them for now.

Das blinkenlights

  1. It’s time now for the “Hello world” equivalent of the embedded systems world. Go to “File->New->C++ Project” as before but now choose “AVR Cross Target Application” as the project type and set the project name to “BlinkenLights

    Image 11

  2. Right click on the BlinkenLights project and choose “New->File”, set the file name to Main.cpp and click on Finish.

    Image 12

  3. Now add the following C++ code to Main.cpp:
  4. C++
    #include "WProgram.h" //Include arduino headers
    
    ///CONSTANTS///
    //The onboard test LED is connected to pin number 13
    const int ledPin = 13;
    const int interval = 1000; //Milliseconds
    
    ///MAIN///
    int main()
    {
        //Initialize the Arduino library.
        //Not doing so will prevent the delay function
        //from working. Calling this functions is a must
        //for all arduino projects.
        init();
    
        //Initialize the serial port. This will be used
        //to send diagnostic information in this project.
        Serial.begin(9600);
    
        //Configure ledPin as an output
        pinMode(ledPin, OUTPUT);
    
        //Announce the start of program. Usually a
        //hyper-terminal is connected to the serial
        //port on the PC so this message can be seen
        //there
        Serial.println("Ready.");
    
        //Enter the infinite loop responsible for making
        //the microcontroller do the same thing over and
        //over again. (Almost every microcontroller has
        //such a loop)
        while(true)
        {
            //Turn on the LED
            digitalWrite(ledPin, HIGH);
            //Wait for half of "interval".
            //The LED remains ON during this time.
            delay(interval/2);
            //Turn off the LED
            digitalWrite(ledPin, LOW);
            //Wait for half of "interval".
            //The LED remains OFF during this time.
            delay(interval/2);
        }
    
        //Unreachable code but it's required by
        //the compiler
        return 0;
    }   
  5. Now compile the project. Whoa, a whole bunch of errors!

    Image 13

  6. Ok let’s fix them. Right click on the “BlinkenLights” project and choose “Properties” and go to the “C/C++ build->Settings->Avr Compiler->Directories” option and click on the “+” icon.

    Image 14

  7. Then click on the “workspace…” button on the subsequent dialog and then choose Arduino->Debug in the sub-subsequent dialog.

    Image 15

  8. Finally you should see the following. Click on ok after you have verified the path.

    Image 16

  9. Do the same for “C/C++ build->Settings->Avr C++ Compiler->Directories”
  10. The go to “C/C++ build->Settings->Avr C++ linker->Libraries” and set the following options.

    Image 17

  11. Now compile the BlinkenLights project again.

    Image 18

    Ok that’s much better now but we still have one error to go. This is a linker error. The linker is complaining here that it could not find an implementation for the function called __cxa_pure_virtual anywhere though it is being referred to/used in other parts of the code. Hmm I hear you say “It’s a lie the function name doesn’t even suit my taste, why would I use it?!” Well I hear you alright but the thing is you are barely getting started and you haven’t seen all the code being used behind the scenes yet.

    Suffice it to say the function is required by the C++ runtime to decide what needs to be done when someone calls a pure virtual function directly. As you’ll remember from your dealings with C++, a pure virtual function cannot be called directly without providing an implementation in some derived class. Well for that matter, a class with a pure virtual function cannot be instantiated at all but the C++ runtime likes to be prepared for any and all eventuality.

    Advanced compilers would have thrown an exception from this function to signal an illegal operation but since we do not have those on the WinAVR platform, all we can do is prevent further harm from being done by entering a never ending loop (assuming the program is running amok in the first place since it has done the impossible by calling a pure virtual function directly!)
    Note: This needs to be done only for the debug build. This function is apparently not used in the release build of Arduino. The debug builds are rigged to fail fast so that the point of failure is as close as possible to the place where the real problem is.

    So here’s how we get rid of the above error…

  12. Add a new .c file to the Arduino project (note it should be .c and not .cpp). Call it missing.c and paste the following code in it and build both projects again. The error should go away. Note you need to build Arduino before you can build BlinkenLights.
    C++
    void __cxa_pure_virtual()
    {
        while(1);
    }
  13. On switching to the “Console” pane, you can see the result of running the avr-size command on the generated .elf file…

    Image 19

    But it is not a pretty sight to behold. A meager led blinking program occupies about 62% of the whole of available program memory. But don’t be alarmed, we are in the debug build and such bloat is par for the course. You will get better results when you switch to release builds.

Switching to the Release Build

  1. Right click on a project and select “Build configurations->Set Active->2 Release”. Do this for all projects. Also please let me know if you find a way of doing this for all projects at once.
    Note: You need to re-specify all the settings for the release build like you did for the debug build in order to make it compile.

    Image 20

    Hmm, much better, but still not good enough 18% for BlinkenLights is still too much.

Premature Optimization Not the Root of All Evils?

  1. Here’s how we go from better to impressive. The following will ensure that you only pay for those functions and data-sections which are actually being used in the program. Add the following additional flags to both the C and C++ compilers in all projects
    -ffunction-sections -fdata-sections 

    Image 21

    Add the following flag to the linker options in all the projects.

    -Wl,-gc-sections  

    Image 22

  2. Rebuild them (in the correct order Arduino first, BlinkenLights second.)

    Image 23

    What a relief!

Uploading your Program to the Arduino

The time has now come when you can upload your very first Arduino program built within the comfy confines of Eclipse.

  1. Right click on the BlinkenLights project and select “Properties”. Go to the AVRDude page and click on new.

    Image 24

  2. Fill the form as follows:
    • Configuration name: Arduino
    • Programmer Hardware: Arduino
    • Override default port: \\.\COM3. Replace COM3 to whatever port the Arduino hardware is connected to.
    • Override default baud rate: 19200. Replace 19200 to whatever baud rate was specified by your board manufacturer / the person who uploaded the Arduino boot loader onto your board.

    Image 25

  3. Select Arduino as the programmer in AVRDude settings and click OK.

    Image 26

  4. Click on the AVR toolbar button to upload your program to the board.

    Image 27

    You should see something like the following in the console window…

    Launching C:\misc\WinAVR\bin\avrdude -pm328p 
        carduino "-P\\.\COM3" -b19200 -Uflash:w:BlinkenLights.hex:a 
    Output:
    
    avrdude: AVR device initialized and ready to accept instructions
    
    Reading | ################################################## | 100% 0.02s
    
    avrdude: Device signature = 0x1e950f
    avrdude: NOTE: FLASH memory has been specified, an erase cycle will be performed
             To disable this feature, specify the -D option.
    avrdude: erasing chip
    avrdude: reading input file "BlinkenLights.hex"
    avrdude: input file BlinkenLights.hex auto detected as Intel Hex
    avrdude: writing flash (2828 bytes):
    
    Writing | ################################################## | 100% 2.16s
    
    avrdude: 2828 bytes of flash written
    avrdude: verifying flash memory against BlinkenLights.hex:
    avrdude: load data flash data from input file BlinkenLights.hex:
    avrdude: input file BlinkenLights.hex auto detected as Intel Hex
    avrdude: input file BlinkenLights.hex contains 2828 bytes
    avrdude: reading on-chip flash data:
    
    Reading | ################################################## | 100% 2.14s
    
    avrdude: verifying ...
    avrdude: 2828 bytes of flash verified
    
    avrdude done.  Thank you.
  5. If everything went right, the on-board test LED (usually red in color) should now start blinking at about 1 blink/sec. Congratulations!

In Conclusion

We have finally seen how to use Eclipse for AVR development. But this is only the beginning. I have shown you how to catch fish and also given you a small fish for today, but tomorrow you must catch your own! Well actually what I mean is… there’s still a lot to explore but I have shown you the basics and you should now be fine on your own. The examples and libraries supplied with Arduino should be a good place to start for further exploration.

History

  • 16th September, 2010: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)