message:
Arduino or Raspberry Pi for my project

A brief description of what I'm doing here. I wanna make a pet project, basically a device (be it Arduino or raspberry pi) that I can connect to via bluetooth / wifi (both preferably), that will be connected to a stereo system and allow me to play music. I essentially want to make a wireless sound system in my house.

My question is, is raspberry pi more adequate for my needs? Or would arduino get the job done? I know that raspberry pis are essentially mini computers, so I feel that the raspberry pi would be too much, since all I really need to do is design a bluetooth / wifi interface and send the signal to the aux cable connected to the stereo.

Any help would be really useful here. I've never worked with either/or, and this is my first project with Arduino / Raspberry pi (hello world). Thanks in advance.

EDIT: In response to comments below, a greater idea of what I want to do:

I want to design an item that will appear on local wifi as a sound device. i.e. on an imac / macbook I'd be able to right click on the speaker icon in the upper right and select it there). From there, I'm hoping to stream audio to the device, and have it play to a stereo that the arduino / raspberry pi would be connected to. I'd love to make this universal (i.e. possible to connect via your android phone / a windows machine), but I can imagine that part being a lot more difficult. I'd also like to add bluetooth functionality at some point, but that'd be in the future. Hopefully this gives everybody more of an idea of what I'd like to achieve here! I appreciate all the help so far.

body:
As mentioned in the comments, a Raspberry Pi would be superior here.

The standard AVR (not Due/Galileo/Yun) Arduino is superior to the Pi in only one area: IO. It has a 5V logic that's more compatible than the Pi's 3.3V (although you can use a *logic level shifter*). The Arduino also features more PWM pins and an ADC, along with interrupts. An Arduino also is a lot simpler to use for basic projects, but it becomes impractical when you need more computing power.

A Pi excels at the data-crunching side of things. It can handle a lot more data than the Arduino could ever dream of, and then some! Just to put things in perspective, the Pi has a clock speed of 700 MHz by default and the Arduino Uno has one of 16 MHz (with a less powerful architecture).

For your purpose, the Pi's audio jack and ethernet port are unmatched on the Arduino. *Sure*, you can get shields that replicate these behaviors, but the Pi's built in functionality doesn't cost extra and it's more powerful.


sender: user

message:
How to check whether my Arduino is working? And how to fix this?

I tried my first project with Arduino Uno. But I can't upload any code. Power green LED is working and orange LED is always on, not blinking, and IC also getting hot. What can I do to fix this problem?

sender: assistant

body:
My suggestion is to find someone else with an arduino, and get them to test (with their computer, known to be working) uploading to your Arduino. That way, you can tell if the problem is with your computer or the Arduino.

You haven't mentioned what your first project was. The most common mistake #1 is to light up an LED without a resistor. If you do that for a split second, you might (OR MIGHT NOT!) get away with it. If you leave it running for a few seconds, you are almost certainly going to burn out your AtMega (the IC on the board). This might very well result in the symptoms you describe. If this has happened, and your chip (IC) is removable (some are, some aren't), you should be able to buy a new chip of the same kind. An Arduino Uno has an AtMega 328, you will want a DIP package (they are the removable ones), and you will want one with an Arduino Bootloader pre-programmed. Replacing the chip may OR MAY NOT fix the problem. Make sure you note down the orientation of the broken chip before you pull it out - it will fit in, but won't work (and could burn out!) if you put it in the wrong way. There should be a little dimple at one end of the chip, right on the end. It should look like this (possibly without the pin labeling sticker): http://www.jaycar.co.nz/productView.asp?ID=ZZ8726&w=atmega328&form=KEYWORD

If your chip is not removable, or replacing the chip doesn't help, then you will need to get a new Arduino.


message:
error: 'CLASS' does not name a type only when creating object inside another object

I'm trying to use [Adafruit's LED Backpack library][1] within a custom class. When I use the Adafruit library directly within a sketch, it compiles fine. When I use an example sketch provided with the library, it compiles fine. However when I create an instance of my custom class with the Adafruit object within it, I get the following error:

> In file included from sketch_feb18a.ino:6:
/Users/lawnmowerlatte/Documents/Arduino/libraries/Bargraph/bargraph.h:18: error: 'Adafruit_24bargraph' does not name a type

All the reasons I've seen for this error stem from the library being missing or otherwise incorrectly installed. However, since I can use it directly, I think something else must be wrong.

**Working**

    #include <Adafruit_LEDBackpack.h>
    #include <Adafruit_GFX.h>
    Adafruit_24bargraph bar = Adafruit_24bargraph();

    void setup() { }
    void loop() { }

**Not Working**

    #include <bargraph.h>
    Bargraph bargraph = Bargraph("Test", "api", 0);

    void setup() { }
    void loop() { }

**bargraph.h**

    #ifndef Bargraph_h
    #define Bargraph_h

    #include <Adafruit_GFX.h>
    #include <Adafruit_LEDBackpack.h>

    #if (ARDUINO >= 100)
    #include <Arduino.h>
    #else
    #include <WProgram.h>
    #endif

    class Bargraph {
      public :
        String name;
     String api;
     Adafruit_24bargraph bar;

     Bargraph(String _name, String _api, int _device,
      String _type="Default");

     void set(String _value);
     void setMax(String _max);
     void update();
        void print();

      private :
       int display[24];

     long max;
     long value;
     int device;
     int size;
     String type;

     void format();
     void write();
    };

    #endif

**bargraph.cpp**

    #define OFF 0
    #define RED 1
    #define YELLOW 2
    #define GREEN 3

    #include <bargraph.h>

    #if (ARDUINO >= 100)
    #include <Arduino.h>
    #else
    #include <WProgram.h>
    #endif

    Bargraph::Bargraph(String _name, String _api, int _device, String _type) : bar() {
     name  = _name;
     api   = _api;
     max   = _max.toLong();
     device  = _device;
     type  = _type;
     value  = 0;

     for (int i=0; i<24; i++) {
      display[i] = OFF;
     }

     bar.begin(0x70+device);
    }

    **Methods Omitted for Brevity**

Can anyone explain what's going on here? I'm pretty certain my class syntax is correct as I have other object-in-object relationships working. I can post code to GitHub if anyone would like to see more context.

  [1]: https://github.com/adafruit/Adafruit-LED-Backpack-Library

body:
I think these lines still need to be in your main sketch file (in addition to being in your custom class file):

    #include <Adafruit_LEDBackpack.h>
    #include <Adafruit_GFX.h>

If I remember the Arduino IDE quirks correctly, it uses the `#include` directives in the main sketch file to determine which libraries to actually link. It's one of those annoying features that was intended to be beginner-friendly but sometimes just makes things more confusing.


body:
If you used the serial port, Arduino sometimes causes confusion.
Close Arduino IDE and
delete files in folder C:/users/[your name]/AppData/Local/Temp/
Its working.
Regards


message:
Arduino interruption (on pin change)

I use the interrupt function to fill an array with values received from `digitalRead()`.

```c++
void setup() {
    Serial.begin(115200);
    attachInterrupt(0, test_func, CHANGE);
}

void test_func() {
    if (digitalRead(pin) == HIGH) {
        test_array[x] = 1;
    } else if(digitalRead(pin) == LOW) {
        test_array[x] = 0;
    }
    x = x + 1;
}
```

That problem is that when I print `test_array` there are values like: `111` or `000`.

As I understand it, if I use the `CHANGE` option in the `attachInterrupt()` function, then the data sequence should always be `0101010101` without repeating.

The data changes quite fast since it comes from a radio module.

body:
The interrupt is being set to fire on a change, and your test_func is set as the Interrupt Service Routine (ISR), called to service that interrupt. The ISR then prints the value of the input.

At first glance you would expect the output to be as you have said, and alternating set of high lows, as it only gets to the ISR on a change.

But what we're missing is that there is a certain amount of time that it takes for the CPU to service an interrupt and branch to the ISR.
During this time the voltage on the pin may have changed again. Particularly if the pin is not stabilised by hardware de-bouncing or similar. Because the interrupt is already flagged and hasn't been serviced yet, this extra change (or many of them, because a pins level can change very quickly relative to the clock speed if it has low parasitic capacitance) will be missed.

So in essence without some form of de-bouncing, we have no guarantee that when the input changes, and the interrupt gets marked for servicing, that the input will still be at the same value when we get to reading its value in the ISR.

As a generic example the [ATmega328 Datasheet][1]  used on the Arduino Uno details interrupt times in section 6.7.1 - "Interrupt Response Time". It states for this microcontroller the minimum time to branch to an ISR for servicing is 4 clock cycles, but can be more (extra if executing multi-cycle instruction at interrupt or 8 + sleep wake time if the MCU is in sleep.)

As @EdgarBonet mentioned in comments, the pin could also similarly change during ISR execution. Because the ISR reads from the pin twice, it would not add anything to the test_array if it encountered a LOW on the first read and a HIGH on the second. But x would still increment, leaving that slot in the array unchanged (possibly as uninitialised data depending on what was done to the array earlier).

His one line ISR of `test_array[x++] = digitalRead(pin);` is a perfect solution to this.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf "ATmega328"


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

**As a sort of prologue** to this overly long answer...

This question got me deeply captivated with the problem of interrupt
latency, to the point of losing sleep in counting cycles instead of
sheep. I am writing this response more for sharing my findings
than for just answering the question: most of this material may actually
not be at a level suitable for a proper answer. I hope it will be
useful, however, for readers that land here in search of solutions for
latency problems. The first few sections are expected to be useful to a
wide audience, including the original poster. Then, it gets hairy along
the way.

Clayton Mills already explained in his answer that there is some latency
in responding to interrupts. Here I will focus on quantifying the
latency (which is _huge_ when using the Arduino libraries), and on the
means to minimize it. Most of what follows is specific to the hardware
of the Arduino Uno and similar boards.

# Minimizing the interrupt latency on the Arduino

(or how to get from 99 down to 5 cycles)

I will use the original question as a working example, and restate the
problem in terms of interrupt latency. We have some external event that
triggers an interrupt (here: INT0 on pin change). We need to take some
action when the interrupt is triggered (here: read a digital input). The
problem is: there is some delay between the interrupt being triggered
and our taking the appropriate action. We call this delay "_interrupt
latency_". A long latency is detrimental in many situations. In this
particular example, the input signal may change during the delay, in
which case we get a faulty reading. There is nothing we can do to avoid
the delay: it is intrinsic to the way interrupts work. We can, however,
try to make it as short as possible, which should hopefully minimize the
bad consequences.

The first obvious thing we can do is take the time-critical action,
inside the interrupt handler, as soon as possible. This means calling
`digitalRead()` once (and only once) at the very beginning of the
handler. Here is the zeroth version of the program upon which we will
build:

    #define INT_NUMBER 0
    #define PIN_NUMBER 2    // interrupt 0 is on pin 2
    #define MAX_COUNT  200

    volatile uint8_t count_edges;  // count of signal edges
    volatile uint8_t count_high;   // count of high levels

    /* Interrupt handler. */
    void read_pin()
    {
        int pin_state = digitalRead(PIN_NUMBER);  // do this first!
        if (count_edges >= MAX_COUNT) return;     // we are done
        count_edges++;
        if (pin_state == HIGH) count_high++;
    }

    void setup()
    {
        Serial.begin(9600);
        attachInterrupt(INT_NUMBER, read_pin, CHANGE);
    }

    void loop()
    {
        /* Wait for the interrupt handler to count MAX_COUNT edges. */
        while (count_edges < MAX_COUNT) { /* wait */ }

        /* Report result. */
        Serial.print("Counted ");
        Serial.print(count_high);
        Serial.print(" HIGH levels for ");
        Serial.print(count_edges);
        Serial.println(" edges");

        /* Count again. */
        count_high = 0;
        count_edges = 0;  // do this last to avoid race condition
    }

I tested this program, and the subsequent versions, by sending it trains
of pulses of varying widths. There is enough spacing between the pulses
to ensure that no edge is missed: even if the falling edge is received
before the previous interrupt is done, the second interrupt request will
be put on hold and eventually serviced. If a pulse is shorter than the
interrupt latency, the program reads 0 on both edges. The reported
number of HIGH levels is then the percentage of correctly read pulses.

## What happens when the interrupt is triggered?

Before trying to improve the code above, we will take a look at the
events that unfold right after the interrupt is triggered. The hardware
part of the story is told by the Atmel documentation. The software part,
by disassembling the binary.

Most of the time, the incoming interrupt is serviced right away. It may
happen, however, that the MCU (meaning "microcontroller") is in the
middle of some time-critical task, where interrupt servicing is
disabled. This is typically the case when it is already servicing
another interrupt. When this happens, the incoming interrupt request is
put on hold and serviced only when that time-critical section is done.
This situation is hard to avoid completely, because there are quite a
few of those critical sections in the Arduino core library (which I will
call "_libcore_" in the following). Fortunately, these sections are
short and run only every so often. Thus, most of the time, our interrupt
request will be serviced right away. In the following, I will assume
that we do not care about those few instances when this is not the case.

Then, our request is serviced immediately. This still involves a lot of
stuff that can take quite a while. First, there is a hardwired sequence.
The MCU will finish executing the current instruction. Fortunately, most
instructions are single-cycle, but some can take up to four cycles.
Then, the MCU clears an internal flag that disables further servicing of
interrupts. This is intended to prevent nested interrupts. Then, the PC
is saved into the stack. The stack is an area of RAM reserved for this
kind of temporary storage. The PC (meaning "_Program Counter_") is an
internal register holding the address of the next instruction the MCU is
about to execute. This is what allows the MCU to know what to do next,
and saving it is essential because it will have to be restored in order
for the main program to resume from where it was interrupted. The PC is
then loaded with a hardwired address specific to the request received,
and this is the end of the hardwired sequence, the rest being
software-controlled.

The MCU now executes the instruction from that hardwired address. This
instruction is called an "_interrupt vector_", and is generally a "jump"
instruction that will bring us to a special routine called an ISR
("_Interrupt Service Routine_"). In this case, the ISR is called
"\_\_vector\_1", a.k.a. "INT0\_vect", which is a misnomer because it is
an ISR, not a vector. This particular ISR comes from libcore. Like any
ISR, it starts with a _prologue_ that saves a bunch of internal CPU
registers on the stack. This will allow it to use those registers and,
when it is done, restore them to their previous values in order not to
disturb the main program. Then, it will look for the interrupt handler
that was registered with `attachInterrupt()`, and it will call that
handler, which is our `read_pin()` function above. Our function will
then call `digitalRead()` from libcore. `digitalRead()` will look into
some tables in order to map the Arduino port number to the hardware I/O
port it has to read and the associated bit number to test. It will also
check whether there is a PWM channel on that pin that would need to be
disabled. It will then read the I/O port... and we are done. Well, we
are not really done servicing the interrupt, but the time-critical task
(reading the I/O port) is done, and it is all that matters when we are
looking at latency.

Here is a short summary of all the above, together with the associated
delays in CPU cycles:

1. hardwired sequence: finish current instruction, prevent nested
   interrupts, save PC, load address of vector (≥ 4 cycles)
2. execute interrupt vector: jump to ISR (3 cycles)
3. ISR prologue: save registers (32 cycles)
4. ISR main body: locate and call user-registered function (13 cycles)
5. read\_pin: call digitalRead (5 cycles)
6. digitalRead: find the relevant port and bit to test (41 cycles)
7. digitalRead: read the I/O port (1 cycle)

We will assume the best case scenario, with 4 cycles for the
hardwired sequence. This gives us a total latency of 99 cycles, or
about 6.2 µs with a 16 MHz clock. In the following, I will
explore some tricks that can be used to lower this latency. They come
roughly in increasing order of complexity, but they all need us to
somehow dig into the internals of the MCU.

## Use direct port access

The obvious first target for shortening the latency is `digitalRead()`.
This function provides a nice abstraction to the MCU hardware, but it is
too inefficient for time-critical work. Getting rid of this one is
actually trivial: we just have to replace it with `digitalReadFast()`,
from the [digitalwritefast](https://code.google.com/p/digitalwritefast/)
library. This cuts the latency almost by half at the cost of a small
download!

Well, that was too easy to be any fun, I will rather show you how to do
it the hard way. The purpose is to get us started into low-level stuff.
The method is called "_direct port access_" and is nicely documented on
the Arduino reference at the page on [Port
Registers](http://www.arduino.cc/en/Reference/PortManipulation). At this
point, it is a good idea to download and take a look at the [ATmega328P
datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf).
This 650-page document may seem somewhat daunting at first look. It is,
however, well organised into sections specific to each of the MCU
peripherals and features. And we only need to check the sections
relevant to what we are doing. In this case, it is the section named
_I/O ports_. Here is a summary of what we learn from those readings:

* The Arduino pin 2 is actually called PD2 (i.e. port D, bit 2) on the
  AVR chip.
* We get the whole port D at once by reading a special MCU register called
  "PIND".
* We then check bit number 2 by doing a _bitwise logical and_ (the C ‘&’
  operator) with `1 << 2`.

So, here is our modified interrupt handler:

    #define PIN_REG    PIND  // interrupt 0 is on AVR pin PD2
    #define PIN_BIT    2

    /* Interrupt handler. */
    void read_pin()
    {
        uint8_t sampled_pin = PIN_REG;            // do this first!
        if (count_edges >= MAX_COUNT) return;     // we are done
        count_edges++;
        if (sampled_pin & (1 << PIN_BIT)) count_high++;
    }

Now, our handler will read the I/O register as soon as it is called. The
latency is 53 CPU cycles. This simple trick saved us 46 cycles!

## Write your own ISR

The next target for cycle-trimming is the INT0\_vect ISR. This ISR is
needed for providing the functionality of `attachInterrupt()`: we can
change interrupt handlers at any time during program execution. However,
although nice to have, this is not really useful for our purpose. Thus,
instead of having the libcore's ISR locate and call our interrupt
handler, we will save a few cycles by _replacing_ the ISR by our
handler.

This is not as hard as it sounds. ISRs can be written like normal
functions, we just have to be aware of their specific names, and define
them using a special `ISR()` macro from avr-libc. At this point it would
be good to have a look at the [avr-libc's documentation on
interrupts](http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html),
and at the datasheet section named _External Interrupts_. Here is the
short summary:

* We have to write a bit in a special hardware register called EICRA
  (_External Interrupt Control Register A_) in order to configure the
  interrupt to be triggered on any change of the pin value. This will be
  done in `setup()`.
* We have to write a bit in another hardware register called EIMSK
  (_External Interrupt MaSK register_) in order to enable the INT0
  interrupt. This will also be done in `setup()`.
* We have to define the ISR with the syntax `ISR(INT0_vect) { ... }`.

Here is the code for the ISR and `setup()`, everything else is
unchanged:

    /* Interrupt service routine for INT0. */
    ISR(INT0_vect)
    {
        uint8_t sampled_pin = PIN_REG;            // do this first!
        if (count_edges >= MAX_COUNT) return;     // we are done
        count_edges++;
        if (sampled_pin & (1 << PIN_BIT)) count_high++;
    }

    void setup()
    {
        Serial.begin(9600);
        EICRA = 1 << ISC00;  // sense any change on the INT0 pin
        EIMSK = 1 << INT0;   // enable INT0 interrupt
    }

This comes with a free bonus: since this ISR is simpler than the one it
replaces, it needs less registers to do its job, then the
register-saving prologue is shorter. Now we are down to a latency of 20
cycles. Not bad considering that we started close to 100!

At this point I would say we are done. Mission accomplished. What
follows is only for those who are not afraid of getting their hands
dirty with some AVR assembly. Otherwise you can stop reading here, and
thank-you for getting so far.

## Write a naked ISR

Still here? Good! For proceeding further, it would be helpful to have at
least some very basic idea of how assembly works, and to take a look at
the [Inline Assembler
Cookbook](http://www.nongnu.org/avr-libc/user-manual/inline_asm.html)
from the avr-libc documentation. At this point, our interrupt entry
sequence looks like this:

1. hardwired sequence (4 cycles)
2. interrupt vector: jump to ISR (3 cycles)
3. ISR prologue: save regs (12 cycles)
4. first thing in the ISR body: read the IO port (1 cycle)

If we want to do better, we have to move the reading of the port into
the prologue. The idea is the following: reading the PIND register will
clobber one CPU register, thus we need to save at least one register
before doing that, but the other registers can wait. We then need to
write a custom prologue that reads the I/O port right after saving the
first register. You have already seen in the avr-libc interrupt
documentation (you have read it, right?) that an ISR can be made
_naked_, in which case the compiler will emit no prologue or epilogue,
allowing us to write our own custom version.

The problem with this approach is that we will probably end up writing
the whole ISR in assembly. Not a big deal, but I would rather have the
compiler write those boring prologues and epilogues for me. So, here is
the dirty trick: we will split the ISR in two parts:

* the first part will be a short assembly fragment that will
    * save a single register to the stack
    * read PIND into that register
    * store that value into a global variable
    * restore the register from the stack
    * jump to the second part
* the second part will be regular C code with compiler-generated
  prologue and epilogue

Our previous INT0 ISR is then replaced by this:

    volatile uint8_t sampled_pin;    // this is now a global variable

    /* Interrupt service routine for INT0. */
    ISR(INT0_vect, ISR_NAKED)
    {
        asm volatile(
        "    push r0                \n"  // save register r0
        "    in r0, %[pin]          \n"  // read PIND into r0
        "    sts sampled_pin, r0    \n"  // store r0 in a global
        "    pop r0                 \n"  // restore previous r0
        "    rjmp INT0_vect_part_2  \n"  // go to part 2
        :: [pin] "I" (_SFR_IO_ADDR(PIND)));
    }

    ISR(INT0_vect_part_2)
    {
        if (count_edges >= MAX_COUNT) return;     // we are done
        count_edges++;
        if (sampled_pin & (1 << PIN_BIT)) count_high++;
    }

Here we are using the ISR() macro to have the compiler instrument
`INT0_vect_part_2` with the required prologue and epilogue. The compiler
will complain that "‘INT0\_vect\_part\_2’ appears to be a misspelled
signal handler", but the warning can be safely ignored. Now the ISR has
a single 2-cycle instruction before the actual port read, and the total
latency is only 10 cycles.

## Use the GPIOR0 register

What if we could have a register reserved for this specific job? Then,
we would not need save anything before reading the port. We can actually
ask the compiler to [bind a global variable to a
register](https://gcc.gnu.org/onlinedocs/gcc/Global-Reg-Vars.html).
This, however, would require us to recompile the whole Arduino core and
libc in order to make sure the register is always reserved. Not really
convenient. On the other hand, the ATmega328P happens to have three
registers that are not used by the compiler nor any library, and are
available for storing whatever we want. They are called GPIOR0, GPIOR1
and GPIOR2 (_General Purpose I/O Registers_). Although they are mapped
in the I/O address space of the MCU, these are actually _not_ I/O
registers: they are just plain memory, like three bytes of RAM that
somehow got lost in a bus and ended up in the wrong address space. These
are not as capable as the internal CPU registers, and we cannot copy
PIND into one of these with the `in` instruction. GPIOR0 is interesting,
though, in that it is _bit-addressable_, just like PIND. This will allow
us to transfer the information without clobbering any internal CPU
register.

Here is the trick: we will make sure that GPIOR0 is initially zero (it
is actually cleared by hardware at boot time), then we will use the
`sbic` (Skip next instruction if some Bit in some I/o register is Clear)
and the `sbi` (Set to 1 some Bit in some I/o register) instructions as
follows:

    sbic PIND, 2   ; skip the following if bit 2 of PIND is clear
    sbi GPIOR0, 0  ; set to 1 bit 0 of GPIOR0

This way, GPIOR0 will end up being 0 or 1 depending on the bit we wanted
to read from PIND. The sbic instruction takes 1 or 2 cycles to execute
depending on whether the condition is false or true. Obviously, the PIND
bit is accessed on the first cycle. In this new version of the code, the
global variable `sampled_pin` is not useful anymore, since it is
basically replaced by GPIOR0:

    /* Interrupt service routine for INT0. */
    ISR(INT0_vect, ISR_NAKED)
    {
        asm volatile(
        "    sbic %[pin], %[bit]    \n"
        "    sbi %[gpio], 0         \n"
        "    rjmp INT0_vect_part_2  \n"
        :: [pin]  "I" (_SFR_IO_ADDR(PIND)),
           [bit]  "I" (PIN_BIT),
           [gpio] "I" (_SFR_IO_ADDR(GPIOR0)));
    }

    ISR(INT0_vect_part_2)
    {
        if (count_edges < MAX_COUNT) {
            count_edges++;
            if (GPIOR0) count_high++;
        }
        GPIOR0 = 0;
    }

It should be noted that GPIOR0 has to always be reset in the ISR.

Now, the sampling of the PIND I/O register is the very first thing done
inside the ISR. Total latency is 8 cycles. This is about the best we can
do before getting stained with terribly sinful kludges. This is again a
good opportunity to stop reading...

## Put the time-critical code in the vector table

For those still here, here is our current situation:

1. hardwired sequence (4 cycles)
2. interrupt vector: jump to ISR (3 cycles)
4. ISR body: read the IO port (on 1st cycle)

There is obviously little room for improvement. The only way we could
shorten the latency at this point is by _replacing the interrupt vector
itself_ by our code. Be warned that this should be immensely distasteful
to anyone who values clean software design. But it is possible, and I
will show you how.

The layout of the ATmega328P vector table can be found in the datasheet,
section _Interrupts_, subsection _Interrupt Vectors in ATmega328 and
ATmega328P_. Or by disassembling any program for this chip. Here is how
it looks like. I am using avr-gcc and avr-libc's conventions (\_\_init
is vector 0, addresses are in bytes) which are different from Atmel's.

    address │ instruction     │ comment
    ────────┼─────────────────┼──────────────────────
     0x0000 │ jmp __init      │ reset vector
     0x0004 │ jmp __vector_1  │ a.k.a. INT0_vect
     0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
     0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
      ...
     0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

Each vector has a 4-byte slot, filled with a single `jmp` instruction.
This is a 32-bit instruction, unlike most AVR instructions which are
16-bit. But a 32-bit slot is too small to hold the first part of our
ISR: we can fit the `sbic` and `sbi` instructions, but not the `rjmp`.
If we do that, the vector table ends up looking like this:

    address │ instruction     │ comment
    ────────┼─────────────────┼──────────────────────
     0x0000 │ jmp __init      │ reset vector
     0x0004 │ sbic PIND, 2    │ the first part...
     0x0006 │ sbi GPIOR0, 0   │ ...of our ISR
     0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
     0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
      ...
     0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

When INT0 fires, PIND will be read, the relevant bit will be copied into
GPIOR0, and then the execution will fall through to the next vector.
Then, the ISR for INT1 will be called, instead of the ISR for INT0. This
is creepy, but since we are not using INT1 anyway, we will just "hijack"
its vector for servicing INT0.

Now, we just have to write our own custom vector table to override the
default one. It turns out it is not so easy. The default vector table is
provided by the avr-libc distribution, in an object file called
crtm328p.o that is automatically linked with any program we build.
Unlike library code, object-file code is not meant to be overridden:
trying to do that will give a linker error about the table being defined
twice. This means we have to replace the whole crtm328p.o with our
custom version. One option is to [download the full avr-libc source
code](http://download.savannah.gnu.org/releases/avr-libc/), do our
custom modifications in
[gcrt1.S](http://svn.savannah.nongnu.org/viewvc/*checkout*/trunk/avr-libc/crt1/gcrt1.S?root=avr-libc),
then build this as a custom libc.

Here I went for a lighter, alternative approach. I wrote a custom
crt.S, which is a simplified version of the original from avr-libc. It
lacks a few rarely used features, like the ability to define a "catch
all" ISR, or to be able to terminate the program (i.e. freeze the
Arduino) by calling `exit()`. Here is the code. I trimmed the repetitive
part of the vector table in order to minimize scrolling:

    #include <avr/io.h>

    .weak __heap_end
    .set  __heap_end, 0

    .macro vector name
        .weak \name
        .set \name, __vectors
        jmp \name
    .endm

    .section .vectors
    __vectors:
        jmp __init
        sbic _SFR_IO_ADDR(PIND), 2   ; these 2 lines...
        sbi _SFR_IO_ADDR(GPIOR0), 0  ; ...replace vector_1
        vector __vector_2
        vector __vector_3
        [...and so forth until...]
        vector __vector_25

    .section .init2
    __init:
        clr r1
        out _SFR_IO_ADDR(SREG), r1
        ldi r28, lo8(RAMEND)
        ldi r29, hi8(RAMEND)
        out _SFR_IO_ADDR(SPL), r28
        out _SFR_IO_ADDR(SPH), r29

    .section .init9
        jmp main

It can be compiled with the following command line:

    avr-gcc -c -mmcu=atmega328p silly-crt.S

The sketch is identical to the previous one except that there is no
INT0\_vect, and INT0\_vect\_part\_2 is replaced by INT1\_vect:

    /* Interrupt service routine for INT1 hijacked to service INT0. */
    ISR(INT1_vect)
    {
        if (count_edges < MAX_COUNT) {
            count_edges++;
            if (GPIOR0) count_high++;
        }
        GPIOR0 = 0;
    }

To compile the sketch, we need a custom compile command. If you have
followed so far, you probably know how to compile from the command line.
You have to explicitly request silly-crt.o to be linked to your program,
and add the `-nostartfiles` option to avoid linking in the original
crtm328p.o.

Now, the reading of the I/O port is the very first instruction executed
after the interrupt triggers. I tested this version by sending it short
pulses from another Arduino, and it can catch (although not reliably)
the high level of pulses as short as 5 cycles. There is nothing more we
can do to shorten the interrupt latency on this hardware.


message:
What kind of Arduino should I pick for a calculator?

I am planning to build a calculator using Arduino as the base. I already know C and I love low-level stuff, so I guess the software part won't be a problem.

However, I've been stuck with Arduino. What I need is something capable of doing math (as I'm not even sure if Arduino has a FPU), and it to have enough inputs for more than the basic 0-9 `+ - / *` keys.

I am a _real newbie_ when it comes to hardware. I don't even have the slightest clue where to start. I barely understand Arduino's specifications, which is why I'm asking here.

I want to do something _more_ than the classic calculator, because the software part is not a problem. I just need help on which hardware should I choose; both on the 'which Arduino' and 'which accesories for the Arduino' parts.

P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

body:
Start with the biggest (AVR) Arduino you can afford, and worry about miniaturizing it once you have the basics in place. You may find that you don't actually want an Arduino in the end, but something like the ATmega169PA instead so that you have native LCD support (instead of having to use a discrete LCD module).

> P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

Doesn't matter. Most of your x86 assembly experience will easily transfer to AVR (but not all, since the AVR core is simpler than x86).


body:
For the most part, none of the AVR based arduinos are any better at number crunching than any others. They all have a single AVR core running at 16Mhz. None have an FPU, but the software floating point code is very efficient and at the time scales you care about for a calculator, it really doesn't make much of a difference.

The biggest differences between models are memory and available IO, so the decision between AVR models should probably come from what kind of peripherals you want to plug in, not what you want to calculate.

That said, if you want to do a lot of high precision, numerical calculations (like numerical integration or something), you will probably want something with more memory, and floating point types larger than 32-bits. I don't have much experience with those models, but I'm pretty sure that a Yun or a Zero would be better suited for those kinds of calculations. They don't use AVR based main CPUs.

For IO there are too many options to enumerate here. Take a look at the usual suspect's pages (sparkfun, adafruit, etc...) for displays and buttons. These sites have good descriptions and example code for everything.

When picking devices, remember that you can have multiple I2C devices plugged in at once, but only one UART serial per port (uno/leonardo 1 port, mega 4). Software serial can give you more UARTs for low speed comms if need be.

If you want a lot of different individual buttons, there are ways to get more than 1 button per pin, but it would be a bit easier electrically to pick an arduino with as many pins as buttons. Some of the keypads available already have a special wiring scheme to get higher than 1-to-1 pin ratios and descriptions of how to use them, so they might be a good pick to get yourself started.


body:
Any Arduino (I would start with the UNO) will be sufficient to make a calculator similar to the regular HP or TI calculator product line.

For the keypad, you will need to buy an I2C compatible keypad and connect it to the I2C lines. For the screen there is an LCD shield.

You will not need to code anything in assembly. You can write cpp code using the libraries provided with the Arduino.


message:
Issue with usbserial for arduino clone

I have attached photo of the clone Uno board recently acquired, and I am working on a Mac OS X 10.7.5

I have sourced the solution from
http://javacolors.blogspot.com/2014/08/dccduino-usb-drivers-ch340-ch341-chipset.html

Which suggests to install 340/341CH drivers and run a sudo code. When I plug in the Uno board, the Arduino IDE still does not show under port selection, the "dev.tty.usbserial"

and as such I cannot contact or upload any command to the Uno board. Been trying for a whole day.. please help if you know a possible solution

This is the board:
![Uno board][1]

I bought the board from this site:

http://www.aliexpress.com/item/UNO-KIT-Upgraded-version-of-the-For-Starter-Kit-the-RFID-learn-Suite-Stepper-Motor-ULN2003/1207142899.html

screenshot from the IDE does now show any usbserial
![IDE screenshot][2]

  [1]: https://i.stack.imgur.com/AV3ks.jpg
  [2]: https://i.stack.imgur.com/YYyRK.png

body:
This may be better asked on http://apple.stackexchange.com

At the terminal run `ioreg -p IOUSB` then plug in the Arduino and see what changed.

On my Mac the setting is serial.port=/dev/tty.usbmodemfa131


body:
You will need to allow the use of unverified drivers for this version of the Arduino. Unlike the genuine Arduino this board needs the ch340 and ch341 drivers and because they are not verified you will need to run the following command in order for them to work:

sudo nvram boot-args="kext-dev-mode=1"

I just got a handful of these clones (so cheap) and once I installed the drivers and then set the nvram kernel extensions to dev mode all was OK.


body:
I have a Mac running OSX that is one version older than yours, and had the same problem. Once I installed the CH340 drivers, then plugged in my $3 Arduino, there was a kernel panic and I had to reboot the computer. After trying every "fix" I could find on the internet, I ordered 2 of every popular USB to serial converter on ebay.

The problem is the CH340 drivers do not always work well with OSX. Some folks are lucky and they work great, and other have issues.

A permanent solution is to use a PL2303HX USB to RS232 adapter: http://www.ebay.ca/itm/For-Arduino-Module-Converter-PL2303HX-Converter-NEW-TTL-USB-To-RS232-Adapter-/142004090259?hash=item21101a7593:g:D70AAOSwSWJXRWJV. You will have to download a driver and install it first: http://www.prolific.com.tw/US/ShowProduct.aspx?p_id=229&pcid=41 (Mac OS X Universal Binary Driver v1.5.1).

To use this converter, power up the Arduino using the power jack with 7 - 9 VDC. Connect the PL2303HX ground, TX and RX to the Arduino and plug it into your computer. If a dialog box pops up just cancel it. After you click the upload button in the Arduino IDE, you will see "Binary sketch size.." in the Debug window. Press the reset button on the Arduino for 1/2 a second then release it. The sketch should upload.

The PL2303HX is VERY dependable. Plug it in, look at the Arduino > Tools > Serial Port in the IDE and there it is. Unplug the adapter then recheck the serial port and it's gone. It doesn't matter which USB port you plug it into, the port name is the same for either and should look something like this:

[![enter image description here][1]][1]

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

You can even use the PL2303HX with a "stand alone" ATMega328P-PU. Make sure to connect a 10k ohm resistor from 5 VDC to pin 1 and momentarily ground pin 1 when you see "Binary sketch size.." in the Debug window.


message:
Stabilizing output values of conductive sheet(Velostat) connected to analog pin A0 of Arduino

I am trying to do some experiments with conductive sheet (velostat). When I apply a force on the sheet it should change the value of resistance(output). I taking the output of the sheet by connecting to analog input Ao of Arduino. But I am not getting constant readings from arduino, even if no pressure is applied. Do I need to build any extra circuitry to stabilize the output value? Can anyone please tell how to stabilize the output value of Arduino?

body: You need to use a matching resistance to create a voltage divider.


message:
How can I obtain the .hex of a file

I have an Arduino Yún running Openwrt-Yún 1.5.3 (which is the latest version, as I upgraded yesterday), and I am trying to obtain a .hex (compiled sketch), so that I can upload a sketch directly into the Yún. I know about compiled sketches, but there are no build directories in "C:\Documents and Settings\MY_USERNAME\Local Settings\Temp".

Where can I obtain the .hex of any file I have compiled, and how?

body:
As noted in comments, enable verbose compilation and look at the output to find the temporary-directory location. (Click File, Preferences, verbose compilation.)

Note, after you click File, Preferences and the preferences window appears with its half-dozen items, you should also see a note about directly editing preferences in the preferences.txt file.  Edit that file (using a plain-text editor, not a word processor) when the arduino IDE is not running.  Change the line

    preproc.save_build_files=false

to

    preproc.save_build_files=true

so the .hex files in the temporary directory have a better chance of sticking around.

(I'm not able to test this suggestion on an MS-Windows system.  On my Linux system most build files stick around anyway in /tmp/)


message:
Fancy Arduino IDE

Do you know an IDE that is Arduino compatible, with:

 - Black background; white hurts my eyes.
 - Some auto completion features maybe?
 - And also one that lets you minimise brackets. Xcode like.
 - A better console...
 - Something to clear the serial console.
 - A **breadboard view**.

Something fancy!

body: Have a look at Fritzing. I don't know how much you can customize there, but it has a whole suite where you can design hardware, write code, and even order PCB if you want to.


body:
I believe Eclipse can do everything you mentioned except for showing hardware layouts. The appearance of editor windows is customizable. If, by minimizing brackets, you mean collapsing them ("just indicate that something is here; I don't want to see the content"), Eclipse does that too. You can clear the console, but I don't know what "better" features you mean so I can't answer that part. It can take some setting up to get it working for you but it's far and away more powerful and feature-filled than the basic Arduino IDE. It is probably the most used IDE by people who look to upgrade from the basic one.

Update:
While it doesn't directly show hardware layouts, it does know about opening files with their default applications. If you put a Fritzing file in your project folder, when you click on it, Eclipse will launch Fritzing. If you put an image file such as a screenshot of the board layout, it will even open that within the IDE.


message:
Arduino Ethernet Shield vendor is null

I bought Ethernet Shield for Arduino Uno! from AliExpress. It is good work but I scanned my network with [Fing][1] and device Vendor name is null.

Can I change/set device Vendor?

    #include <SPI.h>
    #include <Ethernet.h>

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    byte ip[] = { 10, 0, 0, 106 };

    void setup()
    {
      Ethernet.begin(mac, ip);
    }

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

body:
The vendor name is not stored on the device, rather it is indicated only by the first three octets or OUI part of the MAC address which is either stored on the device, or in your case set up by software.  Turning this back into a name on another computer which sees its traffic is done by the help of a local or network-sourced OUI lookup table.

Apparently the table your computer is consulting doesn't have an entry for the OUI 0xDE, 0xAD, 0xBE.

And that's not surprising as this is clearly a dummy value put in as a placeholder - read all 6 octets as if they were a word and you'll see it says "dead beef feed" - a variation on a classic magic "illegal" value.

Technically, this is actually a legal value for use on a local network as the 2's bit of the leading octet is turned on, indicating that it is a "locally administered" address, rather than one guaranteed to be unique in all the world as you would expect a proper piece of network hardware to have.

If you find the table your computer is doing OUI lookups in, you could add a DE:AD:BE entry to it.


message:
How do I listen for a sound that matches a pre-recorded sound?

I'm working on a project that uses an Arduino Uno to listen for a bell ring and then uploads to a web server the exact time the bell was rung using a WiFi Shield.

I want to know how I can listen for the bell ring (a three second long high pitch tone) and be able to detect that that's what the Arduino heard. I think the best way may be to pre-record the sound and then the Arduino will constantly try to match the incoming sounds to the prerecorded sound. I'm wondering how I could go about doing this (or are there better methods).

The bell sounds kind of like this: [bell sound](http://onlinetonegenerator.com/?waveform=square&freq=332)

body:
About the simplest starting point is to use an FFT ([fast Fourier transform](http://en.wikipedia.org/wiki/Fast_Fourier_transform)) library (like [ArduinoFFT](http://wiki.openmusiclabs.com/wiki/ArduinoFFT) at openmusiclabs.com) to characterize the spectrum of an audio stream.

[*Edit:* An alternative method (digital bandpass filter) is mentioned below.]

Audio typically is made up of many frequencies of many amplitudes and phases, mixed together.  FFT sorts some of that out; it estimates the amplitudes of the various frequencies that make up a bit of audio.

The general idea is to use an Arduino ADC to take readings of an audio voltage for a fraction of a second, then use FFT to convert the large set of readings to a small set of numbers, in eg a set of 32 or 64 frequency-bins, to represent amplitudes in given frequency ranges.  For example, if the sound during a sample is a mix of five sine waves at five frequencies, the bins those five frequencies are in should have large numbers assigned, while other bins should have small numbers.

The approach would amount to sampling at 10KHz for 0.1 second or so, computing an FFT with 32, 64, etc. bins in the next 0.1 second, and comparing bin counts to a training pattern.  Whenever bin count patterns match reasonably well, start a three-second timer; if several seconds of matching samples occur, declare a match.

If the bell is electronically generated and mostly a mix of pure sine waves, then its sound will have an easily recognized spectrum.  But if the sound source is buzzy and there is background noise, it may be difficult to compare spectra.  See eg
• [Comparing an audio signal with a previous 'taught/profiled' signal](https://dsp.stackexchange.com/q/15105/comparing-an-audio-signal-with-a-previous-taught-profiled-signal)
• [How do I compare chords played on a guitar with a known sample?](https://dsp.stackexchange.com/q/14827)
• [How do I compare 2 audio files, returning a percentage of difference](https://dsp.stackexchange.com/q/1867)
• [What does the phase of a FFT bin of an audio signal represent?](https://dsp.stackexchange.com/q/15239/what-does-the-phase-of-a-fft-bin-of-an-audio-signal-represent)
• [Sound pattern matching using Fast Fourier Transform in Windows Phone](http://developer.nokia.com/community/wiki/Sound_pattern_matching_using_Fast_Fourier_Transform_in_Windows_Phone)
• [How do I go about detecting whistles, pops and other sounds in live audio input?](https://dsp.stackexchange.com/q/9358)
• [The Frequency Domain
Section 3.4: The DFT, FFT, and IFFT](http://music.columbia.edu/cmc/musicandcomputers/chapter3/03_04.php)

**An alternative: digital bandpass filter**

Digital bandpass filters are based on processing a signal in a way that detects the amplitude of the signal's frequency component within designated limits.

For theoretical background see wikipedia's *[Digital filter](http://en.wikipedia.org/wiki/Digital_filter)* article.  Also see [Vaseghi, Chapter 5, Digital Filters](http://dea.brunel.ac.uk/cmsp/Home_Saeed_Vaseghi/Chapter05-DigitalFilters.pdf), (eg section 4.6.6, Design of Band-Pass FIR Filters) pdf file and
[ECE438 digital filter design lecture notes](https://engineering.purdue.edu/~ece438/lecture_notes/legacy_notes/module_1/1.7_dig_filter_design/1.7.3_iir_filter_design.pdf)
pdf file.

You can use MatLab or Octave to do most of the work of designing a filter.  For example, if you have the Signal package installed and loaded into Octave, commands like

    v=cl2bp(30, 0.48*pi, 0.52*pi, [0.02, 1.02, 0.02], [-0.02, 0.98, -0.02], 2^11);
    freqz(v);
    v

will compute coefficients for a [Constrained L2 bandpass FIR filter](http://octave.sourceforge.net/signal/function/cl2bp.html), plot the freqency response (as below), and display the 60 coefficients.  To use the filter, copy the 30 non-zero coefficients into a program, set up a rolling array of readings, and at each sample compute a new filtered value.  If at some point high filtered values occur, and if they recur for about three seconds at the bell's frequency or twice its frequency, then the bell is ringing.  Note, there are other kinds of bandpass filters; the Constrained L2 bandpass FIR filter is shown for convenience, but other kinds may be better.

![Octave graph of freqz][1]

If you are unfamiliar with signal processing, you might need to try the following approach:
1, On your development system, obtain a few seconds of audio to use for tests. (Eg, allocate two buffers of several dozen bytes each; fill one buffer while using the other buffer to send data from the Uno to your development system.  Use (eg) [Serial.write(buf, len)](http://arduino.cc/en/Serial/write) and a high data rate, eg 115200 bps, to send binary data, with three ADC readings packed per four bytes.)
2, Use Octave or similar software to try out several different FFT or filter approaches.  You would use FFT to determine the bell's fundamental frequency and then could try out digital bandpass filters while developing a recognizer.  You can also use [mkfilter](http://www-users.cs.york.ac.uk/~fisher/mkfilter/) to design filters to try out in C programs on your system, and should be able to iterate more quickly while developing your approach than if you were developing it using the Uno.  When you get satisfactory results on your development system, you then can code a sketch to test the technique on your Uno.

Note, for a given filter order, filters implemented using fixed-point integer arithmetic on an Uno can handle more samples per second than those implemented using floating arithmetic.  An Uno might support 50000 to 100000 floating multiplies and adds per second ([1](http://forum.arduino.cc/index.php?topic=40901.0),[2](https://gist.github.com/projectgus/8279947),[3](http://www.engblaze.com/faster-code-fridays-understand-division-and-speed-of-operations/),[4](https://robotics.stackexchange.com/questions/535/how-computationally-powerful-is-an-arduino-uno-board)), vs. two to four times as many fixed-point operations per second.  If your filter uses a dozen floating point ops per sample, your sample rate probably would have to be under 5000 samples per second.  If it uses half as many floating ops or uses fixed point instead of floating point, your sample rate could be twice as much.

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


message:
How to use Timer1 (AT328Mega) to measure the time between rising edges of two input signals

I'd like to use Timer1 to measure the time between rising edges of two input signals.  Specifically, use Tn to start the timer counter and IPCn to latch the elapsed time since the rising edge of the Tn input signal.  The goal is to measure the time between the rising edges of two input signals.   Is there a Timer1 library out there that alread does this?  Code suggestions welcomed.

body:
It is not perfect for your simpler task, but here is a link to a [sketch](https://gist.github.com/mpflaga/4404996) that I have used to record pulses, using the Timer1 Input Capture.

In short setup the Interrupt

    void initTimer(void) {

      // Input Capture setup
      // ICNC1: Enable Input Capture Noise Canceler
      // ICES1: =1 for trigger on rising edge
      // CS10: =1 set prescaler to 1x system clock (F_CPU)
      TCCR1A = 0;
      TCCR1B = (0<<ICNC1) | (0<<ICES1) | (1<<CS10);
      TCCR1C = 0;

      //catchFallingEdge(); // initialize to catch
      { TCCR1B &= ~(1<<ICES1); TIFR1 |= (1<<ICF1); rising = 0; }

      // Interrupt setup
      // ICIE1: Input capture
      // TOIE1: Timer1 overflow
      TIFR1 = (1<<ICF1) | (1<<TOV1);  // clear pending
      TIMSK1 = (1<<ICIE1) | (1<<TOIE1); // and enable

      // Set up the Input Capture pin, ICP1, which corresponds to Arduino D8
      pinMode(8, INPUT);
      digitalWrite(8, 0);  // leave floating to count 60 Hz etc.
      //digitalWrite(8, 1);   // or enable the pullup
    }

Then service it

    ISR(TIMER1_CAPT_vect) {
      union twobyte {
        uint32_t word;
        uint8_t  byte[2];
      } timevalue;

      timevalue.byte[0] = ICR1L;  // grab captured timer value
      timevalue.byte[1] = ICR1H;  // grab captured timer value

      // watch for the other edge to catch the half-pulse width
      //rising ? catchFallingEdge() : catchRisingEdge();
      if (rising) {
        TCCR1B &= ~(1<<ICES1);
        TIFR1 |= (1<<ICF1);
        rising = 0;
      }
      else {
        TCCR1B |= (1<<ICES1);
        TIFR1 |= (1<<ICF1);
        rising = 1;
      }
    }


body:
For more help and info, and many examples of various detailed aspects of timers, check out Nick Gammon's articles here: http://www.gammon.com.au/interrupts
and here: http://www.gammon.com.au/timers

Under the first link, do a search for **"The sketch below times intervals between RISING interrupts,"** for example, to find one code segment.

**Now, important question: what is the minimum time you need to measure between events?**  Are we talking milliseconds, microseconds, or nanoseconds?  For the former, you can use pin polling, external interrupts, or pin change interrupts, and the millis() or micros() Arduino functions to grab timestamps. For microseconds resolution, it depends. Even the micros() function only has a 4us resolution, so you'd have to custom-configure the timer if you want better than 4us resolution time-stamps, or you could use the timer2_counter library (http://electricrcaircraftguy.blogspot.com/2014/02/Timer2Counter-more-precise-Arduino-micros-function.html), or your own custom timer solution, for 0.5us resolution timestamps.

For nanosecond resolution (down to 62.5ns time steps), youd prob. need to use Timer1's input capture, as the other answer shows. You can also do a search for **"Timing an interval using the input capture unit"** under the 2nd link above, for another code segment on that.


message:
Arduino UNO + CC3000 Wifi Shield, Reading webpage data

I'm new so I might be making a stupid mistake, but I'm declaring:

char dollars;

at the begging of file, afterwards I'm reading a data from a web page, printing it to my serial. That part work well. The data returned from the web page is a number, 55 for instance.

The number get's printed correctly to the serial. But when I try to save the complete number it changes. for instance, when I get 0 from the server. The printed result is 10.

here is the important part of my code:

    unsigned long lastRead = millis();
      while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
        while (www.available()) {
          char c = www.read();
          Serial.print(c);
          dollars = www.read();
          lastRead = millis();
        }
      }

      www.close();
      Serial.println(dollars);

while the www.read is repeating each of the returned characters it works fine `Serial.print(c);` but when I save it to the dollars char var, it get garbled up into something different. What am I doing wrong?

I'm planning to show that number from the web page onto my 4 digit screen at the end.

body:
Webpages usually return data in text format with new line characters at the end.
In case of 55 you would get "55\r\n" or [53, 53, 13, 10] in bytes.
You need to parse the characters, like [Serial.parseInt()](http://arduino.cc/en/Reference/ParseInt) does.

You are also only sending every second byte back to the serial monitor and only saving the last byte from the other every second byte.
After you read a byte with Serial.read() you can't read the same byte again, you get the next one.
In case of 55 you would send back "5\r" to the serial monitor and only store "\n" or 10 into dollars.
In case of 0 you would send back "0\n" to the serial monitor and store some unknown value into dollars, because you read more bytes that was sent.


message:
Am I Running Out of RAM Or Not?

I'm attempting to drive 300 TM1803 RGB LEDs from an Arduino Uno using the FastLED library. My code works fine for 100 LEDs, but when I go to 150, the arrays that store LED values and my sensor data get corrupted, causing the LEDs to flash colors randomly every few seconds. From what I've read these are exactly the symptoms of running out of RAM, leading to something overwriting the RAM that contains my arrays.

However, with 150 LEDs, the MemoryFree library says I'm only using 920 bytes of RAM, no matter where in my code I measure, and the IDE says 880. Does anybody know what's going on? Is there something using 1100 bytes of RAM for a very short amount of time, so that I can't measure it?

My code:

    #include "FastLED.h"
    #include <MemoryFree.h>

    const byte ledsPin = 3;
    const byte sensorPin = A1;

    const int numLeds = 300;
    const int ledTime = 1000;

    const int sensorMin = 0;
    const int sensorMax = 512;

    const CRGB correction = CRGB(80,255,70); // Cool white
    //const CRGB correction = CRGB(160,255,20); // Warm white
    const byte hOffset = 170; // baseline hue value
    const int8_t hDirection = -1; // 1 or -1, direction of rainbow
    const byte s = 255; // saturation (colorfulness)
    const byte v = 255; // value (brightness)

    const unsigned int arrayLength = numLeds+1;
    byte hues[arrayLength];

    CRGB leds[numLeds];
    byte h = 0; // hue (color)

    unsigned long sensorSum;
    unsigned int loopCounter;
    unsigned int arrayCounterLed;
    unsigned int updatesPerLed;
    char sp = ' ';
    int arrayCounter;

    unsigned long time;
    unsigned long timeNextLed;
    unsigned long timeLeft;
    unsigned long time1;
    byte route;

    void setup() {
      FastLED.addLeds<TM1803, ledsPin, RBG>(leds, numLeds).setCorrection(correction);
      FastLED.setDither(0);
      pinMode(ledsPin, OUTPUT);
      Serial.begin(115200);
    }

    void loop() {
      delay(10);
      time=millis();
      sensorSum += analogRead(sensorPin);
      loopCounter++;
      if(time >= timeNextLed) {
        timeNextLed = (time/ledTime+1)*ledTime;
        arrayCounter = (arrayCounter +1) % (arrayLength);
        hues[arrayCounter] = (constrain(map(hDirection*sensorSum/loopCounter, sensorMin, sensorMax, 0, 239), 0, 239)+hOffset)%6;
        updatesPerLed = loopCounter;
        loopCounter=0;
        sensorSum = 0;
      }
      for(int led = 0; led < numLeds; led++) {
        time1=micros();
        arrayCounterLed = pseudoMod(arrayCounter - led -1, arrayLength);
        timeLeft = timeNextLed-time;
        byte dist = abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)]);
        if(abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)])<=128) { // if it doesn't cross through 0
          h = (hues[arrayCounterLed]*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime;
        }
        else if(hues[arrayCounterLed] > hues[(arrayCounterLed+1)%(arrayLength)]) { // if it crosses through 0 forwards
          h = ((hues[arrayCounterLed]*timeLeft + (hues[(arrayCounterLed+1)%(arrayLength)]+256)*(ledTime-timeLeft))/ledTime)%6; // Causing flashing on red pixels?
        }
        else { // if it crosses through 0 backwards
          h = (((hues[arrayCounterLed]+256)*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime)%6;
        }
        time1 = micros() - time1;
        if(led == 0) {
          Serial.print(dist);
          Serial.print(sp);
          Serial.print(route);
          Serial.print(sp);
          Serial.print(timeLeft);
          Serial.print(sp);
          Serial.print(hues[arrayCounterLed]);
          Serial.print(sp);
          Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]);
          Serial.print(sp);
          Serial.print(hues[arrayCounterLed]*timeLeft);
          Serial.print(sp);
          Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft));
          Serial.print(sp);
          Serial.println(h);
        }
        leds[led] = CHSV(h, s, v);
      }
      FastLED.show();
      Serial.print(updatesPerLed);
      Serial.print(time1);
      Serial.println();
    }

    int pseudoMod(int a, int b) {
      if(a<0) {
        return a+b;
      }
      else {
        return a;
      }
    }

body: I found it! I was returning an int8_t variable from my mod function, causing me to not be able to iterate over more than 126 LEDs. Now this little Arduino Uno is maxing out it's RAM at 409 LEDs!


message:
AT command XBee from atmega to disable DIO5 (associated led)

I community! I need put ATcommand to my XBee from my atmega using a "xbee library" and a function that I have found in internet. I think the ATComand is "ATD50" to change the DIO5 to value "0" (disabled). My intention is to turn off a led connected into DIO5 (digital input/output 5 (associated led)) after X second/minutes of turning on the device (so that it doesn't turn one again after initial check).

This is a part of my code:

    #include <XBee.h>
    XBee xbee = XBee();
    uint8_t atdCmd[] = {'A','T','D','5','0'}; //<---command to put DIO5 to "0" (disabled)
    AtCommandRequest atRequest = AtCommandRequest();
    AtCommandResponse atResponse = AtCommandResponse();
    void setup()
    {
    delay(30000);
    atRequest.setCommand(atdCmd);
    xbee.send(atRequest);
    }
    void loop()
    {}

...but it doesn't work!
Thanks guys!

body:
finally I solved the problem with this code:

    uint8_t atdCmd[]={'D','5'};
    uint8_t value[]={4};///pongo DIO5 a output LOW
    uint8_t length=1;
    AtCommandRequest atRequest = AtCommandRequest(atdCmd, value, length);
    xbee.send(atRequest);

The problem was that I tried to put command with 5 caracters,... and only accepts 2 caracters for "AT command"


message:
Programing other Atmel ARM chips using Arduino

Ok, i know professionals generally hate Arduinos, but I would like to know if it would be possible to program Atmel ARM chips using the Arduino IDE. By which I mean, not needing to modify the source code, just add another entry into the "hardware" folder and that's it.

We already know the Atmel ATSAM3X8EA (Arduino DUE) is compattible, but how about a similar chip, like the Atmel ATSAM3X8CA. Or maybe a Cortex-M4 one, like the Atmel ATSAM4E16EA or the Atmel ATSAM4S8CA.

The Atmel ATSAM3X8CA is the closest one to the Atmel ATSAM3X8EA the Arduino Due uses, a bit smaller and with less I/O.

If it isn't possible without much source code modding, I would like to know what would it take to make it work.

Thanks for your answers.

body:
Yes it is possible. IDE 1.5.+ support different platforms, as they call it. Where the AVR and sam are provided by stock. Others are possible.

It is fairly involved setup. In short; within each platform there are the following files:

 - boards.txt, defines the individual boards using the similar processor.
 - platform.txt, defines the compiler arguments
 - programmers.txt, defines how to program it.

With corresponding sub directories to match, under the variants/ folder.
I have not found an complete tutorial on the matter. However, their

[Arduino IDE 1.5 3rd party Hardware specification](https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification)

[An overview of the platform architecture proposed for Arduino 1.5](https://code.google.com/p/arduino/wiki/Platforms1)

are a great place to start.

I have not done much with SAM. I do notice that programmers.txt is empty. So it must be done another way.


message:
Hooking up 12v Push button to arduino uno/nano

I want to use one an push button with an led in middle, similar to this [one][1] on eBay.
The push button has a 12v input I want to hook it up to an Aduino Uno or Nano.

Is there a way to hook it up and receive the signal?

Specifications from the eBay page:

>  - Latching type, push it—on, push it again — off
>  - Switch Rating: 3A/250VAC
>  - LED voltage: 12V only
>  - Contact Configuration: 1NO1NC
>  - Pin Number: 5

  [1]: http://www.ebay.com/itm/16mm-12V-Blue-LED-Power-Push-Button-Switch-Black-Aluminum-Metal-Latching-/231234288662?pt=LH_DefaultDomain_0&hash=item35d6a33c16

body:
Most likely, there will be a push button, and on separate wires, there is a light. If this is the case, you can hook the push button part up to the arduino. You can test this - find two random wires, test the resistance with a multimeter, then press the button and see if the resistance changes. Keep trying until you find two wires that change when you press the button.

Once you find the pair, you can hook one of those two to a digil pin on the Arduino, and via a resister (large, anything 10kilo-ohm or larger is fine) to ground (GND). Then, connect the other side of your pushbutton to 5V. See http://arduino.cc/en/tutorial/button for photos and a circuit diagram - their wiring is more complicated than it needs to be, and their button has 4 pins in two pairs (left pair, and right pair in the picture with the breadboard; the left-top and left-bottom are permanently connected, and the right-top and right-bottom are permanently connected). Have a look at the circuit diagram - that's a lot simpler. The zig-zag at the top is the resistor, and the disconnected looking thing is the switch (open). There is sample code there too.

Note that push buttons typically "bounce" - that is, when you push them, they will go (starting off) on-off-on-off-on-off-on, so if you're counting the number of pushes you will get a result which is way too high. If you delay long enough in between (10ms?) then you won't get these. The code I linked to already has debounce built in.

The other part is the light. This is a little more tricky. The light will probably use too much current for the arduino to supply directly. You will need a transistor and a resistor (again, at least 10 kiloOhm is good).

The transistor should be an NPN transistor, and should look like the top one in http://www.reprise.com/host/circuits/transistor_pinouts.asp. The easiest one is the base - this is the middle one. Connect this via your resistor to another digital pin on your arduino (pin 13 is great for testing this, because it will also light up the led on the Arduino). Next, connect your emitter to ground (GND). Then, IF YOUR POWER SUPPLY IS NO MORE THAN 12 VOLT! you can connect VIN to the + side of the light, and the - side of the light to the collector.

Next, load a sketch - the "blink" sketch is good to test this. Adjust the pin as necessary.

Note that, these switches have a resistor already built in to the light; if you want to do the same with an ordinary led, you will have to add one yourself. Check out http://ledcalc.com/ to tell you which resistor you need.


message:
How to choose between Lithium-ion vs NiMH batteries to power Arduino on the go.

For my next project I'd like to use a battery pack to power my Arduino.
I would also like to get a small solar panel and charging module to charge these batteries when possible (during the day).

1. What is the right type of battery for this kind of application?
2. What are the differences given this context?
3. What are the factors I need to consider when choosing a rechargeable battery for this application?

body:
Look at [**Battery University**](http://www.batteryuniversity.com/) for many good ideas.

Both NimH and LiIon are viable for your application.

LiIon are easier to manage well **if** managed well.
ie do it right and they are easy to manage, but cut corners and they are easier to destroy.

NimH can be abused more with a slow degradation in capacity - although complete destruction is possible.

As a LiIOn cell has a ~= 3.0V to 4.2V range you'd probably probably need a step up inverter with 1 cell, or a buck regulator with 2 cells, which is 'annoying'. If you are prepared to use the cell over say a 3.4V to 4.2V range with an LDO regulator for a 3.3V system then you lose a significant amount of available capacity but increase battery cycle life substantially.

Nimh give 1.0 - 1.2 V/cell so eg

 - 6 cells give 6 - 7.2V for a 5V system,

 - 5 cells give say 5.25V - 7V if run down to 1.05V for a 5V system with a suitable LDO regulator, and

 - 4 cells give 4 - 4.8V for a 3V3 system.

NimH are easier overall to build half well and get half good results.

LiIon are slightly harder to get going with in most cases, work very well if treated well, and are VERY unforgiving of bad treatment past a certain point.


message:
/dev/cu port resource always busy on OS X 10.10

Is there any reason why is my `/dev/cu` port always busy? How can I fix that?

It happened on both Uno clone and Spark Core.

The problem is, I'm having issues doing serial communication. Where (as a programmer) I'm seeing something like dropped packets with `/dev/tty` port. I did a quick test running it on Win 7 (a loaner PC), it works fine...

The code for now is extremely simple. It waits for a command, and write a response.

    String str = String(30);

    void setup()
    {
        Serial.begin(9600);
        str = "";
    }

    void loop()
    {
        if (Serial.available() > 0) {
            char inChar = Serial.read();
            if ((inChar == '\n') || (inChar == '\r') || (inChar == 'z')) {
                str.trim();
                if(str == "READ") {
                    String x = String(random(27, 45)) + "," + String(random(45, 300)) + "," + String(random(35, 250));
                    Serial.println(x);
                }
                str = "";
            }
            else {
                if (str.length() < 30) {
                    str += inChar;
                }
                else {
                    str = "";
                    str += inChar;
                }
            }
        }
    }

body:
Finally figured it out. I need to call [Serial.flush()][1].

> Waits for the transmission of outgoing serial data to complete.

  [1]: http://arduino.cc/en/Serial/Flush


message:
How to wait outside the loop without delay()?

Is it possible to delay a task inside a function that is called only once (meaning, it's not inside the loop) without using delay()?

[This library][1] I'm using, for reading sensor measurements via serial has a delay() in it. I want to get rid of it, but I don't how to do it, because the library's function is not looped.

I guess the simple solution would be to move the library functions inside the loop, so I can do a simple check with millis() and run the delayed part as soon as 250 ms have passed. I would like to improve this library though and do a simple, single call for sensor data that doesn't not hold up the entire program.

This is the function with the delay:

<!-- language: c++ -->

    uint16_t COZIR::Request(char* s)
    {
      Command(s);
      // empty buffer
      buffer[0] = '\0';
      // read answer; there may be a 100ms delay!
      // TODO: PROPER TIMEOUT CODE.
      delay(250);
      int idx = 0;
      while(CZR_Serial.available())
      {
     buffer[idx++] = CZR_Serial.read();
      }
      buffer[idx] = '\0';
      uint16_t rv = 0;

      switch(buffer[1])
      {
        case 'T' :
                rv = atoi(&buffer[5]);
                if (buffer[4] == 1) rv += 1000;
                break;
        default :
                rv = atoi(&buffer[2]);
                break;
      }
      return rv;
    }

I've had a look at the SoftTimer library, but it requires sketches to be written very differently (without a loop). I'm also not sure if I can even pass arguments to delayed tasks with that library.

  [1]: https://github.com/kslstn/cozir

body:
You could split `Request()` into two separate functions: You call `sendRequest()`, then go do other stuff, then, some time later, you call `getResponse()`. If you get `RESPONSE_NOT_READY`, then you know you have to call it later:

<!-- language-all: c++ -->

    #define REQ_WAIT_DELAY     250  // Wait for 250 ms
    #define RESPONSE_NOT_READY ((uint16_t) -1)

    uint32_t time_request_sent;

    void COZIR::sendRequest(char* s)
    {
      Command(s);
      time_request_sent = millis();
    }

    uint16_t COZIR::getResponse()
    {
      if (millis() - time_request_sent < REQ_WAIT_DELAY)
          return RESPONSE_NOT_READY;
      buffer[0] = '\0';  // empty buffer
      int idx = 0;
      // From here, same as original COZIR::Request()
    }

This assumes that `RESPONSE_NOT_READY` (`0xffff`) is not an otherwise valid response. If all 2^16 values of an `uint16_t` may be valid, then you need another way for the library to signal that the response is not ready. Also, make sure you never compare timestamps, because of the `millis()` rollover problem. Taking the difference between two timestamps and comparing this with a specified delay (as in the example above) is rollover-safe.

**Update**: Here is an example of how this could be used:

    COZIR cozir(some_serial_connection);

    void loop()
    {
        static bool waiting_for_a_cozir_response = false;

        if (time_to_get_another_cozir_reading()) {
            if (waiting_for_a_cozir_response) {
                report_something_is_wrong("This COZIR is too slow!");
            }
            else {
                cozir.sendRequest("Hi Cozir! Pliz send me another reading.");
                waiting_for_a_cozir_response = true;
                /* We won't get the response on this iteration. *
                 * We will ask next time.                       */
            }
        }
        else if (waiting_for_a_cozir_response) {
            uint16_t response = cozir.getResponse();
            if (response == RESPONSE_NOT_READY) {
                /* Nothing to do now, really. We will just try again *
                 * at the next loop() iteration.                     */
            }
            else {
                waiting_for_a_cozir_response = false;
                do_something_with_the_cozir_response(response);
            }
        }
        do_whatever_else_has_to_be_done_in_the_loop();
    }


body: You can look at the BlinkWithoutDelay example sketch (under Digital).  Basically you store the current millis as a variable, then have an if statement to check that it has been more than x milliseconds.


message:
Unable to upload sketch after bootloader has been flashed on Arduino Micro

I have created my own custom Arduino Micro, but I am experiencing problems when I attempt to upload an sketch via USB in Arduino IDE.

Here is how I program the Arduino Micro:

    avrdude  -c atmelice_isp  -p m32u4 -P usb -u -v -e -U flash:w:Caterina-Micro.hex

And the result:

    $ avrdude  -c atmelice_isp  -p m32u4 -P usb -v -e -U flash:w:Caterina-Micro.hex
    avrdude: Version 6.1, compiled on Mar 23 2014 at 04:42:55
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "/usr/local/Cellar/avrdude/6.1/etc/avrdude.conf"
             User configuration file is "/Users/aUser/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : usb
             Using Programmer              : atmelice_isp
    avrdude: usbdev_open(): Found Atmel-ICE CMSIS-DAP, serno: J41800023270
    avrdude: Found CMSIS-DAP compliant device, using EDBG protocol
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : JTAG3_ISP
             Description     : Atmel-ICE (ARM/AVR) in ISP mode
             Vtarget         : 4.9 V
             SCK period      : 125.00 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x1e9587
    avrdude: safemode: lfuse reads as FF
    avrdude: safemode: hfuse reads as D8
    avrdude: safemode: efuse reads as CB
    avrdude: erasing chip
    avrdude: reading input file "Caterina-Micro.hex"
    avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
    avrdude: writing flash (32730 bytes):

    Writing | ################################################## | 100% 38.80s

    avrdude: 32730 bytes of flash written
    avrdude: verifying flash memory against Caterina-Micro.hex:
    avrdude: load data flash data from input file Caterina-Micro.hex:
    avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
    avrdude: input file Caterina-Micro.hex contains 32730 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 133.93s

    avrdude: verifying ...
    avrdude: 32730 bytes of flash verified

    avrdude: safemode: lfuse reads as FF
    avrdude: safemode: hfuse reads as D8
    avrdude: safemode: efuse reads as CB
    avrdude: safemode: Fuses OK (E:CB, H:D8, L:FF)

    avrdude done.  Thank you.

The error in Arduino IDE when flashing sketch via USB:

    Sketch uses 23.994 bytes (83%) of program storage space. Maximum is 28.672 bytes.
    Global variables use 1.145 bytes (44%) of dynamic memory, leaving 1.415 bytes for local variables. Maximum is 2.560 bytes.
    Forcing reset using 1200bps open/close on port /dev/tty.usbmodem1411
    PORTS {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } / {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } => {}
    PORTS {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } / {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } => {}
    Uploading using selected port: /dev/tty.usbmodem1411
    /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/tty.usbmodem1411 -b57600 -D -Uflash:w:/var/folders/64/6n0yv9515hz1n6z3bdzcwv6h0000gn/T/build2162381950044145986.tmp/IMUNode.cpp.hex:i

    avrdude: Version 6.0.1, compiled on Apr  3 2014 at 22:00:33
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Users/aUser/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/tty.usbmodem1411
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

body:
Your problem is that your board doesn't have the bootloader loaded into the chip.

You have success with the ATMEL-ICE ISP because it is an in-system programmer (ISP) and you are downloading the code directly into the chip.

When you use the USB, I see from your output that the programmer is "butterfly" and the description indicates AVR109. These both indicate that the program is trying to be loaded through a bootloader.

A bootloader is a bit of code that resides in the codespace section of flash. It allows you to send the program through the UART. The bootloader then saves it to the codespace section of flash such that both the bootloader and your program co-exist.

To fix this, use the Arduino IDE along with your ATMEL-ICE ISP to load the bootloader into the microcontroller. This can be done by going into `Tools` and then `Burn Bootloader` (of course with the correct programmer selected).

This will then allow you to download your code through the Arduino IDE.

PS. You can program your sketch straight to your Arduino using your ATMEL-ICE ISP without downloading the bootloader. Do this by selecting the `Upload Using Programmer` option in the menus.


message:
Metal detector using Arduino

Is anyone out there building serious metal detectors with the Arduino? By "serious" I mean metal detectors with phase sensitivity to discriminate between ferrous and non-ferrous metals, etc.  Seems like the Uno is a good platform for a smart metal detector project.

Update:
Arduino allows me to control phase discrimination which allows ferrous metals to be rejected.
I already know it can be done with an analog phase shift circuit.
Also Arduino can perform target ID function with readout to 16x2 LCD display.

body:
A set of posts on Instructables uses an Arduino Nano to generate a Phase Induction pulse, with a capacitor instead of a dump resistor to set up a decaying oscillation, which is then limited with diodes and detected by the analog comparator with interrupts.  The comparator interrupts then count the frequency of the decaying ringing oscillation producing some ferrous/non-ferrous discrimination, and the duration of the ringing, producing some signal strength and size information.

* Nano doing Pulse induction with LC-trap oscillation: https://www.instructables.com/id/Arduino-Based-Pulse-Induction-Detector-LC-Trap/
* Nano meta detection software with high-frequency ADC sampling: https://www.instructables.com/id/How-to-Program-an-Arduino-Based-Metal-Detector/
* Nano doing Pulse Induction, shifting the recovery pulse to match the arduino's analog comparator: https://www.instructables.com/id/Arduino-Based-Pulse-Induction-Detector/

The tricks in the Pulse Induction LC-trap system of using the analog comparator would be applicable to detecting phase shifts and detecting crossings in sync with a timer-based output.


message:
Atmega328 component library for Protel 99 SE

Any one know a **component library** for Arduino UNO (**Atmega328**, etc) for **Protel 99 SE** PCB design software?

body: All arduino design schematics are available from the Arduino website, e.g. for the [Uno](http://arduino.cc/en/uploads/Main/arduino_Uno_Rev3-02-TH.zip). However, these are in EAGLE format, I don't know if it's possible to convert.


body:
Found it here with 94 chips.

The author states, "I have made a little library for Protel 99SE with schematic sybols of AVR chips."

[http://www.avrfreaks.net/forum/avr-8bit-microcontrollers-protel-99-library][1]

  [1]: http://www.avrfreaks.net/forum/avr-8bit-microcontrollers-protel-99-library


message:
Arduino Uno - What can I make with just the base board

So I just bought my first Arduino (an Uno r3), and dove right in.

All I have currently is the base board (I didn't want to invest too heavily and then realize arduinos weren't for me), so I made a quick script that translates input letters to morse via the LED on the top.

Now that I'm done with that, I figured I'd come here to ask: do you guys have any random ideas for things I can make with JUST the uno? I understand that I should probably just start buying kits and shields, but I'm just curious as to what I can make with the most minimal of items. I consider it a test :)

Thanks in advance guys!

body:
Well,

Your question is very broad. But the Arduino essentially needs controlling gadgteers to make things easy ( and funny ).

However if you know a bit of electronics, then you may be able to use the IN/OUT analog ports and build other interfaces to control, for example the lights of your home, or even better. You can measure and control priate things should be linked. Increasing the power of your home.

If you have interest in cars, then you can perform to connect the on-board computer of your car to the Arduino, like [this][1].

Well, there are numerous ideas, none of these I'm saying is new and there are even libraries ready to be used in these segments mentioned above.

Regards,
Andrew Paes

  [1]: http://arduinodev.com/connect-arduino-to-a-car-through-obd-ii-port/


message:
Arduino PWM output cannot drive MOSFET 0-12V

On an Arduino Uno, the PWM pin 3 is connected to the `gate` pin of an [N-channel MOSFET STP16NF06L][1]. The source pin is connected to ground of a 12 V power supply and drain pin connected to a multimeter. The other end of the multimeter is connected to the positive terminal of the power supply.

**Question:** When Arduino varies its PWM output from 0 to 255, the multimeter reading goes from 11.50 V to 12.10 V. Why isn't it 0 to 12 V?

When the FET gate is connected to the Arduino pin that outputs either 0 V or 5 V, the multimeter reading is as expected at 0 V and 12 V respectively.

  [1]: http://www.farnell.com/datasheets/1690175.pdf

body:
When the FET is saturated (pin 3 is high), I would expect the instantaneous voltage to be the full 12 v. When pin 3 is at 0v, there should be no connection across the FET; I would expect the voltage to fluctuate randomly. you might see the same if you measure voltage with nothing touching the probes, especially if the probes move relative to each other.

I'm fairly new to FETs, so I may be on completely the wrong track.


body:
Assuming you have a suitable FET You should have a circuit in line the following.
http://elinux.org/RPi_GPIO_Interface_Circuits#Using_a_FET

You should have some kind of load (a multimeter will have too high an impedance). Use a resistor 4.7k or smaller. You should also have a resistor on the gate


body: Also put a LED with a resistor connected trough drain, then you read the voltage across the resistor and also have visual feedback with the LED. Resistor should be with 0V when your pin is LOW. It's easier to work with transistor knowing if there is current or not.


message:
Arduino Grounding Issue

I have a project that turns a LED strip on and off using capacitive touch.  The project uses an [Arduino Micro](https://www.adafruit.com/products/1315) as the brain and a [12v wall wart](https://www.adafruit.com/products/352) to power everything.  I have the Arduino ground and negative from the power supply running to a common ground.

Everything works as expected during testing and the Arduino is connected via USB to my computer; however, when I unplug the USB and connect the circuit to the light installation, the lights just flicker on and off.  When I touch my finger to the negative/ground (and presumably provide common ground), everything works as expected.

It seems obvious to me that I have a grounding issue, but really do not know how to proceed. Is there a specific technique for grounding from a wall wart? Do I need to somehow pull the ground/negative down? I feel like there is something obvious that I am missing.

Thank you in advance for any and all help.

body: Seems like there is a problem in your wall wart, actually some people are having problems using wall wart with arduino. The problem is with the circuit of thre arduino regulator and with sime ripple variances with de wall wart, i sugest you to setup in your project a regulator (7805) and see if the problem is gone. This is by far problem not just with grounding, but with the power suply in general. I was used to make PIC projects and once it was happening exatly the same that happaned to you but the microcontroller started to work when i put my hand or finger close without even touching it :x. Crazy thing. If the power supply isn't well suited, the arduino enter in continous reset looping because of supply noise. So just put an external regulator, an maybe an extra capacitor (generally 10 nF) in arduino micro power supply rais (VCC-GND). Here's my tip. Good look man, tell me if it worked :)


message:
What's the smallest (cheap) USB Host solution for Arduino?

I'm building a project that will connect to users' phones (Android at first, but iPhone too, if there's enough interest) via USB. Of course, this means that I need a USB host in the project. The total size of the device has to be about the size of the phone, so answers that seriously suggest shields aren't going to be helpful - they'd put me over my size budget by at least a factor of 3.

I'd also rather not require an adapter to go from the USB Mini B connector type to the Micro B connector type.

Gravitech has a USB Host board for the Nano 3 that has a USB Type A connector, and the combination of a Nano and Gravitech Host is about the right size (maybe a little thick, once the whole thing is soldered to my own board), but the USB host is $25. I can get the Nano for about $4 each and would like to keep the USB host in the neighborhood of $8 each. Are the solder fumes getting to me, or is there such a specimen out there and I'm just not finding it?

body:
The Arduino Due and Arduino Mega ADK can both serve as a USB Host. You can also use the [chip that the Mega][1] uses yourself

  [1]: http://www.maximintegrated.com/en/products/interface/controllers-expanders/MAX3421E.html


body:
Cypress makes very small usb chips capable of host mode. Does this board meet your size requirements? http://www.mouser.com/ProductDetail/Cypress-Semiconductor/CY8CKIT-049-41XX/?qs=FSHIiqjonm0YmFbmBQfo1A==&kpid=1159933375&gclid=CPjl6KOm4cQCFYGUfgodJh4A_g

You may also consider ditching the arduino and running everything on the cypress


message:
Converting Random Binary Data to PWM Signal

I am using a Arduino Due. I am doing a project on Visible Light Communication. I need to convert a binary data into a PWM Signal. Can anyone suggest me a method of generating that PWM Signal based on the binary data given?

Thank You.

body: Count the amount of time a signal is high over a certain period, and use the ratio of on time to period as the duty cycle for the PWM signal.


body:
So, if you simplu has to convert the binary data to PWM signal there are few things you need to cover:

 1. If the binary data that you are receiving from the sensor is linear or non linear.

 2. What is the size of binary byte. Ex: int(16 bits),char(8 bits),long (32 bits).

 3. If it is linear, then if the data is multiplied by some number it will output a value betwen 0-255.
 4. If the data is not linear than you just need to create an giant array with the pwm intensite value direct without any particular mathematical function. Ex: array[1024] = {0,1,1,2,3,4,5,5,6,6,10,9,...}; (1024 values because if you are using analog input. Then you can direct output the values from array:

        analogWrite(3,array[x]); //x being your data

Here's the linear Example:

       //map(value, fromLow, fromHigh, toLow, toHigh);
        y = map(x, 0, 1023, 0, 255);

Doing this, y will receive a value from 0 to 255. You just need to first do a simple serial program that prints you through arduino serial window the binary data and see if the data increases or decreases conform your light project.

 - I don't know about your programming levels or if you are using a digital sensor or analog sensor, but if you are using a digital sensor, so you are probaly using SPI communication or i2c. Then you just need to read that binary data and take where the values bits are with bit wize manipulation.

        y=(x & (0xfff<<3))>>3;

Tell me more about the source of data, how this data is and how is the behavior of the data so i can help you a lot more. Thanks


body:
Rather than completely build everything from scratch,
perhaps you can use some already tested and debugged Arduino library designed for free-space optical communication, such as

* Ken Shirriff. ["A Multi-Protocol Infrared Remote Library for the Arduino"][2].
* A1RONZO at Sparkfun. ["IR Communication tutorial"][3]
* Dave. ["EEVblog #506 - IR Remote Control Arduino Protocol Tutorial"][4]
* ["Multitasked IR transmission"][5]
* ["Arduino universal remote"][6] (has 2-way communication, both send and receive)
* ["IR Remote Control Theory"][7] (links to many different "standard" infrared protocols)

Practically all of these systems convert expand arbitrary binary data to structured "frames" or "packets" of information including some sort of checksum.
Each packet is repeated several times; hopefully the receiver catches at least one of them.
Each bit of the packet is expanded to either the "pattern representing a 0 bit" (typically turning the LED off for the full bit time) or the "pattern representing a 1 bit" (typically blinking the LED at 38 KHz for the full bit time, typically using a PWM).

To make the hardware and the software simpler and cheaper, most of these systems transmit only a few dozen bits per second.
A few free-space optical communication systems are designed to run much faster, such as [RONJA][1].

  [1]: http://en.wikipedia.org/wiki/RONJA
  [2]: http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html
  [3]: https://learn.sparkfun.com/tutorials/ir-communication
  [4]: http://www.youtube.com/watch?v=BUvFGTxZBG8
  [5]: http://playground.arduino.cc/Main/MultiIR
  [6]: http://playground.arduino.cc/UniversalRemote/UniversalRemote
  [7]: http://www.sbprojects.com/knowledge/ir/