body:
**Lasers**

If your blue water bottles are like mine, they are transparent.

Here's what I would try first:

I would get a cheap laser, and shine the light horizontally through the bottle.
I would aim the laser through a short [chord][1] -- not pointed directly through the middle of the bottle; perhaps 1/8 turn to the left of center.

        -------
    L../.......\..........S1
      /         \
     |     o     |        S2
      \         /
       \       /
        -------
    top-down view

When the bottle is empty, the laser beam will shoot pretty much straight through the bottle -- I would put one photo-sensor S1 there.

When the bottle is not quite empty, the laser beam will bend ([refract][2]) -- for redundancy, I would put another photo-sensor S2 there.

As long as the Arduino sees the laser hitting S2 alone, there's still some water in the bottle, at least up to the level of the laser -- turn on the green light.

Anything else -- light detecting only at S1, or nothing detected at either sensor, or light detected at both sensors (yes, it can happen) -- something doesn't seem right, better have the Arduino turn off the green light and turn on the red light.

I would start with [the simplest thing that could possibly work][3].
If I'm lucky, it might work.
If not, there's lots of little tricks involved in getting the light where you want it to go.
There's also lots of tricks for blocking sunlight, etc. from going where you don't want it to go.
Little black tubes, red plastic filters,
pulsing the laser at a few kHz,
collimating lenses,
lock-in amplifiers, etc.

There seem to be lots of tutorials that describe how to detect a laser using Arduino -- see

* ["Laser Harp"][4]
* ["Laser Timing Gate"][11]
* ["Arduino Laser Tripwire"][5]
* ["Arduino Forum: laser detection"][6]
* ["Arduino security with frickin’ laser"][7]
* ["Arduino self-calibrating laser trip wire"][8]
* ["The Arduino Controlled Laser Security System"][9]
* ["Raspberry Pi & Arduino: laser pointer communication"][10]
* etc.

(This would probably work just as well with a medium-power LED or "infrared LED" and some careful optical focusing and alignment. But -- lasers!)

  [1]: http://en.wikipedia.org/wiki/chord_(geometry)
  [2]: http://en.wikipedia.org/wiki/refraction
  [3]: http://www.artima.com/intv/simplestP.html
  [4]: http://www.radioshack.com/graphics/uc/rsk/Support/ProductManuals/Laser_Harp_Online_Instructions.pdf
  [5]: http://www.instructables.com/id/Arduino-Laser-Tripwire/
  [6]: http://forum.arduino.cc/index.php/topic,13046.0.html
  [7]: http://hackaday.com/2010/01/03/arduino-security-with-frickin-laser/
  [8]: http://keithkay.com/2013/03/03/arduino-self-calibrating-laser-trip-wire/
  [9]: http://makezine.com/projects/the-arduino-controlled-laser-security-system/
  [10]: http://pyevolve.sourceforge.net/wordpress/?p=2383
  [11]: https://www.manylabs.org/project/laserGate/


sender: user

message:
Best way to determine if a 5 gallon water jug is getting empty

I have an espresso machine that gets its water from one of those 5 gallon blue water bottles (I would plumb it, but our water here is WAAAAY too hard).

If I ever accidentally let the bottle run out of water, the rotary pump in the espresso machine will be ruined, which would be a costly mistake.

I know that I can install some sort of magnetic float sensor inside the water bottle, but since I have to change it out once every few weeks, having another thing inside the bottle would make changing it out harder, and microbial contamination more likely.  The pump that pumps water out of the bottle forms a tight seal at the lid, and anything running under it or through it would compromise that seal.

Is there something I could use to detect if the water level is low from the outside of the bottle?  Like a laser sensor?

sender: assistant

body:
you can use a metal detector like setup using the fact that electronic [permittivity][1] of water is different than that of air

have a coil with AC next to the bottle and an unpowered coil inside it

then by measuring the current and/or voltage generated by the second coil you can sense the difference between with water next to it and without

  [1]: http://en.wikipedia.org/wiki/Permitivity


body: Try a non contact water sensor: https://www.dfrobot.com/product-1493.html I use them and they work very well. You stick it on the outside of the jug, If it falls off the jug will show empty protecting your pump. The ones I use are similar and have an open collector, so no micro is required.  I think I paid about $6 a year or so ago. They make adjustable ones. Nice point nothing touches the water or can contaminate it.


message:
Make an Arduino board act as both a usb storage device and a keyboard?

I am making an interface project that, when plugged into a computer, shows up as both usb flash storage and can type like a keyboard when some physical buttons on the board are pressed.

I have seen projects that do one or the other, but not both at the same time.

I have gotten it to work using a usb hub and two chips that are sharing the same storage (since I want the hot-key buttons to type out information stored in the flash drive side as well), with one acting like a HID and one acting as usb storage, but this has a few problems. First, it feels redundant. Second it's difficult to program since every time I plug the mess in it randomly assigns a name to each chip with no easy way of telling which to send the HID code to and with to send the USB Drive code to. I have to plug them in one at a time which wont work once this project is all on the same board. The last problem is the buttons work inconsistently since, im assuming, the two chips are not doing a nice job of sharing access to the text file it's trying to read for the text to 'type out' on the computer.

Is there a nicer way of doing this that uses one arduino acting in both roles accessing the one flash storage? Thanks!

body:
You're looking to create a USB composite device.  I don't see any examples within the arduino community, but I don't see a reason why you couldn't [use the 16u2 as a composite device][1], it'll just require more effort than you'd normally put into an arduino project.

  [1]: https://www.google.com/search?q=atmega 16u2 composite device


body:
The Leonardo can easily be used as a keyboard. There are also special codes to turn the USB-to-Serial chip on newe Unos into a keyboard (see [here](http://www.fourwalledcubicle.com/LUFA.php))

USB mass storage is another game all together. The [Brondani EasyUSB](https://www.sparkfun.com/products/10155) is a simple chip that exposes 2MB of storage space on both the USB and microcontroller. They say they will be releasing larger capacities.

The easyUSB also has a serial link built into it from uC to computer.

If you really want, you can make your own USB stack to handle this on you own, but the pitifully small amount of ram on these chips would prohibit it.


body: You can try using an Arduino Mega ADK. This is because it has a separate USB port for USB devices along with many serial ports for other serial device.


message:
sprintf() to assemble String and float pieces locks up

I'm trying to parse many variables into a URL so that I can update a website through a simple HTTP API with sensor data. After talking to a buddy of mine, he suggested going with the code below.

When I put this in, the Arduino Yun boots up. I see the L13 red LED turn on, but then it hoses. When I comment out the `sprintf();` line, everything works fine — except no URL is parsed.

I've tried to debug to the best of my ability and am looking for thoughts on what may be happening.

I'm not sure how much code to post without posting the whole 130 line sketch, so I'm just dumping the parts from the `loop` that is trying to piece together the URL.

      // Get update time
      Process date;
      date.runShellCommand("date --utc \"+%Y-%m-%d% %H:%M:%S\"");
      String utcDateString = "";
      while (date.available()) {
        char d = date.read();
        utcDateString += d;
      }

          char url[512];
          url[0]='\0';
          float humid, baro, windspeed, raingauge;
          int winddir;
          Serial.print("humid: ");
          Serial.println(humid);
            Serial.print("baro: ");
          Serial.println(baro);
            Serial.print("windspeed: ");
          Serial.println(windspeed);
            Serial.print("raingauge: ");
          Serial.println(raingauge);
            Serial.print("winddir: ");
          Serial.println(winddir);
     //sprintf(url,"http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?ID=123456&PASSWORD=xxxxxx&dateutc=%s&temp=%2.2f&humidity=%2.2f&baromin=%f&winddir=%d&windspeedmph=%3.2f&rainin=%3.2f&softwaretype=Custom% Arduino&action=updateraw",
    //         utcDateString,Thermistor(analogRead(0)),humid,baro,winddir,windspeed,raingauge);
            Serial.print("url: ");
          Serial.println(url);

    double Thermistor(int RawADC) {
      double Temp;
      Temp = log(11100.0/((1024.0/RawADC-1)));  // Was 10000... Manually dialed down to increase accuracy. 9400 is a good value. Changing again to match wunderground
      Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
      Temp = Temp - 273.15;            // Convert Kelvin to Celcius
      Temp = (Temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
      return Temp;
    }

Here's the output from those `Serial.print()` calls:

    humid: 0.00
    baro: 0.00
    windspeed: 0.00
    raingauge: 0.00
    winddir: 0
    url:

I'm not sure how else to debug this because when I uncomment `sprintf();` the Yun locks up and I have to press the `32U4 Reset` button and power cycle the Arduino to get it to work again.

body: Looks like `%f` isn't wired up for performance reasons.  You can convert floats to strings first using `dtostrf()`.


body:
This variable:

    String utcDateString = "";

Is a C++ String, not a character array like sprintf() is expecting.  To convert this string to a character array such that sprintf is expecting, you must use .c_str() in your sprintf, i.e.:

    sprintf(foo,"This is a format for %s", utcDateString.c_str());

Doing this should prevent the sprintf line from causing a memory fault.


message:
Sensor for underground water tank level

In a similar way to the question  "[**best way to determine if a 5 gallon water jug is getting empty**][1]", I'm looking for a way to measure water in a container. This is so it can be connected to an Arduino for logging and reporting.  But it's a very different container.

I have a home with the household water supplied from an underground concrete tank (around 3000 US gallons, 11000 litres).  Although there is a float switch cutout when it gets empty (to protect the pump), I'd like to know it's gettting low long before that (as it takes a while before a tanker delivers a fresh load).  Ideally something that measures exactly or in steps (at least in eights of a load), so software can predict when it'll run out based on average usage, and it can be monitored online when away.

The tank has a heavy concrete hatch, and a small hole that has an existing primitive dipstick, so access is limited.  It's in a harsh desert environment, but the pump room and power are only a few feet away.

Some ideas I had:

  - suspend an array of float switches with strings of different lengths from a bar inside the tank, and wire them all back to a controller.  Hard to install, ugly, low tech. Or something similar on a vertical pole.
  - contacts (like a US 2 pin plug) on a vertical pole that again are connected back to a controller (probably using a ribbon cable).  Corrosion/anodes might be a problem, although power could just be a short pulse at times.  Condensation, spiders webs and dead bugs may give false readings.
  - run a fully insulated cable vertically down it, and use as an antenna to send a pulse through, and use the difference between how it works as an antenna in air, and in water, (like an SWR meter) to calculate how far down the water is.
  - ultrasonic (or light?) distance finder mounted under the hatch.  Range needs to be up to 2 metres (6 feet).
  - depth finder (sonar) on a float.  Biggest challenge here is getting the signal out (long cable might get tangled when the tank fills).

The last two would be even better if they were wireless (to save running a cable that might get damaged) but I don't think I'd get the battery life I'd like (1 year or more).

Any other ideas?  Has anybody ever done this?

  [1]: https://arduino.stackexchange.com/questions/488/best-way-to-determine-if-a-5-gallon-water-jug-is-getting-empty

body:
I have a background working on ships where robust and workable tank level gauges are  a huge part of instrumentation available to you. Water is the most forgiving and easiest liquid to measure - it's cool, not too viscous, not corrosive in itself, and easy to clean off. There are a lot of options available to you.

Personally I would avoid any system which involves immersing anything in liquid if at all possible. Waterproofing isn't easy. I would also try to stay with a tried and tested system.

So to run through your solutions:

 1. Multiple float switches - has poor resolution. Would be reliable. You can buy assemblies with LowLow, LowHigh, HighLow, HighHigh float limit switches already on them for maintaining tanks levels, but these are industrial quality with industrial prices.

 2. This would work, but corrosion is going to be an issue. Resolution limited by how many contacts you have.

 3. Interesting idea, but would likely require a lot of DSP work. Not a tried and tested method.

 4. An ultrasonic sensor would be my preferred method. Non-contact, high resolution, range of 2m is easy. Tried and tested system.

 5. Interesting idea, would require a lot of work. Easier to measure depth of air as per 4 and do the simple maths.

A few other methods come to mind:

1. A pressure sensor at the bottom of the tank. This is often used on ships, works well but needs immersion which can be avoided.

2. Inflow/outflow monitoring. A flow meter on the output can tell you how much you have used. Inferring level like this is prone to errors though.

There are a million other methods, but they get more and more complex.

The ultrasound would be a great way to do this. The commonly available [Parallax Ping][1] sensor would do the job. Realistically, you would only need to make measurements at most once every hour, so you could achieve great battery life. The concrete is likely to present a wireless range challenge. Most RF transceivers will get through concrete though, so place the receiver nearby.

If you want ideas on how it is done, google for ultrasonic *oil* level monitoring - there are loads of wireless commercial solutions.

  [1]: http://www.parallax.com/product/28015


body: Id go with an ultrasonic detector as Cybergibbons suggests together with a usage/flow monitor (http://www.ebay.com/bhp/water-flow-sensor) so as to understand if there are any losses through leaks etc. I'd use a YUN or Ethernet or shield to call or email you a monthly report / fill a datbase as well as place the order directly to the water supplier as well as cc'ing you.


body:
http://playground.arduino.cc/Main/Waterlevel

The above link had a nice approach.

![Water level detection using Pressure Transducer][1]

The principle is the same as traditional pneumatic level gauge, excepted that the dial indicator is replaced by a pressure transducer, and the manually-operated pump is replaced by an aquarium air pump.

When the pump is on, air flows through the weighted PVC pipe to the bottom of the tank, where bubbles appear. At this moment, the air pressure in the PVC pipe is equal to the hydrostatic pressure at the bottom of the tank. As the water pressure at the bottom of the tank is directly proportional to the water level, the same goes for the air pressure in the PVC tube. The air pressure is then converted to an analog voltage by the pressure transducer. This voltage can be read easily by the arduino.

A big advantage of this method with regards to other existing techniques is that no electronic or metallic parts needs to be placed in the tank, where the environmental conditions (mainly humidity) are not favorable. This avoids any risk of corrosion.

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


body:
It's tricky when you only have a small hole to work with, so trying to get inside to install a series of floats or contact pins on the side is not ideal. The ultrasonic is a good idea, but I don't know how that would be achieved. Personally, I would try the cable, as it is simple enough to drop it in the hole, and wait for your results.

If you wanted to try running a cable through it, you might want to use this [Water Level Sensor][1], or at least base your own project on it.

  [1]: http://vegetronix.com/Products/AquaPlumb/

It is non-corrosive, and has no moving parts, which is supposed to lead to a heightened accuracy, and less chance of it failing or breaking down. The enclosure is water-proof, and you can buy one with a relay attached to fit your monitoring needs. The only issue that I see is that it isn't wireless, but other than that, it seems to be pretty functional.


body:
The bubble tube method (http://dexautomation.com/?p=9) springs to mind.

Also capacitive measurement is doable (http://olimex.wordpress.com/2012/02/02/duinomite-project-tank-fluids-level-metering-by-capacitance-measurement/) but more tricky. If you can use the steel inside the concrete it can be made completely contactless.

Please note, that if the water is meant for consumption without filtering or purification you may want to refrain from direct-contact methods.

Googling for "tank level measurement arduino" yields lots of potentially useful results.

Also, is consumption so erratic that you can't predict when the tank needs filling?


body:
I know you asked this a few months ago .. but sometimes with something technical the project never gets completed, or at least not in short order.

So while you're building your new-world-order with an Arduino, can I suggest you put a pipe down the dip hole and insert a floating dip stick? 1.5" pipe. 1/4" dowel glued to a ping-pong ball. Flag on top of the dowel. Now you'll see the level any time you walk past.


body: I've been using the Ultrasonic method for close to a year and the biggest problem is the sensor failing due to water infiltration(condensation). My latest attempt lasted for about two weeks. I used plastic spray like the stuff you use on tool handles. I also used the wireless shield to make a website that displayed the level on any device connected to my router. I would like to get it to email me when the level is below 10% but can't get it to work....It's not bad but still needs work for stability...


body: The limited access issue is tough... If you were going to use the float idea, it would be hard to difficult to actually install the thing. The other issue is waterproofing components and making sure that they won't corrode and cause false readings, which defeats the purpose of installing the system. Although it is a different scenario, i use this Water Level Sensor to moniter my home aquarium. the sensor is totally insulated, and is thus waterproof. also the sensor itself is aproximately 1 mm in width,so it probably fit into your reservoir. From what i've seen so far from my use is that it is pretty accurate, and it works in both my salt water and fresh water tanks. Hope this helps!


body:
I have used FM antenna cable successfully as soil moisture sensor and as fluid level sensor. Dip the bottom end into melted glue stick to insulate.
For permanent installation in a water tank I would also dip the cable into a paint tin and hang it up to dry for extra insulation. Antenna cable without any extra waterproofing was used for soil moisture measuring for 3 years with no problems.
The top end is connected to two parts of a LM393. The first one is a Schmitt trigger with 470K feeback and 1M series. The neg side is fed back with 220K. The second one is simply an inverter, and the output feeds back through a 220K. The two 220ks get connected to the sensor cable, and a parallel 100pf cap.The cable is thus excited differentially.
The ciruit oscillates according to the capacitance of the sensor cable. The frequency is measured by your favourite micro. The extra 100pf is only there to keep the frequency in a range where the oscillations can be fed over a line.
A bucket of water is enough to calibrate the setup.


body:
You could take a piece of 2 conductor wire in a U shape that is weighted at the bottom of the "U" to rest at the bottom of the tank.  (The reason to use a U shaped wire instead of a straight wire is to prevent having to insulate one end from the water).  You would then measure the capacitance of the wire, where some baseline capacitance is the wire when dry and any wire that is wet would increase the capacitance proportional to the length that is wet.  Any wire that is rated for outdoor operation, i.e. does not absorb water would do and actually the thicker the jacket the better as the baseline capacitance would be lower.

The capacitance could be measured in the same way as a capacitive touch sensor or a capacitance to frequency converter (Sometimes called an "Oscillator").


message:
Is it better to use #define or const int for constants?

Arduino is an odd hybrid, where some C++ functionality is used in the embedded world—traditionally a C environment. Indeed, a lot of Arduino code is very C like though.

C has traditionally used `#define`s for constants. There are a number of reasons for this:

 1. You can't set array sizes using `const int`.
 2. You can't use `const int` as case statement labels (though this does work in some compilers)
 3. You can't initialize a `const` with another `const`.

You can check [this question][1] on StackOverflow for more reasoning.

So, what should we use for Arduino? I tend towards `#define`, but I see some code using `const` and some using a blend.

  [1]: https://stackoverflow.com/questions/1674032/static-const-vs-define-in-c

body:
*EDIT: microtherion gives an excellent answer which corrects some of my points here, particularly about memory usage.*

---

As you've identified, there are certain situations where you're forced to use a `#define`, because the compiler won't allow a `const` variable. Similarly, in some situations you're forced to use variables, such as when you need an array of values (i.e. you can't have an array of `#define`).

However, there are many other situations where there isn't necessarily a single 'correct' answer. Here are some guidelines which I would follow:

**Type safety**
From a general programming point-of-view, `const` variables are usually preferable (where possible). The main reason for that is type-safety.

A `#define` (preprocessor macro) directly copies the literal value into each location in code, making every usage independent. This can hypothetically result in ambiguities, because the type may end up being resolved differently depending on how/where it's used.

A `const` variable is only ever one type, which is determined by its declaration, and resolved during initialisation. It will often require an explicit cast before it will behave differently (although there are various situations where it can safely be implicitly type-promoted). At the very least, the compiler can (if configured correctly) emit a more reliable warning when a type issue occurs.

A possible workaround for this is to include an explicit cast or a type-suffix within a `#define`. For example:

    #define THE_ANSWER (int8_t)42
    #define NOT_QUITE_PI 3.14f

That approach can potentially cause syntax problems in some cases though, depending on how it's used.

**Memory usage**
Unlike general purpose computing, memory is obviously at a premium when dealing with something like an Arduino. Using a `const` variable vs. a `#define` can affect where the data is stored in memory, which may force you to use one or the other.

 - `const` variables will (usually) be stored in SRAM, along with all other variables.
 - Literal values used in `#define` will often be stored in program space (Flash memory), alongside the sketch itself.

*(Note that there are various things which can affect exactly how and where something is stored, such as compiler configuration and optimisation.)*

SRAM and Flash have different limitations (e.g. 2 KB and 32 KB respectively for the Uno). For some applications, it's quite easy to run out of SRAM, so it can be helpful to shift some things into Flash. The reverse is also possible, although probably less common.

**PROGMEM**
It's possible to get the benefits of type-safety while also storing the data in program space (Flash). This is done using the `PROGMEM` keyword. It doesn't work for all types, but it's commonly used for arrays of integers or strings.

The general form given in the [**documentation**][1] is as follows:

    dataType variableName[] PROGMEM = {dataInt0, dataInt1, dataInt3...};

String tables are a bit more complicated, but the documentation has full details.

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


body:
It's important to note that `const int` does **not** behave identically in C and in C++, so in fact several of the objections against it that have been alluded to in the original question and in Peter Bloomfields's extensive answer are not valid:

 - In C++, `const int` constants are compile time values and **can** be used to set array limits, as case labels, etc.
 - `const int` constants do not necessarily occupy any storage. Unless you take their address or declare them extern, they will generally just have a compile time existence.

However, for integer constants, it might often be preferable to use a (named or anonymous) `enum`. I often like this because:

 - It's backward compatible with C.
 - It's nearly as type safe as `const int` (every bit as type safe in C++11).
 - It provides a natural way of grouping related constants.
 - You can even use them for some amount of namespace control.

So in an idiomatic C++ program, there is no reason whatsoever to use `#define` to define an integer constant. Even if you want to remain C compatible (because of technical requirements, because you're kickin' it old school, or because people you work with prefer it that way), you can still use `enum` and should do so, rather than use `#define`.


body:
**For variables of a specified type which are not altered during execution, either can usually be used.**

**For Digital pin numbers contained in variables, either can work - such as:**

    const int ledPin = 13;

**But there is one circumstance where I always use `#define`**

**It is to define analog pin numbers, since they are alphanumeric.**

Sure, you can hard-code the pin numbers as `a2`, `a3`, etc. all throughout the program and the compiler will know what to do with them.  Then if you change pins then each use would need to be changed.

Moreover, I always like to have my pin definitions up at the top all in one place, so the question becomes which type of `const` would be appropriate for a pin defined as `A5`.

In those cases I always use `#define`

**Voltage Divider Example:**

    //
    //  read12     Reads Voltage of 12V Battery
    //
    //        SDsolar      8/8/18
    //
    #define adcInput A5    // Voltage divider output comes in on Analog A5
    float R1 = 120000.0;   // R1 for voltage divider input from external 0-15V
    float R2 =  20000.0;   // R2 for voltage divider output to ADC
    float vRef = 4.8;      // 9V on Vcc goes through the regulator
    float vTmp, vIn;
    int value;
    .
    .
    void setup() {
    .
    // allow ADC to stabilize
    value=analogRead(adcPin); delay(50); value=analogRead(adcPin); delay(50);
    value=analogRead(adcPin); delay(50); value=analogRead(adcPin); delay(50);
    value=analogRead(adcPin); delay(50); value=analogRead(adcPin);
    .
    void loop () {
    .
    .
      value=analogRead(adcPin);
      vTmp = value * ( vRef / 1024.0 );
      vIn = vTmp / (R2/(R1+R2));
     .
     .

All the setup variables are right at the top and there is never going to be a change to the value of `adcPin` except at compile time.

No worries about what type `adcPin` is.  And no extra RAM is used in the binary to store a constant.

The compiler simply replaces each instance of `adcPin` with the string `A5` before compiling.

-----------------
There is an interesting Arduino Forum thread that discusses other ways to decide:

[#define vs. const variable][1]  (Arduino forum)

Excertps:

Code substitution:

    #define FOREVER for( ; ; )

    FOREVER
     {
     if (serial.available() > 0)
       ...
     }

Debugging code:

    #ifdef DEBUG
     #define DEBUG_PRINT(x) Serial.println(x)
    #else
     #define DEBUG_PRINT(x)
    #endif

Defining `true` and `false` as Boolean to save RAM

    Instead of using `const bool true = 1;` and same for `false`

    #define true (boolean)1
    #define false (boolean)0

---
A lot of it comes down to personal preference, however it is clear that `#define` is more versatile.

  [1]: https://forum.arduino.cc/index.php?topic=44023.0


body:
1. > You can't set array sizes using `const int`.

   You can with `constexpr int`:

   ```
   constexpr auto size{ 15 };
   int array[size]{};
   ```
2. > You can't use `const int` as case statement labels (though this does work in some compilers)

   Again, you can with `constexpr int`:

   ```
   constexpr auto zero{ 0 };
   constexpr auto one{ 1 };

   int number{ 1 };
   switch (number)
   {
   case zero: Serial.println("zero!"); break;
   case one:  Serial.println("one!"); break;
   default:   Serial.println("neither!"); break;
   }
   ```

3. > You can't initialize a `const` with another `const`.

   You can even initialize a `constexpr` with another `constexpr`:

   ```
   constexpr int x{ 1 };
   const     int y{ x };
   constexpr int z{ x };
   ```

Furthermore, `constexpr` guarantees that the variable gets evaluated at compile-time, unlike `const`. `constexpr` also doesn't have some of the disadvantages that preprocessor macros have<sup>([learncpp](https://www.learncpp.com/cpp-tutorial/const-constexpr-and-symbolic-constants/))</sup>:

1. Debuggers like Visual Studio's don't let you *watch* preprocessor macros.
2. Macros can conflict with normal code.
3. Macros don't have scope, which increases the chance of naming conflicts.


message:
How to switch an external circuit with Arduino?

I have an object with a series of led and I want to turn on and off these leds from my Arduino. The input of the LED circuit is 24v DC 100mA.

What I've done is the following:

- I've cut a wire of this object and I connected one end to the collector and the other end to the emitter of a NPN transistor
- I connected the base of the transistor to a digital output (through a 1k resistance)
- I connected the power to the led series while the digital pin was LOW (actually completely disconnected)

**But with no current on the base of the transistor, the LED has turned on to my surprise.** I may have completely misused the transistor and other items. How do I fix this circuit?

body:
If I understand your writeup correctly, this is what you have built:

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

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

<!-- End schematic -->

What you didn't mention in your question is that you made a connection from Arduino ground to the base of the transistor and the seconds circuit's ground connection. I drew the extra lead 'loose' for illustration only, but you see where it should connect. Current needs a return path, it is not sufficient to only have the forward path (from Arduino through R1 and base-Q1). The return path is emitter-Q1 to Arduino-GND.

Do notice though that the two batteries / power supplies must be floating with respect to each other otherwise you're going to short them out.


message:
Is it better to use c_str or toCharArray?

When reading/trying a [recent answer][1], I was surprised to see that Arduino's `String` class supports the `c_str()` method, just like the C++ `std::string` class. As expected, it appears to get a pointer to the string's contents as a null-terminated `char` array (i.e. C-style string).

However, (as far as I can see) that method is not mentioned in the official Arduino documentation. Additionally, in all example code I've seen using `String`, a different approach seems to be used. A secondary `char` buffer is setup, and then the contents of the string are copied to it using [`String::toCharArray()`][2]. This obviously requires double the memory, plus an O(n) copy operation.

It seems like `c_str()` should be the preferred approach. Is there some reason why `toCharArray()` is more commonly used?

  [1]: https://arduino.stackexchange.com/a/511/42
  [2]: http://arduino.cc/en/Reference/StringToCharArray

body:
> It seems like `c_str()` should be the preferred approach. Is there some reason why `toCharArray()` is more commonly used?

basically, I'd say it's a lack of knowledge from the people doing the codes you've seen. Definitely `c_str()` is better. Though, what I see even more often is the use of character arrays `char*` strings instead of `String` (and I plead guilty of that as well in my own codes).

And that's because the Arduino library has been built upon a messy set of C and C++ libraries and coding style. Trying to make things easier actually messed them up and complicated them more.

That's actually why we have new projects like [xpcc][1] trying to make a real and smart use of the C++ abilities in the embedded world.

[1]:http://xpcc.kreatives-chaos.com


message:
Arduino Yun external antenna

Can someone help me understand how the external antenna IPX connector actually stays connected to the Yun? Do I have to "force" it in so it snaps in? I've been somewhat gentle with it in fear I'll break something. However when I get close to getting it in, it just pops back out.

I've never worked with an IPX connector before, and I'm trying to not break anything.

EDIT: I may have figured this out. Looks like the socket on the Yun is an IPEX socket, which is female. The cable I have is an IPX/uFL/u.FL connector, which also appears to be female.

It looks like I need to use an MCX cable adapter as found here: http://www.adafruit.com/products/1532 If someone could confirm this for me, that'd be great.

Here's a picture of the cable I purchased and my Yun.
![enter image description here][1]

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

body:
There's a discussion on the Arduino Forum about this:

[Mystery component on Yun board?][1]

From what I read it's only for testing purposes.

> the connector is a MM8430-2610 ([see this][2]). You can plug in a
> MXGS83RK3000/MM126036: once plugged in, the switch connector will turn
> the internal antenna off and use the probe as an external antenna

  [1]: http://forum.arduino.cc/index.php?topic=188976.0
  [2]: http://www.murata.com/products/catalog/pdf/o33e.pdf


body: Testing with my Yún, it took quite a bit of force to install the connector. I had to use pliers to get extra leverage, but it eventually snapped in place.


body:
I went through this last night.  I got the adapter cable [ .../852] and antenna from Adafruit.
It appeared to be hard to snap into place, but it did go.
**It did not improve performance** though when testing signal strength with the Example>Bridge>WiFiStatus

Which leads me to believe that the connector didn't mate -or- I damaged it -or- it isn't the proper connector.
I am thinking the latter is the case.
Still looking for the answer.

Jim

I bought:
1 ea.     RP-SMA to uFL/u.FL/IPX/IPEX RF Adapter Cable     $3.95
http://www.adafruit.com/products/852
1 ea.     2.4GHz Dipole Swivel Antenna with RP-SMA - 5dBi     $8.95
http://www.adafruit.com/products/945


body:
I have several old mini-pci mini-pcie wifi cards laying around and the poster is correct: for some reason, they put the female end on the board whereas any wifi antenna you pull from a laptop, the cable will be female; all of my cards are the male version of the port on the YUN.

I can actually snap my old wifi cards onto the YUN's antenna port and they snap together perfectly just like the cable does in the laptops they belong.

For hobbyists, an old laptop wifi antennas are something we all have.

Why they did this I don't know.


body: @Jim was very close, the /851 part is the female to work with that connector. I have an adafruit Flora GPS with the same thing, a male connector on the board. I asked Adafruit for the adapter lead for it and they said the SMA to uFL #851 was what I needed. I just tried it on my shield and it fits.


message:
What design patterns can I use to handle user input and display updating?

I've used enough products with embedded microcontrollers and unresponsive UIs to know that it can make or break a product. Even a slight delay or lag between the button presses and the display updating, or button presses being ignored or double counted, can be extremely frustrating.

What design patterns can be used to deal with user input (from buttons) and updating displays without causing these issues?

I currently use the following kind of pattern (this is simplified down to the bare minimum):

    #include <Bounce.h>

    #define GREEN_LED   6 // Pin for green LED

    #define BUTTON_PIN   15 // Pin for button - uses external pull down so active high

    #define DISPLAY_REFRESH_INT 100 // How many MS between display updates

    Bounce button = Bounce(BUTTON_PIN, 5);

    // To signal between the button read and the display update
    bool ledState = false;

    // Used to keep track of last display update
    long displayUpdate = 0;

    void setup()
    {
     pinMode(GREEN_LED, OUTPUT);
     pinMode(BUTTON_PIN, INPUT);
    }

    void loop()
    {
     // Read the button status
     if (button.update())
     {
      if (button.risingEdge())
      {
       ledState = !ledState;
      }
     }

     // Update the display periodically
     if (millis() - displayUpdate > DISPLAY_REFRESH_INT)
     {
      displayUpdate = millis();

      digitalWrite(GREEN_LED, ledState);
     }

    }

What other options are there? Is it ever worth using pin change interrupts to read buttons (if we are not considering battery life!).

body:
The answer depends on exactly how the sketch is meant to respond to the user interaction.

**External interrupts**
If the interaction depends on responding very accurately to the rising or falling edge of an input event (as in your example), then an [external interrupt][1] may be the way to go, if possible.

This is particularly important if the input event might be shorter that the duration of a call to `loop()`. If that happens, consecutive attempts to poll the input could completely miss the state change. It's quite rare for a user input event to be that short though, unless `loop()` is quite slow to execute.

External hardware to get help that though, e.g. by having an input which latches until it is read and reset by the microcontroller.

**Improving polling frequency**
External interrupts often aren't possible (e.g. because the chip only supports a limited number), or they are simply overkill/unnecessary for a given application.

In those cases, it may still be possible to improve the timing precision when using polling. One option is to split up all the different parts of the main loop into separate functions. On each successive iteration of `loop()`, it will call the next function, and then wrap round to the first. In between each of those functions, it can poll the button. Here's a simple example:

    unsigned int g_section = 0;

    void setup() { }

    void pollButton()
    {
        //...
    }

    void runSection0()
    {
        //...
    }

    void runSection1()
    {
        //...
    }

    void runSection2()
    {
        //...
    }

    void loop()
    {
        // Poll the button on every pass:
        pollButton();

        // Execute the next section of the main code:
        switch (g_section)
        {
        case 0: runSection0(); break;
        case 1: runSection1(); break;
        case 2: runSection2(); break;
        }

        // On the next iteration, run the next section:
        if (++g_section > 2) g_section = 0;
    }

One important issue with this approach is that it's very difficult to make each of those `runSectionX()` functions take the same execution time. That can result in the button being polled inconsistently from one iteration to the next. If it's fast enough though, then it shouldn't be too big of a problem.

**Display update**
Updating a display is unfortunately often quite slow, compared to many other operations. That means you need to be quite careful where you do it. Inside an Interrupt Service Routine often wouldn't be appropriate, as that could introduce other timing issues in your sketch.

Realistically, you'd have to do it in the main loop. If you absolutely have to run it quickly though, then it can be included in the faster polling example I've given above -- i.e. update the display on every iteration, the same as polling. You have to be careful to avoid partial updates though.

  [1]: https://arduino.stackexchange.com/questions/316/can-a-function-be-called-automatically-when-an-input-changes/317#317


body:
You could interrupt instead of polling if you can de-bounce the buttons in hardware. Otherwise you'll be take many more interrupts than there were button presses and still have to de-bounce them in software.

But to the primary question, a collection of state machines can be very useful, at least for the ui, and give you most of the benefits of multi-tasking without needed a m/t kernel.  can be  in RAM limited devices, unfortunately, because

The technique could be especially useful on these small devices but for the severe limits on RAM, making it something of a challenge to divide your state-machine data between flash and RAM, to fit.


body:
For program control, I made something of a menu handling framework for one of my projects and [shared the source on Github][1]. *Note that this is for chipKIT but the menu handling code is generic.* After building my 3rd or 4th huge if-else-if and switch structure, I decided there had to be a better way. *[Credit for the source of the static menu structures.][2]*

I just use the main loop to check the button.

I'm wanting to say the first step is to get a TFT. If you try it, you'll never go back... I particularly love the Adafruit 1.8" TFT with joystick. Arduinos are slow enough that I cannot recall caring to debounce user input.

  [1]: https://github.com/cacycleworks/chipKIT_ST7735/blob/master/Libraries/ST7735/examples/simpleMenu/simpleMenu.ino
  [2]: https://github.com/cacycleworks/chipKIT_ST7735/blob/master/Libraries/ST7735/examples/simpleMenu/menu_credit.txt


body:
As Chris K i've also implemented a static menu library with a wide variety of output options like Serial,LCD,TFT, etc..
I've started it to help in a friends project and I'm also sharing it open source for people that with similar problems, hope you can find it useful.

https://github.com/neu-rah/ArduinoMenu


message:
What is the difference between declaring a variable outside of loop and declaring static inside loop?

These are two ways I can hold a variable outside of loop (or any function).

First, I can declare it with global scope outside of loop:

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

    int count = 0;

    void loop()
    {
     Serial.println(count);
     count++;

     delay(250);
    }

I can also declare it static inside the loop:

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

    void loop()
    {
     static int count = 0;

     Serial.println(count);
     count++;

     delay(250);
    }

What difference, if any, will this make?

body:
The most basic difference is of scope.

In the first case, you are declaring a global variable. It is a variable that is accessible in every scope after its definition.

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

    void inc();
    int count = 0;

    void loop()
    {
        Serial.println(count);
        count++;

        inc();

        delay(500);
    }

    void inc() //Can edit the value of count
    {
      count=count+1;
    };

In the second case, you are declaring a static variable with local scope. The variable will persist for the entire program run similar to global variables, but will be accessible only in the code block it is declared in. This is the same example, with only one change. `count` is now declared as a static variable inside `loop`.

    void inc();

    void loop()
    {
        static int count = 0;
        Serial.println(count);
        count++;

        inc();

        delay(500);
    }

This will not compile as the function `inc()` does not have access to `count`.

Global variables, however seemingly useful, come with some pitfalls. These can even cause damage when it comes to writing programs that can interact with the physical surroundings. This a very basic example of something that is quite likely to happen, as soon as programs start getting larger. A function may inadvertently change the state of a global variable.

    void setup()
    {
        Serial.begin(9600);
    }
    void another_function();
    int state=0;

    void loop()
    {
        //Keep toggling the state
        Serial.println(state);
        delay(250);
        state=state?0:1;

        //Some unrelated function call
        another_function();
    }

    void another_function()
    {
      //Inadvertently changes state
      state=1;

    }

Such cases are very hard to debug. *This* type of problem however, can easily be detected, by simply using a static variable.

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

    void loop()
    {
        static int state=0;

        //Keep toggling the state
        Serial.println(state);
        delay(250);
        state=state?0:1;

        //Some unrelated function call
        another_function();
    }

    void another_function()
    {
      //Results in a compile time error. Saves time.
      state=1;

    }


body:
From a functional perspective, both versions generate the same result, since in both cases the value of `count` is stored between the executions of the `loop()` (either because it is a global variable or because it is marked as `static` and therefore keeps its value).

So the decision which to choose come down to following arguments:

 1. Generally, in computer science, it is encouraged to keep your variables as local as possible in terms of **scope**. This usually results in much clearer code with less side-effects and reduces chances of someone else using that global variable screwing up your logic. E.g. in your first example, other logic areas might change the `count` value, whereas in the second, only that particular function `loop()` can do so.
 2. Global and static variables always occupy **memory**, where as locals only do when they are in scope. In your above examples that makes no difference (since in one you use a global, in the other a static variable), but in bigger and more complex programs it might and you could save memory using non-static locals.
*However*: If you have a variable in a logic area that is executed very often, consider making it either static or global, since
    otherwise you loose a tiny bit of performance each time that logic
    area is entered, since it takes a bit of time to allocate the memory
    for that new variable instance. You need to find a balance between memory load and performance.
 4. Other points such as better layout for **static analysis** or **optimization** by the compiler might also come into play.
 5. In some special scenarios, there might be issues with the unpredictable initialization order of static elements (not sure about that point, compare this [link][1] though).

Source: [Similar thread][2] on arduino.cc

  [1]: http://forum.arduino.cc/index.php?PHPSESSID=nt8h6685309s1vv0voea1rbkd5&topic=74180.msg559158#msg559158
  [2]: http://forum.arduino.cc/index.php?PHPSESSID=i4sdu9bn0f8u2jekn5tl5pbeo1&topic=74180.msg559208#msg559208


body:
Both variables are static - they persist for the entire execution session. The global is visible to any function if it declares - not defines - the global, or if the function follows the definition in the same compilation unit (file + includes).

Moving the definition of `count` to inside of a function both limits its scope of visibility to the nearest enclosing set of `{}`es, and gives it function invocation lifetime (it is created and destroyed as the function is entered and exited). Declaring it `static` as well gives it execution session lifetime it exists from the start to the end of the execution session, persisting across function invocations.

BTW: be cautious about using initialized statics within a function, as I have seen some versions of the gnu compiler get this wrong. An automatic variable with an initializer should be created and initialized on every function entry. A static with an initializer should only be initialized once, during the execution setup, before main() is given control (just as a global would be). I have had local statics get reinitialized on each function entry as though they were automatics, which is incorrect. Test your own compiler to be sure.


message:
How to debug an Arduino sketch on a Mac?

I have 2 Lowpowerlab WaterMote's talking to each other using the 'out of the box' pre-installed [sketch][1] that just confirm they're talking to each other. I verified this by opening a COM connection and saw traffic of 'receiving packets...' That was just to show that they are functioning and talking to each other.

Now, using Arduino IDE on Mac OS X 1.9.x (Lion?) I have loaded the WaterMote sketch (found on [Github][2]) on the Moteino with the sensor (not the gateway) as it should be. The traffic looks like it's working, except the text being transmitted (number of Gallons) stays the same at 0.02 Gallons.

So... I want to debug the WaterMote sketch, *but* I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).

My current setup

 - Moteino Gateway (as out of the box) connected to a [Raspberry Pi][3] (with ssh enabled)
  - Connected via USB to the RasPi
 - Moteino with WaterMote sketch loaded
  - Connected via USB to the MacBook Pro
  - Arduino IDE running, but I see strange "[][][]" square output in the Serial connection.
  - I do not know what to make of this since that text is not in the WaterMote sketch.

Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?

I found a debugging article:

 - [Visual Micro][4]

  [1]: http://www.arduino.cc/en/Tutorial/Sketch
  [2]: http://en.wikipedia.org/wiki/GitHub
  [3]: http://en.wikipedia.org/wiki/Raspberry_Pi
  [4]: http://www.instructables.com/id/Arduino-Debugging-Breakpoints-Tracepoints-and-E/

body:
> So... I want to debug the WaterMote sketch, but I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).

It's definitely possible to debug a sketch with OS X. But it's definitely an advanced AVR topic, and if you're not experienced enough with embedded programming you should first try to avoid it, except if it is really necessary.

Debugging a sketch for an [ATmega328][1] implies:

 - Running a flasher such as the AVR Dragon, the JTAG ICE 3, the STK500 or the AVR ONE; no cheap flasher implements the `DebugWire` protocol;
 - Setting up the debug fuse, which is an operation that can brick your [MCU][2].

If you're using an [ATmega32U4][3] (or alike), you won't be able to do it out of the box, as the 32U4 needs a [JTAG][4] connection for on-chip debugging.

Finally, once you got through that, you can bind a `gdb` to the AVR using [AVaRICE][5]. I'm not getting you through all that, because I really, really, strongly advise you not to do it until you're experienced enough to know what you're doing.

>    Moteino with WaterMote sketch loaded
>        connected via USB to the MacBook Pro
>        Arduino IDE running, but I see strange "[][][]" square output in the Serial connection.
>        I do not know what to make of this since that text is not in the WaterMote sketch.
> Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?

It is very likely you did not setup the correct baudrate for the serial outputs. Arduino IDE defaults to 9600 bits/s connections, whereas the [WaterMote source code][6] defines a 115,200 bits/s connection. When you open the `Serial Monitor` change the setting at the right of the status bar.

And finally, be sure to uncomment the [`#define SERIAL_EN` line][7] to enable the serial communication and debug outputs.

  [1]: http://www.atmel.com/devices/atmega328.aspx
  [2]: http://en.wikipedia.org/wiki/Microcontroller
  [3]: http://www.atmel.com/devices/atmega32u4.aspx
  [4]: http://en.wikipedia.org/wiki/Joint_Test_Action_Group
  [5]: http://avarice.sf.net
  [6]: https://github.com/LowPowerLab/WaterMote/blob/master/WaterMote.ino#L31
  [7]: https://github.com/LowPowerLab/WaterMote/blob/master/WaterMote.ino#L30


message:
Why are the files not being created correctly?

I have been through http://arduino.cc/en/Hacking/LibraryTutorial but I can't do it. Whenever I create a new sketch and try to save it as `.cpp` or `.h` from the <kbd>Save As</kbd> button in the Arduino IDE, it gets saved as `_cpp` and `_h`. I am not able to create a library this way. How do I create a new library? What am I missing here?

body:
When you save a file using the Save As button from the Arduino IDE, it saves the current file as a sketch i.e. as an `.ino` file.

To create a `.cpp` and `.h` files for working on a new library, you need to create the files alongside a sketch. For this, you can use the Tab button on the top right (circled in red).

>![enter image description here][1]

Click on it, and select New Tab. You will get a bar at the bottom of the screen asking for a file name. Enter the name with extension (`test.cpp`) and press Enter.

>![enter image description here][2]

Your file has now been added to the current directory.

>![enter image description here][3]

Similarly, follow the same steps for creating the `.h` file.

Once your library is complete and ready to ship, you can move the `.cpp` and `.h` files to a separate directory and then add it under libraries.

  [1]: https://i.stack.imgur.com/lya7P.png
  [2]: https://i.stack.imgur.com/5cIWe.png
  [3]: https://i.stack.imgur.com/1Cp0V.png


message:
What are the tools that I need to program the Arduino in C?

The Arduino IDE by default is oriented towards C++. The linker for example requires `.cpp` files and not `.c` files, otherwise it leads to errors during the linking process. See [name mangling][1] if you want to know more.

So, what are the tools that I need to setup a C environment? Can this be done from the Arduino IDE itself?

I work on a Linux system (Ubuntu 12.04).

  [1]: http://en.wikipedia.org/wiki/Name_mangling

body:
Well, if you want to do more advanced stuff with your AVRs, you should definitely leave the Arduino environment, and integrate your AVR development in your "usual" favorite development environment, whatever it is.

Then you've got two choices, either do 100% pure C with AVR libraries, for which you only need a simple makefile that calls avr-gcc with avr-libc libraries as include path. You can also use Atmel Studio that helps you a lot on that stuff. But if you do so, you're loosing the advantages of the libraries built for/by the arduino community – which, sadly, is not a huge loss for a strong majority of those.

Or you can work your code out as a 100% C external library, used from within the sketch, and included at linking time. Then you'll have all the advantages of working with any C++ library you'd like to have, but still doing the important code in pure C. Having only the `.ino` used to generate the main `.cpp` and any `.cpp` library you'd need. Though, for many basic features like writing on the serial port, you'll have to do it [the good old way][2] or by doing some weird encapsulation of `Serial.println()` call sent as a functor to the pure C parts.

In the [makefile][1] I've written (debian offers another one with the non-gui install of arduino), every `.c` file from declared libraries are detected and compiled with avr-gcc, every `.cpp` file is compiled with `avr-g++` and both gets linked when doing the `.elf`/`.hex` file.

[1]:https://github.com/guyzmo/Arduino-Tools/blob/master/Makefile


body:
Take a look at [ino][1] on linux and PCs and Mac.  It's available in the fedora repos, not sure about other distros; though, I'm sure everyone can install it from the [github project site][2], regardless of the distribution.  According to the website, you can also install it with python setup tools:

    pip install ino
or

        easy_install ino

*BTW: sorry for not including this "answer" in a comment due to reputation restrictions.*

Here's the description from the fedora repos; I think it's taken directly from the `ino` tool website:

>     Summary     : Command line toolkit for working with Arduino hardware
>     URL         : http://inotool.org/
>     License     : MIT
>     Description : Ino is a command line toolkit for working with Arduino hardware.
>                 :
>                 : It allows you to:
>                 : Quickly create new projects
>                 : Build a firmware from multiple source files and libraries
>                 : Upload the firmware to a device
>                 : Perform serial communication with a device (aka serial monitor)
>                 :
>                 : Ino may replace Arduino IDE UI if you prefer to work with command line and
>                 : an editor of your choice or if you want to integrate Arduino build process
>                 : to third party IDE.
>                 :
>                 : Ino is based on make to perform builds. However Makefiles are generated
>                 : automatically and you'll never see them if you don't want to.

  [1]: http://inotool.org
  [2]: http://github.com/amperka/ino.git


body:
> The linker for example requires .cpp files and not .c files, otherwise it leads to errors during the linking process

No, it doesn't.

---

> So, what are the tools that I need to setup a C environment?

Why do you want to?

---

**The answer**

Make a new tab in the IDE (top RH corner). Call it, for example, foo.c. That's your C file.

Put whatever C code you want into it. For example:

    #include <Arduino.h>
    void foo ()
    {
    PORTD = bit (1);
    }

Now in your "main" sketch call that function, eg.

    extern "C"
     {
     void foo ();
     }

    void setup ()
      {
      foo ();
      }  // end of setup

    void loop ()
      {
      }  // end of loop

Repeat as required for any C functions you care to write.

Of course, you can't use Serial (that's a C++ class) or Wire (that's a C++ class) or SPI (that's a C++ class), but if you want to work with C, you can certainly do that.


body:
You're already there with the Arduino IDE; C++ compilers understand plain C just fine, but may interpret C syntax slightly differently in some cases. I write most sketches in C, invoking C++ objects from libraries as necessary.

If you're to the point where you want finer grained control over which compiler, C or C++, gets used for a given module, then it's time to graduate to another environment. Eclipse is a very popular and flexible IDE for a large range of languages, compilers & cross-compilers, and provides a very flexible Arduino environment. Or your favorite shell, programming editor, Make, and the avr-gcc cross-compilation tool-set will give you the ultimate access to and control of every detail - perhaps more than you wanted - of the edit/compile/link/download/debug process.


message:
Arduino + IMU vs ArduIMU

I am working on a UAV and we are currently exploring inertial measurement units or IMUs. The two options that we have come across are:

- Using an Arduino Uno and a 9 DOF IMU like [this one][1]
- Using an ArduIMU chip like [this one][2]

Ignoring the cost aspect and assuming the same microprocessor on board, what would be the pros and cons of either of these approaches?

Keep in mind that performance is very important for a UAV controller as ESCs require 60 Hz or higher refresh rates for stable flight.

  [1]: https://www.sparkfun.com/products/10724
  [2]: https://www.sparkfun.com/products/11055

body:
**Weight:** marginal as the difference between one board (with everything on it) and two boards (Uno plus DOF) may be - for model airplanes every bit counts.

**Size:** the traditional "Uno" is much larger than the ArduIMU integrated boards.

**Power:** the integrated board PROBABLY will use less and thus get away with a smaller (lighter) battery.


message:
How to trigger an alarm when toilet paper is low?

Anyone with kids knows they never help with the toilet paper. Anyone know how to track when it's low or out and sound an audible alarm? I just don't know what sensor to use that may help.

Some that came to mind are: by weight, by reflection (the color of the paper) or some laser tripwire - all right on the spool. I don't mind building it, it's just I don't know which sensor. Anyone know which to use?

body:
One idea that comes to mind would be something like that:

- stick a small magnet inside the paper roll, i.e. inside the cardboard part (this has to be done every time you change it; though)
- use a reed contact (electro-magnetic switch) at the tip of a stick mounted with a spring to be always in contact with the paper roll
- one pin of the reed contact can be directly connected to an input logical pin (set it up as a pullup resistor input)
- the other pin of the reed contact is to be connected to the ground

Thus, as soon as the distance between the magnet and the reed contact is under some limit, the switch will close the circuit. That distance will decrease while the paper roll gets drawn.

Note that, instead of a reed contact, you may also use a Hall Effect sensor, the principles remain the same, only technology and characteristics change.

The difficulty here will be to find the right sensitivity of the reed contact (or the force of the magnet) so that the reed contact gets closed when the distance between it and the magnet is small enough to avoid an alarm that would be activated too soon).


body:
## You have a few options:

Note: The links given are just the first ones that come up. Most of them are pricey compared to other sites. eBay buy it nows can be fairly cheap for most of these items. Check other places, too, including [Sparkfun](http://www.sparkfun.com).

 - [Ultrasonic Ping Sensor](http://www.robotmesh.com/parallax-ping-ultrasound-sensor?gclid=CJvLqNvY9LwCFewRMwod0SQAzw). This isn't ideal by any means, but they're easy to use. Just add one with an enclosure. It isn't ideal because it won't be accurate enough to tell when exactly it's empty. It might be a little over/under sensitive. Weight would be harder, though if it shifts at all.
 - [Color sensor  (preferable, but costs more)](https://www.sparkfun.com/products/10904). You mentioned this and this is probably the best idea. It'll give you analogue values (to read with Arduino) for red, green, and blue. [Assuming that the higher the content of that color, the higher the voltage,] white should be pretty much all of those at 100% and brown I would image that most of them would be about 30-40%. (More later, if you don't understand this, skip this part)

***
**I'm going to go into more detail on the color sensor:**

Colors are read with three values here: red, green, and blue. There are three sensors on the board. One filters out everything except red, another blue, and the other green. The sensors on the board detect the amount of incoming light and then convert that to a voltage: between 5V ("100% red/green/blue") or 0V ("0% red/green/blue"). This then can be converted into a number by the Arduino (0-1024 on an analogue pin).

**A problem with lighting:**
This sensor, from what I can tell, has a LED that's always on. You'll want to either desolder that or cover it up, unless you want an illuminated toilet paper holder. Now wait... your sensor will think that when it's dark, it's brown. No problem... here's something for you mind to think about.

[Use a color picker like I'm using and select a brown](http://www.w3schools.com/tags/ref_colorpicker.asp). On the left of this one, you can control the "simulated brightness." Besides that is the hexadecimal form of RGB. You'll want to convert that to standard [values with this calcuator](http://www.javascripter.net/faq/hextorgb.htm).

In brown, the color blue is almost nonexistent. We should ignore that color, unless you want a way to double check that it's brown. I'd say it should always be under 40% for pretty much any shade of brown.

From what I can tell with a sample shade of brown, the red is pretty much 2x the green. That ratio may vary, but you should verify that it is *somewhat* existent. For white/grey/black, all the colors are proportional 1:1:1. You can use this to detect if it's dark, or if it's brown.

    int rPin = A0;      //Red Pin
    int gPin = A1;      //Green Pin
    int bPin = A2;      //Blue Pin
    int ledPin = 13;    //I made this code with a LED, not a speaker
    boolean testTwice = false;

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

    void loop() {
      int rValue = analogRead(rPin);
      int gValue = analogRead(gPin);
      int bValue = analogRead(bPin);

      if (bPin < 256) { //If this is false, either something is in the way or it's white. Going to verify that something's not in the way...
        int minRed = rPin * 0.4; //A little under a half for padding... this values may need to be adjusted. Adjust this one and the one below farther apart for less sensitive.
        int maxRed = rPin * 0.6; //A little over a half for padding... this values may need to be adjusted.
        if (gPin < maxRed && gPin > minRed) { //Verifys that red between minRed and maxRed
          digitalWrite(ledPin, HIGH);
          delay(5000);
          digitalWrite(ledPin, LOW);
        }
      }
      delay(5000); // No need to waste power... you might want to add an actutal sleep function if on battery power
    }

First, it verifies that the blue is less than 25%. Then, it verifies that the red and green are equal... give or take 20%. (i.e. red = 100 green = 80, red = 110 green = 90, etc.). If that is true, you can pretty much establish that it's brown. Then, a LED turn on for five seconds.

You can modify the LED to be a buzzer if you want. You might have to adjust the if statement with verifying that the blue is less than 256/1024 (1024 = resolution of analog pin) if it isn't working in a lot of light or is working in dark light. Since the code later verifies that the red is about 2x the green, any shade of white shouldn't pass that if statement. You may also have to adjust the `minRed` and `maxRed` to be farther (if not detecting brown) or closer (if detecting brown when it's white). I can't really test this code with no color sensor.
***
Note: these can be a little fidgety. **I would recommend a LED instead** so the whole house isn't woken up in the middle of the night just because of low toilet paper. Also, if you obstruct the sensor at all... If it wasn't in the bathroom, I would recommend a camera and have it take a shot every time it gets very low with a reed switch like @jfpolipret's answer... but... (no pun intended) :)


body:
An short-range ultrasound distance sensor might be an effective (and fairly cheap) option. You can get an emitter+sensor combination mounted on a chip. Different sensors may work in different ways (always check the datasheet). A common output though uses the length of a pulse to indicate the distance sensed. You could process that in Arduino using the [`pulseIn()`][1] function.

In terms of installation, you'd probably fit it directly behind the toilet paper, pointing at the centre of the spool. The readings are often quite erratic, so you want to take several measurements and average them (or use a simple moving average). With a bit of calibration, you could determine what distance represents an empty spool.

When you detect that distance repeatedly for a significant period (e.g. a minute or more), you'd sound the alarm.

A reflectance-based sensor might be another possibility, although I wonder if you might struggle to find one which will work properly on toilet paper (depending on how soft your preferred brand is!).

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


body:
Bring up several rolls at a time and hang one for use. Put the other two on a short vertical pole within reach of the sitter. Sitter can take another roll when needed.

Mechanically sense lack of weight on the shelf at the bottom of the pole. Alarm triggers when the last roll is removed. No one has to get caught short.

To sense the weight use a force sensitive resistor such as the [FSR 400][1] (see [datasheet][2]). Alternatively, you could use a lightweight coil spring to rest the toilet paper on with a micro switch that is released when both rolls are removed. Another option would be an IR beam break detector where the circuit is completed when the last roll is removed.

  [1]: https://www.sparkfun.com/products/9673
  [2]: http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/ForceFlex/2010-10-26-DataSheet-FSR400-Layout2.pdf


body:
Sounds like a cool project, here are my 2 ct:

Point a camera to take photos of the roll from sideways, that is probably the only way to really find out how much paper is left. (edit: You could use a raspberry pi with the csi camera and create an output signal corresponding to the number of sheets and feed that signal to the arduino?!)

For an estimate it might also be enough to count rotations of the roll, but you need to fiix the roll better so it doesn't slip. Or you can use magnets like you do on bicycles, but they need to be attached to the roll directly then.

(edit: one more idea, mesure the thickness of the roll by measuring the angle of the lid)


body:
Use a radiation detector to detect the amount of paper left on the roll. Place some amount of radioactive material in the middle of the spool rod, and place the radiation detector somewhere else (you could mount it on the other side of the surface the roll holder is mounted to, if you want; radiation sensors are extremely flexible), and measure the radiation amounts to determine how much paper is left on the roll.

Alternately, you could have an electronically controlled toilet paper dispenser (push button to dispense a preprogrammed length of toilet paper) and have the arduino just keep track of how much has been dispensed.

Or, attach a rotary encoder to the side of the spool rod (make sure it fits without slipping inside the roll), and count the rotations of the roll to determine how much has been used.

Of course, with any of these methods, you will have to do tests and collect data  depending on the exact type/brand/material/etc of toilet paper.

Especially for the second and third ideas, I would recommend taking data from the system regularly, to keep track of the typical length of a roll so you can adjust the program for any significant variation. Even within one type of toilet paper, I would imagine that there would be some variation in roll length.

For even more fun, you could instrument the detector to collect time series data, so later you can upload it to a computer and make a "toilet paper usage over time" graph or something.


body:
The simplest, yet best solution afaict, would be to use an optocoupler made of one IR LED and an opto-transistor. You make the LED lighten towards the roll, the LED being within the roll tied to the "handle". Once you remove the cardboard roll, the opto-transistor gets the IR light from the LED and triggers a pin change interruption on the Arduino, which can then alert you through many ways (light, SMS, twitter, alarm…).

That design is really cheap, easy and fast to build. Though there's still one thing you need to do: when there's no more toilet paper, you need to actually have the cardboard roll *removed* ;-)

Otherwise, the same kind of solution for the spare rolls is even a better idea :-)


body:
I think I saw this in series 1 episode 2 of James May's Manlab.

Similar to jfpoilpret, use a wide piece of material on a spring that makes contact with the roll at all times. I say 'wide' so that when the roll is empty the reed touches with a contact on one of the roll holders on the side. When it touches it completes a circuit to your alarm.

Here's a crude image describing what I mean.

In Arluin's response it was mentioned that this method would not show that the the roll was empty. Thats pretty much true. If the top contact is as thick as the TP cardboard roll and the bottom contact is positioned inside the inner part of the cardboard roll it should get close enough for practical purposes. One foot of TP roll is not enough after taco night.

![Behold the image of my imagination][1]

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


body: Your best option is attaching a rotary encoder to the side of the roll, and count the rotations of the roll to determine how much has been used. Once you know the number of rotations per roll,you can set where you want your notification to fire. Attach it to a logging system of sorts and you'll have historical data of paper use as well as toilet use.


body:
I believe the reed sensor concept put forth by jfpoilpret and jmathew is the easiest to accomplish. I have drawn a diagram of how I think it would look.

You could adjust sensitivity by adjusting the height of the lower contact.

This really only gets you to a "low" condition and not necessarily out. Unless you want to change rolls while there are still a few sheets left this doesn't seem to me to be a satisfactory solution. I'd rather have an "out" indicator and have an audible buzzer to prompt/shame the user into replacing the roll.

This design could be accomplished using standalone electronics (no arduino needed). However it you wanted to gamify the changing of the roll you could use an arduino for that.

Note also for color based optics sensors, while the vast majority of cardboard tubes used for this purpose are brown, I have seen white ones in use as well.

![Reed Sensor Diagram](https://i.stack.imgur.com/CY76e.png)


body:
I built a reflectance tachometer for an Arduino that'd probably solve your problem.
The basic circuit is quite simple:

![tachometer circuit][1]

I had a photoransistor laying around that responded well to red light, and [another from Radio Shack][2] that was quite sensitive to the IR output of old TV remote LED's.
For your purposes, green wire would be hooked up to Analog Pin 0 of Arduino, and you just have to sample periodically, not set up an interupt driven sketch.
The trick to getting a reflected signal difference between white paper and grey roll is knowing that light sensitivity of a photransistor increases w increasing resistance to GND, but the dark voltage also goes up. I came by the 5 and 3 megohm values empically, by checking the AtoD values off dark and light objects at a distance of a few inches from the detector. Same procedure should work for your detection of grey vs white. Although some things that look quite different visibly have the same reflectance in IR. Here's a pic of the finished red light tachometer:
![enter image description here][3]

It should be simple to make the sensor board small enough to fit into the back of your paper dispenser. IR version is even smaller, but buried too deeply in a home-built centrifuge to get a pic of it today.

  [1]: https://i.stack.imgur.com/IOohy.png
  [2]: http://www.radioshack.com/product/index.jsp?productId=2049724
  [3]: https://i.stack.imgur.com/TlJjj.png


body:
I think another decent and cheap option to use is a proximity sensor like the ones on the phone or a fixed field infrared sensor. These sensor are pretty accurate and can easily be used to "look" at the back of the toilet roll by mounting the sensor to the holder or the wall where the toilet roll is placed.
All the other ideas I saw on the post were either fairly inaccurate or felt intrusive towards the toilet roll which in the long run I feel may provide contamination.
A proximity sensor is not only fairly cheap and easy to use, if calibrated well, they can allow a very good amount of accuracy and reliability. This model is already in wide usage in men urinals to auto-flush.
For example on your phone: Your phone will accurately provide a distance of 2.0 inches or infinity when your hand or your face is near the screen.


body:
A lot of the options here seem overcomplicated and intrusive.

Color Sensor

Another option, slightly complicated (but fun) to implement, but unintrusive and easy-to-install, is to build a cheap [color sensor][1] and mount it on the wall behind the roll. When you detect the color of the roll (or the absence of the color of TP), it's low.

You can also just [buy one for $8][2].

You can adjust the threshold by taking advantage of the thinness of TP and the fact that it starts to look a little darker when there's only a few sheets left.

If necessary, calibration can be done by pressing a button after a new roll is installed with the bathroom lights on.

You would have to make a few adjustments depending on the specifics of your bathroom. If you added some extra complexity and powered it off an AC outlet that was tied to the bathroom light switch, you could only have it powered on when the bathroom lights were on, which would filter out a lot of unreliable data.

This is very easy to install and doesn't involve modification to the roll itself. You could stick the sensor to the wall with double-sided tape, or put it on a tiny shelf under the roll facing up (or on top facing down).

IR beam break

Mount a small IR LED on one side of the dispenser, just above the spool. Mount an IR photo sensor on the other side of the dispenser. When the sensor sees the LED, the roll is low. Could be done with a cheap laser too (e.g. an off the shelf laser pointer on one side and a photosensor on the other; but don't hurt your eyes!)

This is also easy to install (e.g. hot glue to dispenser) and doesn't involve modification to the roll, although the location of the sensors might make them easy to damage when you're replacing rolls.

I also really like the reed sensor and range sensor (BTW: [$10 gets you a great short range distance sensor][3]) options here.

  [1]: http://www.instructables.com/id/Introduction-29/
  [2]: http://www.dfrobot.com/index.php?route=product/product&product_id=540#.UxctDPldWSo
  [3]: http://www.adafruit.com/products/466


body:
Another way to do it, in case you just want to for the fun of it would be to put a metal rod inside the roll, and a metal plate on the outside, and measure the capacitance which should change with the TP remaining due to the dielectric constant of the paper.

But that would be taking the "scenic route" for sure. Still, the Arduino can measure capacitance pretty easily and it might even be sensitive enough, and it would stay out of the way because it would just be a metal plate behind the roll and a metal rod in the roll. You might even be able to retrofit an existing holder without it being noticed.

An easier way would be a stick attached to the shaft of a potentiometer held up by the top of the roll. Less TP, shaft goes lower and turns the pot. Might need a long shaft for leverage because you can't press too hard without impeding the function of pulling toilet paper.

As AJMansfield suggested, Radioactivity actually is used to measure the thickness of things in industrial settings. If you really wanted to go crazy maybe you could use an extremely low energy radioactive source like a can of that weird tasting salt substitute which is a tiny bit above background levels and average over extremely long times(toilet paper shouldn't change much from hour to hour), so this could actually be a reasonable if expensive way to do things.

Infrared beam break sensors are also good, and if you position it right you could get it to block more light the fuller the roll was instead of just giving you and on or off signal.

EDIT:
Working Proof of concept of the capacitative approach. Only needs an arduino and 2 stiff wires. Precise to about an 8th of an inch, with a lot of noise. Pretty sure you could reliably get at least 1inch accuracy. Measurement time is about a minute. It's really sensitive to it's surroundings. You'd have to make sure anything metal within a foot stayed where it was or use shielding.

    float difference;
    unsigned long i;
    unsigned long j;
    unsigned int temp;
    volatile unsigned char blah;

    void setup()
    {
      pinMode(5,OUTPUT);
      Serial.begin(9600);
    }

    void loop()
    {
     difference =0;
     Serial.print("Measuring: ");

     for(i=0;i<100;i++)
       {
         for(j=0;j<5000;j++)
         {
           digitalWrite(5,LOW);

           temp=analogRead(A0);

           digitalWrite(5,HIGH);

           temp = analogRead(A0)-temp;
           if(temp<1024)
           {
             difference += temp;
           }

         }
         //Random delay every 5000 samples helps avoid problems with interference by staggering the samples to cancel aliasing.
         delay(random(1,50));
         Serial.print("|");

       }
       Serial.print("\n");
       Serial.print("Value: ");
       Serial.print(difference/500000);
       Serial.print("\nMeasurement Complete. Press Enter to begin another test.\n");

       while(!Serial.available())
       {
         blah = 20;
       }
       Serial.read();

    }

http://pastebin.com/2W5y81AB


body:
I think 'Arluin' and 'jmathew' have the right idea.
Use a lever resting on the top of the roll.

I would do it slightly different however.
Rather than rely on contacts shutting you can use a potentiometer.
With this system you can measure the amount left instead of simply being notified when it gets low.

With a contact such as those suggested already, you might get paper stuck in the contact as it closes and then low paper would not be detected.

(You may need a weight, shown in blue on the diagram, to push the lever down as the roll is used)

You would need to try and get the pot as close to the roll as possible for maximum swing of the pot and therefore maximum resolution of amount remaining.

Another thing you might want is some kind of roller on the end of the lever so that the paper roll can move easily with little drag where the lever contacts the paper.

![Proposed setup][1]

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


body:
You could just crack open one of those playing birthday cards and adapt the switch to the holder arm. Once you hear 'Happy Birthday" chiming from the toilet you know you're in trouble! (and because they are very low-power these things chime on forever ;-) ) I've shown a LED setup here but you get the idea...

![happy birthday][1]

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


body: I say get a weight sensor, and program it for the roll's weight. When it drops below a certain weight, start flashing an LED or make a beep.


message:
Should all unused analog input ports be tied to ground for accurate A2D measurements?

I am using the A0 port on my Arduino Uno to read the voltage output from an LM35 temperature sensor.  I observed that the reading fluctuates a lot if I leave the remaining analog input ports A1 to A5 floating. Would floating analog inputs affect the accuracy of readings on input ports connected to some signals.

body:
Any floating pin will act as an antenna, and may interfere with values around it, this is one of the major disadvantages of using analog.

To get the most accurate readings with minimal amount of interference, you can pull all unused inputs to ground.

The accuracy will not change, as the accuracy is determined by the sensor itself. However it will reduce the amount of noise / interference, which will give you more accurate readings.

These pull to grounds can be accomplished by configuring the unused analog pins as digital outputs, and setting them low.

    pinMode(A1, OUTPUT);
    digitalWrite(A1, LOW);


body:
Even if setting the unused pins to OUTPUT/LOW consumes a little bit less power than INPUT with PULLUP enabled, i guess the second option is more save.

To quote somebody else:
> If you accidentally touch a hot wire to an output set low you short-circuit your processor and frie it. If you accidentally touch a ground wire to an output set high you short-circuit your processor and frie it. If you accidentally touch either wire to an input with pull-up you won't even notice.


message:
Are there any commonly available and supported backlit, monochrome graphic LCDs with more than 128x64 pixels?

I am currently using a ST7565 graphic LCD for display in a heat pump system.

This LCD has the following characteristics:

 - 128x64 pixels
 - 2.5"x1.5"
 - monochrome, no greyscale
 - backlit
 - good viewing angles
 - serially connected (i.e. only uses a small number of pins)
 - high enough refresh rate to show animated icons
 - low cost (£20)
 - has a high-quality, maintained library
 - available from multiple sources for several years

I am finding the resolution of the screen limiting for my application. Ideally I would like a display that is exactly the same but with a higher resolution. Something between

I do not want:

 - colour (largely as the display is less visible, but also increased cost and code complexity), but red/green/blue on black would be OK.
 - a physically smaller display (all of the OLED displays are small - 2" and below) as it needs to be visible from a distance

Are there any displays that meet these requirements?

I hope that the specific requirements here mean that this is not a simple "[shopping question][1]".

  [1]: https://arduino.meta.stackexchange.com/questions/16/when-should-questions-be-considered-shopping-recommendations

body:
Here you can find a bunch of displays at [new haven display](http://www.newhavendisplay.com/oled-graphic-oled-c-119_577.html?zenid=jpvgfaffukfrnbam6l9mnkbqg1), which are big and OLED and not too expensive:

 * [2.7" 128x64 OLED](http://www.newhavendisplay.com/images/NHD-2.7-12864UCY3-front-NOBL.jpg)
 * [3.12" 256x64 OLED](http://www.newhavendisplay.com/nhd31225664umy3-p-6092.html)

Those OLED Displays have a really excellent viewing angle and can be read from far (given you accept those sizes, which are >2").

Otherwise, the biggest I know about are [LCD ones from NHD](http://www.newhavendisplay.com/lcd-graphic-c-21.html) over there:

 * [320x240 LCD with backlight](http://www.newhavendisplay.com/lcd-graphic-320-x-240-c-21_107.html)

What's good with them, it's that they can cope with production in case this is needed, their prices are decent and their product just work(cTMr). You can find the [u8g library](https://code.google.com/p/u8glib/) to run them.


message:
How can I sense when someone is sleeping with my Arduino?

## Ignore the stalker-like title.
I am thinking about creating a project with Arduino that can sense you sleep habits, when you're asleep, and how much you sleep. It would be convenient to not have to turn it on/off at night; it should know how to do this.

Some ideas that I have:

 - Motion sensor
 - Breathing patterns (if an Arduino microphone could even pick that out... I would be surprised if it could)
 - A RTC clock could assist in deciding *It's midnight. Usual, Steve isn't asleep at this time on Fridays. He's probably not sleeping now.* It won't always be there to help you, but you might be able to try to get more accurate results this way

**How can I accomplish this?** (Extra points for some sort of algorithm that can tell dozing off from a deep sleep.)

body:
I actually did something like this, using a [PIR Motion sensor][1].

The motion sensor is good enough to detect a person turning in their sleep, and my simple algorithm just counts movements per minute and when its over a threshold (found by trial and error), it sounds the alarm to wake you up.

![enter image description here][2]

The image above represents my body movements during a night. The spikes represent a high movements/minute.

> Here we see after about 30 minutes body motion was minimal. This suggests I was in a deeper stage of sleep during that time.
>
> The spike at 250 minutes (around 4:30AM) is when I woke up only to
> realize I could sleep for couple of hours longer. I recall the time
> being 4:38 when I looked at my clock and I was already facing it. This
> means I turned around to face the clock but actually "woke up" 8
> minutes later to see the time, and then turned back around (indicated
> by the shorter spike at 265).
>
> The data suggests I was not able to sleep very well (compared to the
> time period between 30 and 240 minutes) after waking up once and
> finally got up at 400 minutes (7:00AM), when I shut everything down.

Here are a couple of posts from my blog that have a lot more information.

* [Body Movement During Sleep][3]
* [Intelligent Alarm Clock Hardware][4]

  [1]: https://www.sparkfun.com/products/8630
  [2]: https://i.stack.imgur.com/pYBe3.png
  [3]: http://blog.sachleen.com/posts/1353217318/body-movement-during-sleep/
  [4]: http://blog.sachleen.com/posts/1353217790/alarm-clock-hardware/


message:
Build Infrared Camera Remote

I wish to build a remote for my Camera i.e Sony NEX 5R. It has a built in IR receiver and has several Sony as well as aftermarket remotes provided for it. Due to my interest in Micro controller design I wish to build one myself rather than use an aftermarket one.

A friend who did the same for his NEX 5 series camera posted a video of the same on Facebook, which inspired me to build my own. I plan to use an Arduino Uno R3 with the following additional components:

 - IR LED

 - NPN Transistor(for amplification)
 - Schmidt Triggers(for rectification)
 - 9 Volt Battery

Ultimately I would like to swap out the Arduino for a standalone ATmega328 or ATtiny2313 but currently I have some issues as of now:

 1. I currently do not have a schematic or a sample code which I can use. I have been trying to search the internet for the same but to no avail.
 2. I am unsure of the protocol used by my camera. I have found it difficult to find documentation on the same.
 3. How can I replace the 9-Volt battery for something smaller?
 4. I would like to use a smaller micro controller but what differences will I encounter when trying to change my code for the smaller micro controller?
 5. For such a project, will I need additional hardware?

body:
1. Using the Arduino shouldn't be any different than any other microcontroller.
2. The [IRremote library][1] is my go-to library for any IR related stuff.
3. Power shouldn't be an issue, look at the [Moteino from LowPowerLab][2] and check out his [coin cell battery tests][3]. It's definitely possible. Not with a full blown Uno, but with a bare chip, yes.
4. You want to burn the bootloader on the IC first, before you can start writing Arduino code. Check out this tutorial: [From Arduino to a Microcontroller on a Breadboard][4]. It's the same process for an ATTiny, you just have to look at the datasheet to see where to plug things into. Specifically, MOSI, MISO, SCK, and Reset pins. The [Tiny AVR Programmer][5] is also a good choice. It's meant for the 8 pin micros but it has an ISP header so you can use it for almost any chip.

This may be useful for more information about decoding IR signals:

* [EEVblog #505 - IR Learning Remote Control Hack][6]
* [EEVblog #506 - IR Remote Control Arduino Protocol Tutorial][7]

  [1]: https://github.com/shirriff/Arduino-IRremote
  [2]: http://lowpowerlab.com/moteino/
  [3]: http://lowpowerlab.com/blog/2012/12/24/moteino-coin-cell-battery-tests/
  [4]: http://arduino.cc/en/Tutorial/ArduinoToBreadboard
  [5]: https://www.sparkfun.com/products/11801
  [6]: https://www.youtube.com/watch?v=vOzaDQmAW0g
  [7]: https://www.youtube.com/watch?v=BUvFGTxZBG8&feature=youtu.be


body:
1.) I'm not exactly sure what you mean by this. What I'd recommend is a [ATMega328](https://www.sparkfun.com/products/9061) for the heart of the chip. It's what is in the Uno, so with a exception of uploading code, for this project this will cut down on the size of your project. However, an Uno will work pretty much identical. If you do want to use a chip like this, [this design](http://fritzing.org/projects/barebones-arduino) looks pretty complete. You'll probably want to move to a PCB for your final product, but since you have a little electronic experience, I assume you can solder and know about this. [Here is another tutorial for barebones](http://playground.arduino.cc/Learning/AtmegaStandalone).

 2.) Again, what do you mean by "standard?" Like protocol? If so, there's no real protocol to use. [This may be easy for a begginer](http://www.robotmesh.com/ir-kit-for-arduino?gclid=CM650djc97wCFexcMgodK0kAjQ). It's the remote and the receiver. If you want to go all geek you can also [hack an existing TV remote to do the same task](http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html). That library should take care of everything you need (see code later).

****
**A bit of code/wiring:**

The circuit will depend on what receiver you choose. Most IR receivers have one pin for 5v, one for GND, and the last one is connected to a digital pin. Again, look at the information on the specific receiver you choose.

Some sample code with the library I listed:

    #include <IRremote.h>

    int RECV_PIN = 11;        //Using pin 11 for the signal pin
    IRrecv irrecv(RECV_PIN);  //Creates a variable that will be used later to inference between library and code
    decode_results results;   //Use it to store the value of the keycode

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    void loop() {
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        irrecv.resume(); // Receive the next value
      }
    }

You'll have to run this sketch to determine the value of the button you'll use on the remote. It should print on the serial window some sort of hexadecimal value IIRC that you'll have to convert into decimal if you want to use it inside the code to compare that to the button you want to use on the remote. The post I mentioned is a great resource: go and look at it.
****
 3.) I don't recommend building a remote. Like I said, you can use existing TV remotes or buy one for this purpose. Start small, figure out how IR remotes work, and then build one later if you desire. A v2 is often required on Arduino.

 4.) Don't bother for the receiver. It *can* be bigger. If you don't know how to to program it, [this guide is a good reference](http://highlowtech.org/?p=1695). It has some files that you download to add it in the IDE to trick the IDE to think the chip is a board. Note: You'll have to program it with an Uno or similar to upload and to burn the firmware. (I would explain it more in case the site goes down, but you need the files there so it'll be pointless anyway.)

Also a quick tip: don't be afraid to ask your friend for some help. You don't need to rely on him, but if you get stuck ask him.

I don't know how to connect the Arduino to the camera, but you seem to know how to do that.


body:
Well, for your project you can simply buy/rebuild a TV-B-Gone [made by Mitch](https://cornfieldelectronics.com/tvbgone/buy.tvbgkit.php?PHPSESSID=3phhip32unp1ku0di8qe9e6od0), which he uses as a basic project to teach soldering all over the world.

You can "hack" the TV-B-Gone by adding a [TSOP4838](http://www.vishay.com/docs/82459/tsop48.pdf) that can work as an IR receiver (or use another device as a code recorder).

![TV-B-Gone](https://i.stack.imgur.com/LezO4.png)

And as you can see here the TV B Gone features an ATTiny85. A really small and nice beast.

Here you'll find the [source code](https://github.com/adafruit/TV-B-Gone-kit/tree/master/firmware) for the TV B Gone. I'm not sure what format they use for their code database though.


message:
How precise can I get Arduino using rotary encoders?

Stepper motors are often pricey for a large motor. However, with a powerful, standard DC motor and a rotary encoder, you can "simulate" a stepper motor. **How accurate are rotary encoders with Arduino just with a basic loop and not much other code?** Is it going to "miss a pulse" and not record enough rotation often? How can I handle this with much more code? Is there a better way to do this? Would interrupts help? Is there some sort of circuit that would help with this problem?

Note: It will probably not exceed 4 rotations a second... *(That may be a lot but if you're doing a lead screw type mechanism that would only be 24 inches a minute if there is 10 rotations per inch of linear motion.)*

body:
Interrupts are what you would use in this situation.

The rates that you have mentioned are slow enough where you *probably* would be able to count it inside of a loop, however this is not recommended, as a typical loop will take many clock cycles to complete, and depending on the number of instuctiuons per loop, you may miss some counts.

Interrupts are made for this purpose, as they can be triggered at any time, regardless of the state of the loop.

There is a function named `attachInterrupt()` which will take three arguments.

 1. Interrupt Pin
 2. Interrupt Service Routine
 3. Mode

Below is an example for counting an interrupt

    volatile int myCounter = 0;

    void setup(){
        attachInterrupt(0, count, RISING);
    }

    void count(){
        myCounter++;
    }

The Modes are as follows:

>LOW, CHANGE, RISING, FALLING

More information about using interrupts can be found [here][1].

Depending on the encoder you use, you will need to tailor the code your needs, and do some more calculations to determine your position, but this should be a good starting point.

**Edit**
[Here][2] is some example code from Arduino Sandbox for using a rotary encoder.

  [1]: http://arduino.cc/en/Reference/attachInterrupt#.UxVGrvldXvM
  [2]: http://playground.arduino.cc/Main/RotaryEncoders#.UxVIwvldU4J


body:
Adding some references to already-written libraries and examples, to enable comparison between different approaches, and experiences with speed versus susceptibility to missing steps.

Reading rotary encoders:
http://playground.arduino.cc/Main/RotaryEncoders

Quadrature Encoder too Fast for Arduino (with Solution): http://www.hessmer.org/blog/2011/01/30/quadrature-encoder-too-fast-for-arduino/

Teensy Encoder library: https://www.pjrc.com/teensy/td_libs_Encoder.html

Reading rotary encoder on Arduino:
http://www.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino/