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

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;

}

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:

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.
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.
Other points such as better layout for static analysis or optimization by the compiler might also come into play.
In some special scenarios, there might be issues with the unpredictable initialization order of static elements (not sure about that point, compare this link though).

Source: Similar thread on arduino.cc

Re-entrancy should never be an issue on Arduino since it doesn't support concurrency.

True. That was more of a general point, but indeed not relevant for Arduino. I removed that bit.

A static variable declared inside a scope will always exist and use the same space as a global variable! In the OP code, the only difference is what code can access the variable. In scipe static wil be accessible within the same scope.

@jfpoilpret That of course is true, and I see that the respective part in my answer was a bit misleading. Fixed that.

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.

I'm not sure I understand what you mean about a function declaring a global. Do you mean as an extern?

@PeterR.Bloomfield: I'm not sure what part of my post your asking about, but I was referring to the OP's two examples - the first, an inherently global definition and the second, a local static.


text:
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 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) 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 (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

Hello and welcome to Arduino Beta! I cannot find any of these "debugging" pages you are talking about. Can you post a link in your answer? Also, for the strange square output, are you sure you have it on the right baud rate and nothing is connected to pins 1 or 0 on your Arduino clone? Those both could be causes of garbled text in the serial connection window.

Yes, please link to these "debugging" tools you have found

While I did find several articles on how to debug Arduino, I only still had one open, so that's the one I provided (sorry). For those interested, search for "Arduino debugging", "Atmel Arduino", "Arduino Visual Studio" or "Arduino Eclipse". Hope this helps others.

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

If you're using an ATmega32U4 (or alike), you won't be able to do it out of the box, as the 32U4 needs a JTAG connection for on-chip debugging.
Finally, once you got through that, you can bind a gdb to the AVR using AVaRICE. 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 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 to enable the serial communication and debug outputs.

I did use the 115200 baud rate in Serial connection. I know I set this correctly since that's how I was able to upload the WaterMote sketch. I do have it connected to PIN1 since that's what the WaterMote sketch references but I will keep pluging away "#define INPUTPIN      1". When I find the answer I will post it back here. Thanks all !

Aha! Now I understand what you meant! Yes, I did have a cable connected to PIN1, BUT since that prevents uploading sketches, that was the problem. I changed the sketch to use PIN2 AND also moved the cable from PIN1 to PIN2. Now the sketch loads properly and, most importantly, I'm able to see Debug information on the Serial console. Thanks so much!!! Now to figure out how to get proper readings.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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 Save As 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?

Welcome to [Arduino.se]! Could you tell us what you were trying, where you got stuck, what is it that is not clear, and what is the error message you are getting? Stack Exchange works best for Q&A, and not tutorials. See How to Ask.

Well I have created 2 programs with the code .h and .cpp but it keeps changing .h and .cpp to _h and _cpp.

You said that the .cpp and .h files get renamed to _cpp and _h. Could you tell us how you are creating the files? Using the new file button on the right side of the Arduino IDE? Some other way?

A sketch and a library are two different things. For your first experiments, you will probably not need to create any library of your own. Just write your sketch with Arduino IDE and save it the usual way.

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

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.

Your file has now been added to the current directory.

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.

do i copy the same code in .h and .cpp and what do i do after this because the tutorial i have been following is unclear

@user121855 That deserves a separate question. That will involve a purely code-related answer, while this was more about the file structure.

my other question is here http://arduino.stackexchange.com/questions/550/how-do-i-create-a-library-after-i-create-a-h-and-cpp-file

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


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

Why would you want to prgram Arduino in "pure C"? C++ is often seen as superset of C (although purists may say that is not 100% true). Is your problem related to how you can link to libraries developed in C? Or is it more related to performance?

@jfpoilpret Its a matter of personal preference. I prefer using C to C++, most of the time.

OK. But, if you setup a pure C environment for development, that means you won't be able to use 3rd-paarty libraries based on C++, wouldn't that be a problem?

@jfpoilpret Hmm. I didn't give that aspect much thought. Yes, that will be a problem.

In general, it is feasible (and easy) to link a C++ program with pure C libraries, but the opposite is not true. Otherwise, you can still restrict yourself to code "like in C" on Arduino IDE, the C++ compiler would spot any problems the same as a C compiler.

Also, I see AtmelStudio 6 has support for AVR-C projects so you should be able to work in a pure C development environment, but then you will lose all Arduino stuff and would work directly (and only) with AVR libraries.

There are features supported in C that are not supported in C++, such as __flash introduced recently in avr-gcc.

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

Why do you say that Atmel Studio will prevent you from using the Arduino libraries? They work just fine. But I agree fully with your recommendation to exit the Arduino IDE. With Atmel Studio you can add an AVR Dragon for $US50 or so that will support debugwire (for the UNO and friends) and JTAG for the Mega 2560.

Take a look at ino 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, 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.

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.

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.


text:
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
Using an ArduIMU chip like this one

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.

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.


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

Perhaps you should also think about rigging a sensor on the toilet seat, so it will sound the alarm if someone sits down when there's no paper. :)

Maybe one could just try to measure the radial resistance of a roll (hopefully it is not too high) and then it will decrease when there is not eough paper left.

Forget about resistance: just tried to measure it but it's above the max calibre of my multimeter (20M Ohm)

Well, what follows may be a discussion better located on the meta.arduino, but I think that this question is typically one that deceives the point of having an arduino SE. It's not directly bound to arduinos as for every project one shall not design his solution against a tool, but choose the tools that are best for the solution (what if using a RPi is better, or a CC2540?). It's indeed a mechanical+electronical+software engineering solution. And there's no best SE place I know of to ask that kind of questions.

@zmo I would then suggest the OP to edit his question to add the need to drive the alarm through an Arduino; that would make it better for Arduino.SE

http://www.motifake.com/macgyver-demotivational-posters-14554.html

You could just ignore it and wait for your wife to yell at you.

I would define the problem domain as #1 Indicate when very low or out of paper (very low - you want to ensure a refill is standing by when the outage occurs) (outage - to prompt the change); #2 solution must be a one-time modification - requiring irresponsible people to replace the roll is difficult enough, getting them to modify the roll before installing it will be even more difficult; #3 the problem domain should also indicate the reason why a processor is needed (count # of outages, measure time between outage indicator and replacement, developing a game around changing the rolls, etc.)

Why not use a photoelectric sensor?

Mysteriously, this question managed to get more than 600 more views than the next most viewed questions...

Related: How to avoid shortage of toilet paper? at Life Hacks SE.

Or buy one of those industrial-sized toilet roll dispensers, the paper will run out much less often.

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 (see datasheet). 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.

@AnnonomusPerson He is talking about measuring the weight of several full rolls of toilet paper, not individual sheets or empty rolls.

This is a great idea: instead of having to deal with measuring the amount of paper left on the roll, measure the number of rolls left to tell you when you need to get more rolls.

What sensor would you use to detect the lack of weight?

A fabric pressure sensor is one option, or a light sensor on the base that is covered if a roll is present.

Could you provide an example of a specific sensor that could do the job?

Depending on how you'd construct the base, a micro-switch (examples) or a reflection sensor (examples) would be pretty easy to apply.

You could have the trigger make a few web page queries and order you a few new rolls of toilet paper from Amazon or something when you're low, too. (BTW, this kind of reminds me of http://hackaday.com/2009/05/05/twittering-toilet/).

I think that your term for the end user needs an 'h' after the first letter.

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.

Nice diagrams. What did you use to make them?

Just an iportant comment: you don't even need a reed contact in this situation, but just two pieces of metal used as a simple switch. A reed contact is based on magnetic forces opening or closing a switch; that was needed in my answer where there was no real contact between both parts. But here, using a reed just seems useless, I think.

@jfpoilpret I didn't know the term was a specific kind of switch. I was thinking the more general concept of a stiff bendable material. Thanks for the clarification!

@jmathew no problem, after all, we are all here to share knowledge!

This design will still activate the sensor when a little bit of toilet paper is left.

I used MS Visio 2007.

@AnnonomusPerson I agree. And I personally would prefer an absolute "no paper left" indicator. But the question was "how to track when it's low or out".

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.

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.

I'm a huge fan of using a rotary encoder. It could even be designed the the TP holder had the encoder attached to the rod through the roll, thus causing no moving on the encoder. Also a button could be used to reset the count.

But a common problem would be to determine the max number of rotations as this depends on the number of sheets and their thickness.

I would change this from 'Attach radiation device to toilet roll' to attaching it to the middle roller it sits on. The same effect, but less maintennance of having to reattach the sensor for every roll

You could determine the number of rotations by transferring all the TP from a new roll onto the spool in your measured roll and counting the rotations with the encoder (with a simple DYI thing like a couple of vertical dowels and just wrap one onto the other). Then when its empty, repeat. Makes the whole thing easy to use too because you can just keep reusing your same spool that you've already attached the encoder to, and keep wrapping new TP onto it.

@JasonC although toilet paper will tend to come misaligned when you attempt to re-spool it, unfortunately. You would need to design some sort of alignment guides so the paper doesn't spill off the end of the roll. (When TP is put on rolls in the factory, its rolled as a huge 5-10 foot wide roll that is then sliced into the 4 inch rolls we use - that's why the edges are all perfectly aligned on the rolls you buy in stores.)

@AJMansfield I wonder if some circles cut out of cardboard on the sides of the receiving roll (and some care) would give satisfactory results; if the rolls are on dowel rods for transfer you can just poke a hole in the center of the discs and slip them on. On the plus side, if you always buy the same brand of TP, you'd only have to do it once (and you can keep a list handy of the number of spins for different brands/types that you discover -- you could be the proud maintainer of the world's first opensource TP spin count database).

(And if you are going to do it once, instead of transfering, you could just unravel a roll and count that one, then go TP somebody's house.)

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.

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

Can you please edit your question to tell how to connect that item to an Arduino board? Thanks!

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

I had a photoransistor laying around that responded well to red light, and another from Radio Shack 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:

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.

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.

For $10 you can get this http://www.adafruit.com/products/466 1cm-15cm range (perfect for TP roll) and designed to be easily integrated with a microcontroller.

@Jason C: First attempt was using VCNL4000, but like other reports, it would stop/halt/freeze while taking readings. I've not seen anyone resolve this, even when lowering the mA.

@Aditya Using HC-SR04 proximity sensor did not help. There was no difference between a full roll of TP and an empty one. Best I can guess is the 'echo' was going straight through the tissue and stopping at the metal bar holding the TP. So, at least for that sensor, it did not work.

@JoseLeon I see. That's quite odd indeed. I agree with your reasoning. Maybe there is another sensor out there which might work but I think your reasoning that the infrared waves should just go thru the toilet paper seems valid.

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

That won't work, same reason as an ultrasonic sensor. It'll still go off with at least 10 feet still on it. The color sensor is a better idea.

I don't see the relation with ultrasonic sensor. Could you develop further WHY it won't work? There are large quantities of reed contact and hall effect sensors, let alone different kinds of magnets.

A layer of TP is so thin that it might activate with a little left. It theoretically could be tweaked, but it's really inefficient to take out the microscope or whatever to change a roll of toilet paper.

Activating with a little left is not so bad, since the OP question is "... toilet paper is low"; low does not necessarily mean empty.

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

I am not sure you would get enough accuracy with an ultrasound sensor; IIRC, most of them have about 3-4 mm accuracy; in general that's good enough, but considering the diameter of a toilet paper roll, that may be too inaccurate.

Yes, that's often true for an individual reading. The fluctuations are quite uniform though, so you can average out several consecutive readings to counteract it. That can potentially give you a precision of ~1mm.

What happens when the toilet paper wiggles one mm while spinning away from the sensor with a little bit of paper left?

@AnnonomusPerson You'll always get spurious readings when there's movement. That's why you wait until the reading is steady for a significant period before acting on it.

@Peter R: Using HC-SR04 proximity sensor did not help. There was no difference between a full roll of TP and an empty one. Best I can guess is the 'echo' was going straight through the tissue and stopping at the metal bar holding the TP. So, at least for that sensor, it did not work.

@Jose Hmm I thought there would be a little difference. Try mine or the one with the weight sensor and the vertical bear.

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)

Hello and welcome to Arduino Stack Exchange! Can you please say how you connect it to an Arduino? Thanks! Also, I don't know how good of an idea it is to put a camera in a bathroom. :)

I like your last edited idea; it might be simplified further by just using a switch on the lid, that would close the circuit when the lid has reached a certain angle; that seems easier than measuring the angle itself.

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

Arent't optocouplers single chips that include both the emitter and the receiver? See here: http://en.wikipedia.org/wiki/Opto-isolator

[…] is a component that transfers electrical signals between two isolated circuits by using light […] so basically that's what we do, between an IR LED (one circuit), and a phototransistor. Though you're right it's not a single component (like the MOC3020).

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

IR beam was my first thought. Simple and easy to implement and probably more reliable than some of the other solutions, although maybe less fun :)

Hehe, I agree. I think a color sensor would be fun, at least from the software side; it would be a nice challenge to collect data and try and come up with an algorithm that was immune to, e.g., changes in natural lighting or other false triggers.

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.

Ultrasonic Ping Sensor. 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). 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. 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.
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) :)

Shall the color sensor work the same (i.e. without having to tune the sketch) if you change the color of your toilet paper :-) ?

@jfpoilpret I don't know if you reuse your toilet paper or not but... :) I'm adding code with mechanisms so it'll be "similar" but not exact.

I think toilet paper is soft enough to absorb the ultrasonic burst from an ultrasonic sensor

@TheDoctor It's not a good idea really, like I pointed out. It's way to inaccurate.

Well by changing color, I meant buying a new color :-)

An illuminated toilet paper holder does not sound too bad...

the color doesn't work when a single sheet is left on the roll, (a point where you want to know that the roll is out before you need to wipe)

@ratchetfreak It will if you set the threshold right. The sheets look visibly darker when there's only a few left.

@jfpoilpret If you added a "calibrate" button and pressed it with the bathroom lights on after you install a new roll, you can measure the correct color.

@Jason Just don't install brown toilet paper!

@Anonymous: Please see my results using HC-SR04 proximity sensor in this thread. It did not work.

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.

I agree. People seem to be overcomplicating this. Also you can keep reusing the same roll with the encoder attached to it by transferring TP from a new roll to the sensor roll when you refill it (e.g. put rolls on a couple of cheap dowel rods, and wrap it up); that also lets you count how many rotations for that roll (as you refill it).

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.

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

It's better to include code in your answer instead of an external link. If the link breaks in the future your answer will still be relevant.


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

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

Not sure if it is a lucky guess, but driving an output pin (including An) low is the most energy effective way too. Driving high or enabling the pull-up consumes more energy from the power source.

@jippie - If you don't have any board leakage, they're likely to take about the same power. If you do have leakage, it depends on whether it's to power or ground.

@FakeName No they don't. I read an article one on the very issue. Driving the pin low takes approximately as much current as leaving it high impedance. Driving high or pull-up draws more current. I'll try to find the article later today.

I haven't read the article, but can confirm that driving all pins high pulls marginally more current than all low.

@jippie - Huh, that's weird. I'd expect totem-pole outputs to be symmetrical. Go figure!

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.


text:
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".

OLED displays may be smaller, but their much higher brightness makes them readable from a bit further comparatively speaking.

I tested a 1.8" OLED display next to the 2.5" LCD and found that the LCD was much easier to read in a room with daylight.

OLED > LCD --> microview.io

Here you can find a bunch of displays at new haven display, which are big and OLED and not too expensive:

2.7" 128x64 OLED
3.12" 256x64 OLED

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 over there:

320x240 LCD with backlight

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 to run them.

Unfortunately they all seem to be parallel rather than serial. I think I might have to resign myself to using a larger ATmega.

no they aren't. The NHD12864-2.7 can be controlled using 4 wires, and the NHD320240 can be controlled with less pins as well, looking at the S1D13700 Driver's datasheet (never tried that one, but I'm using the former in serial mode and it works very well).

The NHD12864-2.7 doesn't satisfy the requirement of being higher resolution though. All the connection diagrams seem to show D7:0 being connected in the S1D13700 data sheet, don't they?

hm.. looking again, I may have thought wrongly. Indeed, the NHD12864-2.7 is not of a higher resolution, but it's an OLED bigger than 2", and you've got the 3.12" displays, which are wider but having a better resolution (256x64).

N.B.: you may use an i2c port expander as well, or a small cheaper AVR as interface.

by the way, you can check also the supported display list of the u8glib project, to help you make a choice. They got a few big displays.


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

Probably one way to detect sleeping state of someone is to measure heart pulses, and detect when pulses get below a threshold (different for each individual but that could be "guessed" by the system after a few days run). With this, you could even see if the person had some nightmares (pulse increasing) :-) That is intrusive (pulse sensor) but is also the only way to know about the sleep of ONE person when 2 are in the same room.

Neurosky EEG brainwave sensor apparently works fine with Arduino. Measure frequency. Up to 4Hz --> NREM sleep. Up to 8-9Hz ---> REM sleep. Above 8-9 Hz up to 16Hz ---> awake, but eyes closed and relaxed. Above that ---> awake.

I actually did something like this, using a PIR Motion sensor.
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.

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
Intelligent Alarm Clock Hardware

Thanks for the links on your blog. One question I have is how do you decide that someone isn't reading a book or watching TV while doing something while on a bed? It is some good data. Did you project need to be turned off when you got into bed?

Mine is an alarm clock so it only needs to detect movements during the half hour before the alarm goes off. So that's the only time that matters. The overnight graph is just to collect data to figure out how many movements/pin is considered "light sleep, easy to wake"

do you have any suggestions on how to detect whether it's just idle or if it's sleep? I might have to do some of my own data...

I'd see how the graph looks for sleep vs various activities. Weigh that with the time of day (more likely to be sleeping 3am than reading). Hard to say without collecting lots of data.

To help you with your googling, this technique is called actigraphy. Wikipedia has a decent intro.  Some signal processing is apparently necessary, but nothing too difficult or beyond the capabilities of an arduino.    To classify sleep stages (including awake), I would look at academic papers on the subject.  One thing to decide is whether you want to put the sensors on your bed (easy, low accuracy), or on your wrist (harder, more accurate, and you can measure body temperature, ambient light, and skin conductivity).

I am also searching for how to do it and this is the only relavent link I have been able to find. Unfortunately the blog links have expired. If the author could explain how the measurements were taken. E. G. If PIR sensor digital or analog measurements were taken?

@SubhaniMinhas I don't have the original code, but you can use the wayback machine to read the archived copy links. To answer your specific question, the measurements were taken with a Windows Powershell script that wrote a timestamp to a file every time the arduino serial port transmitted data. The PIR sensor is a digital sensor that changes the stage of a pin when motion is detected. It counts the number of movements in a time period.


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

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.
I am unsure of the protocol used by my camera. I have found it difficult to find documentation on the same.
How can I replace the 9-Volt battery for something smaller?
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?
For such a project, will I need additional hardware?

Welcome to Arduino.SE. :) If you're looking for general introductions and tutorials, then the official Arduino website is usually the best place to look at first. You're welcome to ask the more specific questions here, but please try to ask each one separately. It helps us keep the site better organised. Thanks!

Ah. Apologies. As you can see I'm quite new here. I shall take care in the future. I will try and clarify my question as it seems it's quite complicated to understand.

Using the Arduino shouldn't be any different than any other microcontroller.
The IRremote library is my go-to library for any IR related stuff.
Power shouldn't be an issue, look at the Moteino from LowPowerLab and check out his coin cell battery tests. It's definitely possible. Not with a full blown Uno, but with a bare chip, yes.
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. 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 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
EEVblog #506 - IR Remote Control Arduino Protocol Tutorial

Phew. That's a lot of information. Do you think I will need any additional hardware for the same?

additional hardware for what?

In order to complete the remote i.e have a button which can signal the micro controller to control the LED into transmitting the correct bit pattern which is then detected by the camera at a distance of approximately 1-5 meters. Sorry for the ambiguity.

You could probably do without the Schmidt trigger but that should be enough.

1.) I'm not exactly sure what you mean by this. What I'd recommend is a ATMega328 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 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.
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. 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. 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. 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.

Thank you for your answer. The receiver is in the camera. Hence the confusion. Unfortunately my friend is in India and I'm currently living in the US so coordinating for us is largely impossible. I asked him once and was able to procure materials and necessary documentation. I am writing this post for the both of us as he would like to improve his design as well which currently uses ATmega328 with 9 Volt battery.

Also, I have some experience with electronics but not a lot with Micro controller so I can build an IC and to some extent maybe design it too but I do need somewhere where I can start.

@AdityaSomani You should've mentioned that. That's really outside the scope of the question, and I don't know enough about your camera. Unless you can find some data online, you'll need to have an actual remote available to reverse engineer the signals. There's no universal camera shoot protocol.

Oh I see. I'll try and find a data sheet for the camera or talk to my friend about the same. Thanks. Sorry again for the confusion.

@AdityaSomani That's okay!

Well, for your project you can simply buy/rebuild a TV-B-Gone made by Mitch, 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 that can work as an IR receiver (or use another device as a code recorder).

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 for the TV B Gone. I'm not sure what format they use for their code database though.


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

I've used rotary encoders that refused to work properly when spinned fast. I guess it varies with price.

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.

Interrupt Pin
Interrupt Service Routine
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.
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 is some example code from Arduino Sandbox for using a rotary encoder.

An interrupt driven edge detector on a Duemilanove easily handles 100 edges per second (6500rpm on a motor).

@WayfaringStranger So then there's no problem on an Uno, then. Thanks!

@AnnonomusPerson - How much work are you willing to put in? If you go naked (ISR_NAKED()), you can skip the automatic C context saving, and pull off 100-500 Khz interrupt rates without issue, but you're basically writing assembly in C at that point.

If you want a completely banannas document about optimizing the absolute crap out of interrupt response, look here. Placing code directly in the interrupt table to further reduce interrupt latency!

Also, note that if you're going for low-latency interrupts, the arduino attachInterrupt function injects a whole additional function-call overhead versus using the interrupt ISR() directly.

Really, though, if you want low-latency anything, you shouldn't be using arduino anything anyways.

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/


text:
Grove sensors without a Grove shield
There exists a large variety of sensors in the Grove System. Usually these are accessed via a special shield (Grove base shield).
Can I access these sensor directly without a shield. In particular I am interested in using them with an Arduino Pro Mini. My guess is that one definitely needs the 5V version of the Mini, but other than this? How fiddly is it to use these sensors directly?
I am interested in using the Grove dust sensor, but I am also would like to operate a Grove 4 digit display.

From the wiki.
Above is a schematic of a Groove shield. You can see that each of the connectors has two digital pins connected to it and then V (5V) and G (GND). The last two you can connect normally to an Arduino. The first two you connect to the pins that are used in your sketch.
Say it says to connect the connector to the top left DIGITAL pin on the board (D6/D7). You'll 7want to connect the pins as followed: Black → GND, Red → 5V, White → D7, and Yellow → D6.

Notes:

The shield overlaps the pins (i.e. 3-4, 4-5), so that might make things confusing. I think that is a design flaw. If it needs two pins, it should have two connectors. In the current state, you can connect two things together. I don't really know how to figure out if it uses all of the ports attached or not. If you don't have to, I would try not to overlap any two grooves. You would do this by using two digital ports for every groove "module."
You'll also need to have a adapter cable (Link from TheDoctor's Answer.)
For analog connections, it applies the same way as digital. G is ground, V is 5v, and A# is an analog pin.

Inferencing it:
There's no real cookie cutter way to connect to them. However, the wiki seems to be a decent resource once you figure out how to navigate it. The dust sensor you mentioned seems to ONLY use digital pin 8. It was connected to the D7/D8 connector on the Groove shield, so the yellow wire could be ignored since it was never used in the sketch.
It's hard to do much with this system: it's poorly documented and not uniform at all. Plus, some boards could cause problems that could even lead to damaging components. I would say look at something else.

This dust sensor seems pretty good, minus the documentation. On this blog, they say to do this:

Sharp pin 1 (V-LED)   => 5V (connected to 150ohm resister) Sharp pin 2
(LED-GND) => Arduino GND pin Sharp pin 3 (LED)     => Arduino pin 2
Sharp pin 4 (S-GND)   => Arduino GND pin Sharp pin 5 (Vo)      =>
Arduino A0 pin Sharp pin 6 (Vcc)     => 5V

I can't seem to find the cord for it, but I'm sure there are many others like this online. (It lists the cable needed: a 6-pin, 1.5mm pitch connector. That doesn't seem too hard to find).

Here is a 4x7 segment display for much cheaper. It does use a lot of pins and need resistors, but multiplexing and resistors aren't that hard to figure out. That's outside of the scope of this question. There might be some other board with a built in IC for controlling a display like that, but I can't seem to find one now.

Grove sensors use a special socket, a 4 pin JST with two power lines and two data. you would have to make your own board/terminal to get them to connect to a mini.
What you could do is use a Grove proto board, which converts the JST terminals onto .1" pins suitable for connecting to the Mini. There is also a litle proto area if you want it.
You could also use an adapter cable, which would not have a bulky protoboard along with it. The terminals could be soldered directly to the Mini.

I was thinking of using an adapter cable - hooking up the grove sensor does not seem such a big problem. However how can I access/communicate with them?

@A.Schulz: Exactly the same way as if the Grove connector wasn't there. The hardware is still the same, only the pins have been changed.

Not every Grove sensor uses all 4 wires. Most of the basic analog ones use SIG,NC,VCC,GND - where NC means Not Connected. On the Seeed Studio wiki, they publish Eagle files for most of the sensors. If you check them, you'll confirm NC is not connected to anything.

The reason some are 3 and 4 wires is so they can use a common connector. If you use a 4 wire sensor, such as an I2C sensor, you cant use the adjacent socket on your Grove base shield, as adjacent sockets share 1 pin. Socket labelled D4 contains pins D4,D5. Socket labelled D5 contains D5,D6. D5 is common between the two sockets.

I'm pretty sure you could just take the signal cable from the dust sensor and plug it directly into your mcu digital pin of choice and then wire the Vcc and Gnd as well.  I'm working with a CO2 sensor and don't really want the shield overhead.