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

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


sender: user

sender: assistant

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


body:
**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.


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


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


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


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


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


body:
## 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](https://www.arduino.cc/reference/en/) are simply a set of C++ classes and libraries you can use. It is built and compiled using the [GNU gcc/g++ compiler](https://en.wikipedia.org/wiki/GNU_Compiler_Collection). 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](https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/main.cpp#L33)--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"](https://www.geeksforgeeks.org/extern-c-in-c/) (also known as ["name decorating/name decoration"](https://en.wikipedia.org/wiki/Name_mangling)) function calls to C functions implemented by [AVR-libc](https://www.nongnu.org/avr-libc/), which is the C implementation for the ATmega328 and other [AVR-architecture](https://en.wikipedia.org/wiki/Atmel_AVR) microcontrollers.

### Arduino's words:
> "[Can I program the Arduino board in C?](https://support.arduino.cc/hc/en-us/articles/360018448219-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++](https://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_cplusplus) should work in Arduino. For more details, see the page on the [Arduino build process](https://www.arduino.cc/en/Hacking/BuildProcess)."

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

## When to use the [Arduino library](https://www.arduino.cc/reference/en/) 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][1], [Atom][2], [Visual Studio Code][3], or [Eclipse CDT][4] 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][5] here too) so consider using those techniques too.

## Update: Eclipse setup

See [my answer here](https://arduino.stackexchange.com/a/75491/7727) and my document here: [Eclipse setup instructions on a new Linux (or other OS) computer](https://docs.google.com/document/d/1LbuxOsDHfpMksGdpX5X-7l7o_TIIVFPkH2eD23cXUmA/edit?usp=sharing). I wrote a detailed PDF to describe setup.

  [1]: https://www.sublimetext.com/3
  [2]: https://atom.io/
  [3]: https://code.visualstudio.com/
  [4]: https://www.eclipse.org/cdt/
  [5]: http://playground.arduino.cc/Code/Eclipse


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

<!-- language: lang-none -->

 // 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)**

<!-- language: lang-cpp -->

    #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);
        }
    }

body:
As I mentioned in my comments to your question, if you are using [this][1] 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,"i",previous);
        Serial.println(buffer);
       digitalWrite(LED, !digitalRead(LED));
      }
    }

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

 ![look at packet 0102][2]

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,"u",(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.

![add API frame][3]

and click "the create frame using form generator tool"

![form generator tool][4]

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

![result][5]

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

  [1]: https://code.google.com/p/xbee-arduino/
  [2]: https://i.stack.imgur.com/dEu73.png
  [3]: https://i.stack.imgur.com/C2tmh.png
  [4]: https://i.stack.imgur.com/QtGD0.png
  [5]: https://i.stack.imgur.com/db0eF.png


body:
`#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:
              }
          }
      }`


message:
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:

1. Write new sketch/firmware
2. Compile firmware
3. Write a copy firmware onto Arduino A as data (Arduino A is set up to work as ISP)
4. Detach Arduino A from the computer
5. In a seperate location attach Arduino A to Arduino B using ISP headers
6. 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.

body:
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](http://blog.schicks.net/wp-content/uploads/2009/09/bootloader_faq.pdf) ;
 - [The Optiboot Project](http://code.google.com/p/optiboot/) which goal is to make the smallest bootloader possible and
 - [AVRISP](http://code.google.com/p/micropendous/wiki/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


body:
I think [µProg – tiny, fast, portable AVR programmer with SD](http://mdiy.pl/uprog-maly-szybki-przenosny-programator-avr-z-sd/?lang=en) 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

![enter image description here][1]

  [1]: https://i.stack.imgur.com/XZRUr.jpg


message:
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][1] (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:**

1. Why the second code sample works perfectly, whereas the first does not?

2. Is there, in standard Arduino included code, some code that would overwrite some of the settings I perform for Timer2 in `Timer::Timer()`?

3. 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()`.

  [1]: http://www.atmel.com/Images/doc8161.pdf

body:
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()
    {
    }


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


body:
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()
    {
    }


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


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

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


body:
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);


message:
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:  <br/>

>    **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);
      }
    }

body:
There are several things here:

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

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

3. 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--;
        }
    }


message:
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][3]. (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.

>![Connection shown][1]

*Source: [https://bluegiga.zendesk.com/entries/22412436][2]*

  [1]: https://i.stack.imgur.com/OwjIi.jpg
  [2]: https://bluegiga.zendesk.com/entries/22412436
  [3]: https://dl.dropboxusercontent.com/u/65932667/Bluetooth_Smart_Configuration_Guide_v33.pdf

body:
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


body: 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


body:
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*:

 1. Go to the <*usart* > tag and set *flow = "false"*. This "disengages" the RTS and CTS allowing a traditional two wire interface.
 2. 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).


body:
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


message:
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?

body:
> 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](http://arduino.cc/en/Reference/SoftwareSerial):*

> 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](http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html).

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


message:
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?**

body:
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);


message:
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?)

body: The base Arduino source files are in the Arduino installation, under [`cores/arduino/`](https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino). Source for additional libraries included are in [`libraries/`](https://github.com/arduino/ArduinoCore-avr/tree/master/libraries).


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

![Path to library sources (Arduino-Mac)][1]

  [1]: https://i.stack.imgur.com/pY7yE.png


body:
The code is also available online for those times you don't have the IDE installed:

https://github.com/arduino/Arduino


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


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

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

  [1]: https://github.com/arduino/Arduino
  [2]: https://github.com/arduino/Arduino/tree/master/hardware#cores-have-been-moved


body: 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`


message:
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?

body:
This seems to be possible with `as3Glue` as per the [docs][1]:

> 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][2]:

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

  [1]: https://code.google.com/p/as3glue/
  [2]: https://code.google.com/p/as3-arduino-connector/


message:
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....][1]
 - [Upload Timeout Error on Mega 2560 - Not Sure What Changed][2]

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.

  [1]: http://forum.arduino.cc/index.php?topic=135451.0
  [2]: http://forum.arduino.cc/index.php/topic,83079.msg659993.html#msg659993

body:
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


body:
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][1].

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.

  [1]: https://stackoverflow.com/questions/19645441/avrdude-stk500v2-receivemessage-timeout/45167540#45167540


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


message:
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?

body:
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


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


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


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

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


message:
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?

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


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


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


message:
Reading a varying voltage into Arduino

Using an [Arduino Nano][1] and a [current transformer ][2] (CT), I'm trying to sense the current flowing through a 120 V 60 Hz line.

**Circuit**

CT outputs `0-1 V` according to its specifications. This output is biased `AREF/2` = 2.5 V.

![Enter image description here][3]

**`analogRead` Values**

The x-axis represents the index number of the ADC sample, while the y-axis represent the ADC value (0-1024). Sampling rate is about 9 kHz. Peak-to-peak difference is about 1026 samples.

![Enter image description here][4]

Is this waveform what you would expect from the CT? Why are there regions where the values are flat, rather than varying continuously?

Furthermore, if we look at the curve part of the plot, why is Arduino reading values both above `512` and below `512` alternately? It reads a value above `512`, then a value below `512`, then a value above `512` and so on.

Time taken for an `analogRead` was measured to be 110 microseconds for my setup and there are 1026 samples between the waveform peaks. That means there will be about 9 peaks in 1 second, although I would expect 60 peaks since we are sensing a 60 Hz line. What do you make out of this? There's a capacitor, `C1`, in the circuit, would it have anything to do with this?

Are these analogRead values suitable to be used to calculate the RMS voltage, and hence the RMS current passing through the wire being sensed? The final goal of this is to calculate the power usage after determining the RMS current flowing through the wire.

**[Sketch][5] used to get values for plot**

    void setup() {
        Serial.begin(9600);
    }

    void loop() {
       double sensorValue = analogRead(1);
       Serial.println(sensorValue)
    }

**Actual `analogRead` data points in the bump regions**

    487
    534
    487
    535
    488
    537
    484
    536
    487
    538
    486
    536
    484
    540
    484
    539
    485
    540
    483
    540
    484
    541
    481
    539
    481
    540
    484
    540
    480
    543
    484
    539
    481
    540
    484
    541
    486
    542
    485
    538
    485
    538
    488
    535
    489
    534
    491
    530
    491
    529
    493
    531
    492
    526
    498
    526
    499
    524
    499
    520
    503
    518
    502
    518
    507

----------

**Plot of analogRead values**

The analogRead values are now stored in a buffer before being transmitted over Serial. There are now 55 ADC datapoints making up 1 period. Considering the analogRead time is 110 µs, each cycle takes 6.05 ms, giving us a frequency of 165 Hz! What may have gone wrong?

![Enter image description here][6]

    void loop() {
        double sensorValue = analogRead(1);
        char buf[32];

        dtostrf(sensorValue, 8, 2, buf);
        value = buf;

        if (stop == 0) {
            if (i < 10000) {
                message += ',';
                message += value;
                i++;
            }
            else {
                stop = 1;
                Serial.println(message);
            }
        }
    }

  [1]: http://arduino.cc/en/Main/ArduinoBoardNano
  [2]: http://www.seeedstudio.com/depot/Noninvasive-AC-Current-Sensor-30A-max-p-519.html
  [3]: https://i.stack.imgur.com/tgpsQ.png
  [4]: https://i.stack.imgur.com/2Gdcc.png
  [5]: http://www.arduino.cc/en/Tutorial/Sketch
  [6]: https://i.stack.imgur.com/Wjw7T.png

body:
Regarding your measurements, I would completely disregard the first set with Serial.println() in the loop. I would exepect the timing of this to be unreliable.

Your second set of data that you captured in a buffer looks correct, but your Frequency Estimation / timing may be wrong. I would invert a Digital Output at each loop iteration. You can measure the frequency of that with a Multimeter and your ADC sample rate would be twice that value.

For a PC or laptop power supply that's quite a common current waveform.

Without effective Power Factor Correction the current signal shown below would be quite typical (source: [http://www.nlvocables.com/blog/?p=300][1])

![http://www.nlvocables.com/blog/?p=300][2]

You will need to calculate RMS values and it would be wise to filter the signal.

[Here's an instructable][3] I wrote on how to build and code an Arduino Yun based Electricity Monitor with Cloud Support / Temboo and Google Drive. It should be of some help to you.

  [1]: http://www.nlvocables.com/blog/?p=300
  [2]: https://i.stack.imgur.com/oAAF2.gif
  [3]: http://www.instructables.com/id/Yun-based-Electricity-Monitor-with-Cloud-Support-T/


body: if you are measuring a resistive load I would say that the burden resistor you have chosen is wrong, there are some cheap CT's on ebay (SCT-013-xxx) that have versions with and without the burden resistors, these work well for their price but you must read the datasheet. the SCT-013-000 requires a 20R resistor to get 1V out with a 100A load, if this resistor is wrong you can get a severely distorted waveform when measuring higher currents (similar to those you have provided), you would expect the signal to distort more the lower the burden resistor value but this is not the case with CT's.


message:
Pressure transducer / sensor (0.5 - 4.5V) innacurate analog pin readings

I have a relatively cheap 0-15psi pressure transducer. It has 3 pins - ground 5V and signal. The signal outputs a voltage of 0.5V to 4.5V based on pressure from 0psi to 15psi. I can verify it does respond to significant pressure increases so it works at least to a point.

The issue is that the reading from arduino can differ by over 50% when at ambient atmospheric pressure (resting on a table). It should be significantly more accurate if the sensor data are to be trusted. The code is basic:

    void setup(){
      Serial.begin(9600);
    }

    void measurePressure(){
      int rawReading = analogRead(A0);   // Range : 0..1024
      //float rawVoltage = (rawReading * (4.5 / 1023.0)) + 0.5;

      Serial.print("Raw reading: ");
      Serial.println(rawReading);

    }

    void loop() {
      measurePressure();
      delay(1000);
    }

The output variations are not entirely random, it seems that the reading goes down and up in intervals of roughly 5-15 seconds. Below is a sample output:

    Raw reading: 61
    Raw reading: 67
    Raw reading: 70
    Raw reading: 73
    Raw reading: 74
    Raw reading: 78
    Raw reading: 75
    Raw reading: 82
    Raw reading: 85
    Raw reading: 90
    Raw reading: 89
    Raw reading: 97
    Raw reading: 103
    Raw reading: 119
    Raw reading: 146
    Raw reading: 165
    Raw reading: 171
    Raw reading: 168
    Raw reading: 163
    Raw reading: 150
    Raw reading: 143
    Raw reading: 118
    Raw reading: 88
    Raw reading: 70
    Raw reading: 62
    Raw reading: 64
    Raw reading: 72
    Raw reading: 78
    Raw reading: 80
    Raw reading: 82
    Raw reading: 88
    Raw reading: 92
    Raw reading: 102
    Raw reading: 134
    Raw reading: 160
    Raw reading: 170
    Raw reading: 172
    Raw reading: 166
    Raw reading: 158
    Raw reading: 149
    Raw reading: 132
    Raw reading: 100
    Raw reading: 73
    Raw reading: 63
    Raw reading: 61
    Raw reading: 71
    Raw reading: 77
    Raw reading: 79
    Raw reading: 84
    Raw reading: 90
    Raw reading: 90
    Raw reading: 99
    Raw reading: 134
    Raw reading: 161
    Raw reading: 170
    Raw reading: 166
    Raw reading: 161
    Raw reading: 151
    Raw reading: 133
    Raw reading: 103
    Raw reading: 81
    Raw reading: 68
    Raw reading: 63
    Raw reading: 63
    Raw reading: 71
    Raw reading: 73
    Raw reading: 81
    Raw reading: 83
    Raw reading: 85
    Raw reading: 89
    Raw reading: 98
    Raw reading: 128
    Raw reading: 161
    Raw reading: 171
    Raw reading: 166
    Raw reading: 159
    Raw reading: 145
    Raw reading: 120
    Raw reading: 85
    Raw reading: 67
    Raw reading: 57
    Raw reading: 63
    Raw reading: 72
    Raw reading: 75
    Raw reading: 83
    Raw reading: 85
    Raw reading: 89
    Raw reading: 97
    Raw reading: 130
    Raw reading: 164
    Raw reading: 172
    Raw reading: 163
    Raw reading: 155
    Raw reading: 135
    Raw reading: 101
    Raw reading: 69
    Raw reading: 60
    Raw reading: 62
    Raw reading: 72
    Raw reading: 78

I tried adding 4.7k pull down resistor with no change but that was just a blind try. I have a multimeter connected as well and the reading seems to be more stable ranging from about 0.495V to 0.535V (variations do not seem to match arduino output).

What could be causing the issue?

body:
> I tried same setup with arduino uno and the problem is gone. It also works on micro as long as gnd and 5v pin is connected to uno. Uno measured voltage is 4.88V and micro 4.60V could a voltage difference this small cause this? What else could this be?

Reinstatement of incorrect edits by Annonomus Person
(AP: Please do not edit answers in such a way that you entirely change their meaning. In the current discussion "the board" is meaningless. We are trying to distinguish between symptoms seen in two different 'boards', an Arduino Uno, and an Arduino Micro.)

Looks to me like the problem is with the Arduino Micro's 5V supply then.

If you are powering the Micro from an external supply (not USB), then 4.6V on the Micro's "5V" output would indicate that the 5V regulator is not operating within its expected range.

If you _are_ powering from USB, then the regulator is not in play. The 4.6V would indicate a problem with the USB's 5V supply.

Likely possibilities:, either the upstream supply is inadequate, or the micros and whatever is attached to it is drawing too much current.

I suspect that the transducer output is fluctuating in a way that's too rapid to be seen by your meter, but which is sampled by the Arduino Micro, giving your varying result numbers.

Either the "4.6V" is inadequate to run the transducer, causing erratic transducer output, or the 4.6V itself is fluctuating, with similar results at the trans output.

And you might also check the ground between micro and transducer -- are you sure that's wired correctly?


message:
Project Showcase '14

>

> The logo is a derivative of the [Arduino Community Logo][1] licensed under [Creative Commons license CC-SA-BY-NC 3.0][2]

# Update: Winners Announced
The winners of the contest have been announced. Please see the [Meta post for details][3].

To celebrate [10 years of Arduino][4], we are proud to announce the *first event ever* on Arduino Stack Exchange.

> Get your boards and soldering equipment out, dig out the ICs and
> resistors. The first Arduino Stack Exchange contest is just round the
> corner. We will be looking for interesting projects that are built
> using Arduinos. The contest is aimed towards sharing, discussing and
> providing feedback on projects that you and other members are working
> on. [See announcement post][5]

# Details:

 - The prize is an official **Stack Exchange t-shirt**
 - Limit two entries per person. If more than two are provided, only the first two will be considered.
 - Clones *are* allowed.
 - Projects for consideration will be accepted through **March 29th, 2014 at 4:00 UTC.** The question will still remain open in case someone wants to show off their project they made on Arduino Day 2014.

Visit the [Meta post][6] for discussion about this event and further information.

# Answer Format

You may post up to two projects (as two separate answers) as entries for the contest. All extra entries will be deleted. Consider following the following template for entries:

> # Project Title
>
> **Very Brief Description**
>
> # Description
>
> What is your project? What does it do? What problem does it solve?
>
> # Design
>
> Things to include in this section:
>
> - Schematics and other design documentation. [Fritzing][7] is a good tool for drawing breadboard schematics like the one shown in the
> project logo above.
> - Components used to build the project
> - Pictures or video
>
> # Conclusion
>
> Final thoughts. What did you learn from doing this project? What would
> you do differently if you had to start over?

You can copy/paste the following text if you want to use this template.

    # Project Title
    **Very Brief Description**

    # Description
    What is your project? What does it do? What problem does it solve?

    # Design
    Things to include in this section:

    - Schematics and other design documentation. [Fritzing][8] is a good tool for drawing breadboard schematics like the one shown in the project logo above.
    - Components used to build the project
    - Pictures or video

    # Conclusion
    Final thoughts. What did you learn from doing this project? What would you do differently if you had to start over?

# Prizes

There are two prizes! The winner will be the submission getting the maximum number of upvotes (downvotes do not count) and will get a Stack Exchange T-shirt*! There will be something for the runner-up as well. The runner-up will be decided at the discretion of the event organizers.

*Certain restrictions may apply. International shipping may take a few weeks.

# Where do I submit my projects?
Post your projects as answers to this post.

  [1]: http://arduino.cc/en/Trademark/HomePage?from=Main.Trademark
  [2]: http://creativecommons.org/licenses/
  [3]: https://arduino.meta.stackexchange.com/questions/184/project-showcase-14-winners
  [4]: http://day.arduino.cc/
  [5]: https://arduino.meta.stackexchange.com/questions/153/project-showcase-14-is-coming-to-arduino-stack-exchange-updated-3-19-14
  [6]: https://arduino.meta.stackexchange.com/questions/171/project-showcase-14-detailed-information
  [7]: http://fritzing.org/home/
  [8]: http://fritzing.org/home/

body:
# ShiftLCD
**AVR based, Arduino compatible, board that mounts to the back of an 8x1 up to 20x4 Character LCD Screen.**

# Description
I just designed this board and the custom library to make it easier to use and LCD. Though they are pretty easy to use at the moment. It cuts down the number of output pins used from 6 to 3. It also has the option to expand the I/O by adding more shift registers on to the one that drives the display. The processor used is an ATTiny45 or ATTiny85 which has, after using the shift register, digital pins 1 (PWM) and 4 available and analog pin 2 (same pin as digital pin 4) available.

# Design

* [OSH Park permalink which has parts listed][1]<br>
* [Arduino Library][2]

![Schematic][3]
![OSH Park render][4]
![Unsoldered Board][5]

# Challenges
One unforeseen challenge I faced was when I started I was using digital pins 0-2 to run the shift register, these also happened to be the programming pins (MISO, MOSI, SCK). So every time I reprogrammed the device the LCD would get sent a whole bunch of gibberish messages where the power would have to be turned off in order to reset the display. I solved this problem by moving the shift registers latch pin to digital pin 3 which is not a programming pin. Solving this also solved another problem for me because when I moved the latch pin it opened up digital pin 1 which had PWM usage, allowing for more things to be done with the board.

# Conclusion
Granted this may not be the coolest product or idea, it still has its uses. The answer the question directly, "What did you learn from doing this project" I learned how to design from start to finish a PCB board. If I could do anything differently it would have been to use surface mount parts instead of through hole, then again it is just a prototype, one-off board.

  [1]: http://oshpark.com/shared_projects/LKBJyhOP
  [2]: https://github.com/jamolnng/Arduino/tree/master/libraries/ShiftLCD
  [3]: https://i.stack.imgur.com/3nETo.png
  [4]: https://i.stack.imgur.com/aXSfc.png
  [5]: https://i.stack.imgur.com/DqIuw.jpg


body:
# Energy saver for the absent-minded PC user
**This device switches on/off my desk lights when it is dark(ish) and in sync with my PC screensaver.**

# Description
The project is little more than an combination of a light sensitive sensor, a relay and some smart code that monitors the screensaver on my PC. When it is dusk and when screen saver is not active, it switches on the lights over my desk. When I subsequently leave my desk the screensaver will activate, which will in turn trigger the desk light to be turned off. When there is enough light during day time, the lights are not switched on at all. The problem solved is to reduce the waste of energy due to the lighting in my office being switched on when I have left the room.

# Design
Because the power of microcontrollers / Arduino only a little extra hardware is required to create a useful project. The same goes for this project where the hardware is little more than:

- An Arduino
- A couple of screw shields to connect the external components
- An [LDR][1] in series with a resistor to measure ambient light
- A relay card to switch on and off the mains powered lights
- A 10 μF capacitor from GND to RST to prevent the board from being reset and accidentally being programmed.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/cQlSi.png)

<!-- End schematic -->

# Conclusion
I learned how to interface the PC over the USB serial link with Arduino and how to read current state of the screensaver on my PC. If I would start over, I'd use a much smaller controller as I really only need a single digital output and a single analog input. Probably base the project on [V-USB][2]. Arduino however is excellent for the quick and easy proof of concept (PoC). (The PoC has been on my desk for at least two years already).

  [1]: https://en.wikipedia.org/wiki/Photoresistor
  [2]: http://www.obdev.at/products/vusb/index.html


body:
# <small>(fake)</small> Linux on Arduino

**I recently acquired a small composite LCD screen, which I quickly began playing with using the Arduino TVout library. What came next? Linux!**

Description
----

While playing around with my TV screen and the TVout library, I discovered there is a premade terminal handler for the TV. I soon began to experiment with using it as a TV terminal hooked up to a PS/2 keyboard. There were some problems with the PS/2 library I used, so I transitioned it to use the USB library on my Mega ADK along with a USB keyboard. That worked much better. Now for storage.

My SD card shield isn't compatible with my Mega, so I wired it up somewhat haphazardly to the SPI at the end of the board. I wrote command handling to preform a few tasks like listing files and finding disk size, free space, etc.. The entire assembly isn't by any means finished, but I am happy with the progress I have made.

The code will be relocated to Github eventually, watch the comments.

Design
---

![zoomed out pic][1]

![clse up screen][2]

Challenges
--

I had a lot of trouble concatenating the inputted charactars to the string storing the current command because I wasn't casting right. Once I got that figured out, I also needed to fix the problem where some keys printed random garbage to the screen. This was caused by reading memory before the letter definitions, so a few `if`s cleared that up.

Conclusion
--

I am very satisfied with the code. Once I add a few more utilities to it, I will put it on Github, so watch the comments. Overall, it was a very fun project. I learned how to use Stino in the process.

  [1]: https://i.stack.imgur.com/cgzPU.jpg
  [2]: https://i.stack.imgur.com/L9PmB.jpg


body:
# Sonic Ray Gun
**Two projects by kids**

I'm working with a couple of home educated kids and we are having a lot of fun with an arduino. Their first project was a fake-bomb, like you see in the movies, with a LCD countdown timer and a classic "do you cut the red or blue wire?" type problem.

Project two started with showing them the toneMelody example and a small speaker. The quickly found out that if you turn the frequency up to 15kHz it was rather annoying to teenagers. An hour later they had improved the design with a cup, toilet roll and a switch made from a paperclip making a directional sonic ray gun.

Sadly no pictures.

# Conclusion
Don't leave kids unattended with an arduino.