text:
C++ vs. The Arduino Language?
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.

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 .

Visual Micro (www.visualmicro.com) provides a plugin for MS Visual Studio 2013 - even the free/express edition. Visual Mirco is not itself free, but it does allow you to code with tools like intellisense and PROPER syntax highlighting, and even compile and upload to a processor (with a bit of wrangling to get set up).

This is a fairly succinct breakdown of what is meant by (and what's actually under the hood of) the "Arduino Programming Language."

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++.

There is no such thing as arduino language. It is simply a library.

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.

There is no Arduino language.

The Arduino language is a subset of Processing which is a subset of C++, and it has a few extensions that are taken care of in the precompile phase.  It doesn't have a formal name.  It just is what it is.  The IDE environment is definitely not a true IDE because it does not allow stepping through the programs, setting breakpoints, etc.  But with practice and judicious use of Serial.println statements it is easy enough to use.  Meanwhile, this question makes no sense since there is no other choice.

There are definitely subtle differences between C++ and whatever language Arduino uses that will cause experienced C++ programmers confusion. The most obvious of these is the presence of identifiers that don't require declarations from header files. But I suspect there are other differences as well. I declared a C++ global object, and I'm not convinced that the constructor is called like it would be in a C++ program.

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.

Thank you for your thoughts. I'll use the Arduino IDE to learn how to control all the different hardware pieces like sensors and LCD screens etc. Then I'll move up to C++ to make the software for the octocopter. Do you know a good and short book for people who know other languages? The "problem" with many books I've found is they include so much that I don't need because I'm on a small Atmel microcontroller rather than a UI computer.

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.

Thats a good request: a short and good book with the basics of C++ for programmers of other languages. Sorry I cannot give any recommendations, i am not aware of any good one. In fact, I wrote a book, with a practical focus (develop a videogame) for my students, but it is only in spanish. For a good and practical C++ book I would recommend Deitel&Deitel How to program C++, you could skip many advanced chapters.

C++ supports OO features, C language does not.

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.

"you can practically copy&paste arduino code to a C/C++ file, and it will work" Not just practically. Arduino code is written in C++, and if you examine the Arduino library source code you'll find that most/all the functions/classes in it are C++ wrappers around lower-level C libraries; I actually ended up modifying the library code for a project last year in order to use some more of the USARTs on a Due (the Arduino library makes assumptions about how many will be used and what mode they're in) while still being able to utilize the abstractions provided by the Arduino library.

@ChrisO OO features can be used (simulated) in C as well. However, you need to have a certain degree of familiarity with function pointers to be comfortable using this.

@JAB Huh? Are you implicating that all the UART ports can be used as both RX and TX if you modify the library? I mean, since there are 4 UARTs, could you actually get for example 8 RX instead of 4 RX and 4 TX?

@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.

Do you know if there is a reason why they put these limits on the board, when the microcontroller actually supports it? Or is it just bad programming?

@JAB Forgot tag.

@FriendofKim For simplification; one of the purposes of the Arduino project is to make programming embedded systems accessible to a larger audience, so all the detail and nitty-gritty gets hidden from the casual user (similar to Processing, which the Arduino IDE is actually based on). More advanced users who don't need all the abstractions/simplifications provided by the Arduino framework can still use it as a base for their own work if they don't want to rewrite everything on their own.

As a professor you should know that there is no "Arduino language": It's C++ with Arduino specific libraries.

Yeah, you probably want to tell the Arduino maintainers to change their front page for the Arduino documentation: https://www.arduino.cc/reference/en/, in which they define it as the "Arduino programming language". Maybe they don't know it is C++ with libraries either.

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.

Here's my setup for Eclipse, which works fine with Arduino. https://arduino.stackexchange.com/a/75491/7727. I don't use any Arduino plugins, just pure Eclipse for C/C++.

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.

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!

--- 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.

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.

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++.)

Do you think Accelerated C++ is a good book for this?

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, ...

... 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!

Note that the Ellis & Stroustrup book is thorough and wordy with lots of discussion around the bare information, so maybe not your basic quick reference, but you'd learn a lot about C++ and why it is what it is and does what it does. Someone may know of a denser, more reference-oriented book.

I recommend moving your update to the top. Otherwise readers are under the false premise Arduino isn't C++ until they get to your update. See my answer here for additional insight. https://arduino.stackexchange.com/a/50839/7727

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.

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).

Is memory in C++ handled automatically (like the garbage collector in Java) if not specified otherwise?

The C++ standard makes no guarantees about memory sizes - c++ already runs on embedded hardware without modification.

@MichaelThorpe I mean, do you have to specifically release memory when you don't need it anymore? Let's say you define 20 variables inside an infinite loop, will the memory be automatically released for every loop?

You are describing differences between the hardware platforms, not C++ there though.

@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.

It IS c++ with Arduino libraries.

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.

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.

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.

It's not an answer, but very helpful information that I really appreciate.

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.

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.

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.

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.

As of 2023Q3, the main function has moved to architecture-specific repos, here are two examples, one for AVR: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/main.cpp#L33 and another for ESP32: https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/main.cpp#L40

@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.


text:
Arduino unable to read from XBee Series 2
An XBee Series 2 is set to Router AT whose TX and RX pins are connected to an Arduino Nano's Rx and Tx pins respectively. The Arduino is connected to a Mac OSX via USB.
A second XBee Series 2 is connected to a Windows system via USB. It is set to Coordinator API mode.
Using the sketch below on the Arduino, a packet is sent from the Router AT XBee to the Coordinator API XBee, which is seen by XCTU as a Explicit RX frame. However the Arduino LED should blink once if it received a reply packet (should it?)
On another test, I wrote a script to send a frame for the Coordinator API XBee to send to the Router AT XBee. Once again the Arduino LED does not blink, and nothing is seen using Arduino's Serial Monitor.
Testing the Coordinator API XBee
Using the same script to send a packet from Coordinator API XBee to itself, the packet was received as well as a delivery confirmation packet. This shows that both the Coordinator API XBee and the script are working.
// Delivery confirmation
received:  { type: 144,
  remote64: '0013a20040a74613',
  remote16: '0000',
  receiveOptions: 1,
  data: [ 116 ] }

// Received the packet sent to itself
received:  { type: 139,
  id: 1,
  remote16: '0000',
  transmitRetryCount: 0,
  deliveryStatus: 0,
  discoveryStatus: 0 }

Testing the Arduino Sketch Code
Using the same Arduino sketch which continuously sends API frames to the Coordinator, I connected the Router AT XBee's RX pin to Arduino's RX pin, so the frames the Arduino are sending out are going back into its RX pin.
This causes the Arduino's LED to light up! So there is nothing wrong with the code.
Problem: Does this mean the Router AT XBee is not configured properly? I do not think its TX pin is damaged because XCTU can still read the settings off this XBee. Any ideas on how we can troubleshoot this?
Arduino Sketch (Connected to Router Xbee)
#include <XBee.h>

XBee xbee = XBee();
uint8_t payload[] = { 0, 0 };

// SH + SL Address of receiving XBee
XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x40a74613);
ZBTxRequest zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
ZBTxStatusResponse txStatus = ZBTxStatusResponse();

void setup() {
    pinMode(13, OUTPUT);

    Serial.begin(9600);
    xbee.setSerial(Serial);
}

void loop() {
    xbee.send(zbTx);
    delay(1000);

    xbee.readPacket();
    if (xbee.getResponse().isAvailable()) {
        // Response received, blink LED once
        Serial.println('resposne!');
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
        delay(1000);
    }
}

I'm a little confused about how you're sending the Router AT packet to the Coordinator in API mode. Sending out via AT is a Serial.print("sample");. Whereas the sketch you have above only shows us the Coordinator's outwards bound packet. Does that library handle AT mode as well? And what about addresses? You don't need to explicitly set the address outwards of the Coordinator (although it wouldn't hurt), the Coordinator should/can broadcast it's message. Can you confirm the ATDL of the Router is 0x0 or 0xFFFF if ATDH is 0x0.

Just as another afterthought, do put the pertinent XBee settings in the post to confirm you've got it right.  Copy them from the digi software. I just confirmed from https://code.google.com/p/xbee-arduino/ that the library doesn't work in AT mode. Also, it does require ATAP=2 so that's something else to check.

@Madivad I'm so sorry, the arduino code is for Router AT Xbee, not Coordinator XBee. Made the change in the question

As I mentioned in my comments to your question, if you are using this library
then it doesn't actually support AT mode. In fact, AT mode (otherwise known as Transparent Mode) is simply attached to the Serial port and accessed directly through the Serial object.
Example: put this into your Arduino attached to the AT Router.
#define LED 13

void setup() {
    pinMode(LED, OUTPUT);
    Serial.begin(9600);
    Serial.println("\nXBee AT communications test");
}

void loop() {
  static unsigned long previous = millis()/1000;
  if(previous != millis()/1000){
    previous = millis()/1000;
    char buffer[5];
    sprintf(buffer,"%04i",previous);
    Serial.println(buffer);
   digitalWrite(LED, !digitalRead(LED));
  }
}

Then open the console on the XCTU software on the API Coordinator watch the packets.

You will see above the received packets from the router. Because the coordinator is in API mode, you see it like this. (In AT mode, you will see the raw packets.
Ichose numbers to send because they are easy to read in this form. Packet 0102 appears in the packets data as 30 31 30 32 0D 0A
In AT mode there is no packet confirmation, validations, status or anything. They are all handled "transparently".
As a side note, I've seen many references that both XBees need to be in the same mode. That is, in fact, incorrect. If we modify our source to include Serial.read you would see data the other way as well.
edit: I thought I would add communications between AT Router and API Coordinator. I have modified the code in the Router to receive a constructed packet from the Coordinator via the XCTU software.
#define LED 13

boolean serialComplete = false;
char bufferIn[64];
char bufferOut[5];
int count=0;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);
    Serial.println("\nXBee AT communications test");
}

void loop() {
  static unsigned long previous = millis()/1000;
  if(serialComplete) {
    Serial.println(bufferIn);
    serialComplete=false;
    count = 0;
    memset(bufferIn,0,sizeof(bufferIn));
    digitalWrite(LED,!digitalRead(LED));
  }
  if(previous != millis()/1000){
    previous = millis()/1000;
    sprintf(bufferOut,"%04u",(uint16_t)previous);
    Serial.println(bufferOut);
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar == '\n' || inChar == '\0') {
      bufferIn[count++]=0;
      serialComplete = true;
    } else {
      bufferIn[count++] = inChar;
    }
  }
}

Then in XCTU construct a packet for the Coordinator. I'm using version 6.1.0.

and click "the create frame using form generator tool"

here is the packet being received by the router. I am only sending 9999 nul terminated.

Then once the pair are running, you can send the constructed packet from the XCTU software and it will be received by the router.

#include <XBee.h>
uint8_t text[] = {'H', 'e', 'l', 'l', 'o',' ','T','H','I','S',' ','I','S',' ', 'A','R','D','U','I','N','O'};
XBee xbee = XBee();
XBeeAddress64 remoteAddress = XBeeAddress64(0x00000000, 0x0000FFFF);//64 address of remote xbee:
ZBTxRequest zbTx = ZBTxRequest(remoteAddress, text, sizeof(text));// api 2 Tx request frame
ZBRxResponse zbRx = ZBRxResponse();// reading remote xbee response:
void setup()
      {
        Serial.begin(9600);
        xbee.setSerial(Serial);
        Serial.println("starting up yo!");
      }
void loop ()
      {
         xbee.readPacket();// This will read any data that is available:
         if (xbee.getResponse().isAvailable())//Now, to check if a packet was received:
          {
            if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE)
              {
                xbee.send(zbTx);//sending data to remote xbee:
              }
          }
      }

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Arduino as ISP without a computer
Has anyone seen or know of a method of preloading (using a computer or whatever) a firmware as data onto one arduino set up to operate as an isp and then using that arduino plug the isp interface into another and upload the firmware.
To be clear - i'm looking for a way to make uploading arduino sketches possible without a direct connection to a full blown computer.
Ideally the steps involved would be:

Write new sketch/firmware
Compile firmware
Write a copy firmware onto Arduino A as data (Arduino A is set up to work as ISP)
Detach Arduino A from the computer
In a seperate location attach Arduino A to Arduino B using ISP headers
Using some method (maybe a pushbutton) trigger Arduino A to upload the preloaded firmware onto Arduino B.

I'm assuming that theoretically it could work because uploading firmware is just an exchange of bytes across the SPI interface but i'm not sure about the reality.
The scenario for which I'm considering is if I were to install an arduino (permanently) in a location that is remote from my computer (I don't have a laptop nor do I want to get one) it would be troublesome to reprogram it.
The other method I have considered is using the DIL packaged ATMEGA which I can then remove from the board and program at the computer and return to the board - however I would much prefer not to risk bending of pins and the hassle of having to remove the chip each time I want to reprogram.

The result would be that you would only be able to program other Arduinos with the exact sketch/firmware that's been loaded into the programmer (Arduino A). So it would only be useful to make copies as in a production line, is that it? If you need to change anything on the sketch you would need to get back to the computer to modify and load it again. Did I get this right?

Isn't it possible to keep the "flash image" to be copied to the target on another support (like a SD card)?

Yea. I suppose it would also be good for a production line. My situation is I have an arduino glued into a enclosure that is difficult to move and it's in a different room to my computer (also difficult to move). So I would be happy to load the sketch onto Arduino A each time I wanted to change it.

It's been done for the limited purpose of programming a bootloader - https://github.com/WestfW/OptiLoader - but should work for any payload smaller than available flash minus the tool's size.  For a larger payload firmware, an external storage device (or simply an Arduino Mega?) should work.

@ChrisStratton that looks perfect for me to adapt. Thanks

Thanks to both the answers, I will get around to marking one as the answer soon. I just want to make it work first.

I think µProg – tiny, fast, portable AVR programmer with SD does what you want. You can store multiple files in the SD card (hex, eep etc) and select from the device menu which one to write to the target MCU without any need for a PC.
The best part is that it's available for free (PCB, schematic, firmware etc).

One of a kind, portable AVR programmer! Helps wherever you need to
update the device firmware, where target device is in a hard-to-reach
location and you can’t (or don’t want to) bring your laptop with a
bunch of wires with you. Trivially easy to use, super cheap to make,
super small, super fast, uses SD cards…
Features:

super small – dimensions 44 x 39 x 5,5 mm
super fast – write up to 12,5kB/s, read up to 14,5kB/s
uses cheap storage medium – small MICRO SD cards
supports FAT16 and FAT32 file systems
can read, write, verify flash and eeprom memory
can read, write, verify fusebits and lockbits
write and read to BIN, HEX, and TXT files
can set default values of fusebits, erase memories
cheap, easy to obtain, LPH7779 graphic display
shows funny animations after every operation
standard programming header – Atmel 6-PIN ISP
has a function of auto-update its own firmware (from SD)
very simple to use, 4 buttons navigation
user-setting menu
programming speed auto-selection (up to 4MHz)
Operates at 3V, programs chips supplied from 3V to 5V

Supported chip list

Looks good. Will investigate at the weekend.

I don't know how I missed this question the other day. I've only been talking to a friend about creating this exact project ourselves. And then I see your answer.

I have no direct solution for what you want, but yes it is possible to do it. You can hack a bootloader firmware so that it reads the firmware flash code and upload it over ISP.
Though you obviously can't upload 32k of firmware on the target AVR if both arduinos have only 32k of total flash in their MCUs, you'll need to have the flasher have more flash than the target if you want to do so (a 1284p or 2560 Mega will be far enough, or a 328/32u4 will be cood to flash a 168 or an attiny).
The only exception would be to have the firmware to be flashed way smaller than the total memory (like for a blink sketch).
In the end, that won't be easy, it's 100% pure AVR code, but you can do it. Have a look at:

The bootloader FAQ ;
The Optiboot Project which goal is to make the smallest bootloader possible and
AVRISP source code

The way I'd implement that would be to either make everything fit in the bootloader of the flasher device, so it reads the firmware (everything from 0x00 to the bootloader start address) and flashes it through ISP by merging AVRISP with Optiboot.
Anyway, that's an interesting project for a workshop about bootloaders and AVRs I may suggest at my local hackerspace! ;-)
HTH

Thanks, the AVRISP source code doesn't look as complex as I expected. I will look a bit deeper into this over the weekend

Where's your local hackerspace? :)

it's in France Le Loop

no problems, that's what voting up is for ;-)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Timer2 does not work as it should
I am currently playing with Arduino timers (on UNO currently) and I am building a library that  has a function that must be called every millisecond.
There is plenty of code samples on Internet so I went with something that seemed perfect for my needs. I have then updated it to make it a reusable C++ class.
Here is my code (simplified to just isolate the issue):
#define BIT(x) (0x01 << (x))

static volatile uint32_t milliseconds = 0;

class Timer
{
    public:
    Timer()
    {
        // Disable interrupts
        uint8_t savedStatus = SREG;
        cli();
        // Use Timer2 with 1 ms interrupts
        // OC2A & OC2B disconnected, mode 2 (CTC, Clear Timer on Compare match)
        TCCR2A = BIT(WGM21);
        // Don't force output compare (FOCA & FOCB), mode 2, Clock Select clk/128 (CS = 5)
        TCCR2B = BIT(CS22) | BIT(CS20);
        // Set timer counter compare match (when value reached, 1ms has elapsed)
        OCR2A = 125 - 1;
        // Reset Timer2 counter
        TCNT2 = 0;
        // Set Timer2 interrupt mode (Set interrupt on OCR2A compare match)
        TIMSK2 = BIT(OCIE2A);

        // Restore interrupt enabling state
        SREG = savedStatus;
    }
};

static void callEveryMillisecond(uint32_t ms)
{
    // Do something here
}

// Attach interrupt routine to the Timer Compare Interrupt
ISR(TIMER2_COMPA_vect)
{
    milliseconds++;
    callEveryMillisecond(milliseconds);
}

After checking ATmega328 datasheet (section 17) several times, I came to the conclusion that what I do in Timer class constructor above is correct, and for Arduino UNO, the values used must lead to one call of the ISR every ms:

CPU frequency = 16MHz
Prescaler = 128
-> timer frequency = 16MHz/128 = 125KHz
-> max counter value = 125

I decided to use the CTC (Clear Timer on Compare match) mode, which means that when the timer TCNT2 (which is incremented at 125KHz frequency), reaches OCR2A value, then it will trigger the ISR, and then will be reset on next tick; the additional tick to reset the counter explains why we use 125 - 1 for OCR2A and not just 125.
Now comes the weird stuff. In order to check that my code worked, I decided to blink the LED on pin 13 every 10 seconds, hence I have added the following code to my program:
static void callEveryMillisecond(uint32_t ms)
{
    if (ms % 10000 == 0)
        digitalWrite(13, digitalRead(13) ^ 1);
}

static Timer timer;

void setup()
{
    pinMode(13, OUTPUT);
}

void loop()
{
}

Then I measured the time during which pin 13 LED is lit on (or off, both measures are the same). Measures are not very accurate (I just used my wristwatch) but good enough for my check.
I was surprised to see the measured time to be about 20 seconds instead of 10s.
Initially I thought about a mismatch in CPU frequency, but after performing a lot of small changes, here is what I found which worked perfectly:
//static Timer timer;

void setup()
{
    static Timer timer;
    pinMode(13, OUTPUT);
}

Just moving the Timer instance into setup() did the trick: my measures rightly indicated 10 seconds between 2 states of the pin 13 LED.
Now my questions are:

Why the second code sample works perfectly, whereas the first does not?
Is there, in standard Arduino included code, some code that would overwrite some of the settings I perform for Timer2 in Timer::Timer()?
Is there a way to make the first code sample work? Note that I don't like the second sample because it does not seem natural coding, also, I will need access to Timer timer instance in several locations of my future program, hence it can't be possible if it is declared in the scope of setup().

Is there, in standard Arduino included code, some code that would overwrite some of the settings I perform for Timer2 in Timer::Timer()? You can easily check it, read the timer registers in the start of setup and send them through the serial port in the console to see if they match the values they should have.

Good idea! Initially I did not want to add Serial to the picture but that could help. However that will not tell what changed these register. I'll check that tonight and report back on the results.

We'll take it step by step, lets make sure first that something does change and then we can search further what changed the timer values.

I have located the source of the problem.
In file wiring.c (arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino) which gets called before setup(), there is the following part that tries to changes the timer 2 prescaller to 64 by setting the CS22 bit.
// set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
    sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
    sbi(TCCR2B, CS22);
#else
    #warning Timer 2 not finished (may not be present on this CPU)
#endif

You already set CS20 and  CS22 so this doesn't affect you. What does affect you is the following part which sets bit WGM20
    // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
    sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
    sbi(TCCR2A, WGM20);
#else
    #warning Timer 2 not finished (may not be present on this CPU)
#endif

and you have already set WGM21 so WGM21 and WGM20 set changes the timer mode to fast PWM , top=0xFF which gives almost double delay that the mode you were trying to use (CTC top=124).
How to workaround this issue?
Timer2 is used when its associated PWM pins are used with an analogWrite() call, so the Arduino setup code sets all prescalers to well-defined values just in case the timers might get used later.
I would not try to fight that code; instead, I would just make sure that my setup code runs later, e.g. by moving it to a separate setup() method in your Timer class and calling that from the global setup() routine.

Great! Do you have an idea why wiring.h does that? I mean, normally Arduino default libraries don't use Timer2 on UNO, so this behavior is strange.

Do you think there is a way to "disable" this code from wiring.h?

Timer2 is used when its associated PWM pins are used with an analogWrite, so the Arduino setup code sets all prescalers to well defined values in case the timers might get used later. I would not try to fight that code; instead, I would just make sure that my setup code runs later, e.g. by moving it to a separate setup() method in your timer class and calling that from the global setup() routine.

@jfpoilpret The wire.c gets called from init() and if timer2 registers are defined it applies the values shown above, why , I have no idea (one of the reasons I code in native C using AVRstudio).

@jfpoilpret Normally it would be very easy to use a conditional define (like #ifndef _LEAVE_TIMER2_ALONE_ ... #endif) in wire.c to exclude the timer2 part, but a #define from inside the sketch will not reach it. This can only work if you add the define in arduino.h or wiring_private.h but that is not convenient at all, because if you forget to remove it in an new sketch it will mess things up. Setting the timer inside setup is your best bet I think.

I have just checked wiring.c content and I have to say the init() function content seems to exceed its responsibilities somehow. Obviously there's no usable #if in the function to bypass this code block. Hence I'll have to find another solution to solve my problem. However I consider you have fully answered my question and therefore accept your answer. Maybe I'll edit the content to mention the fact we cannot really bypass this code block.

@jfpoilpret, if you truly care about bypassing this code block, it’s very easy to clone a “new” Arduino core from the standard one.

@microtherion maybe but that must reduce the possibilities to share my code with other people as they'll have to do the same cloning work on their installs. I think I'm gonna find a simpler solution to workaround the issue. I already have an idea, I'll post about it later today.

As a follow-up up to @alexan_e answer, here is what I finally did to ensure that my Timer2 settings are not overwritten by the init() method in Arduino wiring.c.
#define BIT(x) (0x01 << (x))

static volatile uint32_t milliseconds = 0;

class Timer
{
    public:
    // Don't use the constructor anymore
    void init()
    {
        // Disable interrupts
        uint8_t savedStatus = SREG;
        cli();
        // Use Timer2 with 1 ms interrupts
        // OC2A & OC2B disconnected, mode 2 (CTC, Clear Timer on Compare match)
        TCCR2A = BIT(WGM21);
        // Don't force output compare (FOCA & FOCB), mode 2, Clock Select clk/128 (CS = 5)
        TCCR2B = BIT(CS22) | BIT(CS20);
        // Set timer counter compare match (when value reached, 1ms has elapsed)
        OCR2A = 125 - 1;
        // Reset Timer2 counter
        TCNT2 = 0;
        // Set Timer2 interrupt mode (Set interrupt on OCR2A compare match)
        TIMSK2 = BIT(OCIE2A);

        // Restore interrupt enabling state
        SREG = savedStatus;
    }
};

static void callEveryMillisecond(uint32_t ms)
{
    if (ms % 10000 == 0)
        digitalWrite(13, digitalRead(13) ^ 1);
}

// Attach interrupt routine to the Timer Compare Interrupt
ISR(TIMER2_COMPA_vect)
{
    milliseconds++;
    callEveryMillisecond(milliseconds);
}

static Timer timer;

void setup()
{
    // Explicit call to Timer initialization; this occurs AFTER
    // Arduino wiring.c init() has been called
    timer.init();
    pinMode(13, OUTPUT);
}

void loop()
{
}

The way most of the libraries do this is to put an instance of (in your case) Timer in the Timer.cpp file, and reference it with an extern definition when needed - typically in your main cpp file.
Also you are calling digitalWrite() and digitalRead() during an ISR. This can be bad since those functions are slow, and may not be guaranteed to behave when interrupts are disabled (as they are during an ISR). A safer approach is for your ISR to set a flag in your Timer class that can be read by an Timer.isExpired() or similar method in your loop() code.

Putting an Timer instance in Timer.cpp won't change the issue: the problem is the well-known C++ initialization order chaos.

I don't see anything indigitalRead() or digitalWrite() that should prevent it from being called from an ISR.

In your setup function, you need to instantiate your timer, like this:
static Timer timer;

void setup()
{
    timer = new Timer();                       <<<--- here
    pinMode(13, OUTPUT);
}

void loop()
{
}

There is no need for a new as timer is not a pointer but an instance of Timer: it is in the static data section, not the heap. Its constructor is called (otherwise my ISR would never get called)

That will bloat the code with the malloc library and consume a bit of the precious RAM for no good reason. The only thing needed here is to get the init code called after the static object constructors. You don't need another instance to do that, just move the object creation inside setup() or put the init code in a separate method that you will call inside setup().


text:
LCD scrolling down problem
I have a list of set-ups and I only have 2 rows in the lcd , I'm trying to scroll down for the moment and I'm doing this by changing the row in the setcursor function to either 0 or 1.
However since that I'll be having about 10 set-ups I used an equation that will change the rows to 0 and one for the ones I want to display and a negative number for those that I don't want to appear.
The problem is when setting the cursor's row to -1 or 2, it will ignore the one with row one (which is the 2nd row).
Is there a way that I can overcome this problem ? by setting it to a row that will not appear on my LCD?
I'm using #include <LiquidCrystal.h>
and I already set lcd.begin(16, 2);
int  colom[5] = {
    0-goDown,1-goDown,2-goDown,3-goDown,4-goDown  };
for (int i = 0; i < 4; i++) {
    if (colom[i] > 1) colom[i] = -1;
}

  lcd.setCursor(0, colom[0]);
  lcd.print("choise 1 ");
  lcd.setCursor(0, colom[1]);
  lcd.print("choise 2 ");
  lcd.setCursor(0, colom[2]);
  lcd.print("choise 3 ");
  lcd.setCursor(0, colom[3]);
  lcd.print("choise 4 ");
  lcd.setCursor(0, colom[4]);
  lcd.print("choise 5 ");

So here goDown is 0 so choice 1 and 2 should appear, but I'm only getting choice 1 and in the second row it's changing quickly between 2 and 5, it's not constant.
I thought about doing an if condition for each choice but that will be a lot of code to write and it won't be efficient for my application.

What is the LCD library you're using?

#include <LiquidCrystal.h>

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets. Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem. Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant. Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem

This is a bad strategy in general. You should not be issuing print calls for things you don't want to print and relying on the lcd library to filter for you because they're out of bounds.
Call print for only the choices you want to display.
char* menu[] = {
    "choice 1",
    "choice 2",
    "choice 3",
    "choice 4",
    "choice 5",
};
const int numMenuItems = sizeof menu / sizeof *menu;
const int numLcdRows = 2;

// start out at the top of the menu
int scrollPos = 0;

void drawMenu() {
    for (int i=0; i < numLcdRows; ++i) {
        lcd.setCursor(0, i);
        lcd.print(menu[i + scrollPos]);
    }
}

To scroll up or down, just adjust the scroll offset:
inline void scrollUp() {
    if (scrollPos > 0)
        scrollPos--;
}

inline void scrollDown() {
    if (scrollPos < numMenuItems - numLcdRows)
        scrollPos++;
}

Note this is untested code written for a library I've never seen (just inferring how it works from your post); it's for illustration purposes only.

I have written some abstraction code for handling LCD menus, located here: https://github.com/red-green/Arduino_Mobile_OS
Here is the main snippet:
byte menu(String title,const String* strings,byte length) {
  boolean select, esc; static byte item, selection;
  select = false;
  esc = false;
  item = 1;
  lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(title);
    lcd.print(": ");
    lcd.print(item);
    lcd.setCursor(0,1);
    lcd.print(strings[item]);
    delay(100);

  while (!select) {
    uint8_t buttons = lcd.readButtons();
    if (buttons) {
    if (buttons & BUTTON_UP) {
      item--;
    }
    if (buttons & BUTTON_DOWN) {
      item++;
    }
    if (buttons & BUTTON_LEFT) {
      esc = true;
    }
    if (buttons & BUTTON_SELECT) {
      selection = item;
      select = true;
    }

    item = constrain(item,1,length - 1);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(title);
    lcd.print(": ");
    lcd.print(item);
    lcd.setCursor(0,1);
    lcd.print(strings[item]);
    if (esc) {
      select = true;
      selection = 0;
    }
    delay(100);

  }
  }
  return(selection);
}

You may need to change the button handling to work with your setup. To call, have an array of items before setup, like this:
const String utilmenuitems[6] = {"back","Random Numbers","Uptime","Device Info"};

You can then call it like:
byte return = menu("Utilities",utilmenuitems,4);


text:
XBee+Arduino communication problem
I tried testing the system and I’m not sure if the problem is with the XBee’s, the transmitting code, or the receiving code. Before I post my code, I will explain what we are doing with the signals.
We have three analog signals that will be sent serially through one XBee using an Arduino and XBee shield.  We want to send these signals to the receiving xbee where the Arduino will output these signals to be connected to a third Arduino through wires to be used in a Simulink program.
We are using an Arduino mega for the transmitting side and an Arduino uno for the receiving side. I was told I need to do serial streaming but I’m not sure how that’s done. I understand the XBee and Arduinos both digitize signals but we are hoping to get a signal very similar to the analog signals we are transmitting. Any amount of help is greatly appreciated!!
This is how I have my XBees configured (series 1) both in AT mode:

Transmitting XBee:
      Channel:10
      Pan id: 1234
      MY: 10
      DL: 11
Receiving XBee:
      Channel:10
      Pan ID: 1234
      MY: 11
      DL: 10

Transmitting Arduino code:
void setup() {
  Serial.begin(9600);
}
void loop() {
  // read the input on analog pins
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);
  int sensorValue3 = analogRead(A2);
  // print out the value you read:
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);
  Serial.println(sensorValue3);
  delay(1);
}

Receiving Arduino code:
int received1=8;
int received2=9;
int received3=10;
void setup(){
  pinMode(received1, OUTPUT);
  pinMode(received2, OUTPUT);
  pinMode(received3, OUTPUT);
  Serial.begin(9600);
}
void loop(){
  if(Serial.available() )
  {
    byte output1 = Serial.read();
    byte output2 = Serial.read();
    byte output3 = Serial.read();
    digitalWrite(received1, HIGH);
    digitalWrite(received2, HIGH);
    digitalWrite(received3, HIGH);
  }
}

There are several things here:

Increase your delay, you don't want to be sending the data that often, even if you only increase it to 100-200ms, although I'd recommend making it in the order of 1-30 seconds.
You're reading in analog inputs which will be in the range of 0-1023 but your serial reads are in byte format (which will actually be reading the first three bytes (or the first three DIGITS of the first reading). More about this below.
You're reading in three arbitrary bytes, you're not identifying them at all, you have no idea what you're reading (other than by testing for a 1ms delay--which over XBee is not practical).

You have two options, transmit the data as ASCII (not a good idea IMHO), pre-pending some identifier such that:
1:259
2:0
3:1019

or even some other delimiter:
259:0:1019

But I would probably lean towards byte encoding:
byte0 :0xEA    // just some custom header for yourself
byte1H:0x01
byte1L:0x03
byte2H:0x00
byte2L:0x00
byte3H:0x03
byte3L:0xFB
byte4 :0xXX    // checksum

Or you could map the inputs down to a range of 0-255 for single byte transmission.
Next you'll need to work on receiving the data, how you do that is going to depend on how you encode the stream.
edit: I've removed the code sample that was here and replaced it with two working sketches below.

I have two XBees, running in AT mode, mine are Series 2, but programatically I THINK they are the same. If not, you'll have to tweak these, but I'm pretty sure you'll be right.
What we have are two apps, the first is the "SENDING" app, it takes three arbitrary values, they are: minutes (0-60) the micro has been running, seconds (0-60) the micro has been running, and 100 (it was random, and you can put that back if you want). Also, if you comment out the #define TESTAPP instead of using these values, it can pull three analog values from A0-A2 instead. (If you change it in the receiving app, you could have three LEDS on Pulse Width channels and vary the brightness).
/* * * * * * * */

XBEE SENDER (131)

#define TESTAPP        // Just serial data based on time

#define PACKETLENGTH   7
#define LED            13

/* * * * * * * */

void setup(){
    Serial.begin(9600);
    Serial.println("\nSender");
    randomSeed(analogRead(0));
    pinMode(LED,OUTPUT);
}

unsigned long m1 = 0;
unsigned long m2 = 0;

void loop(){
    m1 = millis()/1000;
    if(m2 != m1){
        m2 = m1;

#ifdef TESTAPP
        uint8_t  s = m1 % 60;           // how many seconds on millis()
        m1 /= 60;                       // now we're working with minutes
        uint8_t  m = m1 % 60;           // how manu minutes on millis()
        uint8_t  r = 100; //random(256);
        Serial.print("x.x");            // this is just pre-pended data for testing
        Serial.print('<');
        Serial.write(m);
        Serial.print('-');
        Serial.write(s);
        Serial.print('-');
        Serial.write(r);
        Serial.print(">  x-x");        // we want to ignore these chars
#else
        Serial.print('<');
        Serial.write(map(analogRead(A0),0,1023,0,255));
        Serial.print('-');
        Serial.write(map(analogRead(A1),0,1023,0,255));
        Serial.print('-');
        Serial.write(map(analogRead(A2),0,1023,0,255));
        Serial.print('>');
#endif
        digitalWrite(LED,!digitalRead(LED));  // toggle the LED everytime we're here
    }
    // do other stuff here...
}

You'll notice garbage characters around the data we are transporting, this is to demonstrate cycling through all serial communications to arrive at the 7 particular characters we need. That's done in the next app, the receiver:
/* * * * * * * * */

XBEE RECEIVER (121)

#define TESTAPP  // if you attach 3 LEDS to 9, 10 and 11, the remove this line.

//#define DEBUG  // uncomment this line to see all the data stream coming in

#define PACKETLENGTH  7

/* * * * * * * * */

int LED[3]={9, 10, 11};

void setup(){
  Serial.begin(9600);
  Serial.println("\nReceiver");
}

byte  buffer[PACKETLENGTH]; // what holds our serial data
byte  idx         = 0;      // the index for the buffer character being written
byte  validBuffer = 0;      // flag to tell us if we're ready to go

void loop(){
  if(validBuffer){
      #ifdef TESTAPP
          // we're just going to print it out in a different format
          validBuffer=0;
          #ifdef DEBUG
              Serial.print('\n');
          #endif
          Serial.print("Data: (");
          if (buffer[1]<10) Serial.print("0");
          Serial.print(buffer[1]);
          Serial.print(":");
          if (buffer[3]<10) Serial.print("0");
          Serial.print(buffer[3]);
          Serial.print(") (");
          Serial.print(buffer[5]);
          Serial.println(")");
      #else
          // this is the more practical side of things
          // instead of serial.printing, change the brightness
          // on three attached LEDs via PWM Pins (9, 10, 11)
          analogWrite(LED[0],buffer[1]);
          analogWrite(LED[1],buffer[3]);
          analogWrite(LED[2],buffer[5]);
      #endif
      memset(buffer, 0, PACKETLENGTH);  // we've used the data, clear it out
      idx = 0;                          // and reset the index marker
  }
}

// This is where the real magic is done. We have a buffer of
// PACKETLENGTH that takes in all Serial data and waits until
// it finds PACKETLENGTH characters in the format we're after
// Probably not the best method, but it would be unlikely to
// stumble across this pattern, although not impossible :)
// use at your own risk

void serialEvent(){
    if(validBuffer) return; //we don't want to process new Serial
                            //until we've processed the buffer
    buffer[idx] = Serial.read();
        #ifdef DEBUG
        Serial.write(buffer[idx]);
        #endif

    if (++idx==PACKETLENGTH){
        // we have enough bytes for testing, this next part could be handled better
        if(  buffer[0]=='<' &&
             buffer[2]=='-' &&
             buffer[4]=='-' &&
             buffer[6]=='>' ) { // we have a valid data packet
               validBuffer=1;
        } else {    // we don't have valid data yet, but keep
                    // what we have, shift it all over one byte and
                    // we'll check again once the next byte is received
            memmove(buffer, buffer + 1, PACKETLENGTH-1);
        }
        idx--;
    }
}


text:
How do I connect Arduino to a Bluegiga112?
I am a new user of Arduino (I have a Arduino Due) and also I am a new user of BLE112 (Bluegiga module 112)
My teacher told me to make the BLE112 advertisable and furthermore he told me to look for information about UART@115K. (The Ble112 he gave me came with wires already soldered to the selected pins: I'm assuming I only need to use those.)
PIN NUMBER [PIN NAME] for BLE112

    2         AVDD                    (Supply voltage 2-3.6V)
    3         AVDD                    (Supply voltage 2-3.6V)
    4        [P2_2]  DC- Debug clock  (DIGITAL I/O)
    5        [P2_1]  DD- Debug data   (DIGITAL I/O)
    9        VDD_USB                  (Supply voltage 2-3.6V)
    20        DVDD                    (Supply voltage 2-3.6V)
    23       [P0_5]  RXD(Rx)          (DIGITAL I/O)
    24       [P0_4]  TXD(TX)          (DIGITAL I/O)
    25       [P0_3]  RTS              (DIGITAL I/O)
    26       [P0_2]  CTS              (DIGITAL I/O)
    29        RESET
    30         GND

I put:
BLE pins [2,3,9,20]    to     3.3v pin of Arduino
BLE pin  [30]          to     GND pin of Arduino

Then I found a picture (attached at the bottom of this post) that describes that I should put CTS of BLE on RTS of Arduino and vice versa. Where is the CTS on an Arduino board? I think I have to program one of the Digital pins.
I tried some other connections. I put:
BLE pin 26(CTS)   to    Arduino random digital pin 32, and
BLE pin 25(RTS)         Arduino random digital pin 34.

BLE pin 24(TX)          Arduino RX pin 0
BLE pin 23(RX)          Arduino TX pin 1

I didn't connect DC(Debug clock), DD(Debug data) and Reset on the BLE112.
So then I found some more info on the web that if I use USART than I should use a wake up pin which is by the default P0_0(??) more about that in this PDF. (Search wake_up)
Now I should mention sleep mode Ble112 (there are three kinds of it) and I believe that the one I am after is MODE 3 (that means that it consumes the minimum (power) of them all)
I found some example named UART@115K

UART@115k
  This example configures the BLE112 or BLE113 Bluetooth Smart module to expose the BGAPI protocol over UART interface with the following settings: 115200 bps, 8n1 and hardware flow control enabled. The power mode 3 is enabled in this example and the wake-up pin is configured to P0_0 pin (P0_0 button on DKBLE112
  and DKBLE113). When the power mode 3 is enabled the device will not be able to receive commands or data over UART unless the wake-up pin is asserted.
The example uses UART in the pin configuration channel 1 and alternate 1, which is the configuration used in the DKBLE112 and DKBLE113 development kits.
  If you try this example with DKBLE112 or DKBLE113 make sure the UART interface is enabled and the device is NOT powered with a CR2032 battery as it’s not able to power up the level shifter or UART to USB converter.
This is also the factory default configuration for BLE112 and BLE113 Bluetooth Smart Modules.

Source: https://bluegiga.zendesk.com/entries/22412436

The PDF link seems broken... it gives me this error: Sivua ei löytynyt! which translate into Page not found. Good think I know Finnish! (Just kidding: Google Translate)

First off all I am a new user of this forum so I make a mistake.. the reason i culd not answer sonner was that i got sick...
Here is that PDF https://dl.dropboxusercontent.com/u/65932667/Bluetooth_Smart_Configuration_Guide_v33.pdf

And some more abut BLE112 (if you want more literature you need to registrate on their website (it's for free)
Links:
Ble112 Datasheet https://dl.dropboxusercontent.com/u/65932667/BLE112_Datasheet.pdf
Ble112 Modul https://dl.dropboxusercontent.com/u/65932667/BLE112_Module.pdf

@FirsTime No problem. Three things that I should tell you: 1.) <br /> doesn't work in comments (like this here), 2.) Next time edit the link in. I changed it for you 3.) Some people might be offended if you call it a forum. It doesn't really matter, but since this site is a different setup, it's generally called a "Q&A Site." Just a minor detail... :) I'll look at the PDFs and see if I can find anything out.

The most popular way to establish communication between an Arduino (I've used a Duemilanove) and a BLE module (I've used BLE113 that's on a DKBLE113) is through UART.
UART is a two wire interface (don't forget the common GND) with one RX and one TX.
You can use the SoftwareSerial library to define your communication object on the Arduino.
In contrast, the BLE113 uses four. The additional two are RTS and CTS (Request To Send and Clear To Send).
However, you can configure the UART in two ways using hardware.xml:

Go to the <usart > tag and set flow = "false". This "disengages" the RTS and CTS allowing a traditional two wire interface.
Had you set flow = "true", you need to connect the RTS and CTS as well, which I had a big problem with, though the two are both digital.

Further, in hardware.xml, you need to disable sleep mode by including <sleep enable="false" /> within the <hardware> tag. This will solve all your problems.
If you intend to use sleep mode, you need to skip the previous step and instead govern the module's mode through the P0_0 pin. Moreover, there are additional definitions to be included in hardware.xml, which are documented by BG. These work nicely for the BLE112 too.
In my exercise, I'd established communication at 9600 baud. It worked the same way when I increased it to 115200 baud (this is a plus in the BLE113).

Software serial would be important for an ATmega328 based Arduino with only one hardware serial port already used for loading.  The Arduino Due of the question appears to have multiple hardware ports.

I would connect TX and RX to one of the 3 extra serial ports on the Due. Pins 0 and 1 are used for the USB-Serial communication

To communicate with the Arduino, it is only necessary to connect the RX and TX pins between the module and the Arduino.
Source: http://www.mkroll.mobi/?page_id=386

Well I found another way how to make it work, you just need to put CTS from BLE on GND, and RTS open "in the air" and that's it!
You can see these on this link: https://bluegiga.zendesk.com/entries/23143152--REFERENCE-Using-or-bypassing-flow-control-with-UART-communication


text:
How to use RS-232 sheild as software serial port?
I would like to be able to use a USB port at the same time as an RS-232 port with my Arduino Uno board. I unwittingly bought a shield that (I think?) overrides the USB port when it is mounted to the Arduino board:
http://www.dfrobot.com/wiki/index.php/RS232_Shield
Would anyone be able to give me any advice on how to connect the hardware so that I can have two serial ports accessible from my Arduino Uno? The format I was thinking was (Arduino => RS-232 Sheild):
GND => GND
5V => 5V
Digital Pin 2 => 232RXD
Digital Pin 3 => 232TXD
The accompanying code for initializing the serial port which I've written:
const int rxpin = 2; // pin used to receive
const int txpin = 3; // pin used to send
SoftwareSerial Serial_rs232(rxpin, txpin); // new serial port

Any ideas as to why this may or may not be a good method of using the hardware I have available for the purpose I had in mind?

GND => GND 5V => 5V Digital Pin 2 => 232RXD Digital Pin 3 => 232TXD

A better choice of board would be the Leonardo, since you could connect such a shield and use the USB port right out of the box. However, since you have the Uno, there is a solution.
From Arduino:

The SoftwareSerial library has been developed to allow serial communication on other digital pins of the Arduino, using software to replicate the functionality (hence the name "SoftwareSerial"). It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.

It then goes on to reccomend the library AltSoftSerial.
Here is some example code from the link above:
#include <AltSoftSerial.h>

AltSoftSerial altSerial;

void setup() {
  Serial.begin(9600);
  Serial.println("AltSoftSerial Test Begin");
  altSerial.begin(9600);
  altSerial.println("Hello World");
}

void loop() {
  char c;

  if (Serial.available()) {
    c = Serial.read();
    altSerial.print(c);
  }
  if (altSerial.available()) {
    c = altSerial.read();
    Serial.print(c);
  }
}

It acts like a standard serial port, only you declare the connection as a variable first. This code is written for a board with an additional serial port, like you have.
All is good, except for one problem:
The problem is the shield is wired to connect to pins 0 and 1: the ones used by the USB adapter. The AltSoftSerial library uses pins 8 for TX and 9 for RX. (Note: You cannot use PWM on pin 10 on the Uno... it should still work as a digital pin.) In that case you would not attach the shield by plugging it into the Arduino, and you would wire it like this:

GND => GND | 5V => 5V | Digital Pin 8 => 232RXD pin 0 on the shield headers | Digital Pin 9 => 232TXD 1 on the shield headers

So then, you would be manually wiring the shield to the Arduino with jumpers. As long as it doesn't connect to any other Arduino pins I'm not aware of (it shouldn't besides maybe 13 for a LED or something like that), it should function like it would stacked and using pins 0 and 1.
Note: (Obviously) You cannot connect anything to the headers on the shield (You cannot connect to pin 5 and get a signal).

Thanks for the informative reply! Do you definitely advocate AltSoftSerial in place of the SoftwareSerial library then? Your hardware recommendation involving the Uno sounds great, but I'm unsure about why you've chosen the RX/TX digital pins on the shield, in favour of the pins labelled RS-232 on the wiki diagram?

@user_name I do think AltSS. would be the best choice: Arduino themselves said this library is better for simultaneous connections (see link in my post). For the second part, that should work as long as you don't stack them on top of each other. The reason is, both the USB adapter and the RS-232 use pins 0 and 1. By doing the wiring I said, you are "rerouting" them onto different pins on the Arduino. Just, most people don't have female jumpers needed to connect to the "232TX"/"232RX"... Remember use pins 8 and 9 and connect the TX and RX accordingly.


text:
How to build (concat) a string with big numbers
new to arduino I'm struggling with what sounds like fairly n00b problem...
I've wired up a adafruit GPS-board to my Arduino and it is working as it spits out GPS data to the serial port with Serial.print(GPS.latitude, DEC)
I Now want to concat a string which I can process (read: I want to sent it via an ethernet client.)
This is what I got already:
......
String vnnt = "$VNNT,";

if (GPS.fix) {
   vnnt += "GPS,";

   //this works:
   vnnt.concat(GPS.fix);

   //but this not:
   vnnt.concat(GPS.latitude);

}else{
   vnnt += "INFO,Acquiring Sats";
}

Serial.println(vnnt);

The error message is: Call of overloaded 'concat(float&)' is ambiguous
When I Serial.print(GPS.latitude, DEC) it results in: 4418.5937996050
So it is probably to big or something...
How can I concat the vars and create the long string?

Aren't you missing a semicolon?

and one says vnnt while another says vannut

Sorry some typo's :)

Do you know the datatype of GPS.latitude? E.g. is it a float, int, etc.?

I think it's a float? It says float in the error-message. How can I find out? Is there a var_dump or something?

@stUrb I managed to look it up in the GPS library, and it is indeed a float.

@stUrb, you can check that it is actually a float in the code, in the folder you downloaded, online here: https://github.com/adafruit/Adafruit-GPS-Library/blob/master/Adafruit_GPS.h

The concat function does not implement a float version, but some of char, int, unsigneds...
unsigned char String::concat(long unsigned int)
unsigned char String::concat(unsigned int)
unsigned char String::concat(int)
...

so the compiler does not know how to cast (truncating probably the float) to integer, as there are several options.
You have to convert first your float to string, use dtostrf() or sprintf() then concat to your string.
char outstr[25];
sprintf(outstr, "%f", GPS.latitude);

or
dtostrf(GPS.latitude, 6, 2, outstr);  //check docs for 6, 2 values, and set them for your needs

And then:
vnnt.concat(outstr)

Also note that sprintf is very handy for compact creation of a (char) string:
char msg[80];
sprintf(msg, "$VNNT,GPS, %s %f", GPS.fix, GPS.latitude);

+1 when in doubt, sprintf it out :)

One point of caution though: sprintf() is a complex function, hence it is rather slow and uses quite some memory. Generally, I would avoid it for "production" code (only keep for debug purposes).

That is a good point @jfpoilpret, I didnt take into account. Do you have some order of magnitude of efficiency vs a dtostrf+concat version? Does the same apply to sscanf()? (btw, I now doubt if sscanf() actually works fine in arduino)

I did not perform actual measurements to compare both calls, but I guess one could just take a look at the C code and possibly check the generated assembly. Regarding sscanf, IIRC it has some limitations (with floating point numbers I think).


text:
How can I get the source files for Arduino libraries?
I've been looking for a while inside Arduino's files to find the core library. However, I haven't found them yet. Where on my hard drive can I obtain the core library files (.cpp and .h) necessary for all Arduino code?
Looking around on Google, I couldn't find a way to find the above files. I did see something about getting an .a file while Arduino is compiling, however, that isn't what I want. I want to browse the code and look at functions such as delay to see how they would react when given the values not expected. (i.e. Will my code stall if I use delay(-200); by not being to exit the loop, or will it create a black hole and disrupt the space-time continuum?)

I was interested in the question, but what I want is the source code for strcpy and strcat in assembler source code. I downloaded the Master Library but I cannot locate anything remotely similar to strcpy or strcat.
OR
Maybe I cannot see the wood for the trees?

@bobzic I suggest that you ask another question specifying which files you want to find.

The base Arduino source files are in the Arduino installation, under cores/arduino/. Source for additional libraries included are in libraries/.

And don't forget /usr/lib/avr/include/ or whatever that translates to on non-Linux systems.

Too bad I installed it as Windows 10 app and cannot access the installation folder.

This information seems outdated. The libraries folder is empty now and hardware has moved

The code is also available online for those times you don't have the IDE installed:
https://github.com/arduino/Arduino

Can't find the header files there.

see my answer below: https://arduino.stackexchange.com/a/68658/59512

On a Mac, the path to the source code folder is:
Arduino.app/Contents/Resources/Java/Hardware/Arduino/Cores/Arduino. I'd expect it would be the same from /Java/ on down in other OSes.

The arduino source files can be found on Github at https://github.com/arduino/Arduino, however the libraries have been moved to their own repositories:

https://github.com/arduino/ArduinoCore-avr
https://github.com/arduino/ArduinoCore-sam
https://github.com/arduino/ArduinoCore-samd

There are multiple places where you can look. As at IDE 1.6.4 (Ubuntu version) some are in:
(install location)/libraries

But these are the high-level libraries, in particular:
Bridge
Esplora
Ethernet
Firmata
GSM
LiquidCrystal
Robot_Control
RobotIRremote
Robot_Motor
SD
Servo
SpacebrewYun
Stepper
Temboo
TFT
WiFi

That does not cover the low-level libraries like Tone, Print, main, etc. These are in:
(install location)/hardware/arduino/avr/cores/arduino

There you would find the Arduino core libraries like:
abi.cpp
Arduino.h
binary.h
CDC.cpp
Client.h
HardwareSerial0.cpp
HardwareSerial1.cpp
HardwareSerial2.cpp
HardwareSerial3.cpp
HardwareSerial.cpp
HardwareSerial.h
HardwareSerial_private.h
HID.cpp
hooks.c
IPAddress.cpp
IPAddress.h
main.cpp
new.cpp
new.h
Printable.h
Print.cpp
Print.h
Server.h
Stream.cpp
Stream.h
Tone.cpp
Udp.h
USBAPI.h
USBCore.cpp
USBCore.h
USBDesc.h
WCharacter.h
WInterrupts.c
wiring_analog.c
wiring.c
wiring_digital.c
wiring_private.h
wiring_pulse.c
wiring_shift.c
WMath.cpp
WString.cpp
WString.h

However even that does not locate things like strcpy. The header files for them can be found at:
(install location)/hardware/tools/avr/avr/include/

There you will find:
alloca.h
assert.h
ctype.h
errno.h
inttypes.h
math.h
setjmp.h
stdfix-avrlibc.h
stdint.h
stdio.h
stdlib.h
string.h

Even that is not the full story. In a subdirectory (avr) you will find the avr-related things, with files for different processors, such as (in part):
boot.h
builtins.h
common.h
cpufunc.h
crc16.h
delay.h
eeprom.h
fuse.h
interrupt.h
io1200.h
io2313.h
...
iox64d4.h
iox8e5.h
lock.h
parity.h
pgmspace.h
portpins.h
power.h
sfr_defs.h
signal.h
signature.h
sleep.h
version.h
wdt.h
xmega.h

As for the source of strcpy, I don't think it is in the distribution. They include the standard libraries, pre-compiled. For example, if you look in:
(install location)/hardware/tools/avr/avr/lib

You will see various pre-compiled libraries, for example:
libc.a
libm.a
libprintf_flt.a
libprintf_min.a
libscanf_flt.a
libscanf_min.a

To find the source you would need to find where the AVR source of libc is (possibly at http://www.nongnu.org/avr-libc/).

As for the Mac, all this stuff is a few levels down in the "Application Package" which you can view by right-clicking and selecting "Show Package Contents". Look in the Contents/Resources/Java folder.

None of these places are where you should put your own libraries (ones you write or download). They should go into the libraries folder which is a subdirectory of your sketchbook folder. Create the libraries folder if it does not exist. That way user-installed libraries persist from one version of the IDE to the next.

I think this may have changed in newer versions. On my Mac Big Sur, Arduino 1.8.15 they are here: /Applications/Arduino.app/Contents/Java/libraries

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Connect to more than one Arduino with Adobe AIR
I am using the arduinconnector ANE to connect to an arduino baord in an AIR application. https://code.google.com/p/as3-arduino-connector/
Can anyone tell me if its possible to connect to more than 1 board, simply by instantiating additional instances of the ANE and passing in unique port #'s?
Or is there some reason why this isn't possible and a unique AIR application is required for every arduino you connect to?

don't know if this is a definitive answer, or only pertains to this ANE, but was told by the dev that The flash runtime is all shared memory space, so you will run into conflicts. Needs to be reengineered.

This seems to be possible with as3Glue as per the docs:

as3Glue is an ActionScript 3 library that enables communication between Flash/Flex/AIR applications and Arduino boards. It can together with one or several Arduino boards be used to monitor sensors (such as rotary encoders and motion detectors), control actuators (such as LEDs and motors) and interface other electronics (such as RFID readers) from Flash, Flex and AIR applications.

as3Glue can be used with as3-arduino-connector as mentioned in the docs:

Using with as3Glue
Download either the SWC or Source Code from the Downloads section of this project for a patched version of as3Glue. This patched version has the exact same interfaces as v20, with a notable exception of the constructor. When you instantiate a new "Arduino" object, replace the IP address and port with the COM port and baud rate. For example :
public var myArduino:Arduino = new Arduino("COM10", 57600);


text:
Arduino Mega timeout communication with programmer error
I have an Arduino Mega 2560 and it was working fine until about lunch time when I started getting this error:
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

I know it isn't the code I'm running as I tried to load it onto an Uno and it seemed to load without issue. I need to use the Mega as it has more ports, though.
From what I have read this is potentially an issue with the bootloader and is possibly related to the current version of Arduino. I know virtually nothing about the bootloader; all I know is that it is used to upload code to the Arduino (I think...), therefore I have a fear of just messing around with related files unknowingly.
These pages are the ones I've been looking at, but like I said, I don't really know enough to feel comfortable with just messing around with the files.

Mega2560: timeout communicating with programmer....
Upload Timeout Error on Mega 2560 - Not Sure What Changed

I tried uninstalling my Mega totally, then reinstalling it. I also downloaded an older version of Arduino (0022) and neither option seemed to work.
I don't know what to do, or how to change the 'AVR' files if necessary.

possible duplicate of Some dude named avr won't let me upload my program, aka "avrdude: stk500_getsync(): not in sync: resp=0x00"

Ohhh I didn't notice that post. I've tried everything except burning the bootloader... is there a simple way to do this without having to buy software?

usually you just go to the IDE, look under the tools menu, select "Burn Bootloader". Make sure to select the right board first.

@TheDoctor, I've seen that option, but I have no idea what to do afterwards. I presume I have to load it again with a new "bootloader" program? One site (https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader) says I need to buy hardware and download specific software... all to replace the software on the bootloader?! I'm not sure I understand why.

I think the menu item is only for arduinos that have a progrmmer built in, like the Uno and Mega

So if I clicked that menu item... do you know what would happen? I don't want to do anything I don't understand just in case there is a simpler solution. Thanks for help.

This is the super-simple solution. buying hardware is a more complex task. Do you have any other arduinos?

I have an Uno, but I got the Mega because the Uno can't cope as well and doesn't have as many ports (it's used to control a robot vehicle)

You can use the Uno to reprogram the Mega. Look up ArduinoISP

Has something changed that means you can burn a bootloader without an ISP?

I've been having this exact issue with my Mega2560 lately. Click upload -> compiles -> upload begins (serial tx/rx blinking) -> avrdude timeout. But this is an intermittent problem. It uploads correctly maybe 20% of the time.

The bootloader on an arduino is just a piece of software written to enable you to update your sketches using the usb connection. Without the bootloader you can't upload sketches using just the arduino ide.
More information about the bootloader can be found here: http://arduino.cc/en/Guide/Environment?from=Tutorial.Bootloader
Look under the heading entitled uploading which explains the part the bootloader plays in uploading sketches.
When you use the "Burn Bootloader" button in the arduino ide it will attempt to write a new copy of the bootloader onto the attached Arduino board. To do this the board must be attached in a specific manner - that is - using the icsp/isp header rather than the usb cable.
Now to program the avr chip directly you have to use an external (hardware) programmer. Fortunately you don't have to buy one if you have a second arduino because the second arduino can be used as a programmer. Instructions for doing so can be found here: http://arduino.cc/en/Tutorial/ArduinoISP
Even more info about the bootloader: http://arduino.cc/en/Hacking/Bootloader?from=Main.Bootloader

Unfortunately this error refers to many different issues and there are so many posts here and on other platforms none with a definite answer. Maybe Arduino team should try to give better errors to differentiate. But I have tried to answer the same question here in this SO post.
what solved my issue was to go to Tools>Boards>Board Manager... select "updatable" for "Type" on top left and then select the updatable packages below and click on update.

This resolved my issue. I selected the update for the board and that it

I got this same error when my Arduino COM port was busy with other apps. I closed that app and upload Arduino sketch and error disappeared.


text:
Can I corrupt my Arduino if it's unplugged during an upload?
When messing around with code and uploading a sketch to my Arduino board, I almost accidentally pulled out the USB cord. Everything is fine, but then I started thinking what would've happened if I had pulled it out.
How safe is avrdude? Could it damage or brick the board? I'd imagine that you would just have to upload code to it again... but what would happen before you upload the new code? I've seen something about how you can always upload new code if the bootloader is intact, but I would imagine that there would be some problems. If this were to happen, should I unplug everything connected in case Arduino writes a HIGH to an input (or similar) that would damage the component?

So I accidentally did this to my Arduino Nano 33 BLE and now my computer cant see it.. I tried restarting my computer, hitting the reset button on the board, unplugging and plugging it back in and still nothing. Is there a way to revive it?

@Coy, use double reset to activate the bootloader

AVRDUDE does not actually perform the write, it merely directs it. The actual writes are performed either by the bootloader or by the ISP firmware/hardware within the MCU itself.
With the bootloader it depends on how itself is coded, but at worst it would finish off the flash byte or page or EEPROM page zero- or one-filled and then fail to communicate further with AVRDUDE, aborting programming.
With ISP, the page write command would never be received and the programming would be aborted at the last full page. Fuse bytes are done singly and so programming a single fuse can be viewed as an atomic operation.
In either case, a chip erase operation should reset the MCU to a known working state, fuse changes excepted.

With the bootloader it depends on how itself is coded, but at worst it would finish off the flash byte or page or EEPROM page zero- or one-filled and then fail to communicate further with AVRDUDE, aborting programming. Wait... how could it abort it if there is no power?

@AnnonomusPerson: External power, USB/serial programming.

What if I'm only using USB power? That doesn't answer my question about your answer.

If all you have is USB power then everything just stops. The bootloader is unable to finish the current byte. But that won't damage any flash cells.

One safety feature that hasn't been mentioned so far is that the ATmega328 has a set of lock bits that prevent read/write access to certain areas. To the best of my knowledge, the way Arduinos are set up, those bits are always set to prevent writing to the boot loader area unless the "Burn Bootloader" command is currently active, and since you can only use that command with an external programmer, you can always write a new bootloader if something goes wrong.
I think the only way of bricking the board (in the sense of leaving the MCU in a state that is functional, yet almost irrepairably unresponsive) is writing bad fuse settings.

It should be fine.
Most boards don't require you to reupload the bootloader every time you upload a sketch, so your program will be corrupted but your bootloader won't. I assume the bootloader is similar to the bootloader on other chips I have seen*, it will stop execution if the code doesn't work properly. I would also think that the micro would not accept a transmission if it's checksum is missing.
I wouldn't try it if I were you, but you can be a little less cautious about this sort of thing.
*: the Propellor chip, among others

Very few embedded MCUs have any sort of error catching facilities. If by the code doesn't work properly you mean the code in the program memory is invalid/corrupted, you are incorrect. The MCU will just happily continue executing the invalid code, leading to undetermined behaviour. If you mean the bootloader will ignore invalid commands, that is entirely dependent on the bootloader.

Yep, nothing to catch or check for errors in user code in Optiboot. This is what the watchdog timer is for.


text:
Acrylic enclosure for Arduino
I've been browsing Aliexpress and eBay for decent Arduino enclusures, but I've found out they are even pricier then boards themselves.
Then I've realized that there are multiple firms that offer cheap laser cutting - I can buy 1 sq.m acrylic sheet and order cutting multiple parts of boxes at once.
Obviously I am not the first one who came up with this idea. Has anyone seen downloadable vector layouts I can use as something to start from? Thanks.

Found something here - https://www.thingiverse.com/tag:arduino_case/page:1 - but it is still far, far away from what I've imagined :(

What do you want to case exactly? If it's just the Arduino, wouldn't any project box of the right size do?

I'd like to have small box that would be used to store the completed assembly, protect it from dust and mechanical damage. I currently use small flat food containers - I drill holes for wires and then seal them with construction silicone glue. They are sturdy and cheap, but it looks ugly, they are usually 1.5-2 times larger than needed.

Making your own is quite possible, especially if you own a router (or even better a router table). You need a V shaped 90 degree router bit, a tube of proper perspex glue and some acrylic sheet. The glue is hard to find, but plastic sign manufacturers generally will sell it. Unless you are a DIY expert, I suggest the gap filling type of glue rather than the watery product that only fills perfectly matched surfaces. Try searching Youtube on "acrylic box making". There are several videos. My first two efforts were pretty bad, but the last couple are fine, and are of course exactly the right size.

cutting and gluing aren't the issues - as I said, there are multiple firms around that will take your blueprint and cut whatever you want, for peanuts. It is vector blueprints (in CorelDraw, or DWG format, for example) I can't find. I ended with obtaining original EAGLE schematic files for Arduino and getting exact dimensions and positions for mounting holes from there. But it looks like I'll need old-fashioned caliper and ruler for stuff like LCD screens and other peripherals :(


text:
Does any board provide more than 1024 analog input values?
The Arduino boards provide an analog input range of 0V to 5V which translates to 0 to 1023 integer values. The range is determined by the on-board ADC, which in the case of the Uno is a 10 bit ADC (2^10 = 1024).
Do any of the official boards have a larger (>10 bits) ADC? Do any boards provide a wider range of analog input values?

why do you need more bits of resolution specifically?

AVR-based Arduinos only have 10-bit ADCs, but the ATSAM3X in the Due has 12-bit ADCs. Additionally, it is possible to interface to higher-resolution external ADCs via I2C or SPI.

Remember that more bits imply higher sensitivity to power supply various other sources of noise.

Could you please provide some references of external ADC chips that connect through I2C or SPI?

@jfpoilpret:http://www.ti.com/lsds/ti/data-converters/analog-to-digital-converter-products.page#p84=11;31&p158=Serial%20I2C;Serial%20SPI;Serial%20SPI%20Interface
http://www.microchip.com/ParamChartSearch/chart.aspx?branchID=11022&mid=10&lang=en&pageId=79
http://parametric.linear.com/analog-to-digital_converters_%28adc%29#!cols_1049,1030,2201,1097,1059,1058,1054,1367!s_1049,1!gtd_!1049_%3E=11!1054_Serial%20I2C|Serial%20SPI
http://www.analog.com/parametricsearch/en/10169?mtuid=MTS5KSkLdcfF-PC#10169?p7=11|12|13|14|15|16|18|20|22|24&d=sel|0|-1|7|165|4162|88|164|-3|4365&p4365=SPI|I%B2C/Ser%202-Wire

@jippie, remember that multi-sampling is always available for ADC chips that don't lock in their value...

How much accuracy do you really need? If it's just 1 or 2 extra bits of resolution you are after, you might be able to achieve that with a bit of oversampling.
Basically, you take a ton of readings and average them. It only works if there is at least a few mV of random noise in your signal or in your ADC, and if your input signal bandwidth is low enough to be averaging samples together.
Otherwise, go with a dedicated ADC chip.

They all do with oversampling. You can evaluate the quality of doing this for your own use.

Welcome to Arduino SE! Can you please add to your post to explain how you do this? Thanks!