body:
I would actually suggest LiFePo4 for anything DIY. Not only is it safer so one false move won't cause an inferno, but it will last two to four times as long at the CONST of a little extra size and weight.

Since you are just running an arduino, I would use only 1 single cell, and avoid cell balance woes.

I would use a boost regulator to step up the voltage from the cell to the required 5v.

To actually charge the cell, I would probably use a cheap ebay CC-CV charger board, and set the voltage for about 0.15V below the max for your lifepo(you only lose 10% of the energy but You make the battery last much longer), and set the current as appropriate for your panel and battery.

If your circuit is drawing power while the charger is charging, your circuit will take what it needs and any extra the charger puts out will go into the battery.

You might need a diode, to make the battery not discharge back through the charger.

Use a protection pcb like you can get from batteryspace, or better yet a protected lifepo with the pcb built it.

Remember to size your solar panel so that there is enough energy to keep the circuit running. Even with the protected cells overdischarge kills.

What I'd really like to do is design a lifepo4 charge control board that had all this in one unit since everyone seems to want it...


sender: user

message:
Circuit diagram interpretation and electrical flow

![Arduino Robotics : Circuit Example][1]

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

I'm new to Arduino and consequently, to circuits. I've been reading Arduino Robotics by Warren and this was a circuit present in the book.

From what Warren has said, electricity in the circuit travels from the negative pole to the positive, BUT to imagine it as going the other way for simplicity. So, looking at this circuit... it seems useless to have the resistor placed after the LED, based on the + --> - model. Wouldn't the LED turn on before going through the resistor, rendering the resistor useless?

Sorry if this seems like a basic concept, I'm entirely new to this.

sender: assistant

body:
**Should the Resistor be Placed Before or After the LED?**

The important thing to remember is that the direct current electricity must flow *through* the circuit to be useful. Since the resistor is part of the circuit (meaning that there isn't another path for the current to take) it resists the overall flow, thereby helping to protect the LED. Whether before or after the LED, it would still be in the circuit, and would therefore still reduce current flow.

**Visualizing the Flow of Water**

Think of it like a water hose, where the LED is a flow meter and the resistor is your foot. If you step on the hose before the flow meter it will cause the overall flow to slow down. Stepping on the hose after the flow meter but before the nozzle will have the same result, as the water must pass through the entire length of the hose before being released.


message:
Arduino LED matrix and 2D array, data seems to be corrupting

Duplicate of [this question](https://electronics.stackexchange.com/q/102224/38392)

I'm trying to drive an 8x8 LED matrix with an arduino nano, but I can't get the LEDs to display what I tell it to.

I'm using [this](http://www.aliexpress.com/store/product/Free-shipping-10-pcs-8-8-3-75MM-Red-16P-dot-matrix-module-Dimensions-38-38/605870_879542981.html) LED Matrix

Here's my code:

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

    int row1 = 2;
    int row2 = 3;
    int row3 = 4;
    int row4 = 5;
    int row5 = 6;
    int row6 = 7;
    int row7 = 8;
    int row8 = 9;

    int col1 = 10;
    int col2 = 11;
    int col3 = 12;
    int col4 = 18;
    int col5 = 14;
    int col6 = 15;
    int col7 = 16;
    int col8 = 17;

    void setup() {
      int i;
      for(i = 2; i <= 18; i++) {
        pinMode(i,OUTPUT);
      }
      for(i = 2; i <= 9; i++) {
        digitalWrite(i, HIGH);
      }
    }

    void loop() {

      int display [8][8] = {
      {1,0,0,0,0,0,0,0},
      {0,1,0,0,0,0,0,0},
      {0,0,1,0,0,0,0,0},
      {0,0,0,1,0,0,0,0},
      {0,0,0,0,1,0,0,0},
      {0,0,0,0,0,1,0,0},
      {0,0,0,0,0,0,1,0},
      {0,0,0,0,0,0,0,1}
      };

      updateScreen(display);
    }

    void updateScreen(int screen[8][8]) {

      Serial.begin(9600);
      int i;
      for (i = row1; i <= row8; i++) {
        Serial.println(i-1);
        digitalWrite(i, LOW);
          digitalWrite(col8, screen[i-2][0]);
          Serial.print(screen[i-2][0]); Serial.print("|");
          digitalWrite(col7, screen[i-2][1]);
          Serial.print(screen[i-2][1]); Serial.print("|");
          digitalWrite(col6, screen[i-2][2]);
          Serial.print(screen[i-2][2]); Serial.print("|");
          digitalWrite(col5, screen[i-2][3]);
          Serial.print(screen[i-2][3]); Serial.print("|");
          digitalWrite(col4, screen[i-2][4]);
          Serial.print(screen[i-2][4]); Serial.print("|");
          digitalWrite(col3, screen[i-2][5]);
          Serial.print(screen[i-2][5]); Serial.print("|");
          digitalWrite(col2, screen[i-2][6]);
          Serial.print(screen[i-2][6]); Serial.print("|");
          digitalWrite(col1, screen[i-2][7]);
          Serial.println(screen[i-2][7]);
          delay(1);
          blank();
        digitalWrite(i, HIGH);
      }

    }

    void blank() {
      digitalWrite(col1, LOW);
      digitalWrite(col2, LOW);
      digitalWrite(col3, LOW);
      digitalWrite(col4, LOW);
      digitalWrite(col5, LOW);
      digitalWrite(col6, LOW);
      digitalWrite(col7, LOW);
      digitalWrite(col8, LOW);
    }

And here is the output:

    1
    1|0|0|0|0|0|0|0
    2
    0|1|0|0|0|0|0|0
    3
    0|0|1|0|0|0|0|0
    4
    0|0|0|1|0|0|0|0
    5
    0|0|0|0|1|0|0¾j
    6
    0|0|0|0|0|1|0|0
    7
    0|0|0|0|0|0|1|0
    8
    0|0|0|0|0|0|0|1

So I can tell that the error (probably) isn't my wiring, because those array values are clearly wrong, I have no idea where the `¾j` is coming from.

body:
Your initial problem can be sorted out by using a longer `delay`.

    void updateScreen(int screen[8][8]) {

      Serial.begin(9600);
      int i;
      ........
          delay(100); //Longer time duration
          blank();
        digitalWrite(i, HIGH);
      }

    }

As far as the chess pattern is concerned, it displays correctly for me.

    void loop() {

      int display [8][8] = {
      {1,0,1,0,1,0,1,0},
      {0,1,0,1,0,1,0,1},
      {1,0,1,0,1,0,1,0},
      {0,1,0,1,0,1,0,1},
      {1,0,1,0,1,0,1,0},
      {0,1,0,1,0,1,0,1},
      {1,0,1,0,1,0,1,0},
      {0,1,0,1,0,1,0,1}
      };

      updateScreen(display);
    }

Check your array declarations for errors.


body:
Because of my psychic abilities*, I am able to tell that you actually used `.` in a few places you should have used `,` in your array initialization. Replacing the `,`s with `.`s should fix the problem.

*[Okay, okay, not really.][1]

  [1]: https://arduino.stackexchange.com/questions/672/arduino-led-matrix-and-2d-array-data-seems-to-be-corrupting#comment1193_672


message:
How does the Space Replay record audio?

>[The Space Replay][1]
>
> A hovering object that explores and manipulates transitional public
> spaces with particular acoustic properties. By constantly recording
> and replaying these ambient sounds, the levitating sphere produces a
> delayed echo of human activity.
>
> ![](https://blog.arduino.cc/wp-content/uploads/2014/03/replay.jpg)

In this project, the Arduino board and an [Adafruit Wave Shield][2] is used. The Wave shield is not designed to record audio however, they say that they use the board for both *recording* and playback.

> The sphere responds sonically to people and its surroundings by means of a battery-powered Arduino, an Adafruit Wave Shield hacked to record and playback audio on-the-fly and a small speaker.

This generates a few questions.

- How would this be done?
- Where would the microphone be placed inside the balloon for decent audio capture?
- Would there be a better way to design this?

  [1]: http://ied.rca.ac.uk/de-computation/space-replay
  [2]: https://www.adafruit.com/products/94

body: As jippie said, you can use the Arduinos ADC to record audio, and presumably save that to the Arduino's RAM (the SD card is probably too slow for directly saving it). Then it writes the buffer to the SD card.


body:
It seems to be possible to record with the shield using a library called [waverp][1]

> WaveRP is an Arduino library for recording and playing Wave files with
> the Adafruit Wave Shield. It records 8-bit mono files at 4,000 to
> 44,100 samples per second.

Some details [adafruit blog][2]:

> It records 8-bit mono files at 4,000 to 44,100 samples per second.

  [1]: https://code.google.com/p/waverp/
  [2]: https://www.adafruit.com/products/94


body:
Maybe is kind of late but I found the code for the Space Replay
is in [here][1] at the bottom of the last image, specifically in [here][2]

    /*------------------------------------------------------------------------------

            __-__         Code for Space Replay, a floating black orb that records
          .X+..   Â·       and plays back ambient sounds. This sketch was adapted by
        .Xx+-Â·..    Â·     Francesco Tacchini, with the help of Oliver Smith & Brock
        XXx++-...         Craft, from the original WaveRecordPlay example sketch
        XXxx++--.....Â·    written by Bill Greiman.
        `XXXxxx++---'     This project was created as part of a university project at
          `XXXxxxx'       the Royal College of Art. It's a collaboration with Julinka
             """          Ebhardt and Will Yates-Johnson. See more: vimeo.com/88992597

    ------------------------------------------------------------------------------*/

    #include <SdFat.h>
    #include <WaveRP.h>
    #include <SdFatUtil.h>
    #include <ctype.h>

    #define MIC_ANALOG_PIN 0             // Define the analog pin
    #define RECORD_RATE 44100            // Define the record rate
    #define ADC_REFERENCE ADC_REF_AVCC
    #define PRINT_FILE_INFO 0            // Useful for debug: print file info and
    #define PRINT_DEBUG_INFO 1           // bad wave file size or SD busy errors
    #define MAX_FILE_SIZE 104857600UL    // 100MB or 150 min at 11025 samples/second
    #define DISPLAY_RECORD_LEVEL 1

    // debugging led
    int playLED = 7;
    int recLED = 8;
    int delStopLED = 9;

    // global variables
    Sd2Card card;           // SD/SDHC card with support for version 2.00 features
    SdVolume vol;           // FAT16 or FAT32 volume
    SdFile root;            // volume's root directory
    SdFile file;            // current file
    WaveRP wave;            // wave file recorder/player
    int16_t lastTrack = -1; // Highest track number
    uint8_t trackList[32];  // bit list of used tracks

    //------------------------------------------------------------------------------
    // print error message and halt
    void error(char* str) {
      PgmPrint("error: ");
      Serial.println(str);
      if (card.errorCode()) {
        PgmPrint("sdError: ");
        Serial.println(card.errorCode(), HEX);
        PgmPrint("sdData: ");
        Serial.println(card.errorData(), HEX);
      }
      while(1);
    }
    //------------------------------------------------------------------------------
    uint8_t trackName(int16_t number, char* name) {
      if (0 <= number && number <= 255) {
        strcpy_P(name, PSTR("TRACK000.WAV"));
        name[5] = '0' + number/100;
        name[6] = '0' + (number/10);
        name[7] = '0' + number;
        return true;
      }
      PgmPrint("Invalid track number: ");
      Serial.println(number);
      return false;
    }
    //------------------------------------------------------------------------------
    // start file playing
    uint8_t playBegin(char* name) {
      if (!file.open(&root, name, O_READ)) {
        PgmPrint("Can't open: ");
        Serial.println(name);
        return false;
      }
      if (!wave.play(&file)) {
        PgmPrint("Can't play: ");
        Serial.println(name);
        file.close();
        return false;
      }
    #if PRINT_FILE_INFO
      Serial.print(wave.bitsPerSample, DEC);
      PgmPrint("-bit, ");
      Serial.print(wave.sampleRate/1000);
      PgmPrintln(" kps");
    #endif // PRINT_FILE_INFO
    #if PRINT_DEBUG_INFO
      if (wave.sdEndPosition > file.fileSize()) {
        PgmPrint("play Size mismatch,");
        Serial.print(file.fileSize());
        Serial.print(',');
        Serial.println(wave.sdEndPosition);
      }
    #endif // PRINT_DEBUG_INFO
      PgmPrint("Playing: ");
      Serial.print(name);
      return true;
    }
    //------------------------------------------------------------------------------
    // play all files in the root dir
    void playTracks(void) {
      dir_t dir;
      char name[13];
      uint8_t np = 0;
      root.rewind();
      while (root.readDir(&dir) == sizeof(dir)) {
        //only play wave files
        if (strncmp_P((char *)&dir.name[8], PSTR("WAV"), 3)) continue;
        // remember current dir position
        uint32_t pos = root.curPosition();
        // format file name
        SdFile::dirName(dir, name);
        if (!playBegin(name)) continue;
        PgmPrintln("");
        while (wave.isPlaying()) {
          uint8_t c = Serial.read();
        }
      }
      file.close();
    }
    //------------------------------------------------------------------------------
    // delete a track
    void trackDelete(int16_t track) {
      char name[13];
      if (!trackName(track, name)) return;

      if (SdFile::remove(&root, name)) {
        PgmPrintln("Deleted!");
      }
      else {
        PgmPrintln("Delete failed!");
      }
    }
    //------------------------------------------------------------------------------
    // Finally we have the normal SETUP and LOOP functions -------------------------
    //------------------------------------------------------------------------------
    void setup(void) {
      Serial.begin(9600);
      if (!card.init()) error("card.init");
      if (!vol.init(&card)) error("vol.init");
      if (!root.openRoot(&vol)) error("openRoot");

      pinMode(playLED, OUTPUT);
      pinMode(recLED, OUTPUT);
      pinMode(delStopLED, OUTPUT);

    }
    //------------------------------------------------------------------------------
    // loop to play and record files.
    void loop() {
      digitalWrite(delStopLED, HIGH);
      if (file.isOpen()){
        file.close();      // Make sure file is closed
      }

      int16_t track = -1;
      uint8_t c;
      if (track < 0 ) {
        track = lastTrack;
      }

      char name[13];
      if (track < 0) track = lastTrack + 1;
      if (!trackName(track , name)) return;
      if (file.open(&root, name, O_READ)) {
        file.close();
        trackDelete(track);
        return;
      }
      digitalWrite(delStopLED, LOW);
      digitalWrite(recLED, HIGH);
      Serial.println( "Recording" );    // Record new file...

      if (!file.createContiguous(&root, name, MAX_FILE_SIZE)) {
          PgmPrintln("Create failed");
          return; }
      if(!wave.record(&file, RECORD_RATE, MIC_ANALOG_PIN, ADC_REFERENCE)) {
          PgmPrintln("Record failed");
          file.remove();
          return; }

      delay(5000);     // ...for x milliseconds
      digitalWrite(recLED, LOW);
      wave.stop();
      wave.trim(&file);
      file.close();     // Stop the recording, trim and close the file

      digitalWrite(playLED, HIGH);
      playTracks();     // Play the file
      digitalWrite(playLED, LOW);
    }

About your questions,

 - In the latest WaveRP library there's a folder where it explains how to attach a microphone to the waveshield. And I'm guessing I don't know for sure, but I'd say they're using a contact mic, the contact mics are both, mics and speakers, some cheap walkies also use them. So I'm guessing that they're using only one?

 - Contact mics pick up vibration so, I think the plastic cone that they're using is for de contact mic to pick up the vibrations of the surroundings sounds.

 - A better way to design it? I think that it depends. In a way is an art piece. So, a better way to design it... is like to ask VanGogh a better way to paint sunflowers.
But I think always the sound can be better. A way to improve it could be  making a better amplifier circuit for reduce the noise or separating the mic and the speakers... But I don't know, I think it depends what you want to make and what you want to achieve. Because if you want it to float is better to have the leastest components. But if the sound is the priority I think it can be much more better using an amplifier, a better mic, etc.

Also, now in the Adafruit Wave Shield's page there is a project of realtime voice changer, that also record and playbacks. More information [here][3]

  [1]: http://tacchini.fr/space_replay/
  [2]: http://tacchini.fr/code/spaceReplay.txt
  [3]: https://learn.adafruit.com/wave-shield-voice-changer/


message:
Connecting Something Big to an Arduino - Sending more than 5V

So I am turning a relay on and off with my Arduino. I am using python to control it but wrote the simple basic code in the Arduino IDE. I am able to send 5 or 0 volts to the pin. My question is, how can I turn something on and off that requires more than 5 volts to turn on?

Thank you.

body: Use a transistor, amplifier, opto-isolator or if you can drive a 5V relay use that relay to drive a higher voltage/current item item.


message:
Is using malloc() and free() a really bad idea on Arduino?

The use of `malloc()` and `free()` seems pretty rare in the Arduino world. It is used in pure AVR C much more often, but still with caution.

Is it a really bad idea to use `malloc()` and `free()` with Arduino?

body:
Typically, when writing Arduino sketches, you will avoid dynamic allocation (be it with `malloc` or `new` for C++ instances), people rather use global -or `static`- variables, or local (stack) variables.

Using dynamic allocation can lead to several problems:

- memory leaks (if you lose a pointer to a memory you previously allocated, or more likely if you forget to free the allocated memory when you don't need it anymore)
- heap fragmentation (after several `malloc`/`free` calls) where the heap grows bigger thant the actual amount of memory allocated currently

In most situations I have faced, dynamic allocation was either not necessary, or could be avoided with macros as in the following code sample:

**MySketch.ino**

    #define BUFFER_SIZE 32
    #include "Dummy.h"

**Dummy.h**

    class Dummy
    {
        byte buffer[BUFFER_SIZE];
        ...
    };

Without `#define BUFFER_SIZE`, if we wanted `Dummy` class to have a non-fixed `buffer` size, we would have to use dynamic allocation as follows:

    class Dummy
    {
        const byte* buffer;

        public:
        Dummy(int size):buffer(new byte[size])
        {
        }

        ~Dummy()
        {
            delete [] bufer;
        }
    };

In this case, we have more options than in the first sample (e.g. use different `Dummy` objects with different `buffer` size for each), but we may have heap fragmentation issues.

Note the use of a destructor to ensure dynamically allocated memory for `buffer` will be freed when a `Dummy` instance is deleted.


body:
Using dynamic allocation (via `malloc`/`free` or `new`/`delete`) isn't inherently bad as such. In fact, for something like string processing (e.g. via the `String` object), it's often quite helpful. That's because many sketches use several small fragments of strings, which eventually get combined into a larger one. Using dynamic allocation lets you use only as much memory as you need for each one. In contrast, using a fixed-size static buffer for each one could end up wasting a lot of space (causing it to run out of memory much faster), although it depends entirely on the context.

With all of that being said, it's very important to make sure memory usage is predictable. Allowing the sketch to use arbitrary amounts of memory depending on run-time circumstances (e.g. input) can easily cause a problem sooner or later. In some cases, it might be perfectly safe, e.g. if you *know* the usage will never add up to much. Sketches can change during the programming process though. An assumption made early-on could be forgotten when something is changed later, resulting in an unforeseen problem.

For robustness, it's usually better to work with fixed-size buffers where possible, and design the sketch to work explicitly with those limits from the outset. That means any future changes to the sketch, or any unexpected run-time circumstances, should hopefully not cause any memory problems.


body:
My general rule for embedded systems is to only `malloc()` large buffers and only once, at the start of the program, e.g., in `setup()`. The trouble comes when you allocate and de-allocate memory. Over a long run session, memory becomes fragmented and eventually an allocation fails due to lack of a sufficiently large free area, even though the total free memory is more than adequate for the request.

(Historical perspective, skip if not interested): Depending on the loader implementation, the only advantage of run-time allocation vs. compile-time allocation (intialized globals) is the size of the hex file. When embedded systems were built with off the shelf computers having all volatile memory, the program was often uploaded to the embedded system from a network or an instrumentation computer and the upload time was sometimes an issue. Leaving out buffers full of zeros from the image could shorten the time considerably.)

If I need dynamic memory allocation in an embedded system, I generally `malloc()`, or preferably, statically allocate, a large pool and divide it into fixed-size buffers (or one pool each of small and large buffers, respectively) and do my own allocation/de-allocation from that pool. Then every request for any amount of memory up to the fixed buffer size is honored with one of those buffers. The calling function doesn't need to know whether it's larger than requested, and by avoiding splitting and re-combining blocks we solve fragmentation. Of course memory leaks can still occur if the program has allocate/de-allocate bugs.

Update 02/16/23:

> I'm curious why the Arduino library's malloc implementation doesn't
> implement some coalescing of the free blocks like a full OS would.

That's interesting to think about, but let's first be clear that in C/C++, malloc() and free() are implemented as library functions at the application-level not the OS level, even in major OSes. And they are based on fragmenting the heap, just as the Arduinos' malloc() functions do.

Embedded systems, are relatively new, at least as an influential force in the design of OSes, languages, and libraries' design. Which is to say, programs that had to run "forever" without failing (other than, perhaps the OS itself) were outliers. Most programs we run on our desktops or (once upon a time) ran on mainframes, were started, processed a batch of data, and exited.

Secondly, the malloc()/free() method of memory allocation/deallocation was simple, where anticipating the sizes of memory requests was not; and some allocations are used briefly and returned, where some are kept for the duration of the run. How is a library designer to provide for coalescing currently free and newly deallocated memory with no knowledge of the allocate/deallocate usage and sizes of requests? The fixed-size buffer scheme I described above doesn't suffer the fragmentation problem that "malloc() an arbitrary number of bytes" scheme does. It is still limited to available memory but within that limitation, could meet the "run forever" requirement. There may be algorithms that split and coalesce memory, but probably only for a few - statistically predictable - patterns of allocation and deallocation.

Update 02/18/23:

@edgarbonet points out that Arduino's `free()` does try to coalesce free blocks. This is a good example of an algorithm that works for certain cases: Properly done, it would work for "last-out / first-in" cases, and to some extent for some other cases.

The trouble is, most of our use patterns are not very regular, if they're regular at all. An alogrithm that does no splitting, but merely allocates & deallocates fixed-size pieces (rather like loaning library books) can still run out of memory but won't end up with fragmented resources. In fact, because it doesn't split, it *will* need more memory to meet the same random-sized requests than even a coalescing `malloc()` and `free()`.


body:
I have taken a look at the algorithm used by `malloc()`, from avr-libc,
and there seems
to be a few usage patterns that are safe from the point of view of heap
fragmentation:

## 1. Allocate only long-lived buffers

By this I mean: allocate all you need at the beginning of the program,
and never free it. Of course, in this case, you could as well use static
buffers...

## 2. Allocate only short-lived buffers

Meaning: you free the buffer before allocating anything else. A
reasonable example might look like this:

    void foo()
    {
        size_t size = figure_out_needs();
        char * buffer = malloc(size);
        if (!buffer) fail();
        do_whatever_with(buffer);
        free(buffer);
    }

If there is no malloc inside `do_whatever_with()`, or if that function
frees whatever it allocates, then you are safe from fragmentation.

## 3. Always free the last allocated buffer

This is a generalization of the two previous cases. If you use the heap
like a stack (last in is first out), then it will behave like a stack
and not fragment. It should be noted that in this case it is safe to
resize the last allocated buffer with `realloc()`.

## 4. Always allocate the same size

This will not prevent fragmentation, but it is safe in the sense that
the heap will not grow larger than the maximum _used_ size. If all your
buffers have the same size, you can be sure that, whenever you free one
of them, the slot will be available for subsequent allocations.


body:
I disagree with people who think you shouldn't use it or it is generally unnecessary. I believe it can be dangerous if you don't know the ins and outs of it, but it is useful. I do have cases where I don't know (and shouldn't care to know) the size of a structure or a buffer (at compile time or run time), especially when it comes to libraries I send out into the world. I agree that if you're application is only dealing with a single, known structure, you should just bake in that size at compile time.

Example: I have a serial packet class (a library) that can take arbitrary length data payloads (can be struct, array of uint16_t, etc.). On the sending end of that class you simply tell the Packet.send() method the address of the thing you wish to send and the HardwareSerial port through which you wish to send it. However, on the receiving end I need a dynamically allocated receive buffer to hold that incoming payload, as that payload could be a different structure at any given moment, depending on the application's state, for instance. IF I'm only ever sending a single structure back and forth, I'd just make the buffer the size it needs to be at compile time. But, in the case where packets may be different lengths over time, malloc() and free() are not so bad.

I've run tests with the following code for days, letting it loop continuously, and I've found no evidence of memory fragmentation. After freeing the dynamically allocated memory, the free amount returns to its previous value.

<!-- language: cpp -->

    // found at learn.adafruit.com/memories-of-an-arduino/measuring-free-memory
    int freeRam () {
        extern int __heap_start, *__brkval;
        int v;
        return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
    }

    uint8_t *_tester;

    while(1) {
        uint8_t len = random(1, 1000);
        Serial.println("-------------------------------------");
        Serial.println("len is " + String(len, DEC));
        Serial.println("RAM: " + String(freeRam(), DEC));
        Serial.println("_tester = " + String((uint16_t)_tester, DEC));
        Serial.println("alloating _tester memory");
        _tester = (uint8_t *)malloc(len);
        Serial.println("RAM: " + String(freeRam(), DEC));
        Serial.println("_tester = " + String((uint16_t)_tester, DEC));
        Serial.println("Filling _tester");
        for (uint8_t i = 0; i < len; i++) {
            _tester[i] = 255;
        }
        Serial.println("RAM: " + String(freeRam(), DEC));
        Serial.println("freeing _tester memory");
        free(_tester); _tester = NULL;
        Serial.println("RAM: " + String(freeRam(), DEC));
        Serial.println("_tester = " + String((uint16_t)_tester, DEC));
        delay(1000); // quick look
    }

I haven't seen any sort of degradation in RAM or in my ability to allocate it dynamically using this method, so I'd say it's a viable tool. FWIW.


body:
> Is it a really bad idea to use malloc() and free() with Arduino?

The short answer is yes. Below are the reasons why:

It is all about understanding what an MPU is and how to program within the constraints of the available resources. The Arduino Uno uses an [ATmega328p][1] MPU with 32KB ISP flash memory, 1024B EEPROM, and 2KB SRAM. That is not a lot of memory resources.

Remember that the 2KB SRAM is used for all global variables, string literals, stack and possible usage of the heap. The stack also needs to have head room for an ISR.

The [memory layout][2] is:

[![SRAM map][3]][3]

Todays PC/laptops have more than 1.000.000 times the amount of memory. A 1 Mbyte default stack space per thread is not uncommon but totally unrealistic on an MPU.

An embedded software project has to do a resource budget. This is estimating  ISR latency, necessary memory space, compute power, instruction cycles, etc. There are unfortunately no free-lunches and hard real-time embedded programming is the most [difficult][4] of programming skills to master.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [2]: http://www.nongnu.org/avr-libc/user-manual/malloc.html
  [3]: https://i.stack.imgur.com/YJsy5.png
  [4]: https://en.wikipedia.org/wiki/COCOMO


message:
Is it possible to build a 1080p OSD webcam shield?

What do I need to build a shield capable of receiving 1080p video from USB camera, timestamp each frame and send the frame to memory card?

body:
None of the ATmega based boards have the hardware (in terms of acting as a USB host) or power (in terms of handling probably compressed 1080p video).

Potentially one of the ARM boards could do this. The Arduino Due can act as a host, but it sounds fairly experimental, and none of them will have drivers to connect to the camera.

If a shield was developed to do this, it would have so much more power than the Arduino that the Arduino would probably better be viewed as a slave to the other device.


message:
attiny85 and arduino - analogRead + pwmOut

I am using the Arduino IDE to program the attiny85. I want to take an incoming analog reading, then based on that reading, output a specific PWM value. Here's my circuit:

![my circuit][1]

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

and here's my code:

    // to run on attiny85

    const byte pwmPin = 0;
    const byte analogInPin = A2;

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

    void loop() {
      int analogIn = analogRead(analogInPin);
      analogWrite(pwmPin, analogIn);
    }

should be very simple- I have no problems uploading code to the attiny85, and no problems with simple tests like outputting a specific PWM value (not based on the analog read). but when I try to combine the two- read, then write that value, I can't seem to get things to work. In this circuit for example- I get a reading of 1023 (5v) on the arduino micro- instead of a reading of ~ 790 (3.85v) which is what I should expect. I've used a multimeter to verify the voltages in this circuit- so I think I must either be doing something wrong with my expectations of how to wire up or program the attiny85.

body:
Analog read is 10-bits (2^10 = 0-1023 range), analog write is 8-bits (2^8 = 0-255 range). Ditch the lower two bits of the result either by doing:

    analogIn = analogIn >> 2;

which can be shortened to:

    analogIn >>= 2;

Or you can use the rather complex map function:

    analogIn = map( analogIn(0, 1023, 0, 255) )


body:
i needed to re-range the 10bit input to 8 bit for the pwm out.

    // to run on attiny85

    const byte pwmPin = 0;
    const byte analogInPin = A2;

    void setup() {
    }

    void loop() {
      pinMode(pwmPin, OUTPUT);
      int analogIn = analogRead(analogInPin);
     analogIn = map(analogIn, 0, 1023, 0, 255);
     analogWrite(pwmPin, analogIn);
    }


message:
Arduino time keeping using millis() is not accurate or correct?

I have been using the Arduino to record some data. In my Arduino sketch I also used the `millis()` function so I can keep track of the time at which each value I am measuring is taken. However, I noticed that the timing isn't correct. For example 30 seconds in real life only comes out as 10 seconds (made up example).

Am I correct in saying that the Arduino delay function affects the time keeping using `millis()`? In other words suppose I have a delay of 50ms, does that mean the `millis()` function stops for that duration as well and then continues and so on for the duration of the connection? I noticed this when I tried plotting some data and finding that the frequency of the peaks in my data was too frequent given the time which had passed by. So I want to know if that is the reasoning for this mismatch of timing and if so, how do I fix this so that I can keep the time each sample occurs?

To give some context here is my sketch:
<!-- language: lang-cpp -->

    #include <eHealth.h>

    unsigned long time;
    // The setup routine runs once when you press reset:
    void setup() {
      Serial.begin(9600);
    }

    // The loop routine runs over and over again forever:
    void loop() {

      float ECG = eHealth.getECG();
      time = millis();
      Serial.print(time);
      Serial.print(" ");
      Serial.print(ECG, 5);
      Serial.println("");

      delay(50);
    }

body:
`millis()` is interrupt driven so `delay()` won't impact it, at least not on an ATmega based board.

That isn't to say that `millis()` is totally accurate either. Each tick of the timer is not exactly 1ms, but is 1.024ms. This error gradually accumulates until a correction is made. This can be seen in the implementation of the TIMER0_OVF (timer 0 overflow) interrupt handler.

Another source of inaccuracy is the oscillator/crystal itself, which is not exactly 16MHz. It is pretty close though, and as long as temperature doesn't change too much, is relatively stable.

The above means that you might be about 1ms out when using `millis()`. This doesn't sound like your problem.

Another potential issue would be what `getECG()` is doing - it might be very slow.

    float eHealthClass::getECG(void)
     {
      float analog0;
      // Read from analogic in.
      analog0=analogRead(0);
      // binary to voltage conversion
      return analog0 = (float)analog0 * 5 / 1023.0;
     }

`analogRead()` is slow, but not so slow as to impact a loop like this.

Another problem I have seen people have is when they change the clock speed but don't correctly change boards.txt. This means that the constants used in the `millis()` implementation are wrong and the times are wrong.

If you actually want to read values every 50ms, a much better way of implementing this is to do the following

    static long lastUpdate;

    if (millis() - lastUpdate > 50)
    {
        lastUpdate = millis();
        //Do stuff
    }

We'd really need to see the timestamps you are getting. If you actually seeing 30s showing as 10s, then there is something else at work.


body:
If interrupts are turned off for any significant fraction `eHealth.getECG()` call duration, `millis()`'s count could fall behind. Otherwise, `millis()` should return much more accurate time than the 3x errors you described.

You said your sampled signal appears higher in frequency than what you expected, which could happen if your sample rate is lower than you intended. Are you a assuming a 20Hz sample rate? Your loop could be taking a fair bit longer than 50ms, which you would see in the printed times, but those should still track the clock time. If you didn't account for that but assumed 50ms/sample, you'd see an apparent speed up of of the data.

If this is not the issue, then the next step would be to toggle an output while you're in `loop()`, and measure the frequency of the resulting square wave with a frequency meter (some inexpensive DVMs can do this) or a 'scope. Do the same thing with an empty `loop()`. The first experiment will your real sampling rate or interval; the second will tell you whether `millis()` (ie., the timer0 frequency) is what you expected.


body: Same here. I can add that if interruptions are turned off, the time measured is "real time". Anyway, I dont understand why this delay, because if the loop take too long, anyway the millis() should return real time values (only with more distance between each value)


message:
How do I know the sampling frequency?

I am beginning to get a bit confused about sampling rates and baudrates etc. I have this Arduino code:

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

    #include <eHealth.h>

    extern volatile unsigned long timer0_overflow_count;
    float fanalog0;
    int analog0;
    unsigned long time;

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

    void loop() {
      while (Serial.available()>0){
        serialByte=Serial.read();
        if (serialByte=='S'){
          while(1){
            fanalog0=eHealth.getECG();
            // Use the timer0 => 1 tick every 4 us
            time=(timer0_overflow_count << 8) + TCNT0;
            // Microseconds conversion.
            time=(time*4);
            //Print in a file for simulation
            //Serial.print(time);
            //Serial.print(" ");
            Serial.print(fanalog0,5);
            Serial.print("\n");

            if (Serial.available()>0){
              serialByte=Serial.read();
              if (serialByte=='F')  break;
            }
          }
        }
      }
    }

Since there is no delay interrupt, what is the sampling rate/frequency? Is it based on the Arduino ADC speed? When I increase the baudrate am I increasing the sampling frequency or just the rate at which I send data over the serial port?

body:
Each loop you are printing 8 characters over a 9600bps serial link. Each character takes 10 bits (1 start, 8 bits for the character, 1 stop). That means you can only go through this loop ~120 times/sec.

The `analogRead()` function can sample at about 9600 times/sec in theory, realistically it is about 8600 times/sec.

You are being bounded by the serial communication.


body:
The Arduino ADC clock speed is set in ..arduino-1.5.5\hardware\arduino\avr\cores\arduino\wiring.c

Here is the relevant part

    #if defined(ADCSRA)
     // Set A/D prescale factor to 128
     // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
     // XXX: this will not work properly for other clock speeds, and
     // this code should use F_CPU to determine the prescale factor.
     sbi(ADCSRA, ADPS2);
     sbi(ADCSRA, ADPS1);
     sbi(ADCSRA, ADPS0);

     // Enable A/D conversions
     sbi(ADCSRA, ADEN);
    #endif

For a 16 MHz Arduino the ADC clock is set to 16 MHz/128 = 125 KHz. Each conversion in AVR takes 13 ADC clocks so 125 KHz /13 = 9615 Hz.

That is the maximum possible sampling rate, but the actual sampling rate in your application depends on the interval between successive conversions calls.
Since you read the result and send it through the serial port, you are getting a delay that increases as the baud rate decreases. The lower the baud rate the longer it will take to send the same length of data and the longer it will take to call the next ADC conversion.

The actual sampling rate in your application can be determined with the use of a debugger or a simulator, but an easier solution is to toggle a digital pin every time you execute a conversion and measure the frequency that the digital pin toggles at.


body:
I also wanted to get a high sampling rate, for a project. turns out that the ADPS2,ADPS1,ADPS0 bits of the ADCSRA register can be configured to get a sampling rate of 76923 s/s or 76.8 ks/s. But, beware that I am running my arduino's ADC in free running mode, the following lines worked for me.

    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    void setup() {
    // Set the Prescaler to 16 (16000KHz/16 = 1MHz)
    // WARNING: Above 200KHz 10-bit results are not reliable.
    //ADCSRA |= B00000100;
    sbi(ADCSRA, ADPS2);
    cbi(ADCSRA, ADPS1);
    cbi(ADCSRA, ADPS0);

    // Set ADIE in ADCSRA (0x7A) to enable the ADC interrupt.
    // Without this, the internal interrupt will not trigger.
    //ADCSRA |= B00001000;
    sbi(ADCSRA,ADIE)
    }

At this frequency the usual 10-bit results are not reliable. It means that increasing the sample rate will decrease the precision of the results. So I only use the upper 8 bits because at this prescalar the upper 8-bits are reliable. You can go into more detail on this page, this dude rocks! he made a high sample rate oscilloscpe using UNO http://www.instructables.com/id/Girino-Fast-Arduino-Oscilloscope/


body: Sending 11 bits over serial at a baud of 9600, but for the sampling, I store it in an array with as little delay as possible, then once it's done, I send it through the serial port to be read by a python script. I'm doing this for an FFT using matplotlib. I listen to a 0-5V signal, then without using the delay() function, I store the analogRead() values into that array. In a split second the reading is done, then the serial data dump starts. When I calibrated the input frequency using tone() from another connected Arduino, I realized that I had to divide the index by 8915 in order to get accuracy to within .1 Hz. Because one would have to divide by the frequency of the sampling to get the proper index intervals, my guess is the Arduino sampling frequency (at least mine with my code) is 8915Hz.


body:
Referring to the part about the difference between sample rate and baud rate, they are different measurements.

Sample Rate is the frequency at which the device (arduino) can recreate a digital representation of incoming analog values.

Baud Rate is the rate at which information is transferred in a communication channel. It describes the rate of communication between the microcontroller and the outside world (the computer).

I would recommend this electronics_stack_exchange link.
https://electronics.stackexchange.com/questions/135056/sampling-rate-data-rate-and-bandwidth


body:
8915Hz - it is very close to 125000/14 ~= 8928.6
My initial guess that exactly one gap is required between adjacent conversions
One ADC clock for sampling and 13 ADC clocks for conversion itself.
Small error could be effect of not perfect clock source of Arduino.
I am not sure yet.
This topic is actual for me now as sampled data must feed digital filter.


body: Have you considered getting A Saleae or similar logic analyzer. The simple inexpensive ones work great and allow you to make these measurements quite easily. This works better then a scope in most of my applications. If there is signal overlap it will show. I simply devote one pin for testing and call it testpin. Just set it high when starting the routine and then low when finished.  It has 8 inputs so you can see the relationship between signals. You could monitor the A/D, starting the trigger and place the serial on another pin. You still have 6 left for other things. Spend a few hours with it and it will become one of your most important tools. I use Linux Mint so I just keep it on another screen so a simple click brings it in view and it will run whether the window is in view or not. Be careful if you have unused inputs they will act as antenna and pick up stray signals especially from switching power supplies. Just select the channels you want or ignore the ones that are not relevant. The built in analyzers make short work of serial signals.


message:
How to use a Pololu 5v AVR ISP Programmer to program an AVR at 3.3v

I have a [Pololu 5v AVR ISP](http://www.pololu.com/product/1300) which I have successfully used to program several Arduinos (a Mega, an Uno and a Pro Mini 5v). I now have a new Arduino compatible clone which is basically a clone of the pro mini 3.3V.

I am wondering if anyone else has used this programmer to program a 3.3V board without issues. I've seen a forum post on [pololu's forum](http://forum.pololu.com/viewtopic.php?f=3&t=7368) which discusses modifications required - but I don't really understand what is necessary.

I've also found the software tool mentioned in the above forum post [here](http://www.pololu.com/docs/0J41) and I have downloaded it and built it.

When I run the aforementioned tool I get these options:

    PgmCmd: Configuration and status utility for the Pololu USB AVR Programmer.
    Version: 1.0.1.0
    Options:
     -l, --list             list available devices
     -d, --device SERIALNUM (optional) select device with given serial number
     -s, --status           display complete device status
         --freq NUM         sets the ISP frequency (in units of kHz)
         --linea ID
           or --lineb ID    set serial control signal associated with line A or B.
                            Valid IDs are: none, cd, dsr, ri, dtr, rts.
                            Warning: dtr and rts are outputs: -f option is required
         --swminor HEXNUM   AVR ISP software version minor (in hex, e.g. A)
         --swmajor HEXNUM   AVR ISP software version major (in hex)
         --hw HEXNUM        AVR ISP software hardware version (in hex)
         --vddmin NUM       set minimum allowed target vdd (units of mV)
         --vddmaxrange NUM  set maximum allowed target vdd range (units of mV)
         --restoredefaults  restore factory settings
         --bootloader       put device in to bootloader (firmware upgrade) mode

I then ran the --status option with the serial number of my programmer and got this:

    Serial number:                  00048632
    Firmware version:               1.07
    Settings:
      ISP Frequency:                200 kHz
      Line A Identity:              None
      Line B Identity:              None
      AVR ISP hardware version:     F
      AVR ISP software version:     2.A
      Target VDD allowed minimum:   4384 mV
      Target VDD allowed max range: 512 mV
    Last programming:
      Error: None
      Measured Target VDD Minimum:  N/A
      Measured Target VDD Range:    N/A
    SLO-scope:
      State:                        Off
      Line A output:                Off
      Line B output:                Off

From this I deduced that my programmer is currently set at between about 4.38V and 4.89V which I presume corresponds to the 5V approximate voltage of the normal Arduino chips.

Given that the utility program allows me to set both the target minimum Vdd and the target Vdd max range should I therefore set it to something like a minimum of 2704 with a max range of 512 which should put the signal voltages at up to ~3.2V.

Is that all I have to do to get this to work?

body: Since AVR ISP is simply a modified form of SPI, the most universal way to handle this is to use a 3/1 level translator such as the MAX3392E. Once you provide it with 5V on VCC and 3V3 on VL it will translate the MOSI, SCK, and nRESET signals to 3V3 and the MISO signal to 5V.


message:
High precision timing on Arduino for serial communication

I am using an Arduino Uno to send time and voltage information over the serial port to Python to plot. However the interval timings between successive time stamps appears to be increasing over time, affecting my plotting. This is especially true when the baud rate is set to 9600, where my initial time differences maybe 1320 and increases to 16400 after a relatively short period of time. When this rate is put to maximum of 115200 bps the change is slower and less noticeable, from around 1340 to 1500 even after a relatively long run of sending. All times are given in microseconds.

I would like to know if I can reduce or eliminate this effect, and if not understand why it exists. I have read things about interrupts and delays causing this, but I do not fully appreciate the complexity of the electronics at hand and would like to know:

1. Can I get greater precision in the timing?
2. What causes this change in timing?

Here is what I currently have:

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

    #include <eHealth.h>

    extern volatile unsigned long timer0_overflow_count;
    float fanalog0;
    int analog0;
    unsigned long time;

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

    void loop() {
      while (Serial.available()>0){
        serialByte=Serial.read();
        if (serialByte=='S'){
          while(1){
            fanalog0=eHealth.getECG();
            // Use the timer0 => 1 tick every 4 us
            time=(timer0_overflow_count << 8) + TCNT0;
            // Microseconds conversion.
            time=(time*4);
            //Print in a file for simulation
            //Serial.print(time);
            //Serial.print(" ");
            Serial.print(fanalog0,5);
            Serial.print("\n");

            if (Serial.available()>0){
              serialByte=Serial.read();
              if (serialByte=='F')  break;
            }
          }
        }
      }
    }

body:
I can think of a few things that can impact the "consistency" of the serial write timings:

 * size of the data to be printout

this may be the most obvious thing to think of, but indeed the more you print, the more it'll take to handle it.

Solution: print format the string into a string of known length.

 * using buffered serial

on unix you can access the serial port using a buffered or an unbuffered way. Using the buffered way for a long time may make it a bit slower as the buffer fills, usually it happens when data is incoming faster than you're reading it…

Solution: use the unbuffered serial line (*e.g.*: on Darwin/OSX it's `/dev/cu.usbmodemXXX` instead of `/dev/tty.usbmodemXXX`)

 * priority of the timers

it looks like your using a TC interrupt, and AVRs have priorities in the way interrupts are handled, I don't know the order of priority for the Atmega328, and it's not one of the most documented feature around, so I don't know how safe is TC0 versus the UART interrupt.

Solution: look up further in the documentation/datasheet about interrupt priorities and change the timer if needed ; and/or do a test without having the other timer running.

 * the data you're reading from takes more time to read from over time

some drivers need to average or do some operations over the previous values, so the more values you measure, the longer the buffer is, and the longer it takes to calculate the value, until you've reached the maximum size of the buffer.

Solution: look at the source code of the library you're using, and either optimize it, remove the calcul if there's one or take that increasing processing time into account.

 * avoiding the arduino framework overhead

but if you *really* want to optimize serial output from the arduino, you should avoid using the arduino overhead… But it's way less elegant and comfortable to use.

I'm pretty sure there are other points I'm missing, but that's the first things that I'd check before digging further.

HTH


body:
Use a timer and ISR (interrupt service routine) to make timing more accurate.

Take a look at my [1ms timed interrupt Proof of Concept](http://blog.linformatronics.nl/213/electronics/timed-1-millisecond-interrupt-routine-for-arduino). The idea is to have a reasonably accurate 1ms 'heartbeat' in the system that can be used to trigger other events. In the PoC it is used to blink an LED at ½Hz, but having access to the new variables `millisecondCounter` and `secondCounter` enables you to trigger events in the main loop at arbitrary (but accurately timed) moments.


body:
Your code includes the duration of the output in subsequent measurements. Thus depending on the length of the output you will measure different times. This can be fixed by formating to fixed length output.

The next issue is that the UNO has a very poor timebase. Have a look here for a [comparison of different Arduino types vs. the DCF77 time reference.][1]

Conclusion: if you need precise timing either get an Arduino with crystal or go for an RTC. I can highly recommend DS3231 / DS3232 RTCs since these usually achieve 2 ppm accuracy out of the box.

  [1]: http://blog.blinkenlight.net/experiments/dcf77/dcf77-scope/


message:
XBee shield communication

I need to communicate between two Arduinos using XBee. I am new to XBee and hardware. The two Arduino Unos need to send a message (number) to each other and light an LED or play a sound, when they come close within a 10 meter distance.

So my doubt is which XBee shield and XBee module I need to purchase. I read about XBee series 2, XB24 etc.

body:
The "XBee" brand has two major types. Series 1 are the original ones, and are often NOT referred to by their series number. Series 2 are the newer mesh network brethren.

Most XBee's and their clones are pin compatible (there is even a Bluetooth replacement 'Bee), thus any XBee shield or adapter can be used for either series.

The difference is largely in their communication protocols. The Series 2 allow more robust mesh networking options. But for a beginner - the original (S1) provide simpler out-of-the-box networking.

There are retail packages available that include a pair of S1 XBees, an Arduino compatible breakout board, and a USB adapter to program them. This allows you to get "on the air" and setup the XBees quickly. For communication between two arduinos, a pair of shields will make physical connectivity much easier.


body:
Adding to Ron's answer, the Series 1 is a lot easier to use, because you have to flash firmware onto Series 2s and do all kinds of setup. The S1s work out of the box.

Another thing to keep in mind is that Xbees use 3.3v I/O pins, while the Arduino uses 5v. Most Xbee shields have a Logic Level Converter to handle this, but there are some that don't, and those could damage your Xbee.


body:
The only way I can think of accomplishing this without some sort of proximity sensor is to measure the signal strength of the XBees.

From [page 41 of the datasheet][1]:

> **DB (Received Signal Strength) Command**
>
> **AT Command:** ATDB
>
> **Parameter Range [read-only]:**  0x17-0x5C (XBee), 0x24-0x64 (XBee-PRO)
>
> <Diagnostics> DB parameter is used to read the received signal
> strength (in dBm) of the last RF packet received. Reported values are
> accurate between -40 dBm and the RF module's receiver sensitivity.
> Absolute values are reported. For example: 0x58 = -88 dBm (decimal).
> If no packets have been received (since last reset, power cycle or
> sleep event), “0” will be reported.

You can use this as a **rough** estimate of the distance between two sensors. You will have to correlate signal strength to actual distance and obstructions and other factors will cause the reported value to be off.

[How to measure XBee signal strength?][2]

This page has an example using Processing (on the computer): [XBee Signal Strength][3]

  [1]: https://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-Datasheet.pdf
  [2]: http://forum.arduino.cc/index.php?topic=151145.0
  [3]: http://www.makingthingstalk.com/chapter8/22/


message:
Using more than one Ping Ultrasonic Range Finder

I have done various applications with the Ultrasonic [example project](https://github.com/alexmac131/NodeXbeeTank) but it is always using one pinger. I'd like to make a scanner resting on a servo sweep but to reduce sweep time use more than one censor.

the documentation is rather basic [ping sonic](http://www.parallax.com/sites/default/files/downloads/28015-PING-Sensor-Product-Guide-v2.0.pdf) that states the signal 40khz is used.

Down to the question now. Is there a means to tell one pinger to use 40Khz and another say  45Khz.

This would allow me to scan two areas (different directions) per cycle, reducing the time frame to complete area scan by half.

body: I don't think it would be very easy to change the frequency unless Parallax decides to release the firmware for the Ping. It is possible to use two, as long as you use a different data pin for each, but the ultrasonic signals may interfere.


body:
There is no way to change the frequency, however there are other ways of doing what you want to accomplish. I think the best thing to do is stagger the timing of the pings so they don't happen at the same time.

Example code, modified by me:

    #include <Servo.h>
    Servo servo; // create servo object to control a servo

    int pingPins[] = {7,8}; //The pins for the two sensors
    char *pingString[] = {"Ping1", "Ping2"};

    void setup()
    {
      servo.attach(10); // attaches a servo to pin 10
      Serial.begin(9600);
    }

    void loop()
    {
      unsigned long ultrasoundValue;
      for(int i = 0; i < ultraSoundSignalPins.length; i++)
      {
        ultrasoundValue = ping(i);
        Serial.print(pingString[i]);
        Serial.print(": ");
        Serial.print(ultrasoundValue);
        Serial.print("in, ");
        delay(50);
      }
      Serial.println();
      delay(50);
     }

    //Ping function
    unsigned long ping(int i)
    {
      unsigned long echo;

      pinMode(pingPins[i], OUTPUT);         // Switch signalpin to output
      digitalWrite(pingPins[i], LOW);       // Send low pulse
      delayMicroseconds(2);                 // Wait for 2 microseconds
      digitalWrite(pingPins[i], HIGH);      // Send high pulse
      delayMicroseconds(5);                 // Wait for 5 microseconds
      digitalWrite(pingPins[i], LOW);       // Holdoff
      pinMode(pingPins[i], INPUT);          // Switch signalpin to input
      digitalWrite(pingPins[i], HIGH);      // Turn on pullup resistor
      echo = pulseIn(pingPins[i], HIGH);    //Listen for echo
      return (echo / 58.138) * .39;         //convert to CM then to inches
    }

Sources:

 - https://stackoverflow.com/questions/20273971/arduino-multiple-ultrasonic-sensors-interference
 - http://forum.arduino.cc/index.php?topic=17898.0


body:
The Ping))) sensor uses a crystal for timing.
Some of the cheap knock-offs actually use a MAX3232 chip (which is an RS232 serial port/usart) to detect the return pulse, just for the carrier detection. If the parallax is similar, these have a fairly wide range of frequencies they work at, since you never know the baud rate to expect, from 9600 up to 1mhz, although they are deliberately not very fussy about accidentally picking up nearby frequencies.
Since there's probably some other logic on the other chips, and everything is probably run off the one crystal, I'd recommend going to lower frequencies, otherwise you're overclocking.
Also, make sure to send a longer trigger pulse because all the logic will be slower.
From the picture, it looks like a 16MHz crystal, which must be divided down to the 40KHz.
So solder in a 14MHz, and an 11MHz, lengthen the 5 uS trigger pulse accordingly, and you should be good to go.

As an aside, you might also consider scanning further apart. If it's taking you 30 seconds, you're probably checking every degree; maybe try every 15 or 30 degrees (just make sure to give the servo time to move)


message:
How do I manipulate a large number of moving platforms?

I am trying to build a device that will allow me to control at least a couple hundred raising platforms. The goal of this is to create a real time editor for board games (*Dungeons and Dragons*).

Ideally:

 - All the platforms would move simultaneously
 - The platforms would be transparent to allow us to place LEDs inside them to color the platform so we can make colors like blue for water and brown for dirt.

In our current setup, we use some acrylic prisms that are 1 inch x 1 inch x 6 inch (width, length, height). We wanted to use a CNC motor like system to move something around and move a platform. Obviously, this can only raise/lower one item at a time. We calculated (on paper) quite a long update time (calculated approximately 1 sec per platform) to raise/lower a platform. A CNC linear drive type system is the only solution we found that had a reasonable cost/quality (a CNC motor for every platform also raised the power consumption very high). After a few weeks of looking around, planning and throwing stupid ideas away, we found [this](http://www.youtube.com/watch?v=lvtfD_rJ2hE).

Clearly, it's way better then our idea but I have no idea how they did this. They have 900 platforms and they all work simultaneously. We also don't need real time interaction. Loading from computer and staying static until we change it is good (though water movement would be really nice).

What would you guys recommend to raise simultaneously a thousand small platforms?
****
After looking at this [document](http://tmg-trackr.media.mit.edu:8020/SuperContainer/RawData/Papers/527-inFORM Dynamic Physical Affordances/Published/PDF) that the devs made, and doing a bit more research I found that the device they used to move the platforms cost approxomently $30; I don't think I need to say this, but I don't have $27,000.

Key difference between their implementation and our goal:

 - No real-time interaction with the table. Controlled by an Arduino is fine.
 - Size of the platforms will be closer to 1 inch^2
 - All sides of the platform should be light up, but I believe this is mostly a question of choosing the right material

body:
In terms of cost, perhaps it would be best to build a 4x4 prototype.

My first thought was to use inexpensive servos with a flexible rod inside a sheath, perhaps a wire, like a bicycle brake/gear.  The amount of movement could then be governed by the size of the armature on an inexpensive servo.

Servos will position themselves after being given the command, so there's no need to wait and do them one-by-one.  Fire off the command, then use some sort of multiplexed output like multiple 74HC595 shift registers to connect to the next one.

If the tiles were spring loaded, such that they returned to the topmost position by themselves, only a simple pull-string is needed to adjust the tile height.  Even a very light filament (like fishing line) would be strong enough for the pull.  This would allow the servos to be positioned even some metres away from the table.


message:
Attiny84 and 2-Axis Joystick

I have a [Parallax 27800 2-Axis Joystick][1] wired up to a [AVR 14 Pin 20MHz 8K 12A/D - ATtiny84][2]. The joy stick sends out a x y analog signal. I have programmed the Attiny84 to read the signals and set one of the attiny84 pins (high or low) depending on the direction of the joystick. In this example, each pin is wired up to a LED. The problem I am having is there is about a 1 second delay for the LED to light. The Attiny84 has a built in 8MHz clock. Would connecting an external 20MHz crystal fix this issue?

  [1]: http://www.radioshack.com/product/index.jsp?productId=12345958
  [2]: https://www.sparkfun.com/products/11232

    int UD = 0;
    int LR = 0;

    int DWN = 0;
    int UP = 1;
    int LEFT = 4;
    int RT = 5;

    int LRMID = 0;
    int UPMID = 0;
    void setup(){

      pinMode(DWN, OUTPUT);
      pinMode(UP, OUTPUT);
      pinMode(LEFT, OUTPUT);
      pinMode(RT, OUTPUT);

      digitalWrite(DWN, LOW);
      digitalWrite(UP, LOW);
      digitalWrite(LEFT, LOW);
      digitalWrite(RT, LOW);

      //calabrate center
      LRMID = analogRead(3);
      UPMID = analogRead(2);
    }

    void loop(){

      UD = analogRead(2);
      LR = analogRead(3);
      // UP-DOWN
      if(UD < UPMID - 5){
       digitalWrite(DWN, HIGH);
      }else{
       digitalWrite(DWN, LOW);
      }

      if(UD > UPMID + 5){
       digitalWrite(UP, HIGH);
      }else{
       digitalWrite(UP, LOW);
      }
      // LEFT-RIGHT
      if(LR < LRMID-5){
       digitalWrite(LEFT, HIGH);
      }else{
       digitalWrite(LEFT, LOW);
      }

      if(LR > LRMID +5){
       digitalWrite(RT, HIGH);
      }else{
       digitalWrite(RT, LOW);
      }

      delay(100);

    }

body:
- Are you absolutely sure your AVR is running at 8MHz, because default I believe it is scaling the 8MHz internal RC-oscillator down to 1MHz system clock. Change your F_CPU macro to 1MHz to see what happens.

<!--
- If the 8MHz (or 1MHz for that matter) clock is really the issue (which I doubt), then you can first try to set the fuses to use the internal 16MHz clock. Cheaper solution than adding an external clock circuit.
-->


body:
Several AVR devices including ATtiny 84, have a clock prescaler that can be used to lower the core frequency.

The divider can be controlled two ways.

The first way is the **CKDIV8** fuse that controls the default loaded value to CLKPR (Clock prescale register) to either

- **fuse disabled:**  Clock Division Factor 1 (clk/1)
- **fuse enabled:** Clock Division Factor 8 (clk/8)

The fuse is enabled by default and applies the clk/8 setting, it can be changed with a programmer.

The second way is by changing the prescaler value during runtime. All you need to do is to include the following header

    #include <avr/power.h>

and call one of following functions with the appropriate value you want to use

       clock_prescale_set(clock_div_1);    // Clock Division Factor 1
       clock_prescale_set(clock_div_2);    // Clock Division Factor 2
       clock_prescale_set(clock_div_4);    // Clock Division Factor 4
       clock_prescale_set(clock_div_8);    // Clock Division Factor 8
       clock_prescale_set(clock_div_16);   // Clock Division Factor 16
       clock_prescale_set(clock_div_32);   // Clock Division Factor 32
       clock_prescale_set(clock_div_64);   // Clock Division Factor 64
       clock_prescale_set(lock_div_128);   // Clock Division Factor 128
       clock_prescale_set(clock_div_256);  // Clock Division Factor 256

[power.h manual](http://www.nongnu.org/avr-libc/user-manual/group__avr__power.html)

Note that the above functions can be applied at any part of the program, for example you can lower the cpu frequency to reserve battery and then set it higher again for intensive tasks. Just be aware that all peripheral will work with the divided clock too so PWM, timers, SPI, UART etc will all be affected.

If the problem you are facing is caused by the clock divider being in the /8 setting then you can change it at runtime.

Add the header at the start of the sketch

    #include <avr/power.h>

And then set the prescaler value to 1 at the start of setup()

    void setup() {
                   clock_prescale_set(clock_div_1);  // set the clock prescaler to /1
    }


body:
While @alexan_e’s suggestion fixed your practical problem, I would argue that it did not address your root cause, which is that whatever board setting you’re working from in boards.txt assumes a clock rate of 8MHz, while in reality your fuses are set to boot the microcontroller at 1MHz. This caused your delay(100) to take 800ms, and was the entire reason for the slowdown.

Instead of fixing this at runtime, as aleman_e suggested, it seems more natural to me to bring your fuse settings into alignment with your compiler settings, using the “burn boot loader” Arduino command (which on Attinys generally does NOT burn a boot loader, but only sets the fuses to be in sync with the compiler settings).

If your application is not going to become much more complex, running at 1MHz might be a more efficient choice than running at 8MHz.


message:
Bootup on lower power not functioning

I have a custom Arduino ATMega328 board that generally runs at 5V @ 8MHz (using the Arduino Pro 3.3V 8MHz profile and bootloader). The main reason I'm using this setup is so that I can put the board to sleep when main power is disconnected and it starts being run off of battery power (3V from a coin cell). The 5V and 3V sources are diode OR'ed together and the 5V input is tied to INT0. In code, when it detects that INT0 has fallen low, it initializes sleep mode and everything powers down with the exception of the watchdog timer that keeps a 1Hz cycle to keep an internal count and check it the chip should be woken back up. This works *beautifully* when 5V power is applied first, then the battery is inserted, *then* 5V is disconnected. It goes to sleep and when 5V is brought back it wakes up and I can see it hasn't lost count.

However, the problem comes when 3V is applied *first*. I'm honestly not sure if it's even booting. But what it is supposed to do is boot, check if INT0 (Digital 2) is low and, if so, go right to sleep. By watching the current draw I see that it powers up to a few mA for a couple seconds, then drops to about 0.3mA (still higher than it should be in sleep mode). But when I re-apply 5V, *nothing*. The power draw goes back up but it is unresponsive (over FTDI serial).

Is there maybe something I'm missing that it can't be booted on 3V... in theory it should run just fine.

**Update:** I dropped an LED onto D13 and tried the blink sketch. Works fine when starting from 3V or 5V. However, when I run my firmware and start it from 3V, the LED just starts flashing wildly. I have no idea what's causing it since I never even setup D13 as anything in my code. But it makes me thing it's something to do with the bootloader...

body:
I think the problem is with your bootloader, but not in the way you think.

When an Arduino starts up, a bootloader profiting several tasks, such as looking for a serial host or loading program data from flash is going to take a lot more energy than a sleeping Arduino.

I think the reason why your Arduino will not start is because the bootloader requires an accurate clock source, but applying 3v to it will mess up that clock and it will perhaps crash or wait for 3.3v to be applied for a stable source.

Looking at the datasheet:

![copyright ATMEL][1]

We see that current draw while waking up (running the bootloader) is probably going to be around 2mA, while sleeping current is about *0.8 microamps*. This could certainly lead to a blackout on startup without the proper current.

Perhaps you should only turn it on with 5v power, or maybe you need a higher current, higher voltage battery.

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


body:
Exactly what is happening and why cannot be determined based on the amount of info provided. However, I see at least one potential problem which would at least partially explain the symptoms described.

You said that you are using diodes to select the voltage supply, and one supply is a 3V battery. If you are using standard diodes that drop ~0.6V then the supply voltage to the MCU is only ~2.4V. If you are using Schottky diodes with a voltage drop between 0.15-0.45, the supply voltage is potentially as low as 2.5V. You have the BOD voltage set to 2.7 volts, so in theory the MCU will never boot with the battery.

As for why you can start it at 5v, drop to 3v, and bring it back up again- I'm not sure. You could be disabling the BOD in code...maybe… Not sure why it works, but it's likely not guaranteed to work.

I setup a diode switch circuit with 5v and 3.3v to see what it looks like on my oscilloscope when the voltages switch. When at 3.3v switching up to 5v, the voltage oscillates quite a bit initially. This may potentially cause some problems when the MCU tries to come out of sleep. Putting a cap between VCC and GND smoothed the signal very nicely. When switching from 5v to 3.3v, there really wasn't any oscillating, just a clean drop.

From this information, it seems that you should lower the BOD threshold or turn off the BOD, and put a decoupling cap between VCC and GND. You probably also should make sure you have a pull-down resistor on INT0, and read the MCU datasheet sections explaining the various sleep modes all the considerations for sleeping and waking – it’s pretty involved. Cheers


body: So... turned out what was happening was all in code. Turns out that I was initializing an interrupt on INT0, when it was low, at the very beginning of my code. Problem was that when it started up on 3V backup power, INT0 was always low because INT0 is tied to the 5V line (it's how it knows to go to sleep). Because INT0 was low and the interrupt was triggering on low it was causing a constant interrupt to occur, never giving the rest of the program any time to run. Switched to enabling that interrupt only once I've entered full waking mode and it works fine now.


message:
How to implement multiple LED modes in a sketch with potentiometers?

My hardware is 4 potentiometers connected to Arduino Analog 0-3, the output is an RGB led driver connected to Digital outputs 9,10,11. The output channels provide access to PWM control of those pins. So idea is the color and intensity can be controlled by the Arduino. I wrote a simple Sketch that reads the potentiometers and then outputs PWM to the RGB driver circuitry. This works great! So the hardware is working! Now comes the last potentiometer...

I want to make the last potentiometer a "mode select" control. It would function like this: If the last potentiometer (Pot4) is turned down all the way, then all lights are off. If the level is turned up a little, the Arduino then controls the RGB channels via Pots 1, 2 & 3. If Pot4 is turned up to just past halfway, the sketch enters a "strobe flash pattern" pulsing all channels on and off. And if the mode control Pot4 is turned up all the way, Arduino turns on all RGB channels.

How do I implement? Mode selection via a potentiometer?

body: It would be relatively simple to do a threshold test on analogRead() to switch modes *(e.g. if the value is above 512 (analogRead() gives values between 0-1023)* then you switch modes (probably with a boolean variable that you can then use to decide whether to strobe the LEDs).


body:
Since you already know how to hook up a pot and read it's value, it's quite simple. You already have it hooked up in a voltage divider configuration and are getting a 10 bit (0-1023) value using [`analogRead()`][1], you just need to decide what to do with it.

Assume `potVal` has the value of the pot.;

    if (potVal < 256) {
        // Pot is one quarter turn or less
    } else if (potVal < 512) {
        // Pot is between 256 and 512, so its more than quarter but less than half
    } else if (potVal < 768) {
        // Pot is between half and 3/4ths of the way there
    } else {
        // Pot is greater than 3/4 of it's full range
    }

So I have broken it down into four quadrants for you, but you can do it however you like.

  [1]: http://arduino.cc/en/Reference/analogRead


message:
How has Arduino been used in the classroom?

I remember seeing [Primo](http://techcrunch.com/2013/11/24/primo/), this robot that is based on Arduino and serves to teach kids to program. My interest in the platform comes from there, but it is always nice to learn about other cool applications.

What other applications are there that utilise Arduino for K-12 education?

body:
I've used [Sparki][1] from Arcbotics as a robotics platform. It's uses Arduino Sketch to program and a modified Arduino IDE.

Sensors for line following , edge detection, distance and light level sensing are built in. Also the creators are focused on education so the material and projects are teaching oriented.

The Community seems pretty active and engaged too so the material should build over time.

  [1]: http://arcbotics.com/products/sparki/start


body:
We have been using Arduino's to teach basic microcontroller concepts in classes focused on environmental monitoring & instrumentation, rather than just electronics:

[An Arduino UNO based Datalogger for the Classroom](http://edwardmallon.wordpress.com/2015/12/22/arduino-uno-based-data-logger-with-no-soldering/)

The IDE abstracts away enough of the low level details that you can get students into programming quickly, while still exposing them to enough of hardware side of things. I am not sure what other platform would let us take true beginners so far, so quickly.


message:
Digital RGB LED animation

I've been trying to get colours fade into each other for a project I'm working on.
I have achieved this with the rainbow effect that some from Adafruit's example code, however I want to be able to choose the colours (eg. dark blue into light blue).

I've got the colours changing and fading, however the fade turns off all the LEDs and starts to increase the brightness of the new colour. I need the colours to blend rather than fade out and increase in brightness.

Is anyone able to point me in the right direction?

    #include "LPD8806.h"
    #include "SPI.h"
    #define stripSize 64

    int nLEDs = 160;

    int dataPin  = 2;
    int clockPin = 3;

    // First parameter is the number of LEDs in the strand.  The LED strips
    // are 32 LEDs per meter but you can extend or cut the strip.  Next two
    // parameters are SPI data and clock pins:
    LPD8806 strip = LPD8806(64, dataPin, clockPin);

    // You can optionally use hardware SPI for faster writes, just leave out
    // the data and clock pin parameters.  But this does limit use to very
    // specific pins on the Arduino.  For "classic" Arduinos (Uno, Duemilanove,
    // etc.), data = pin 11, clock = pin 13.  For Arduino Mega, data = pin 51,
    // clock = pin 52.  For 32u4 Breakout Board+ and Teensy, data = pin B2,
    // clock = pin B1.  For Leonardo, this can ONLY be done on the ICSP pins.
    //LPD8806 strip = LPD8806(nLEDs);

    void setup() {
      // Start up the LED strip
      strip.begin();

      // Update the strip, to start they are all 'off'
      strip.show();
    }

    void loop() {
      //turnAllOn(strip.Color(30,30,30),4000);
      fade(0, 127, 0, 100); //red, green, blue, delay - fade up all pixels one color
      //turnAllOn(strip.Color(30,100,30),4000);
      fade(50, 127, 02,100); //red, green, blue, delay - fade up all pixels one color
      //turnAllOn(strip.Color(100,30,100),4000);
      fade(50, 127, 50, 100); //red, green, blue, delay - fade up all pixels one color
    }

    void fade(uint32_t r, uint32_t g, uint32_t b, uint32_t wait) {
      int i, j;
      for (j=0; j < 384; j++) {
        for (i=0; i < strip.numPixels(); i++) {
          strip.setPixelColor(i, strip.Color((r*j)/1000,(g*j)/1000,(b*j)/1000));
        }
      strip.show();
      }
      delay(wait);
    }

    void turnAllOn(uint32_t c, uint32_t wait) {
      int i;
      for (i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, c);  // turn all pixels on
      }
      strip.show();   // write all the pixels out
      delay(wait);
    }

    uint32_t Wheel(uint16_t WheelPos)
    {
      byte r, g, b;
      switch(WheelPos / 128)
      {
        case 0:
          r = 127 - WheelPos % 128;   //Red down
          g = WheelPos % 128;      // Green up
          b = 0;                  //blue off
          break;
        case 1:
          g = 127 - WheelPos % 128;  //green down
          b = WheelPos % 128;      //blue up
          r = 0;                  //red off
          break;
        case 2:
          b = 127 - WheelPos % 128;  //blue down
          r = WheelPos % 128;      //red up
          g = 0;                  //green off
          break;
      }
      return(strip.Color(r,g,b));
    }

body:
Currently, your fade function is starting at 0 and effectively interpolating up to the desired colour. To fade between colours, you would need the sketch to remember the previous colour it used, and start fading from that instead of from 0.

The approach I'd use is to start by calculating how much each component needs to change by on each step. For example, if you want to fade from 100 to 200 across 50 steps, then it needs to change by +2 on every step. If you wanted to do the same in reverse (200 to 100) then it would have to change by -2.

One of the problems is that each component will probably be changing by a different amount (red might go from 0 to 200, but blue might only go from 50 to 70). If you're using integers all the time then it could result in some uneven transitions, so I'd recommend using floating point instead. It's technically slower (less efficient), but probably not enough to worry about.

This is how I'd probably write it:

    void fade(uint8_t oldR, uint8_t oldG, uint8_t oldB, uint8_t newR, uint8_t newG, uint8_t newB, uint32_t numSteps, uint32_t waitPerStep)
    {
        // Guard against division by zero
        if (numSteps == 0) numSteps = 1;

        // Calculate how how much each colour needs to change on each step
        const float
            stepR = (newR - oldR) / (float)numSteps,
            stepG = (newG - oldG) / (float)numSteps,
            stepB = (newB - oldB) / (float)numSteps;

        // These values will store our colours on the way along
        float r = oldR, g = oldG, b = oldB;
        uint8_t byteR = oldR, byteG = oldG, byteB = oldB;

        // Go through each fade step
        const uint16_t numPixels = strip.numPixels();
        for (uint32_t step = 0; step < numSteps; ++step) {
            // Move one step towards the target colour
            r += stepR;
            g += stepG;
            b += stepB;

            // Round the colours to integers here so we don't have to do it repeatedly in the loop below
            byteR = (uint8_t)(r + 0.5f);
            byteG = (uint8_t)(g + 0.5f);
            byteB = (uint8_t)(b + 0.5f);

            // Apply the colour to each pixel
            for (uint16_t pixel = 0; pixel < numPixels; ++pixel) {
                strip.setPixelColor(pixel, byteR, byteG, byteB);
            }

            strip.show();
            delay(waitPerStep);
        }
    }

As you can see, you pass it the old colour (which you're fading *from*) and the new colour (which you're fading *to*). As I mentioned above, this means your sketch has to remember which colour it previously used, as I don't think the library provides a way to read the current colour back.

I've included some optimisations in there to make it run faster. There's more you could do to optimise it even further, if necessary.

To use this, you'd do something like this:

    // Fade from black to red and pause briefly
    fade(0, 0, 0,  255, 0, 0,  100, 10);
    delay(500);

    // Fade from red to purple and pause briefly
    fade(255, 0, 0,   255, 0, 255,  100, 10);
    delay(500);

    // Fade from purple to green and pause briefly
    fade(255, 0, 255,  0, 255, 0,  100, 10);
    delay(500);

I've made a couple of other changes compared to your own fade function function. First of all, I've made it so that you can set the number of steps to fade over. This can be quite useful because bigger colour changes will need more steps to look smooth.

I've also modified the `wait` parameter. In your code, you put the delay after the entire fade was complete, which seems like an odd approach. It makes more sense to allow a small delay between each step of the fade, so you can control how fast it goes.

In my example above, you can see the `100, 10` parameters at the end of each call to `fade()`. That means it will divide the colour change into 100 steps, with a delay of 10ms between each step. The result is that each fade will take roughly 1 second (not counting the time taken to actually update the LED strip).


message:
Arduino program only works when run as root

Uploading simple sketches seems to work when I run the Arduino program as root (`sudo`). I would like to run it as a regular user. Has anyone faced the same problem before and fixed it?

Here is what I obtained from `lsusb`:

    $ lsusb
    Bus 002 Device 022: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)

And the Arduino program identifies it as `/dev/ttyACM0`. Here are its permissions:

    $ ls -l /dev/ttyACM0
    crw-rw---T 1 root dialout 166, 0 Mar 14 22:03 /dev/ttyACM0

Here is the output from `id`

    groups=1000(abhiram),20(dialout),24(cdrom),25(floppy),29(audio),
    30(dip),44(video),46(plugdev),105(scanner),110(bluetooth),112(netdev)

When I upload an sketch from the examples, as a regular user, I encounter this error:

    avrdude:stk500_recv(): programmer not responding

Any suggestions are welcome.

body:
The easiest solution is to add yourself to the `dialout` group.

First make a note of the output from `id`. Save it in file (not in `/tmp` as that gets cleaned out on a reboot). If you look at the output, you'll notice that your user is signed up for several groups and those groups represent extra privileges on the system. By default your Arduino is assigned to the group `dialout` because it registers as a serial interface and in the old days these were often used to ... dial out, using a modem.

To add yourself to the `dialout` group, issue the following command:

    sudo usermod -a -G dialout $USER

Don't forget the `-a` flag (for appending groups rather than replacing) or you will have entirely different problems. This is the reason for making a copy of the `id` output to a file, so in case you do mess up at least you know what your user was configured like before.

Then log out and log in and it should work from that point.

Optionally you can double check the output for `id` against the output you saved before.


body:
The oft-repeated advice to "just do `sudo usermod -aG dialout <username>` never worked for me, and I finally figured out why. On my machine, `/dev/ttyUSB0` is of the group `serial` and not `dialout`, so adding my username to `dialout` did nothing.

    # ls -l
    # crw-rw---- 1 root serial 188, 0 Mar 31 20:52 /dev/ttyUSB0
                        ^^^^^^ (group-name)

Finally: `sudo usermod -aG <group-name> <username>` fixed it for me.

Embarrassingly, this is also explicitly mentioned [here](http://playground.arduino.cc/Linux/All#.UzoSq1VX-uZ) under "SET THE PERMISSION". Sigh.


body:
This happens to me.
In my case, I had upgraded the version of arduino and seems the preferences file was causing the problem.
Just delete ~/.arduino/preferences.txt file (with Arduino IDE closed).

Steps:

1. Close Arduino IDE
2. execute this:

    rm ~/.arduino/preferences.txt

3. Launch Arduino IDE

This worked for me, hope it works for someone else.
I am using Linux Mint 17 and I upgraded from Arduino 1.05 to Arduino 1.06 by extracting the Arduino IDE, I am not using the one in the repo.
(Of course, after adding your user to the corresponding group as mentioned by others, but if that wont help you try this)


message:
Arduino error message that I don't understand

I downloaded Arduino code from this: https://github.com/BabyWrassler/MissionControl/ Github, and got the  error message below.

It is designed to work with a Raspberry Pi, and I installed the two Adafruit libraries.  I also have not hooked it up to either the Pi, or the two Adafruit devices, but that is partly because I cannot get it to run without the error message.

Update:
Here is what was highlighted:
`Adafruit_LEDBackpack matrixA = Adafruit_LEDBackpack();`
The orange bar says:
    Variable or field ‘matrixOff‘ declared void
I cannot tell what of the following was from before, but here is the entire console log:

        mcDesk.ino:2:53: error: Adafruit_LEDBackpack.h: No such file or directory
        mcDesk.ino:3:45: error: Adafruit_GFX.h: No such file or directory
        mcDesk:11: error: variable or field 'matrixOff' declared void
        mcDesk:11: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:11: error: expected primary-expression before 'buffer'
        mcDesk:12: error: variable or field 'ledOn' declared void
        mcDesk:12: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:12: error: expected primary-expression before 'buffer'
        mcDesk:12: error: expected primary-expression before 'cat'
        mcDesk:12: error: expected primary-expression before 'an'
        mcDesk:13: error: variable or field 'ledOff' declared void
        mcDesk:13: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:13: error: expected primary-expression before 'buffer'
        mcDesk:13: error: expected primary-expression before 'cat'
        mcDesk:13: error: expected primary-expression before 'an'
        mcDesk:14: error: variable or field 'dispMat' declared void
        mcDesk:14: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:14: error: expected primary-expression before 'buffer'
        mcDesk:17: error: variable or field 'threeDigitDisp' declared void
        mcDesk:17: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:17: error: expected primary-expression before 'buffer'
        mcDesk:17: error: expected primary-expression before 'cats'
        mcDesk:17: error: expected primary-expression before 'ans'
        mcDesk:17: error: expected primary-expression before 'number'
        mcDesk:18: error: variable or field 'digitDisp' declared void
        mcDesk:18: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:18: error: expected primary-expression before 'buffer'
        mcDesk:18: error: expected primary-expression before 'pos'
        mcDesk:18: error: expected primary-expression before 'cat'
        mcDesk:18: error: expected primary-expression before 'an'
        mcDesk:18: error: expected primary-expression before 'num'
        mcDesk:23: error: variable or field 'switchBars' declared void
        mcDesk:23: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:23: error: expected primary-expression before 'buffer'
        mcDesk:23: error: expected primary-expression before 'grphCats'
        mcDesk:23: error: expected primary-expression before 'grphAns'
        mcDesk:23: error: expected primary-expression before 'cmnd'
        mcDesk:23: error: expected primary-expression before 'offset'
        mcDesk:24: error: variable or field 'barDisp' declared void
        mcDesk:24: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:24: error: expected primary-expression before 'buffer'
        mcDesk:24: error: expected primary-expression before 'grphCats'
        mcDesk:24: error: expected primary-expression before 'grphAns'
        mcDesk:24: error: expected primary-expression before 'pos'
        mcDesk:24: error: expected primary-expression before 'offset'
        mcDesk:25: error: variable or field 'cBarDisp' declared void
        mcDesk:25: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:25: error: expected primary-expression before 'buffer'
        mcDesk:25: error: expected primary-expression before 'grphCats'
        mcDesk:25: error: expected primary-expression before 'grphAns'
        mcDesk:25: error: expected primary-expression before 'pos'
        mcDesk:25: error: expected primary-expression before 'offset'
        mcDesk:11: error: 'Adafruit_LEDBackpack' does not name a type
        mcDesk:12: error: 'Adafruit_LEDBackpack' does not name a type
        mcDesk:13: error: 'Adafruit_LEDBackpack' does not name a type
        mcDesk:14: error: 'Adafruit_LEDBackpack' does not name a type
        mcDesk:15: error: 'Adafruit_LEDBackpack' does not name a type
        mcDesk.ino: In function 'void decodeCommand()':
        mcDesk:193: error: 'matrixE' was not declared in this scope
        mcDesk:193: error: 'ledOn' was not declared in this scope
        mcDesk:199: error: 'matrixE' was not declared in this scope
        mcDesk:199: error: 'ledOff' was not declared in this scope
        mcDesk:204: error: 'matrixC' was not declared in this scope
        mcDesk:204: error: 'cBarDisp' was not declared in this scope
        mcDesk.ino: In function 'void allMatrixOff()':
        mcDesk:213: error: 'matrixA' was not declared in this scope
        mcDesk:213: error: 'matrixOff' was not declared in this scope
        mcDesk:214: error: 'matrixB' was not declared in this scope
        mcDesk:215: error: 'matrixC' was not declared in this scope
        mcDesk:216: error: 'matrixD' was not declared in this scope
        mcDesk:217: error: 'matrixE' was not declared in this scope
        mcDesk.ino: At global scope:
        mcDesk:220: error: variable or field 'matrixOff' declared void
        mcDesk:220: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:220: error: expected primary-expression before 'buffer'

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

body:
It seems to me that those Adafruit libraries were not correctly installed on your PC or your sketch.

In addition to downloading and installing the library onto the Arduino library directory (on Windows, that's normally `C:\Users\UserName\Documents\Arduino\libraries`), when you want to use that library with Arduino IDE, you must add the library for your sketch with the menu command "**Sketch -> Import Library...**"

**Important note**: it seems just adding `#include "library.h"` does not work with Arduino IDE, you absolutely need to use the menu.


message:
Reading multiple bytes from *software* serial

I have Arduino Leonardo board operating lots of AC relays in quite noisy environment. USB works unstable, which sometimes causes the board to hang, so I decided to use secondary serial connection as "debug console":

      Serial1.begin(115200);
      .....
      .....
      if (Serial1.available()) {
        char ch = Serial1.read();
        if ( isalnum(ch) ) {
          switch (ch) {
            case 'M': {
              turnOn_pin_Motor();
              break;
            }
            case 'm': {
              turnOff_pin_Motor();
              break;
            }
            .......

My problem is that noise affects Serial1 the same way it messes USB (but at least it doesn't cause it to freeze). I'd like to use some sort of error checking to prevent Leonardo from acting on "phantom" commands. I could, for example, prefix each keyboard command my Arduino should receive with special symbol, maybe "!".

So I must be reading one char, checking if it is "!" and reading second character.

Unfortunately, I can't modify my code so it would use 2-character buffer and shift its contents as characters arrive, without locking the main loop while waiting for the next char. Any hints on what should I do in this case?

body:
Serial1 on the Arduino Leonardo is hardware serial, not software.

There are several ways to read in multiple bytes from Serial.

Instead of detecting `Serial.available()` (i.e. non-zero), change it to `Serial.available() >= 2`

    if (Serial.available() >= 2) {
      for (int i=0; i<2; i++) {
        buffer[i] = Serial.read();
      }
    }

Or you can leave it as it is, and read into the buffer one at a time.

    static int bufferIndex;

    if (Serial.available())
    {
     buffer[bufferIndex++] = Serial.read()
    }

You'll need to detect the contents of the buffer in another `if` statement, and also deal with the bounds of the index.

Honestly though, noise is your issue here - this is an example of an [XY problem][1]. There's nothing inherent in using a microcontroller with relays that should mean that serial won't work.

  [1]: https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem


message:
Is my Arduino destroyed or are the pins destroyed?

I made a working model of Bluetooth light control with arduino and Bluetooth. Everything worked fine and then after some time I connected the circuit again it didn't work and the pins 7,10,11,12 aren't working . I was using a Bluetooth shield but I tried the simple LED flash program and even that's not working .

Please suggest any good way of making it working again or at least explain what happened with it.

body:
Try running the blink LED, on a different terminals.
If the LED is working properly, then most likely the pins are destroyed.
Why are they destroyed?
Most likely, you've withdrawn more current than the pins can actually provide.

According to the datasheet of the Arduino uno, the IO pins can handle up to 40mA.

![enter image description here][1]

The only possible way to solve this problem is to change the IC (Atmega328) by another one. It's not guranteed that it will work, but the microcontroller is reletively cheap.

The definite answer can not be determined unless you showed us a schematic of your connection.

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