body: [The Arduino Uno Page](http://arduino.cc/en/Main/arduinoBoardUno) doesn't say the temperatures that it can operate in. I'm thinking about placing it outdoors. How can I make sure my Arduino Uno is safe in weather that can reach -20 to 105 degrees Fahrenheit? (-26 to 40 degrees Celsius).

title: How cold or hot can my Arduino Uno get?

Answers: 5

body:
**It's not that big of deal.** [The ATmega 328p datasheet](http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet.pdf) states this:

> Temperature range: -40 to 85 degrees celsius.

The same goes for the [USB chip on the Uno (ATmega 16u2 for UNO R3)](http://www.atmel.com/Images/7799S.pdf).

That's inside your limits. It probably could go a bit colder than mentioned, but it'll shorten the length of the board a little bit.

However, there are some things that may go wrong:

 - EEPROM might not be stored as long in extreme temperatures. Keep this in mind if you're storing critical data.
 - The voltage regulator may not perform as well in hot conditions
 - The crystal oscillator may not produce exact values. However, I would imagine that a few hertz more or less wouldn't affect a 16 MHz processor. The tolerance is actually a little less than 1%. You may have some issues with serial (baud rate not correct). I would look into any communications like I2C also. (I don't know exactly how the clock line works... it might be fine for I2C.)
 - Resistors/capacitors may not produce the *exact* values. I'd imagine that the tolerance won't be more than 8% on resistors: most resistors are rated at 5% for normal temperatures. It does depend on the manufacturer. Capacitors do have a bigger tolerance, but their main purpose is to "smooth" a signal.
 - Extreme cooling/warming may cause minor expansion problems. (Note: it's fine once in a while, but not on an hourly basis of dropping 30 degrees.)
 - Other components (LCDs, etc.) should be kept in mind also when looking at the viability of keeping it outdoors.

So as long as all the other components not on the board will happily run in the temperatures that you need, you should be fine. Also, as with all engineering, values often have added "padding" built in. (i.e. 5% tolerance is often 3-4%, maximum 12V it can run on 12.5V, etc.)*

*What I mean by that is your Arduino won't explode when it's -41 degrees C. It's not great for it, but most likely you should be fine as long is it isn't a regular occurrence.

body:
For hot temperature, just follow the datasheet.

For low temperature, I remember someone last year trying to [overclock a UNO with liquid nitrogen][1] so I guess you won't ever meet any problems with low temps :-)

In [his blog][2], that person shows that he could run his UNO at 65 MHz by reducing temperature to -196°C.

Of course, the process was more complex than just reducing the temperature and checking what happens: a lot of improvements were performed on the board.

The blog explains very well how various components can react to cryogenic temperatures; the major issues seemed to be capacitors which capacitance **dramatically** reduces under low temperatures.

  [1]: http://blog.arduino.cc/2013/08/29/overclocking-arduino-with-liquid-nitrogen/
  [2]: http://3.14.by/en/read/arduino-liquid-nitrogen-overclocking

body:
Like everyone mentions, as long as you're in the shade, hot temperature probably doesn't matter too much as it's within the limits of the components.

I'm more worried about condensation in the mornings.  Water vapors will condense on electronics just like it does on grass.  You could try electrical epoxy to cover the circuit.  The Arduino doesn't run very hot, so the epoxy doesn't do much in terms of preventing it from cooling down.  But epoxy does keep water vapor condensation from being a problem.

body:
I agree with the advice to read the data sheets, but here is a personal answer to the question.

I installed a Raspberry Pi in an enclosure in which the existing Arduino survived last summer.

Even though they have the same overall temperature limits (except the communications section) it was the Pi that stopped working first.

The good news is that bringing it inside it booted right back up.

The temp/humidity went up to 140 F (like a hot car in Phoenix).

So in the end, the data sheet was right in terms of survival.  But I would suggest a more conservative approach, such as placing them into a white-painted enclosure to minimize the effects of the sun.

After removing the pi, the Arduino woke up like nothing happened, still outside.

These things are very resilient.

body:
If you must place your device outside, I would suggest a diecast box. The main heat generating component is probably the regulator (Think about it - at 12V, the reg drops 7V, where the micro runs on 5V or maybe 3V3). So running the lowest voltage into the arduino is recommended, I think its good to 7V (for a 5V unit). If you can connect a heat pathway from the chip surface to the case, good (Use heavy guage - at least 2mm thick). Take care you do not connect to the reg tab - use mica or thin mylar and heatsink paste (Avoid galvanic interations). Normal finned heatsinks on the outside of the box actually do the job of shedding heat to the atmosphere. This whole thing should be in a slatted wooden white painted container (A stevenson screen) so direct sun (and rain/dew) dont hit the containing box.
This would be a solution for extreme environments.
Remember that any heat build from the board must get to the box internal environment - using trapped air you get a very poor thermal contact. Then it has to get through the box and into the air again.
Dont forget that current sinks you use on the chip generate some (small) heat in the process.


body:
Presumably, one powers an Arduino board with car batteries for long-term operation away from the power grid.

How can this be done, and what are the most (1) economic, and (2) reliable ways to do this? Specifically, do any additional risks to short the board with an extraneous discharge exist?

title: Powering Arduino with car batteries

Answers: 6

body: I'm a big fan of USB car chargers for things like this, or USB buck converter boards that you get from ebay.

body:
Use a switching regulator such as the [LM2596][1]. You can get a ready board from [eBay][2] for about US$1.

![Enter image description here][3]

Just set the output voltage to 5 V and feed the Vcc input of Arduino; this bypasses the onboard regulator.

The benefit is that unlike the linear onboard regulator, a switching regulator is very efficient which means less consumption and less generated heat on the regulator. An additional benefit is that it can withstand a higher input voltage (about 35 V for the specified regulator), just in case the circuit is used in a vehicle that has 24 V batteries.

The regulator has already several protections like for [short circuiting][4], overheating, etc.

  [1]: http://www.ti.com/product/lm2596
  [2]: http://en.wikipedia.org/wiki/EBay
  [3]: https://i.stack.imgur.com/HyLG8.jpg
  [4]: https://en.wikipedia.org/wiki/Short_circuit

body:
There is also the higher-end Akafugu breadboard power supply - takes input from 7V all the way to 35V, but costs 11$ apiece in the bargain.

![enter image description here][1]

[Akafugu][2]

  [1]: https://i.stack.imgur.com/IB0rt.jpg
  [2]: http://store.akafugu.jp/products/30

body:
"Practical Arduino book" has a very interesting circuit for this purpose: http://www.practicalarduino.com/projects/vehicle-telemetry-platform

Here is how I've recreated it:

It uses LM2940CT and huge electrolytic cap - even if supply voltage drops, you'll have about a second to shut down your Arduino gracefully (close files on SD properly, and so on).

"Arduino Cookbook" (2nd ed.) has a chapter with examples on how to reduce Arduino's power consumption to absolute minimum - have a look at it, too.

body:
Two more options - battery pack with convenient pre-made screw holes for Arduino, Raspberry.PI, and Beagle Board:

![Smart Power Base][1]

[Smart Power Base][2]

Kicking it up a notch - using a cordless drill's 18V battery.  The project is meant for R.PI, but it would work just as well on Arduino, as the power supply is USB

![Portable PI Power][3]

[Portable PI Power][4]

  [1]: https://i.stack.imgur.com/T0aHD.jpg
  [2]: http://www.makershed.com/product_p/mkmts01.htm
  [3]: https://i.stack.imgur.com/I9ct9.jpg
  [4]: http://makezine.com/projects/portable-pi-power-raspbery-pi-to-go/

body:
Standard car batteries are 12.6 volts there are 6 2.1V cells.  AGM batteries (i.e. Optima batteries, some interstates, and many other brands make AGM), in my experience with AGM batteries they are around 12.8 volts (I do not know the technical voltage).  Without the car running you do not need to worry about voltage spikes **AS LONG AS THE WIRES TO AND FROM THE BATTERY ARE SHORT**.  When the car is running the serpentine belt turns the alternator which is an AC generator.  The alternator is connected to a rectifier to change it back to DC and the unit has a voltage regulator.  When the car is running the alternator runs the electrical system and charges the battery.  When you connect to the battery while the car is running you are actually connected to the alternator.  When connected to the alternator there is a ton of electrical noise, voltage spikes, etc.

I have always had success connecting straight from the battery to the Arduino through its barrel jack connector, I have not tried any analog read function when the car is running.  On the Arduino website it recommends 7-12V, however the limits (as listed on the Arduino website below the recommended) are 6-20. I have actually experienced problems with lower input voltages.  If you feel uncomfortable just buy a 5 volt regulator and power through the usb.


body:
So am I using an Arduino with a shield to gain some voltage values for an ECG. I am then plotting that data in Python. However whenever I "observe" the serial port, be that through the Arduino serial monitor or in attempting to plot the values of time (using millis()) against ECG (voltage) the values reset, so millis() resets the zero, which is fine, except that some of the older values still show up. Now this is especially a problem in Python because it means the plot is malfunctioning at the start of the script, because it is plotting some of the older values and then after a couple of seconds it resets and the plot looks normal again.

To demonstrate this I have recorded it on video and put it on YouTube, here it is:

https://www.youtube.com/watch?v=dNpUakcRPec

Now initially I thought the problem was with Python or the Pyserial module so I labelled the video as such, but since it occurs in the serial monitor I realised the solution would be in the Arduino sketch. I have tried flushing, didn't work, I have tried even to not start the data till I send a start byte, but this didn't work on Python.

Ideally I could start the Python plotting script and it would skip, or ignore those initial values from the serial port before beginning again.

Here is the Arduino sketch I am using:

    #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, 3);
      Serial.println("");

      delay(50);    // wait for 50 millisecond
    }

title: Arduino serial port reset in Serial monitor & Python

Answers: 3

body:
Take a look at [if(Serial)][1]

That makes the Sketch wait for the serial port before continuing.

    void setup() {
    //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
    ; // wait for serial port to connect.
      }
    }

I have a sneaking suspicion that may only work on the Leonardo.

If so you could try an alternative:

 1. Have Python send something to Arduino after it connects.

 2. Wait until this is received in setup(): if (Serial.available() > 0) {...}

 3. Execute the loop() normally

e.g.

    // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, DEC);
        }

  [1]: http://arduino.cc/en/Serial/IfSerial#.Uxhl8xARfxw

body: The Arduino is designed to reset when a Serial monitor or script connects to it. The best way to mitigate this would be to send the Arduino some kind of "start sending" signal when you connect to the serial port. It would then send the data when your script was ready.

body:
I the answer from @TheDoctor. An alternative is for the client listening on serial port to wait for a "successful reset" signal from the Arduino.

    void setup() {
    //Initialize serial and wait for port to open:
        Serial.begin(9600);
        while (!Serial) {
            ; // wait for serial port to connect.
        }
        Serial.println('reset successful')
    }

There are pros and cons to each solution. In the @TheDoctor solution, it seems like there is an edge cases where the Arduino is already sending when the client connects and you'll get some junk before the reset occurs.


body:
This problem doesn't seen to be very common around the Arduino community.

Basically, what's happening is that as soon as I click the upload button, the Arduino IDE tells me that my Arduino board is not connected. What's strange though is that the python application ino is able to upload my code just fine, so my only guess is that there is something wrong with the IDE itself.

Here's a copy of the error message I am getting at the time of uploading the sketch:

> Binary sketch size: 444 bytes (of a 32,256 byte
> maximum)processing.app.SerialException: Error opening serial port
> '/dev/ttyACM1'.at processing.app.Serial.<init>(Serial.java:178)at
> processing.app.Serial.<init>(Serial.java:77)at
> processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:77)at
> processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:174)at
> processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)at
> processing.app.Sketch.upload(Sketch.java:1671)at
> processing.app.Sketch.exportApplet(Sketch.java:1627)at
> processing.app.Sketch.exportApplet(Sketch.java:1599)at
> processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)at
> java.lang.Thread.run(Thread.java:744)Caused by:
> gnu.io.UnsupportedCommOperationException: Invalid Parameterat
> gnu.io.RXTXPort.setSerialPortParams(RXTXPort.java:213)at
> processing.app.Serial.<init>(Serial.java:163)... 9
> moreprocessing.app.debug.RunnerException: Error opening serial port
> '/dev/ttyACM1'.at
> processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:101)at
> processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:174)at
> processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)at
> processing.app.Sketch.upload(Sketch.java:1671)at
> processing.app.Sketch.exportApplet(Sketch.java:1627)at
> processing.app.Sketch.exportApplet(Sketch.java:1599)at
> processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)at
> java.lang.Thread.run(Thread.java:744)

I am expecting to hear a few questions regarding this issue, so I'll go ahead and answer all the questions I can think of.

> *Is this the first time you trying to connect to the Arduino from this computer?*

No. In fact, I was able to upload the same source code just fine less than two hours ago.

> *Did you try a different USB cord?*

Yes, I did.

> *Can you upload the source code from a different computer?*

Yes, I can.

> *Have you tried removing and reinstalling the IDE?*

Yes, I have.

> *Have you tried a different USB port?*

Yes, I have.

What seems to be the problem here?

title: Arduino disconnecting at upload

Answers: 4

body:
First of all, you must test if the device that you are trying to access, actually exists. The device file may change when you replug the Arduino. The easiest way to accomplish that is to find the device name in the error message, in this case `/dev/ttyACM1`. Then check two things:

1. Does the device file exist in  the `/dev` tree? `ls -l /dev/ttyACM*`
2. Is the Arduino IDE configured to use the correct device? Check under `Tools` => `Serial Port`.

Maybe another application is using the device. When working on Linux, you can verify this with the following commands:

    $ lsof /dev/ttyUSB0
    COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF      NODE NAME
    avrdude 7356   jippie    3u   CHR  188,0      0t0 266450197 /dev/ttyUSB0

or

    € fuser /dev/ttyUSB0
    /dev/ttyUSB0:         7356

Where of course you have to replace `/dev/ttyUSB0` with the device file as mentioned in the error message. In case of this question `/dev/ttyACM1`, but do notice that the number can change when you unplug the board for a moment and then replug it.

In both results, the `7356` is the PID of the process that is locking the device. In my example I was reading flash from the command line, so the output for your specific situation will be different. To identify the process, you can use:

    $ ps -fp 7356
    UID      PID  PPID  C STIME TTY          TIME CMD
    jippie  7698 28116  1 20:34 pts/8    00:00:00 avrdude -patmega1280 -carduino -P/dev/ttyUSB002 -b57600 -D -Uflash:r:/tmp/flash:i

or a more portable command:

    $ ps -ef | grep 7356
    jippie  7698 28116  1 20:34 pts/8    00:00:00 avrdude -patmega1280 -carduino -P/dev/ttyUSB002 -b57600 -D -Uflash:r:/tmp/flash:i

body:
Try setting the baud rate to 9600 in the Serial Monitor. You need a working serial port to open the Serial Monitor. Or go to >File >Preferences> and edit the preferences.txt (must close Arduino IDE before editing) "serial.debug_rate=9600"

I have several Arduino boards and had the exact same issue with the boards that use the Atmel mega8U2 as the USB - serial bridge. The boards with the FTDI USB bridge (SparkFun Red board, Pro mini) did not show the same problem. Setting the baud rate solved my problem.

There is a firmware upgrade for 8U2 that might fix it but I didn't want to risk making bricks. ;-)

body:
I have same problem after set baud rate to 14400.
For fix this I manual set serial.debug_rate=115200 in config file ~/.arduino/preferences.txt

body:
A pretty detailed troubleshooting guide is available at [arduino.cc][1]. Besides the checks already mentioned in the question and the answers, it is recommended to check that `serial.download_rate` is set to `19200` in `~/.arduino/preferences.txt`.

`19200` is the default baud rate used by most [bootloaders](https://www.arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader), so this doesn't apply if you don't use one, or use a modified version.

  [1]: https://www.arduino.cc/en/Guide/Troubleshooting2#toc8


body:
I'm trying to replicate a waveform exactly using external and timing interrupts. I've got an external that's setup as a 0ms reference, TIMER1 which is used to determine on time, and TIMER2, which sets the low period. Unfortunately, I can't get the pin low for 2ms. TIMER2 must have something wrong with it, but I can't find it. Instead of banging my head against the wall, I thought I'd ask you guys. Anyone know the answer?

    //3 is interrupt for Timing
    //4 through 11 are Time dependent receivers
    //3-11 Pins 12-19

    //Current Serial Byte(Letter or Number)
    char incomingByte = 0;
    //Previous Byte in the Serial Chain
    char previousByte = 0;

    //Iterator for Interrupt Values
    volatile unsigned int maincount = 0;

    //Time of High Period or Timer Duration
    volatile unsigned int timerhigh;

    //Output Pin for Timer Waveform
    volatile unsigned int waveout;

    //Time for Timer Delay in milliseconds, default tim
    volatile unsigned int groundtime = 0;

    //Receiver Pins in an Array, except for 3, which serves as 0 source reference
    int pins[9] =
    {
      3,4,5,6,7,8,9,10,11
    };

    void rising()
    {
      // set up Timer 1
      TCCR1A = 0;  // normal mode
      TCCR1B = bit(WGM12) | bit(CS11);  // CTC, scale to clock / 8
      OCR1A = timerhigh;          // time before timer fires
      TIMSK1 = bit (OCIE1A);            // interrupt on Compare A Match
    }

    //Sets Pin Low, then sets up another timer interrupt for the jump back to high
    ISR(TIMER1_COMPA_vect)
    {
     //Brings Pin Low for Keypress
     //Serial.println("We're in Timer 1");
     pinMode(waveout,OUTPUT);
     digitalWrite(waveout, LOW);

     //Stop Timer 1
     TCCR1B = 0;                      // stop timer
     TIMSK1 = 0;                      // cancel timer interrupt

     //Disables Interrupts Before Messing
     cli();
     // set up Timer 2
     TCCR2A = 0;  // normal mode
     TCCR2B = 0;
     //  TCCR2A = bit(WGM21) | bit(CS21);  // CTC, scale to clock / 8
     TCCR2A = (1 << WGM21); //Enables CTC for timer
     TCCR2B = (1 << CS21); //Sets 8 bit prescaler
     OCR2A = groundtime;          // time before timer fires
     TIMSK2 = (1 << OCIE2A);

     //Cancel Rising Interrupt on D3
     EIFR = bit (INTF1);
     //Reenables interrupts
     sei();
    }

    //Timer Interrupt for Low Period
    ISR(TIMER2_COMPA_vect)
    {
    //Serial.println("WE'RE IN TIMER2");
    //Brings Output pin high
    digitalWrite(waveout, HIGH);

    //Stop Timer 2
    TCCR2B = 0;                      // stop timer
    TIMSK2 = 0;                      // cancel timer interrupt

    //Cancel Rising Interrupt on D3
     EIFR = bit (INTF1);
    }

    void setup() {
      // put your setup code here, to run once:

    //Sets all the pins for output use
    for(int i=0;i<8;i++)
    {
      pinMode(pins[i], INPUT);
    }

    //Sets Reference Pin as Input
    pinMode(3,INPUT);

    //Begins Serial
    Serial.begin(115200);

    //Cancels Timer 1
    TCCR1A = 0;  // normal mode
    TCCR1B = 0;  // stop timer
    TIMSK1 = 0;   // cancel timer interrupt

    //Cancels Timer 2
     TCCR2A = 0;
     TCCR2B = 0;                      // stop timer
     TIMSK2 = 0;                      // cancel timer interrupt
    detachInterrupt(1);

    }

    void loop() {

      //Time of Ground Drop(2 mS), Universal for all letters and offsets
      groundtime = 40000;     // spark time (4000 * 500 nS) = 2 mS

      // because of prescaler of 8, each unit is 500 nS (0.5 µS)

         if(Serial.available()> 0);
        {
       //Reads Serial Value and assigns to incomingByte
       incomingByte = Serial.read();
       attachInterrupt(1,rising,RISING);
        }
      //  noInterrupts ();  // atomic change of the time amount

       //In this area, we'll set the output pin to be used by the timing interrupt,
       //and the time delay off the default waveform present on pin 4

       //We can use switch case arrangement, don't know if that's the optimal setup though
     switch(incomingByte)
     {
       default:
       //Do Nothing
       break;

       //Cases FOR ALL THE LETTERS
       case 'a':
       break;
       case 'b':
       break;
       case 'c':
       break;
       case 'd':
       break;
       case 'e':
       break;
       case 'f':
       break;
       case 'g':
       break;
       case 'h':
       break;
       case 'i':
       break;
       case 'j':
       break;
       case 'k':
       break;
       case 'l':
       break;
       case 'm':
       break;
       case 'n':
       break;
       case 'o':
       break;
       case 'p':
       break;
       case 'q':
       break;
       case 'r':
       //Output pin 17 Frequency Pin 10
       //microseconds
       timerhigh=8000;
       waveout=9;
       break;
       case 's':
       break;
       case 't':
       break;
       case 'u':
       break;
       case 'v':
       break;
       case 'w':
       break;
       case 'x':
       break;
       case 'y':
       break;
       case 'z':
       break;

       //Cases FOR ALL THE NUMBERS
       case '0':
       break;
       case '1':
       break;
       case '2':
       break;
       case '3':
       break;
       case '4':
       break;
       case '5':
       break;
       case '6':
       break;
       case '7':
       break;
       case '8':
       break;
       case '9':
       break;

       //Cases FOR ALL THE PUNCTUATION
       case '.':
       break;
       case ',':
       break;
       case '!':
       break;
       case '"':
       break;
       case '#':
       break;
       case '$':
       break;
       case '%':
       break;
     }

    //Enables Rising Interrupt for 0ms detection
    //attachInterrupt(1,rising,RISING);

    //Reenables interrupts after offset time change
    //interrupts ();
    }

title: Two Timer Interrupts, One Incorrect?

Answers: 1

body:
Turns out the problem was that timer 0 and 2 on the arduino uno are 8 bit. Set a different prescaler and I'm golden

    // set up Timer 2
        TCCR2A = 0;  // normal mode
        TCCR2B = 0;
        //  TCCR2A = bit(WGM21) | bit(CS21);  // CTC, scale to clock / 8
        TCCR2A = (1 << WGM21); //Enables CTC for timer

        TCCR2B |= (1 << CS21);
        TCCR2B |= (1 << CS22); //Sets 256 bit prescaler
        TCCR2B |= (0 << CS20);
        OCR2A = groundtime;    // time before rising edge
        TIMSK2 = (1 << OCIE2A);
        //Cancel Rising Interrupt on D3
        EIFR = bit (INTF1);
        //Reinables interrupts


body:
I'm playing around with a SparkFun Redboard (essentially, an Arduino UNO).

I have a simple 5V sensor that I'd been trying to get to work with A2 and analogRead(). Nothing seemed to work. It's supposed to be cycling from 0 to 5V, which should give me values from 0 to 1023, and instead I get constant values of around 260.

In desperation, I tried using other ports. On A0, A1, and A3 I get the signals I expect. On A2, still nada.

So, the question. Is there something I could have done in configuring things that would have made A2 and only A2 stop reading correctly? If so, how can I reset it?

Or is there some other function that I might be using that could interfere with A2? Currently, I'm only using Serial over USB - could that interfere with A2?

Or could I simply have fried the port?

title: Have I fried my A2 port?

Answers: 1

body: I wrote a simple program that used all six analog pins as digital outputs, and wired up an LED. All of the pins except A2 would blink the LED. So yes, it is fried.  Thanks.


body:
When running the board at room temperature (20 C) without any extra cooling mechanisms added, how much can the Arduino Uno be overclocked?

Also, what would I need to change/update to overclock the board?

title: How much can an Uno be overclocked?

Answers: 1

body:
With no active cooling, most ATmega328P will run at 30MHz but you will need to up the supply voltage to ~6V. I have never done this on an Arduino board, just an ATmega328P.

I provided an external clock from a signal generator.

The only way to achieve a speed faster than 16MHz is to change the crystal/oscillator/clock input for one faster than 16MHz.

As this was just an experiment, I didn't alter f_cpu in boards.txt, so all timers etc. would be incorrect. Baud rates would also be incorrect - the only way to upload code was to change back to 16MHz.


body:
I have sourced an LPG consumption meter from China with pulse output. I am looking to hook the output up to an arduino to get the consumption metrics. Unfortunately there is not too much documentation available on the unit that I can find. The suppliers inform me that:

1. Black wire(signal 1)
2. Black wire(signal 2)
3. Red wire(earth wire)

So that's a start, I know the unit pulses a signal for every cubic meter of gas consumed.
What I'm wanting to know is:

1. What are the input [likely] voltages for the unit (or how could I establish this)?
2. How do I wire the unit to an arduino?
3. I can cook up a sketch to do the reading but what is the signal I am looking for?

The mechanical meter itself has a metallic strip on the 0 digit of the wheel (how it achieves the pulsing itself no doubt) so another approach would be something like this <http://phk.freebsd.dk/Gasdims/> which is a more accurate option. For this option any suggestions on what photoreflectors are available for the Arduino which could do the job.

![meter][1]
![output wiring - one red two black][2]

  [1]: https://i.stack.imgur.com/sHmUd.jpg
  [2]: https://i.stack.imgur.com/WTD8F.jpg

title: How to interface to LPG consumption meter

Answers: 1

body:
Start with earthing the red (!?) wire to the ground of the arduino.
Apply 5 volts via a 10k resistor to one of the black wires and also connect the black wire to the arduino as well.
Basically :

    5V ----(10K resistor)---+---Black wire----( Gas Meter)-----ground
                            |
                            |
                            +--- arduino digital input

You should either get a high or a low signal. Try the other black wire, it might be inverted (as in high and then pulse low, vs low and then pulse high).

Failing that, pop the top off that cover and have a poke around. Might give you a clue as to what's what.


body:
Currently I am developing a graphic LCD system to display temperatures, flows, voltages, power and energy in a heat pump system. The use of a graphic LCD means that half of my SRAM and ~75% of my flash have been used up by a screen buffer and strings.

I am currently displaying min/max/average figures for energy At midnight when the daily figure resets, the system checks if the consumption for the day is above or below the previous minimum or maximum, and stores the value. The average is calculated by dividing the cumulative energy consumption by the number of days.

I would like to display the daily average over the last week and month (4 weeks for simplicity) i.e. a rolling average. Currently this involves maintaining an array of values for the last 28 days and calculating an average over the whole array for monthly and last 7 days for weekly.

Initially I was doing this using an array of floats (as the energy is in the form "12.12kWh"), but this was using 28 * 4 bytes = 112 bytes (5.4% of SRAM). I don't mind having only a single decimal point of resolution, so I changed to using uint16_t and multiplying the figure by 100. This means that 12.12 is represented as 1212, and I divide by 100 for display purposes.

The size of the array is now down to 56 bytes (much better!).

There is no trivial way to reduce the figure down to a uint8_t that I can see. I could tolerate the loss of a decimal place ("12.1kWh" instead of "12.12kWh"), but consumption is frequently higher than 25.5kWh (255 being the highest value represented by a 8-bit unsigned integer). Consumption has never been below 10.0kWh or above 35.0kWh, so conceivably I could subtract 10 from the stored figures, but I know that one day we will exceed these limits.

I then tested code to pack 9-bit values into an array. This gives a range of 0-51.2kWh and uses 32 bytes in total. However, accessing an array like this is pretty slow, especially when you have to iterate over all values to calculate an average.

So my question is - is there a more efficient way of calculating a moving average with three windows - lifetime, 28 days and 7 days? Efficiency means smaller in terms of SRAM usage, but without the penalty of huge code. Can I avoid storing all values?

title: Efficient algorithm/data structure to calculate moving averages

Answers: 5

body:
you can use a different method, you keep the current average and then do

    average = (weight1*average+weight2*new_value)/(weight1+weight2);

it's not a true rolling average and has different semantics, but it may fit your needs nonetheless

for a more efficient calculation method for your 9 bits per value solution you could keep the 8 highest bits of the values in an array and separate out the least significant bits:

    uint8_t[28] highbits;
    uint32_t lowbits;

to set a value you need to split it out

    void getvalue(uint8_t index, uint16_t value){
        highbits[index] = value>>1;
        uint32_t flag = (value & 1)<<index;
        highbits|=flag;
        highbits&=~flag;
    }

resulting in 2 shifts an AND and an OR and a not

to calculate the average you can use various bit tricks to speed it up:

    uint16_t getAverage(){
        uint16_t sum=0;
        for(uint8_t i=0;i<28;i++){
            sum+=highbits[i];
        }
        sum<<=1;//multiply by 2 after the loop
        sum+=bitcount(lowbits);
        return sum/28;
    }

you can use an [efficient parallel bitcount][1] for the `bitcount()`

  [1]: https://stackoverflow.com/questions/3815165/how-to-implement-bitcount-using-only-bitwise-operators

body:
If your data has low standard deviation, then one method would be to sum values over the window, and then keep subtracting the mean from the sum, while adding the new value.

This would work well if there are *no outliers*, thereby leading to the aggregate error tending to zero over time.

    //Pseudocode

    count=0
    while new_reading and count<7:
        sum += new_reading        //Calculate the sum of first 7 values
        count++

    while new_reading:            //Loop till new readings available
        avg = sum / 7             //Calculate average
        sum -= avg                //Subtract average from sum
        sum += new_reading        //Add next reading to sum
        print avg

body: How about only storing the difference from the previous value? In electronics there is a similar concept called Delta Sigma converter, which is used for DA/AD converters. It relies on the fact that the previous measurement is reasonably near the current one.

body:
Why couldn't you just add the values together as soon as you obtain them. So what I mean is you get the value for day 1, you divide it by 1 and store it and the 1 somewhere. Then you multiply the 1 by the value and add it to the next value and divide them both by 2.

Doing this method would create a rolling average with two or three variable as I can think of. I would write some code but I am new to stackexchange so please bear with me.

body:
> is there a more efficient way of calculating a moving average with
> ... 28 days and 7 days?
...
> needing to remember 27 days of history ... ?

You might get close enough storing 11 values rather than 28 values,
perhaps something like:

    // untested code
    // static variables
    uint16_t daily_energy[7]; // perhaps in units of 0.01 kWh ?
    uint16_t weekly_energy[4]; // perhaps in units of 0.1 kWh ?

    void print_week_status(){
        Serial.print( F("last week's total energy :") );
        Serial.println( weekly_energy[0] );
        int sum = 0;
        for( int i=0; i<4; i++ ){
            sum += weekly_energy[i];
        };
        Serial.print( F("Total energy over last 4 complete weeks :") );
        Serial.println( sum );
        int average_weekly_energy = sum/4;
        int average_daily_energy = average_weekly_energy/7;
        Serial.print( F("Average daily energy over last 4 weeks :") );
        Serial.println( average_daily_energy );
    }
    void print_day_status(){
        Serial.print( F("Yesterday's energy :") );
        Serial.println( daily_energy[0] );
        Serial.print( F("average daily energy over the last 7 complete days: ") );
        int sum = 0;
        for( int i=0; i<7; i++ ){
            sum += daily_energy[i];
        };
        int average = sum/7;
        Serial.println( average );
    }

In other words, rather than storing every detail of every day for the last 27 days,
(a) store 7 or so values of detailed daily information for the past 7 or so days, and also
(b) store 4 or so "summarized" values of total or average information for each of the past 4 or so weeks.


body:
C on embedded systems has traditionally use structs to hold structured data.

Arduino brings C++ to the table, so we can use classes instead.

Lets say we have two different data structures which could be considered very similar:

    typedef struct
    {
     int valueOne;
     int valueTwo;
     int valueThree;
    } value_t;

and:

    class Value
    {
     public:
      int valueOne;
      int valueTwo;
      int valueThree;
    }

In terms of memory, what difference will this make?

I still see the struct technique being used heavily - why is this?

title: What overheads and other considerations are there when using a struct vs a class?

Answers: 5

body:
As taken from the accepted answer from [When should you use a class vs a struct in C++?][1]

> The only difference between a class and a struct in C++ is that
> structs have default public members and bases and classes have default
> private members and bases. Both classes and structs can have a mixture
> of public and private members, can use inheritance, and can have
> member functions.
>
> I would recommend using structs as plain-old-data structures without
> any class-like features, and using classes as aggregate data
> structures with private data and member functions.

Memory wise the access modifier makes no difference and given the memory constraints of the Arduino, people are less likely to use classes with complex hierarchies, but prefer the POD structs anyway.

  [1]: https://stackoverflow.com/a/54596/731620

body:
Unlike C, an instance of a `struct` in C++ is an object in exactly the same way as an instance of a `class`. From the point-of-view of the compiled code, they are identical. Memory usage, alignment, access times etc. are exactly the same (i.e. there are no overheads).

From the programmer's point-of-view, there is a very minor difference. Members of a `struct` have public visibility by default, whereas members of a `class` have private visibility by default. Otherwise, all language features work the same on both, such as constructors/destructors, inheritance, polymorphism, templates, and operator overloading. You can even derive a `struct` from a `class`, and vice versa.

Despite the similarity, it's quite common to see people deliberately using a `struct` in C++ for very simple structures, e.g. where it only consists of a few data members, but no functions. A `class` would be used for anything more complex. This is purely a matter of convention or personal preference though, and can be used as a subtle indication of the structure's intended complexity.

body: As other answers have pointed out, your particular `struct` and `class` are indistinguishable performance wise (There are slight differences in the scopes of the type names, due to the way you defined your struct). The delineation in C++ is not between `struct` and `class`, but between types that are *POD (plain old data)* and types that are not, as explained in [this discussion](https://stackoverflow.com/questions/146452/what-are-pod-types-in-c).

body:
Note that

    typedef struct { ... } Foo;

is obsolete in C++ and you should just use

    struct Foo { ... };

It's not very clear in the answers but the other effect of structs is public inheritance by default vs private inheritance by default with classes.

As mentioned by others, using struct is generally a convention for POD types.

Also technically 'struct vs object' should be 'struct vs class' (as instantiating a struct or a class still gives an object).

body:
> In terms of memory, what difference will this make?

None. Structs and classes are the same thing, differing only in protection levels, and instantiating either creates an 'object'.

> still see the struct technique being used heavily - why is this?

Less typing if you're not trying to hide data members.


body:
Clearly, an Arduino can be powered with solar panels.

 1. What is the most optimal configuration?
 2. Can you recharge and discharge at the same time?
 3. Is LiPO the best battery cache technology, or is there something more durable out there, for fielded deployment?
 4. What are the most economic, and reliable ways to do this?

title: Powering Arduino with Solar Panels

Answers: 2

body:
**First of all you want to buy some solar panels or cells.** Although they can be found on eBay for very cheap, but they not be as efficient as they say. I would say try to buy from a reputable dealer to see reviews on the product or trust that they work efficiently. Sparkfun datasheets are generally accurate and can be trusted.

 - Most optimal configuration: **Do not use a regulator and some sort of step-up booster.** Try the TPS61200 or TPS61202 chips. They will not *regulate* the voltage, they *boost* the voltage dynamically. This is much more efficient and therefore generates less heat. They work like a reverse voltage regulator, taking .3V to 5.5V and turning it into anywhere from 1.8V to 5V (xxx0) or 5V exactly (xxx2). Hack a USB B end and just connect the power lines to the Arduino.
 - Discharge/charge simultaneously: Yes, however I'm not sure how to. I believe that if you hook up a charger IC and a load, the voltage won't go through the battery, it will go through the path of least resistance. However, your battery wouldn't get charged then. This is outside the scope of the question, so I would recommend EE on how exactly to do this.
 - Is LiPO the best: **Try a Lithium-Ion Battery.** (A.K.A. Li-ion) According to [this site](http://www.androidauthority.com/lithium-ion-vs-lithium-polymer-whats-the-difference-27608/):
> Although the lithium-polymer battery is sleeker and thinner, lithium-ion batteries have a higher energy density and cost less to manufacture.

 Therefore, it seems like Li-ion is the best choice for you. **Note: Since you are dealing with very dense batteries that [if overvolted can go up into flames [Note: please mute your speakers!]](https://www.youtube.com/watch?v=SMy2_qNO2Y0&feature=youtu.be&t=2m), make *sure* to go with Sparkfun/Adafruit/etc...**

 - Economic way: If you don't mind a big "homemade" solar panel, go this way. Buy through eBay or a similar site solar *cells*. They are small plates that are connected to create a solar panel. Try looking for "grade B" or similar solar cells that work fine, they just may have minor imperfections. It won't be as pretty, but you'll save some cash.

See [this EE.SE post for more information](https://electronics.stackexchange.com/questions/85757/how-do-i-go-about-building-a-charger-circuit). One cool thing that I saw was:
> This is really cool. You can connect the Li-Ion voltage through an op-amp to generate a pulse wave, which can be picked up by your MPU to tell your bot to go charge –  Raaj Oct 18 '13 at 18:44

I'm not exactly sure how to do this, but it might be useful. I couldn't find anything online about it.

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


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

title: Circuit diagram interpretation and electrical flow

Answers: 1

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.


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

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

Answers: 2

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


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

title: How does the Space Replay record audio?

Answers: 3

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/


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

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

Answers: 1

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.


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

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

Answers: 7

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

body:
Ok, I know this is an old question but the more I read through the answers the more I keep coming back to an observation that seems salient.

The Halting Problem Is Real
---------------------------

There seems to be a link with Turing's Halting Problem here.  Allowing dynamic allocation increases the odds of said 'halting' so the question becomes one of risk-tolerance. While it is convenient to wave off the possibility of `malloc()` failing and so forth, it is still a valid outcome.  The question the OP asks only appears to be about technique, and yes the details of the libraries used or the specific MPU do matter; the conversation turns towards reducing the risk of the program halting or any other abnormal end. We need to recognize the existence of environments that tolerate risk vastly differently.  My hobby project to display pretty colors on a LED-strip won't kill someone if something unusual happens but the MCU inside a heart-lung machine likely will.

Hello Mr. Turing My Name is Hubris
----------------------------------

For my LED-strip, I don't care if it locks up, I'll just reset it.  If I were on a heart-lung machine controlled by an MCU the consequences of it locking up or failing to operate are literally life and death, so the question about `malloc()` and `free()` should be split between how the intended program deals with the possibility of demonstrating Mr. Turing's famous problem. It can be easy to forget that it is a mathematical proof and to convince ourselves that if only we are clever enough we can avoid being a casualty of the limits of computation.

This question should have two accepted answers, one for those who are forced to blink when staring The Halting Problem in the face, and one for all others. While most uses of the arduino are likely not mission critical or life-and-death applications, the distinction is still there regardless of which MPU you may be coding.


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

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

Answers: 1

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.


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

title: attiny85 and arduino - analogRead + pwmOut

Answers: 2

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


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

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

Answers: 3

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)


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

title: How do I know the sampling frequency?

Answers: 7

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.


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

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

Answers: 1

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.


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

title: High precision timing on Arduino for serial communication

Answers: 3

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/