103

What are the advantages of each language when using the Arduino?

I'm thinking this is a good general question, but I'll add a bit about why I'm asking if anyone wants to give me a tip.

I'm experienced in preprocessed languages like JavaScript, PHP, and have fiddled with languages like Java and Visual Basic. In other words I know programming techniques and both classical and prototypal object orientation, but nothing about communicating directly with hardware.

I'm making an octocopter, and am thinking that an object oriented approach will be the easiest. (The software will have very many features...) However I have never written in C++.

Since this is a Q&A site that's supposed to help others, only the general question presented at the beginning is of much importance, but I'd appreciate any comments on my situation.

9
  • 23
    Avoid Arduino IDE as it does not deserve its IDE name, it is even a very poor editor: it may be good for beginners and simple sketches but one should rapidly go to something better .
    – jfpoilpret
    Commented Mar 20, 2014 at 0:22
  • 8
    This is a fairly succinct breakdown of what is meant by (and what's actually under the hood of) the "Arduino Programming Language." Commented Nov 15, 2015 at 22:21
  • 16
    C++ vs. The Arduino Language? - The "Arduino Language" is C++. There is a bit of preprocessing to save you doing function prototypes, but it most definitely is C++.
    – Nick Gammon
    Commented Mar 5, 2016 at 7:02
  • 3
    There is no such thing as arduino language. It is simply a library.
    – Overdrivr
    Commented Mar 5, 2016 at 11:50
  • 2
    Not so related to the question as to the comments: Atmel studio is free and IMHO it is better than visual studio for arduino programming. Also supports Visual Micro plugin, although it is not necessary at all for programming and debugging arduinos.
    – cyberponk
    Commented Apr 12, 2017 at 18:25

9 Answers 9

66

My personal experience as professor (programming, mechatronics) is that if you have previous programming experience and you are aware of concepts as OOP, it is better to go for C/C++. The arduino language is really great for beginners, but have some limitations (e.g. you must have all your files in the same folder). And it is basically a simplification of C/C++ (you can practically copy&paste arduino code to a C/C++ file, and it will work). Also it makes sense that you can go and use a full well known IDE as eclipse:

http://playground.arduino.cc/Code/Eclipse

Initially it is required a bit more of setup and configuration of your dev environment, but IMHO it is worth it for programmers with experience in any other language.

In any case, it won't harm you to start using the arduino language and the arduino IDE for a few days to get familiar with the arduino hardware and then move to C/C++ with Eclipse for really developing your project.

14
  • 1
    There is a nice book "C Programming for Arduino" by by Julien Bayle which is useful. It is C not C++ language but should help you to understand the basis.
    – fenix688
    Commented Mar 19, 2014 at 15:55
  • 1
    C++ supports OO features, C language does not.
    – Chris O
    Commented Mar 19, 2014 at 17:33
  • 3
    Why on Earth would you need folders for your Arduino code? It only has 32kb to work with. I really don't see why so many people dislike the Arduino IDE so much. It is fine for what it's meant for. I wish it had an integrated emulator though so I didn't actually need to wire up LEDs to test things and Intellisense would be nice but it is still as helpful as it needs to be.
    – krowe
    Commented Mar 20, 2014 at 9:48
  • 1
    @FriendofKim Not exactly what I meant (though technically you could, the Due is fast enough to support a software solution for non-megabit serial communication, and it does have 5 U(S)ARTS in total while the Arduino libraries only provide 4 of them but iirc the Due board does not provide pins for one of the USARTs anyway); the Arduino libraries configure the USARTs to use asynchronous mode, but I needed synchronous at up to 6Mbps (and I had to use SPI mode as the input had to be treated as a raw bitstream so no stop bits/etc.), which also involved modifying the default PIO controller config.
    – JAB
    Commented Mar 21, 2014 at 13:18
  • 1
    As a professor you should know that there is no "Arduino language": It's C++ with Arduino specific libraries.
    – RichieHH
    Commented Mar 19, 2019 at 2:03
53

In theory...
There isn't really an Arduino language as such. It's really just C++ with some domain-specific libraries. These add on various features, such as functions you can call to control the hardware. If you didn't have those functions, you'd need to fiddle directly with special registers to control everything. That's how embedded programming is usually done. It's fast, but it can be quite hard to learn and understand.

In addition to the functions, the libraries add alternative names for some types. For example, boolean and byte are not in the C++ standard. However, they are directly equivalent to bool and unsigned char.

All of these things mean you can probably port general C++ code directly to Arduino without difficulty. However, going back the other way may require some minor editing.

But note that not all features of modern C++ versions are available on all Arduino platforms. In some cases, they aren't realistically possible, such as std::thread on an 8-bit microcontroller. Others simply haven't been made available, such as std::array.

In practice...
Having said all of that, programming for Arduino isn't exactly the same as general C++ programming. A lot of the differences are common to all embedded programming though (such as limited memory and processing power).

It's also worth noting that if you're using the official Arduino IDE then there are all sorts of annoying quirks and limitations on how you setup your code. There are workarounds in all cases (as far as I'm aware), but they are sometimes quite frustrating.

For full flexibility, use a third-party IDE (such as Eclipse) with a plug-in to support Arduino. That should give you all the advantages of C++, along with the Arduino libraries.

1
28

What are the advantages of C++ vs the Arduino language when using Arduino? I'm experienced in preprocessed languages like JavaScript, PHP, and have fiddled with languages like Java and Visual Basic.

First, the Arduino compiler/IDE accepts C and C++ as-is. In fact many of the libraries are written in C++. Much of the underlying system is not object oriented, but it could be.

Thus, "The arduino language" is C++ or C.

C++ is not garbage collected. It does manage variables in scope - if you write:

int led = 13;

void blinkTimes(int value)
{
   int i;

   for(i=0;i<value;i++)
   {
      digitalWrite(led, HIGH);
      delay(1000);
      digitalWrite(led, LOW);
      delay(1000);
   }
}

Then you'll find that led and i don't grow or leak, no matter how many times you call blinkTimes.

If i were a class, it would similarly be disposed of once the function ended. So as long as you aren't using new or similar memory allocation functions to create new objects, then you won't have to worry about leaks.

You may still run out of memory, if you create huge classes and use a lot of them in deeply nested functions, but in general you aren't going to run into trouble until you start dealing with new and free functions.

If you are using new, then you'll have to call delete at appropriate times. C++, and by extension Arduino, has no automatic garbage collection, you have to explicitly manage your own memory.

1
  • 1
    Okay, if instantiated objects (with new) aren't garbage collected, I'll have to learn that as well. I suppose any book on C++ will cover that. Thank you for a good answer! Commented Mar 19, 2014 at 18:44
17

--- Update 170412
I wrote my original answer three years ago from the perspective of there existing a distinct "Arduino C++". The language used in the IDE is standard C++, because it is implemented by the GNU C++ compiler. "Apparent" differences creep in because the IDE will do some pre-processing to help newcomers to the language avoid a couple of 'gotcha's, by filling in some #includes, f/ex. But you can - and I do - write correct C++ to it and get just what you expect to get.
--- end update

Do limit your use of C++ language features to those whose implementation you fully understand. There are some features that compile to more resource-intensive code than is obvious from reading the source code. The optionally generated .lss (merged source and assembly) listing can give you some good insight into what the C++ compiler did when you weren't looking.

To your question about memory: C++ does not garbage-collect. Stack-based languages like C and C++ do allocate temporary storage on the stack for automatic variables at function entry, which then gets released when the function returns, but this is not true garbage-collection. Objects created in heap- or global memory live until you explicitly delete them. Make sure you know where, when, and for how long different kinds of objects will be created. You really don't want your code new-ing and delete-ing objects willy-nilly. They will be built in heap memory, fragmenting it and causing it to grow up into the stack. That's when your code - and your nice 'copter - will crash.

C does less for you so it can do less to you. It's not a bad choice. C with a few of C++'s features can be an even better choice, given you choose the extra features judiciously.C++, if those are your two choices:

[Original answer] - C++ is a standardized language. It is widely deployed in many environments including embedded systems and therefore is more thoroughly tested than the very-like-C++ language that is "Arduino". This is especially important for mission-critical / safety-critical applications such as you are planning. Crashed code means a crashed 'copter and even if it doesn't hurt someone, it will break your expensive machine.

  • Being standard, C++ is portable. Need to upgrade your processor? Everything but silicon-specific code will port to the new one. Need to change your toolset, development system, host OS? C++ will be supported everywhere. Though Arduino IDE will run anywhere Java is supported, it is the only tool that uses Arduino C++ and it is a very limited tool. If you want to use Eclipse, the AVR tools, go barefoot on the command-line, develop within Emacs, or whatever other environment you prefer, standard C++ will be supported.

  • The Arduino IDE does things behind your back - specifically, it #includes .h files when it thinks you need them. Even if it is correct, you really want to write, or at least see and understand, everything the compiler is going to see. Programming languages aren't made for computers (computers eat bits for breakfast); they're made for people, specifically the people who follow you on the project, the most important of whom may be ... you!, when 6 months after you wrote a module, you have to come back to enhance it, or more likely, fix it. You really want to be able to see everything the compiler sees.

7
  • 2
    This is a REALLY good answer. It seems clear that you like C++ and that I should like it as well! ... But seriously, I'll jump right onto C++ as soon as I've understood how the "communication" with the different sensors etc. work. Commented Mar 19, 2014 at 18:49
  • Do you know any good books on the subject? (Suited for me who have been programming for years in other languages, and only need the "embedded part" of C++.) Commented Mar 19, 2014 at 18:50
  • Do you think Accelerated C++ is a good book for this? Commented Mar 19, 2014 at 18:58
  • 2
    I wish I could help you with the 'right' book, but I came to C++ with a whole lot of C behind me and Kernighan & Ritchie's The C Programming Language is still my go-to book (bad pun) for anything not explicitly C++, and Ellis & Stroustrup's The Annotated C++ Reference Manual for C++. But for writing to hardware, you'll do well to look at some of the device libraries contributed by users at Arduino.cc. Start off tweaking I/O ports with pinMode(), digitalWrite() and digitalRead() functions, then their analog i/o counterparts, and eventually, ...
    – JRobert
    Commented Mar 19, 2014 at 21:21
  • 1
    ... plan to write directly to I/O registers for speed and memory-space improvements. Programs like blinky.cpp and hello.cpp are good places to start messing around with hardware. Add a simple multimeter, and a few LEDs with the right current-limiting resistors permanently soldered to one leg and you should be able to see real, if simple, results from your efforts. After that, read data-sheets for any hardware that interests you to learn what signals you can read / must write to them to make them play. Temperature sensors are easy to use and doesn't everyone need a fridge logger? Have fun!
    – JRobert
    Commented Mar 19, 2014 at 21:30
15

The Arduino language is C++, but it is very different from most C++ varieties. The Arduino language has a lot of abstraction built in, especially in the hardware interfaces, which makes it very simple to use. If you have a background in Java, C and C++ should be very similar.

The main differences between Arduino and C++ are in the memory storage. Usually a modern computer has more than 2GB of RAM, while the Arduino Uno has 2kB (1 million times less). The Arduino also uses 8-bit instructions in stead of the 32 bit ones a computer uses. This will mainly affect the amount of information you can store in a variable.

If you are very new to the Arduino world, you should look up a tutorial, as there are many good ones out there.

7
  • You mention memory. I have the Due which has got 96KB of RAM. But the last thing I want is for the copter to crash because of a memory leak (having a very expensive camera mounted on the copter). Commented Mar 19, 2014 at 15:29
  • Is memory in C++ handled automatically (like the garbage collector in Java) if not specified otherwise? Commented Mar 19, 2014 at 15:30
  • 2
    The C++ standard makes no guarantees about memory sizes - c++ already runs on embedded hardware without modification. Commented Mar 19, 2014 at 16:00
  • 2
    You are describing differences between the hardware platforms, not C++ there though. Commented Mar 19, 2014 at 16:12
  • 5
    @FriendofKim In C++, there are two different ways of instantiating variables/objects. If you instantiate them locally (e.g. int blah = 5;) then they will be destroyed automatically when they go out of scope (i.e. at the end of the loop or function). However, if you instantiate them on the heap (e.g. int *blah = new int(5);) then you need to release them yourself. It's not usually wise to use heap data in embedded programming though. Commented Mar 19, 2014 at 16:43
12

In my experience, it is best to avoid new and delete when running on machines with limited memory.

  • The memory management itself uses valuable program and RAM space
  • ISR vectors are set at compile tme. It is difficult (impossible?) for a class instance to claim an ISR at run time
  • Generally you will know at compile time what class instances you need - e.g. 3 button debouncers, a display driver and a 2-line display driver
  • Memory management introduces unknown delays when you use new or delete.

There may be cases where it is justified to use dynamic instance construction and destruction, but I suspect they are rare.

3
  • Being completely new to C++, I have a followup question regarding the STD. Is it a bad idea memory wise to use it? If not, how can it be added (Eclipse)? I've set up the AVR compiler and its working well. Commented Mar 31, 2014 at 9:53
  • 1
    All what you say is correct but I don't see how this is an answer to OP question. new and delete are available in Arduino IDE too.
    – jfpoilpret
    Commented Mar 31, 2014 at 11:06
  • It's not an answer, but very helpful information that I really appreciate. Commented Mar 31, 2014 at 13:32
9

As mentioned in several answers, if you are programing an embedded system in general you should avoid new unless you are managing your own memory heap and you really know what your object life cycles will be. Static allocation or stack variables are much safer. That said, one common trick to manage things like variable length buffers allocated for the duration of a function is to have an automatic variable (on the stack) that is an object that calls new in its constructor, and then put the delete in the destructor so when the object goes out of scope the buffer is released back to the heap. Again, this is usually of limited use in little micros but it is a nice pattern to remember.

8

In addition to the comments above, I would like to further stress the problems with working RAM that you have on Arduino boards, particularly with the Uno (and others that share the same microcontroller). I recently wrote a simple Space Invaders game running on a 32x32 LED matrix and repeatedly ran into problems caused by low memory.

The Uno only has 2048 bytes of RAM. The library for my matrix took over 3/4 of that leaving me with around 400 bytes for the game. As it is my intention to "upgrade" the project at some point to run multiple games with the same program base on the more powerful Due, I designed the code with OO principals and a lot of class inheritance. (The game class was inherited with virtual update and draw calls, the game entities were all inherited).

I pretty much ran out of memory just adding the invaders. I tried to save memory by bit-fielding their member variables but ran out again when adding the shield objects. After a bit more scraping I ran out adding the bombs/bullets. At this point I scoured the code and removed all "virtual" tags (all my class prototypes are built from a Visual Assist snippet and destructors are all virtual automatically). This halved my memory usage instantly, freeing enough to be able to complete the code.

Long story short, the end result is C++ code that doesn't really use any C++ features. You might be as well just sticking to C and being very aware of your memory usage. You get no help if you exceed the 2KB - particularly if you are using any dynamic allocation, the code just stops working and you are left scratching your head for a while until you consider the possibility of memory overflow.

PS - Bit fielding variables is bad. Very bad. Apart from adding processing overhead, I lost track of the number of times I'd add a new state to the game but the code wouldn't run and I couldn't understand why. My state variable was not wide enough to hold the new state value so I was getting some unexpected state.

1
  • This is a pretty useful anecdotal answer detailing how OO C++ sucks for small embedded. I'll be sure to stick to procedural programming when using C++ on Arduino. Commented May 7, 2020 at 7:36
6

Arduino is C and C++ (it is a mix of the two, linked together); there is no "Arduino" programming language

The Arduino language is C++ (albeit usually implemented in a style more like "C with classes," which is actually fairly common in the embedded systems microcontroller world). End of story. Enough with people thinking it's a different language already! It uses the g++ compiler.

Proof:

Enable verbose output during compilation in the Preferences and upload and you'll learn a lot just reading those lines.

Here's some additional insight:

My own words:

Arduino code is C++. The Arduino core functions are simply a set of C++ classes and libraries you can use. It is built and compiled using the GNU gcc/g++ compiler. Your setup() and loop() functions are simply placed into the mandatory (meaning: required by both C and C++ in order to even be considered a valid program) main() function (right here actually--notice the file is main.cpp, which is a C++ source file) automatically for you and there is some extra preprocessing done to make sure it is a valid C++ program (ex: scanning for all function prototypes [aka: declarations] for you so you can use a function even though its prototype comes later in your .ino file). Much of Arduino is written in C, however, and therefore requires the # extern "C" {} braces around it to prevent C++ from "name-mangling" (also known as "name decorating/name decoration") function calls to C functions implemented by AVR-libc, which is the C implementation for the ATmega328 and other AVR-architecture microcontrollers.

Arduino's words:

"Can I program the Arduino board in C?
In fact, you already are; the Arduino language is merely a set of C/C++ functions that can be called from your code. Your sketch undergoes minor changes (e.g. automatic generation of function prototypes) and then is passed directly to a C/C++ compiler (avr-g++). All standard C and C++ constructs supported by avr-g++ should work in Arduino. For more details, see the page on the Arduino build process."

Source: https://support.arduino.cc/hc/en-us/articles/360018448219-Can-I-program-the-Arduino-board-in-C-

When to use the Arduino library vs pure C or C++?

So, use the Arduino language where it simplifies things, and write your own functions where you need more specialization. I do recommend getting away from the IDE quickly though for writing code--just use it for compilation. Set the IDE preferences to use "External Editor." Then use a professional source code editor/IDE such as Sublime Text 3, Atom, Visual Studio Code, or Eclipse CDT to write your code. You can then click back to the Arduino IDE to compile and upload. If you go with Eclipse, there are ways to do that in Eclipse (see the other answers here, and see the Arduino playground Eclipse article here too) so consider using those techniques too.

Update: Eclipse setup

See my answer here and my document here: Eclipse setup instructions on a new Linux (or other OS) computer. I wrote a detailed PDF to describe setup.

2
  • 1
    As of 2023Q3, the main function has moved to architecture-specific repos, here are two examples, one for AVR: github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/… and another for ESP32: github.com/espressif/arduino-esp32/blob/master/cores/esp32/…
    – j0057
    Commented Jul 17, 2023 at 10:42
  • 1
    @j0057, on the AVR core in the first link, you found the C and C++ required main function. In the 2nd link, for ESP32, the loopTask function still isn't the C and C++ required main function, rather, it is a FreeRTOS task (thread) being spun up and called in the xTaskCreateUniversal(loopTask... call later in that same file. Point taken, though, I'll update my links in the answer. Commented Aug 8, 2023 at 17:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.