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.

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.

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.

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.

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

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.

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.

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

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:
Have I fried my A2 port?
I'm playing around with a SparkFun Redboard (essentially, an Arduino UNO).
I have a simple 5V sensor that I'd been trying to get to work with A2 and analogRead(). Nothing seemed to work. It's supposed to be cycling from 0 to 5V, which should give me values from 0 to 1023, and instead I get constant values of around 260.
In desperation, I tried using other ports. On A0, A1, and A3 I get the signals I expect. On A2, still nada.
So, the question. Is there something I could have done in configuring things that would have made A2 and only A2 stop reading correctly? If so, how can I reset it?
Or is there some other function that I might be using that could interfere with A2? Currently, I'm only using Serial over USB - could that interfere with A2?
Or could I simply have fried the port?

Do you have an LED and resistor near you? Try blinking it using A2.

This is a very long-shot, but have you tried connecting all the other analog pins to ground while testing A2? Floating analog pins can sometimes cause problems (although it seems very unlikely in this case).

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

The Redboards use soldered TQFP ATMega328, so unless you're interested in doing a SMT hot-air rework to replace the microcontroller, you're stuck with a dead pin. Luckily it could've been worse.

source: Stack Exchange

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

sort: votes


text:
What is the best way to unit test my code without controller?
I want to unit test my Arduino code. Ideally, I want to execute and test my code without uploading it to the board. What tools or libraries can help me with this?
There is an Arduino emulator in development which could be useful, but it doesn't yet seem to be ready for use.

Unit testing and running the code in an emulator are quite different things however.

Yes, there are two questions here, one is about unit testing arduino code, and the other about emulators for the arduino to execute the code. Maybe create a specific question for each, especially the unit testing one that has not been addressed before.

I always try to isolate the hardware logic from the rest of the domain logic.
Classes (or whatever) from domain logic can be programmed in c++ (with the known arduino restrictions like exceptions or std lib) and can be tested with gtest.
When these classes are tested, simply instance from arduino program excluding the main with tests.
If your project is pure hardware this solution will not help you very much, but if you have your own algorithms, protocols...etc, test them with Google test will save you hours of on board testing and memory problems with unexpected results and your software will gain in quality.

Yes, this is an important point in SW dev that is almost always skipped in arduino development. Testing small units of your code can save hours of time if your project has complex functions or algorithms.

You can easily simulate your Arduino code using the famous Proteus ISIS.
You just will have to search for the specific Arduino simulation library for Proteus.
Here you a small tutorial of how to make this thing done:
First, identify the path the Arduino IDE generates the hex file to?
for example if you are using the official IDE you will find the hex file location in the "arduino IDE path/lib/preferences.txt"
Or if you are using Arduino ERW which I recommended the most on windows! So you can simply open the output folder by "Sketch > Copy HEX file as path".
Second, download the Arduino library from Here. Then copy ARDUINO.LIB and ARDUINO.IDX to folder "library" in the install directory Proteus.
Third, open ISIS and you should be able to find the component.
Please find this image of the worksheet after finishing the above steps, and simulation works just fine!

And as a head start for you, please find this small memo I prepared for the Arduino Uno Pins Layout:
0-14: I/O
A0-A5: Analog

We can use analog as digital:
=============================
Pinout:
00: Rx      | Can't be used as I/O if I wrote in the code Serial.begin
01: TX      |
02: Interrupt
03: Interrupt & PWM
04:
05: PWM
06: PWM
07:
08:
09: PWM
10: PWM & SPI
11: PWM & SPI
12: SPI
13: SPI
A0:
A1:
A2:
A3:
A4: TWI
A5: TWI

Have you looked at the AVR simulator that's part of Atmel Studio? Considering Atmel designed the processor, the simulation may very well be running the HDL that was used to produce the MCU itself.
I suspect if you're doing something involved enough to be using unit-testing, you should probably stop thinking of your device as an "Arduino", but rather "An ATmega MCU on a PCB". There are much more information and tools available about ATmega CPUs in general then Arduinos.

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


text:
Arduino + WiFi 101 Gerber Files
Is it possible to get the Gerber files for the Arduino Uno r3 and the WiFi 101?  I've been teaching myself the SW side of this hobby (with much help from SE Arduino) and I'd like to better understand, or at least get some exposure to, the HW side.
Are the Arduino Uno and WiFi 101 Gerber files available to the general public or are they considered IP?  I am under the impression that it is open source but I'm not sure where the OS boundary ends.

On the Arduino UNO and Wifi shield websites in the Documentation section you can download the Schematic (PDF) and PCB layout (Eagle) files. The page already says

The Uno is open-source hardware! You can build your own board using
  the follwing files

With the free version of Eagle, you can open it and export to gerber file format.

Thank you for explaining it to me.  I'll take a look.  I did see Eagle files I just didn't know what they were.


text:
Quick start on Arduino for experienced embedded programmer?
I'd like catch up the Arduino concepts (programming & IDE). There are excellent online tutorials available for Arduino but all of them which I saw are made for those who didn't have embedded/electronics background. Going through them is heavily time consuming as I'm already familiar with the embedded programming other than Arduino or Raspberry Pi.
Does any one know any quick reference materials for Arduino which excludes electronic/embedded basics which is meant for experienced embedded programmer? That could be a big time saver for me.
Thanks in advance!

What exactly do you want to know about the Arduino, that you cant find in the tutorials? Given your supposed  experience, you should be able to begin using the Arduino for projects and such; its a dev-board that can be programmed in C/C++, with libraries all over GitHub, thats about all you need to know. The indepth details about its workings can be found at the arduino.cc site.

If you are experienced with embedded programming, forget about the IDE and the Arduino specific libraries, they tie down an experienced user. Grab the AVR's datasheet and just use Arduino board as just another dev board, you can program it using avrdude and there is a good gcc based toolchain. Use C or C++ whatever you are used to.

that little icon with the arrow pointing rightwards is the one that uploads your code,  everything else should be fairly obvious.

Does any one knows any quick reference materials for Aurduino which excludes electronic/embedded basics which is meant for experienced embedded programmer? - there are so many things you can conceivably do, it would be helpful to know what you have in mind. Controlling model trains? Building a rocket ship? House management? Measuring temperature? If you exclude the basics it is still a big field.

So I need to go through the existing Arduino code and help them to solve the issue that they are facing. - now we are getting closer. Perhaps if you post the code in question, and describe the problem.

Hi Nick, the project has a dozen of .h file and a main file which has the setup and loop function. The main file has around thousand lines of code. My intention is to have the basic understanding of  the code first and then narrowdown the issue (from my gut feeling the issue could be related to RTC module). Anyway I already going through the code. My first impression is, Arduino abstracts the low level drivers and system services . So that the  programmer can only focus on the application code and there are number of libraries (driver abstraction) available for different hardware modules.

As far as I know, there is no tutorials about using Arduino's for, e.g. "multi-tasking, real time response". That is not the focus of the Arduino community.
The Arduino UNO development board is built around Atmel's ATmega328. The Summary datasheet gives an overview of its hardware capabilities on the first page. If you are familiar with MCU development, that should give you a feel for its hardware capabilities. The complete ATmega8/168/328 datasheet is over 600 pages, and describes every feature, with all registers in detail.
The Arduino IDE uses gcc under the covers. So you likely already know how to use that. When you download and install the Arduino IDE, gcc and gnu binutils for AVR will be installed too.
The Arduino IDE has all of the Atmel header files, so much of the code in the datasheet should compile, link and upload.
The IDE is really designed for beginners. It is to easy to use, but has very few features beyond basic editing, compiling and loading. It does support a serial-monitor to see text printed by the uploaded application, but it doesn't support a debugger like GDB out-of-the-packet.
However, it doesn't prevent you writing C++ code and header files, and it will build the whole collection of files.
Because the IDE lets you create and edit C++ directly, you can install the IDE on any of the three main platforms, and get started very quickly.
You will probably want to visit AVRFreaks who tend to focus at a lower level than Arduino.
There is also AVR LibC library which points you at the documentation for the AVR upload tool, avrdude, and debugger.
Summary: Install Arduino IDE, do a couple of quick projects to get a feel for the system. Then start writing C++ as normal. Install AVR LibC library for a more traditional library, and visit AVRFreaks forums for more technical help and information.

No need to install avr-libc, as it is already there: the Arduino core is built on top of it.

But I suppose to debug an existing Arduino project (which my friend gave to me because the developer left from his small electronic company) developed for GSM based remote motor control product. They haven't used Arduino board but used Arduino IDE/library for coding. Flashed the hex output from Arduino on their custom board with Atmel processor. So I need to go through the existing Arduino code and help them to solve the issue that they are facing.

This is maybe one of the worst type of projects to get involved in. Code that needs debugging on a platform that you have not used before. Code that you might not know the status of and where the requirements are loose.
I would recommend starting by getting all the details on the table. Understand the intended software architecture, estimate memory foot-print, and processing, etc - if the product is feasible. There might be a reason for the developer ditching this project?
AVR is small scale embedded and that implies a very different implementation strategy. There is no operating system and much of the code is bare metal.
The Arduino core is a platform (library) that abstracts a small set of basic hardware functions. It was originally intended for Media/Design Students.
To help reduce the threshold when getting started the IDE has build support, i.e. pre-processing, such as an implicit add of the Arduino header file (Arduino.h) and generation of forward declarations for functions in a sketch. The IDE does not use make/makefiles. Source code is C/C++ (AVR GCC) and if necessary AVR assembly.
The quick reference for the Arduino core function can be found here. There is also a list of libraries. Some are packaged with the Arduino IDE/core while others need to be installed. There is a library manager in the IDE to download and install some of the libraries. New libraries are added more or less daily right now.
Depending on the code you will have to read more about the libraries used and/or internal AVR hardware (registers, functions, etc).
Cheers!

There are a couple of generic Arduino Makefiles floating around the Web. These let you work on Arduino projects without the IDE. The one I use tells gcc to -include Arduino.h, but it does not do forward declarations for you.

In Cosa I have adapted Arduino-Makefile to allow make based build without makefiles. Make allows parallel build using all processor cores (on the host) and advanced library caching. Bottom-line: ultra fast build. Ref. https://github.com/mikaelpatel/Cosa/tree/master/build

Hi Mikael, The links you have pointed are a really a quick reference for me. Many things I came to know about AVR /Ardunio after I post my question here. As you said, it's different than any other controllers/IDE that I worked for like NEC, ST, etc. May be targeted for different applications. Thanks to every one!

authors: Жанна Грамота


text:
Problem with sending a POST request using the WiFiEsp library
I'm using an ESP8266 version 1 with the WiFiEsp library to connect to WiFi, and that works just fine.
I'm setting up the device using the same code as in the example WebClientRepeating.
I need to send a POST request instead of a GET request, but I can't get it to work as I want. If I create my POST request like this, it works just fine:
if (client.connect(server, 3005)) {
  Serial.println("Connecting...");

  // send the HTTP POST request
  client.println("POST /open/peripherals HTTP/1.1");
  client.println("Host: 192.168.10.137:3005");
  client.println("User-Agent: Arduino/1.0");
  client.println("Connection: close");
  client.println();

  // note the time that the connection was made
  lastConnectionTime = millis();
}
else {
  // if you couldn't make a connection
  Serial.println("Connection failed");
}

I get the response like this:
[WiFiEsp] Connecting to 192.168.10.137
Connecting...
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 19
ETag: W/"13-jSAaqMh5E3R94/b2aONzvg"
Date: Sun, 13 Nov 2016 10:20:58 GMT
Connection: close

{"temp":"Testdata"}

However, if I try to send some body data in the request it fails:
if (client.connect(server, 3005)) {
  Serial.println("Connecting...");

  // send the HTTP POST request
  client.println("POST /open/peripherals HTTP/1.1");
  client.println("Host: 192.168.10.137:3005");
  client.println("User-Agent: Arduino/1.0");
  client.println("Connection: close");
  client.println("Content-Type: application/x-www-form-urlencoded");
  client.println("Content-Length: 16");
  client.println();
  client.println("temperature=22.7");

  // note the time that the connection was made
  lastConnectionTime = millis();
}
else {
  // if you couldn't make a connection
  Serial.println("Connection failed");
}

Then the response from serial output is:
[WiFiEsp] Connecting to 192.168.10.137
Connecting...
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Data packet send error (1)
[WiFiEsp] Failed to write to socket 0
[WiFiEsp] Disconnecting  0

However, the POST request including the body is received by the Web server just fine, but the response sent to the Arduino I can't read because it shows me an error instead of a proper response. From my webserver the response for the POST call that works and the POST call that fails is the same.
Does anyone knows why this fails when I add Content-Type, Content-Length and some body data?
Thanks in advance!

The first response doesn't correspond to the first code. It is hard to guess where is the problem without the full code.

Your content length is actually 18, considering the CRLF appended by println().

Your problem is the content you are sending. While this format works well e. g. in Python libraries, this library seems to have a problem with it.
I solved it this way, when I happened to face this problem:
//all your other code, including the remaining HTTP-Request
String content = "{\"temperature\":\""+String(value)+"\"}";
client.println("Content-Length: 16"); //insert, well, your content length
client.println(content);

One major problem seems to exists within the AT firmware of most ESP's. By default, the http headers it sends include "Connection: close". However, the firmware seems to be buggy and unable to cope with the server closing the connection after it sends the response. Thus, in order to be able to get a response back from the target server you need to have "Connection: keep-alive" instead. This means you must explicitly add this to your header since "Connection: close" will be added if nothing else is said.
Also to make life easier for the WifiEsp library you could make sure your server returns an already well-known status string for the library like fx "SEND OK"… I'm doing this on a barometer logger that sends data to a MVC Web Api written in C# and it works perfect...
Here's my code:
String PostHeader = "POST http://" + server + ":" + String(port) + "/api/values HTTP/1.1\r\n";
PostHeader += "Connection: keep-alive\r\n";
PostHeader += "Content-Type: application/json; charset=utf-8\r\n";
PostHeader += "Host: " + server + ":" + String(port) + "\r\n";
PostHeader += "Content-Length: " + String(jsonString.length()) + "\r\n\r\n";
PostHeader += jsonString;
Serial.println(PostHeader);
client.connect(server.c_str(), port);
client.println(PostHeader);
client.stop();

And the full log looks like this:
POST http://192.168.10.197:8001/api/values HTTP/1.1
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Host: 192.168.10.197:8001
Content-Length: 144

{"IpAddress":"192.168.10.230","MacAddress":"5c:cf:7f:d9:2f:c8","Temperature":34.6,"Pressure":1007,"Altitude":48.48573,"PressureAtSeaLevel":1007}

[WiFiEsp] Connecting to 192.168.10.197
[WiFiEsp] Disconnecting  3

In the file debug.h located in the WifiEsp library source code you could alter a define and get more output to your serial console. Open the file and change
#define _ESPLOGLEVEL_ 3

to
#define _ESPLOGLEVEL_ 4

Save the file and recompile/deploy your source code to your Arduino and you will get extensive information about all AT commands the library sends and what the library receives in return.

Connection: close tells the server to close the connection once it is done sending the response. If you can't get the response with Connection: close, that's a bug of yours: don't blame that header. BTW, header lines should be terminated with "\r\n", not just "\n".

Cool, I struggled for a long time with this and experimented with a lot of things, changing from \r\n to \n was one of the things I tried (that didn't work). Only forgot to change it back to what it should be. The only way to get it to work with the ESP8266 and the WifiEsp library was to mark the header with keep-alive though. I have debugged the library and tried to find anything that could affect this but nada, most likely it's some bug in the AT firmware... Everyone is complaining about this issue in all devsites, just wanted to add my 2 cents to it...

If that's the case, then you should rephrase your answer: “There is a know bug in the XXX library [link to the bug discussion] that prevents it to work with Connection: close, therefore...”. As it stands, your answer implies that using Connection: close is an error.

Better? I don't have any general link to any discussions around this subject because everyone, everywhere is having a wild goose chase to how to solve this issue, many blame the library but as far as I can see there's no issue with it and it seems to be doing what it is supposed to do :)

Also changed to \r\n...

It still looked like the error was the use of Connection: close, which it isn't. I took the liberty to edit the post myself to make explicit that your are accusing the firmware of a bug that prevents it to work with Connection: close.

the answer is based on unjustified suspicions. they are not true. the WiFiEsp library expects SEND OK from the AT firmware not from the HTTP response. I very very doubt that the AT firmware adds an HTTP header, since a valid HTTP request ends with an empty line and everything after that is a HTTP request body

Didn't say that either @Juraj, I said that you have to add a headervalue as a workaround since something is going wrong somewhere. The http response will not reach the Arduino or WifiEsp library properly and you get following feedback from the library:
    [WiFiEsp] Data packet send error (2)     [WiFiEsp] Failed to write to socket 3     [WiFiEsp] Disconnecting 3

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


text:
Keypad giving random inputs
I have a keypad like this:
here is another, closer look at the bottom part.
Basically, I want the LED to power the amount that I pressed.
this is my code:
int LED = 1;
int inputs[4] {
  6,
  4,
  2,
  0
};
int outputs[4] {
  13,
  12,
  10,
  8
};
void outputAllBut(short int);
int numberInputCheck();
int inputCheck();

void setup() {
  for (int i = 0; i < 4; i++) {
    pinMode(outputs[i], OUTPUT);
    pinMode(inputs[i], INPUT_PULLUP);
  }
  pinMode(LED, OUTPUT);
}

void loop() {
  while (true) {
    int x = numberInputCheck();

    if (x == 500) {
      break;
    }

    delay(500);

    for (int i = 0; i < x; i++) {
      digitalWrite(LED, HIGH);
      delay(500);
      digitalWrite(LED, LOW);
      delay(300);
    }
  }
}

int numberInputCheck() {
  while (true) {
    for (int i = 0; i < 4; i++) {
      outputAllBut(i);
      for (int m = 0; m < 4; m++) {
        if (digitalRead(inputs[m]) == LOW) {
          switch (i) {
          case 0:
            if (m == 3) {
              return 500;
            } else {
              return m + 7;
            }
          case 1:
            if (m == 3) {
              return 500;
            } else {
              return m + 4;
            }
          case 2:
            if (m == 3) {
              return 500;
            } else {
              return m + 1;
            }
          case 3:
            return 500;
          }
        }
      }
    }
  }
}

void outputAllBut(short int b) {
  for (int i = 0; i < 4; i++) {
    if (i != b) {
      digitalWrite(outputs[i], HIGH);
    }
  }
}

int inputCheck() {
  for (int i = 0; i < 4; i++) {
    if (digitalRead(inputs[i]) == LOW) {
      return i;
    }
  }
  return 5;
}

for reference, the numberInputCheck function is the one that might go wrong here, I want it to wait for an input and return the number that I pressed. i is the rows and m is the columns.
My problem is that whenever I press the keypad at one of the numbers, it will give me a random amount of times that the LED turns on, there doesn't seem to be any pattern.
m+1, m+4 & m+7 is because m is my columns so if I press 0 and the row is 0 then I add 1, same goes with everything else. Can anyone help me?

Your outputAllBut function is wrong. It turns all but the specified output high, but it doesn't turn the specified output low. As a result, after calling it multiple times, you end up with all of the outputs high forever (since you don't have code anywhere else that would turn them off), so it's just a question of timing which one it considered "on" any time you press a button.
Side note: toggling the outputs between low and high to do the matrix read is dangerous, as pressing multiple buttons at a time can cause a short circuit that way. You should instead always keep all of them low, and control which one is active by setting it to output mode and the rest to input mode.

your answer helped the situation but I'm still getting mixed signals. my button 2 just pressed only once for some reason

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


text:
8 bits 62.5kHz PWM signal
// TIMER/COUNTER 0
// PIN 6(OC0A) = NON-INVERTED [_BV(COM0A1)]
// PIN 5(OC0B) = INVERTED     [_BV(COM0B1) | _BV(COM0B0)]
// PWM MODE    = FAST PWM     [_BV(WGM01) | _BV(WGM00)]
// PRESCALER   = 1            [_BV(CS00)]
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(COM0B0) | _BV(WGM01) | _BV(WGM00);
TCCR0B = _BV(CS00);

// TIMER/COUNTER 1
// PIN 9(OC1A)  = ?????
// PIN 10(OC1B) = ?????
// PWM MODE     = FAST PWM 8BIT[_BV(WGM12) | _BV(WGM10)]
// PRESCALER    = 1            [_BV(CS10)]
TCCR1A = ????? | _BV(WGM10);
TCCR1B = _BV(WGM12) | _BV(CS10);

// TIMER/COUNTER 2
// PIN 11(OC2A) = NON-INVERTED [_BV(COM2A1)]
// PIN 3(OC2B)  = NON-INVERTED [_BV(COM2B1)]
// PWM MODE     = FAST PWM     [_BV(WGM21) | _BV(WGM20)]
// PRESCALER    = 1            [_BV(CS20)]
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(CS20);

Hi. My intention of writing the codes is to clarify my doubts regarding arduino timer.
First of all, I intend to have 6 consistent PWM outputs which is 8 bits and runs at 62.5kHz. The confusion here is FAST PWM and PHASE CORRECT PWM. TIMER 1 and 2 is usually presented as PHASE CORRECT PWM. So does changing the PWM mode of TIMER 1 and 2 to FAST PWM enables the PWM to reach a frequency of 62.5kHz (prescaler set as 1)? Is the code that I have written correct? Do take note of the inverted and non-inverted pin mode.
Secondly, as seen from my code above, Timer/Counter 1 is not properly written (?????). I wish to control pin 9 and 10 so that it can invert or non-invert individually.
Timer 0 and 2 allows me to set the pins individually (inverted and non-inverted). However from the atmega328p datasheet, Timer 1 control register is  weird. How can I set the register so that I can do what I want to do which is to control the pins individually?

I truly apologize for any confusion caused by my sentence structure. I am aware I have a poor way of organizing and presenting my idea. And lastly, thank you for taking your time reading these doubt of mine.

Just out of curiosity, why have 6 outputs all at the same frequency? Why not just have one or two?

I am working on a DC/DC converter project. Initially I am using 2 outputs only so only Timer0 is used. But now i need to control 2 extra things, thus a total of 4 outputs to be controlled. Reaching to this point, might as well learn how to use all 6 of them :)

Where did you get your datasheet from, exactly. I have several datasheets for ATmega328P (for 2013 and 2014), but I certainly do not have the same info as you have. The chapter titles themselves look weird. On mine, I have "TCCR1A – Timer/Counter1 Control Register A" and the bits description is complete. It seems new datasheets edited by microchip have lost quite some information. Try to find youself an older datasheet from Atmel.

And for your information, the bits COM1xx are the same as for COM0xx and COM2xx, in terms of their position in the register.

The datasheet I referred to is atmega328p 2016. I just checked an older version and you are right! It shows me 'COM1A1|COM1A0|COM1B1|COM1B0'. Now down to one question. Will be more than willing to set your answer as answered if you can answer the first question together with the second question

As mentioned in my comment, it seems latest ATmega328P datasheet from Microchip have lost some information. I use the datasheet from 2014 and it is complete:

Regarding PWM frequency of Timer1 and Timer2, as you spotted yourself, those timers support Phase Correct PWM in addition to Fast PWM.
To reach a 62.5KHz PWM frequency, you have to apply the formulas available in the datahseet.
For Fast PWM

i.e. with 16MHz MCU frequency and prescaler set to 1:

fPWM = 16000000/(1 . (1 + 255)) = 62.5 KHz

which is what you want.
For Phase Correct PWM

i.e. with 16MHz MCU frequency and prescaler set to 1:

fPWM = 16000000/(2 . 1 . 255) = 31.4 KHz

which is the maximum PWM frequency you can get here.
Conclusion
To get 62.5KHz PWM frequency with Timer 1 and Timer2, you shall absolutely use FastPWM, not Phase Correct PWM.
For Timer 1, that means setting WGM12 and WGM10 to 1.
For Timer2, that means setting WGM21 and WGM20 to 1.
Hence your code snippet is correct towards what yu want to achieve.

for an arduino, 16Mhz / 62.5Khz = 256 -> prescaler = 1 and single sloped pwm, with its top at 255.
the number of timer modes meeting those conditions are limited.
if you move outside of arduino, a lot more of choices.


text:
How to connect an ESP8266 using an ESP-01 adapter to an Arduino Uno?
I am pretty new to Arduino programming and wanted to learn how to connect an ESP8266 generic WiFi module to an Arduino Uno using the ESP-01 Adapter shown in the image below.
I tried doing it on my own while connecting the Vcc, GND, Tx and Rx pins of the adapter to the 5V, GND, Tx and Rx of the Arduino Uno respectively but was getting the following error while trying to upload the sketch:

warning espcomm_sync failed
error espcomm_open failed
error espcomm_upload_mem failed

To the best of my knowledge there is no tutorial on the internet that explains about the above mentioned adapter and its interfacing with the wifi module in detail. It would be a great help if someone could please guide me through the process so as to convert my Arduino into a server.

io 0 most be LOW at startup to put esp8266 into flashing mode

@Juraj thanks for the reply, could you please help me with the exact steps that I need to follow or refer a tutorial where I can learn about the same including the adapter part.

I enhanced the answer

Recommended tutorial
you can't flash an esp-01 module with this adapter, unless you find a way to connect io 0 to ground in this setup

I have this type of adapter with esp8266 glued. I can't recommend this type of adapter boards. Easier is to use a development board like Wemos or NodeMCU with on-board USB adapter. And they are cheap.
The adapter has the esp-01 2x6 header J2 but the io 0 and io 2 pins were not connected on my version. I patched io 0 to JP2 header to be able to flash the module. On the picture you see a paperclip jumper connecting GPIO0 to ground.

I'm going to leave this here as well: Flashing the ESP8266 using an Arduino UNO

...connecting the Vcc, GND, Tx and Rx pins of the adapter to the 5V,
  GND, Tx and Rx of the Arduino Uno respectively...

At least one issue is the serial connections. Rx and Tx need to be cross-connected with whichever Arduino pins you are connecting to the ESP. Using the Arduino's built-in UART, Arduino pin #s 0 and 1, cannot work for uploading (to either board) since those pins are used to communicate with your PC.
If you are trying to upload to the Arduino, try removing the ESP adapter board during the upload. Even with that, communicating at run-time from the Arduino to the ESP (with it plugged back in, of course) may run into interference from the Arduino's 16U2 chip (serial <-> USB processor) which is hard-wired to those pins. And if it does work at run-time, you will have to forego serial communication to/from your PC, which uses those same pins.
The alternative is to use the SoftwareSerial library in your code, which will let you select two other Arduino pins as a second "software UART" to communicate to/from the ESP. This route come with it's own initial-setup complexities - you'll first have to change your ESP's default baud rate to 9600, about the maximum that SoftwareSerial can reliably receive. See my post about how to do this. To implement it, you'll need a short sketch that continuously tests Arduino's terminal for an available character and sends any to the ESP, and likewise tests the SoftwareSerial and sends to the Arduino's terminal.

did you read my answer? the part about io 0? and you can flash esp8266 over Uno. with RX to Rx and TX to TX and Armega in reset. (or with pass-through sketch. even over SoftwareSerial). but first the esp8266 must be in flash mode initiated by io 0 LOW


text:
Why can't I define the constant A0 (some pin) to something?
What I'm doing wrong or why is it not working:
#define Uin A0;

void setup() {
}

void loop() {
  analogRead(Uin);
}

Results in a Error (expected ')' before ; token.
I thought #define just exists as a place holder.

Because you have a ; at the end of your #define.
#define Uin A0;
analogRead(Uin);

becomes:
analogRead(A0;);

The Arduino website mentions this in their reference. For more in-depth detail about the C pre-processor you can read the (rather large) manual here.

That's it. Thank you.
Could you please link to the reference. (It is also answered there - I'm sorry) [In 5 min I can accept the answer]
link


text:
How do I load an image using fopen()?
I am trying to write a program that fopen()s an image so I can use it later.
I've wired my SD card adapter exactly the way shown here:
[![enter image description here][1]][1]
And I'm using the following code to fopen():
FILE *streamIn;
streamIn = fopen("pic.bmp", "r");

When  I compile, I get the following error:

In function main:
ccA5H011.ltrans0.o:(.text.startup+0x29a): undefined reference to `fopen'

I have the most up-to-date Arduino software.
I am using the Arduino MEGA.
The image "pic.bmp" is 100x100 and is not in any folder of the SD card, it is located right in it instead (If I click on the SD Card in "My Files" when it is plugged into my computer, pic.bmp is there).

Where did you find fopen() in here?

You need to use the SD library and its functions instead.

Simple answer: use the SD library provided by the IDE.
Long answer: fopen etc are designed for use with an operating system. While it is possible to 'bend' them to work without a kernel or filesystem abstraction layer, it's not easy. The AVR compiler and libraries don't provide the facilities for doing it.
So you need to use the method that is specific to the Arduino, which is contained in a library supplied with the IDE called SD.h. It has examples with it to show you how to use it.
There are other alternatives, as well, such as the much better written FatFS that has been ported to many platforms, Arduino included.


text:
Wiring LED strips in parallel & ground
Schematic:

I am making some light fixtures controlled by an Arduino UNO. Each fixture will host two approx. 1 meter long analog RGB LED strips with a current draw at full power of ~1.2 A per meter. I have a 12 V power supply that I will wire directly to the strips, with the RGB channels wired to the Ardiino PWM pins via NPN MOSFET (note in the schematic I've only shown one color channel for simplicity, but there would of course be three transistors hooked up to three PWM pins). The Arduino itself will be powered by USB.
My main difficulty in wiring the system is that for so much current I need fairly thick wire. The pads on the LED strips are delicate and I have several times damaged them by mechanical stress from the wire while soldering. The thick wire also crowds the narrow space between the pads creating a risk of a short. Therefore my first question is (bear with me, I'm pretty new to this):
1) How should I wire the LED strips?
My thought is to wire up the strips in parallel with thinner, more flexible wires. This brings up two sub-questions:
1a) How should I join the thinner wires to the thick wire coming from the power supply?
1b) At the junction between the wires leaving the lights and running to the transistor, does the wire need to become thick again? (I think the answer is yes – the current should be the same as coming out of the power supply.)
I also am unsure about the ground.
2) Does the wire coming from transistor to ground need to be joined to the ground pin on the Arduino or can it run directly to the ground terminal of the power supply?
Sub-question:
2a) Does the wire coming from transistor to ground need to be thick?
I don't really understand how transistors work (basically my understanding is that the Arduino uses a small amount of current over the PWM pins to somehow control how much current is allowed to flow through the rest of the circuit.
I've drawn a schematic showing how I think maybe this system needs to be wired up. Do I need to make changes?

You need to connect the two grounds. Otherwise there isn't a path for the electrons to flow from to Arduino to the mosfe, and back!

Thank you! No one else has addressed that question yet.

It's all a question of losses.
Wire is basically a resistor. The thinner and longer the wire the higher the resistance. Current flowing through a resistor causes a voltage drop across the resistor.
Long thin wires with large amounts of current through them will basically mean you get less than your 12V at the LED strips. The question has to be: how much less a voltage is tolerable?
Each strip takes 1.2A. Take for example 24AWG wire. That has a resistance of 0.0842Ω per meter. With 1.2A flowing through a meter of that you get 0.10104V dropped across the wire. That turns your 12V into 11.9V.
Conversely, a meter of 14AWG wire has a resistance of 0.00829Ω - so you would lose 0.009948V over that length.
Now you want two strips - which is double the current, and thus double the voltage drop. On 14AWG you would lose about 0.02V over a meter. Not really enough to worry about. But you can't connect 14AWG to the LED strips. You can connect thinner wire (say 24AWG as above) to them. But that looses too much voltage. Well - over a meter it loses too much voltage. But what about over, say, 10cm? That's a 10th the length of before, and so a 10th the voltage loss: 0.01V.
So what is to stop you having a short length of thin wire connected to the LED strips, which then connects to a longer length of thick wire? Answer: absolutely nothing.
And how do you join them together? Well, I find the best way is with solder. Insert the thin wire (stripped) into the end of the fat wire (stripped) and twist them together (axially) then flood the joint with solder.

Is there any heat dissipation risk?

From what ... ?

Resistive/Joule heating in the thin gauge wire.

Not at those lengths / currents. P=I²R = (10cm wire) 1.2²x0.0842 = 0.121W

I think you are overestimating the size of wire required to attach to the LED strips, I have connected a lot of single color LED strip (in excess of 1mtr) with the wire that was already attach and it was reasonably light gauge.
Look at this Example on Ebay and you can see what i mean.
I am note an Electrical Engineer so i don't know the method to calculate the minimum wire gauge, but if in doubt contact the manufacturers and ask them or search on the web.
As for the Transistor mounting/wiring you would mount that on a small circuit board with terminal block fitted for ease. Any power/connecting wire should not be less that used to the LED strip.
Also you will need a current limiting resistor attached to the Base pin on your transistors. You will have to work out the value of that based on the spec sheet.
There is a bit of learning required first, once you have researched the above you will have you exact answers.

For mosfets the base resistor isn't strictly necessary. To calculate the wire gauge you have to measure the resistance. After that combined with the max current you can calculate the voltage drop across the wire, and the power disappated in the wire.

@Gerben It depends on the gate capacitance. Too much gate capacitance can cause too much inrush current which can cause voltage droop on the pin. With big MOSFETs often come big gate thresholds. If the droop drops below the threshold the MOSFET will fail to switch properly and you will get large switching losses. By including a small resistor you limit that inrush current and thus avoid the droop.  I like to include a 100Ω resistor in all my gates to be safe. Yes, it slows down switching slightly, but helps protect the pin from stress.


text:
Decoding 2.4G RF remote controller?
There is tons of information on how IR remote controls work and how to use an Arduino to decode those signals and use any IR remote to suit your project. But I couldn't find much info about 2.4G RF remotes.
I want to control a string of addressable LEDs and cycle through different patterns using one of these 2.4G RF remotes

Is it possible to use these remotes with Arduino? If yes, how can I read the signals and assign tasks to different buttons on the remote?

First step would be to open it up, and see what chip is inside. Just the 2.4GHz isn't saying very much, as 2.4Ghz is also used by WiFi, Bluetooth, some Zigbee. All different kinds of encodings and protocols.

The usual approach for 2.4 GHz is to open the product, identify the radio chip, and use a USB logic analyzer on the SPI bus that usually connects it to the MCU to capture the configuration and data traffic, and figure out what the configuration register accesses mean from the radio chip data sheet.
The occasional appearance of combined MCU/radio parts prevents that approach, but often that is only used on one end of the link and the other will still have a distinct MCU and radio with an SPI bus in between.
This is heavily practiced in the radio control community, as people want to use their nice transmitters to fly cheap toys.  And there is code out there to transmit compatibly with some of the odder chips like the X297, using more common ones like the NRF24L01 or its workalikes from Beken, etc.
A key advantage of SPI sniffing versus over-the-air sniffing is that the usually implemented channel-hopping doesn't mean you loose the signal ever time it moves to a new channel - and you actually get to the see the frequency registers being written.  To capture a hopping scheme over the air, you would need something more like a spectrum analyzer to figure out the sequence, and then have software track the signal while you attempt to figure out the data.  However, a remote which only sends occasional button presses may not use hopping in the way something sending data continuously (like an R/C set, or possibly a keyboard/mouse) would.

I was having same issue and at the end of the day I have made it working. For the communication I have used openmili library  (project started by Henryk Plötz who has reverse engineered protocol for communication of these remotes). This didn't work with new remotes as they have changed couple of things:

Listens on a different channelset (this was true of different bulb types among the old bulbs too). The new bulbs use channels 8, 39, and 70.
Different PL1167 syncword. It uses 0x7236 , 0x1809 .
Packets have 9 bytes instead of 7.
Packets are scrambled. The same command can look completely different.

(information taken from Chris Mullins blog)
Confirmation of these info I have found in ESP8266 Milight hub project where I have found config for remotes (https://github.com/sidoh/esp8266_milight_hub/blob/master/lib/Radio/MiLightRadioConfig.cpp)
In my case I was using rgb+cct remote so it tells me that I should use 0x7236, 0x1809 as syncwords, packet length 9 and channels 8, 39, 70.
Applying those changes I was able to get data from the remote. One more usefull link.

If it is based on the nRF24L01+ (or the nRF31512C SoC, which is a combined MCU and nRF24L01+ in one chip, and used in most wireless mice and keyboards) then it may be possible to sniff the signal. If not, you're probably not going to have much luck.
You'd be better off trying to hack the existing receiver that is paired with the remote to get usable signals out of it.


text:
Converting a char* with numbers to a double is giving me 0.0 in return
I recently made a thread where I read BLE data that has three different numbers/values. The data changes but it typically looks something like this:
0,5 -0,1 0
I successfully store the three numbers in a unique char* but when I try to convert the char* to a double I get the value 0.0 in return.
This is my code:
        while (tok)
        {
            if (currentRow == 0)
            {
              currentRow = currentRow +1;
              double a = atof(tok);
              Serial.println (a);
            }

            else if (currentRow == 1)
            {
              currentRow = currentRow+1;
              double b = strtod(tok, NULL);
              Serial.println (b);
            }

            else {
              currentRow = 0;
              double c = atof (tok);
              Serial.println (c);
            }

            tok = strtok(NULL, " ");
        }

Comments are not for extended discussion; this conversation has been moved to chat. Comments are for clarifying the question - not answering it.

The value that was being sent used a comma "," instead of a dot "." that was needed in order to convert the number.


text:
Super-fast USB communication; how is it possible?
On Arduino forums, there's a post where someone improved the USB communication and made it super-fast. I don't understand how he did this, and I'm trying to recreate this, but failing.
My test code
I made a simple program on Python for testing; here it's:
import serial
import sys
import datetime

ser = serial.Serial(
   port = 'COM9',
   baudrate = 26*115200, #biggest number acceptable by python
   parity = serial.PARITY_NONE,
   stopbits = serial.STOPBITS_ONE,
   bytesize = serial.EIGHTBITS
)

if ser.isOpen() == False :
   ser.open()
   if ser.isOpen() == False :
      print("Can't open serial port")
      sys.exit(1)

start = datetime.datetime.now()
s = b'abc'*10000
ser.write(s)
total_len = len(s)
end = datetime.datetime.now()
speed = total_len/(end - start).total_seconds()/1e6
print("Speed: " + str(speed) + " MB/s")

And I made a simple Arduino program to read:
char buf[500];

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

void loop() {
  if (Serial.available() > 0) {
     Serial.readBytes(buf, 500);
  }
}

With this, my best result was 0.2 MB/s with my Arduino mega. However, on that post, they reached 12 Mbit/s = 1.5 MB/s!!!!! This is insane!
Atemmpting to achieve their result:
Apparently Arduino libraries are different than before, so just taking their code and putting it in my arduino\avr\cores\arduino directory doesn't work. So I started trying to edit the code myself. I'm a C++ dev, so supposedly this should be doable... but...
The problem I faced
So eventually, the problem I faced was that there are two Serial communication modes (apparently) UART and CDC. The code from the forum uses CDC, while my Arduino IDE uses UART. I tried enabling CDC using:
#define USBCON

but this lead to the error:
error: #error "Targets with both UART0 and CDC serial not supported"

At this point I don't know how to continue, as I'm not a hardware expert. But I'd like your opinion on this whole thing:

Is it possible to get these speeds? How?
If it's, why is it not in the default Arduino library?
In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

Is it possible to get these speeds? How?

Not without a 32-bit Arduino with a USB interface.

If it's, why is it not in the default Arduino library?

Because you can't use it on an 8-bit Arduino without a USB interface.

In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

Yes, get a 32-bit Arduino with a USB interface such as the Arduino Due that the poster of that thread used.

Oh, I see. So the only problem is that I'm using mega? So Due or Teensy 3.6 should be fast? Thanks for explaining! I ordered these and they're on their way :)

You can't use that code on the Teensy, it's a completely different system. The Teensy already has very optimized USB anyway.

Hello again. May I ask, what's the best speed I should expect from Teensy 3.6? I got 1.15 MB/s. I was hoping of getting to the full 480 mbps = 60 MB/s. Is that possible?

You'd be better off asking that kind of thing on the teensy forums. I'd say 1.15MBps on a HS USB connection is fine for a bulk endpoint.


text:
Arduino/ESP8266 no SPI data coming from MCP3008
I'm using an ESP8266 (NodeMCU Dev Kit v1) to read analog data via an MCP3008 ADC chip.
However I'm receiving only zeros when I know non-zero data should be present. I'm using the following code, which works perfectly when using the MCP3008 with my Arduino UNO. Using verbose mode on compilation, I can confirm that when compiling for the ESP8266, that is indeed linking the ESP8266 SPI library.
Am I missing something here in the code?
#include <SPI.h>

#define CS_PIN 15 // Use 10 when compiling for Arduino

int adcRead(int channel) {
  if ((channel > 7) || (channel < 0)) {
    return -1;
  }

  digitalWrite(CS_PIN, LOW);

  SPI.transfer(1);
  uint8_t r1 = SPI.transfer((channel + 8) << 4);
  uint8_t r2 = SPI.transfer(0);

  digitalWrite(CS_PIN, HIGH);

  return ((r1 & 3) << 8) + r2;
}

void setup() {
  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setFrequency(1000000); // 1 MHz -- remove line when running on Arduino UNO
  Serial.begin(9600);
  digitalWrite(CS_PIN, HIGH);
}

void loop() {
  Serial.println(adcRead(0));
  delay(50);
}

In terms of wiring, I have the following
MCP3008   ESP8266
V_DD      3v3
V_REF     3v3
AGND      GND
CLK       GPIO14 (D5)
D_OUT     GPIO12 (D6)
D_IN      GPIO13 (D7)
CS        GPIO15 (D8)
DGND      GND

I dont see any pinMode(CS_PIN, OUTPUT);

That fixed it! Guess I managed to overlook that.

I was having trouble with this code and setup with the Adafruit Feather HUZZAH ESP8266.
Solution
In addition to adding the pinMode(CS_PIN, OUTPUT); to setup(), I also dropped the frequency to something much lower. In my case, dropping the frequency to 10000 gave me good readings.


text:
How to call 5 different functions in a loop based on serial input?
I have 5 types of such functions with different input parameters.
blink(int a,char* b, int c);
fade(int a,int b,int c);
split(int a,int d);

and so on from serial input what i want is to call this three functions in any combinations that can be later executed in a loop. For example  my serial input is this ..
[blink(a,b,c),fade(a,b,c),blink(a,b,c),fade(a,b,c),split(a,d),blink(a,b,c)]

The  Code should also be saved  in memory so that when a person reset Arduino. The order of functions execute without waiting for serial input.The order of functions would get change only when person enter serial data to arduino.
I have no clue where to begin please help me out.

This sounds very much like a school assignment?

@MikaelPatel That's My school assignment Dot matrix demo  for which i am making an custom app to add multiple transations  with arduino

This answer isn't going to give you the code to solve your problem, it is just ideas that you can look at and see what suits you best.
You should be able to find an example on how to read from a serial connection, I'm sure there is at least one example in the IDE.
You need to work out how to encode your data, having it in nice human friendly format (like you have above) is great if you are processing it on a PC but on a processor that is slow and have very limited memory using A,B,C... as the function names might be more practical.  It will be smaller to store and quicker to compare.
You want to store the input so it can be read back later.  There are a number of ways you can do this but they all need a non-volatile storage medium.  You could use an SD card, obviously you'd need an SD reader and the type of reader you get will affect the code you need, but these can be problematic.  You can also use EEPROM chips that, you can get little I2C interfaced modules, they have less space than an SD card, but are generally faster (they also have a shorter lifespan, but don't worry I don't you'll ware one out).  You can also use the EEPROM that is in the Arduino itself (I've never done this).
It is best to build you program up in small parts, get the reading from serial working, then calling functions, then saving and loading.  That way you only have to debug a small bunch of issues at once.  If you wanted you could abstract the storage device away from the code by writing a base class that has virtual save and load functions.  You could then inherit from this class for the EEPROM or the SD card and changing wouldn't affect the rest of the code.
Like I said at the start I appreciate this answer hasn't given you a step by step guide on how to solve your problem, but hopefully it has given you a few pointers on what you could do and you can research the options from there.  Remember when you get stuck on one particular aspect just post a minimal example of what you have tried and explain what you expect it to be doing and people will be more than willing to help.


text:
Traffic lights using timer
My traffic light code for the Arduino doesn't run. I was wondering if anyone could point out where my issues lie. The red and green LEDs should be on for 15 seconds and the amber on for 5 seconds.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdint-gcc.h>
/*15 second interrupt*/
#define INTERRUPTS 975

/*
 * col = current colour of light.
 * 'g', 'a', 'r', 'o'
 */
volatile uint8_t count;
volatile char col;

ISR(TIMER0_OVF_vect)
{
    count++;
    if (count >= INTERRUPTS){
        if (col == 'g'){
            /*switch to amber*/
            col = 'a';
            /*reset counter*/
            count = 0;
            /*timer counter to 171 as we only need 85 clicks for 5s*/
            TCNT0 = 171;
            PORTD = 0b00000010;
        } else if(col == 'a'){
            col = 'r';
            count = 0;
            TCNT0 = 0;
            PORTD = 0b00000100;
        } else if (col == 'r'){
            col = 'o';
            counter = 0;
            TCNT0 = 171;
            PORTD = 0b00000010;
        } else if (col == 'o'){
            col = 'g';
            count = 0;
            TCNT0 = 0;
            PORTD = 0b00000001;
        } else{
            return;
        }
    } else{
        if(col == 'g' || col == 'r'){
            TCNT0 = 0;
        } else if(col == 'a' || col == 'o'){
            TCNT0 = 171;
        }
    }
    return;
}

int main(void)
{
    /* normal mode */
    TCCR0A = 0b00000000;
    /* prescaler = 1024 */
    TCCR0B = 0b00000101;
    /* enable overflow interrupts */
    TIMSK0 = 0b00000001;
    TCNT0 = 0;
    sei();
    /*Initialise output*/
    DDRD = 0b11111111;
    count = 0;
    col = 'g';
    PORTD = 0b00000001;
    while (1){
    }
}

#define INTERRUPTS 975

volatile uint8_t count;

if (count >= INTERRUPTS){

count is an 8 bit integer, so the maximum value of it is 255. Therefor count will never be bigger of equal to 975.
Use volatile uint16_t count; instead.
PS instead of messing with the TCNT0 register, I'd use 2 different values of INTERRUPTS to change between 15 and 5 second intervals.
Something like if( count>=975 || ( (col=='g'||col=='r') && count>=325 ) ){

How would I time using 2 different values? Won't the 5 second count occur every time so the 15 second interrupt never occurs?

Something like if( count>=975 || ( (col=='g'||col=='r') && count>=325 ) ){

Ok, nice, thanks for the advice. Does everything else look ok, I won't have a board to test it again until Monday.

It would be nicer to use an enum rather than a char for the current colour. And then use a switch rather than if () {} else if () .... But those are style points rather than functionality.

Looks okay. Though I'd make it more readable. E.g. use two extra letters and change col to color.

As far that i understand, you set the color using the Ports directly. In case green and red you set PORTD = 0b00000010;

Yes, for example to turn on the amber light I directly toggle the port so the amber LED will be turned on. If the color is currently green or red then 0b0000010; will turn on the next LED which is amber in both cases.

Ah, yes i see, my fault.

Well that's the theory anyway, but it doesn't work for some reason

And what does it do instead, is the timer not working, or does the lighth not work?

The lights are the issue

If you want solution with a timer, I suggest to setup a 35 second cycle (35 = 15+15+5).
Then, you will trigger next LED when 0,15,30 seconds passed, and restart cycle at 35 seconds.
Other ways to achieve same effect are:
1. Use classic delay() function.
while (true)
{
    TurnOn(Green);
    delay(15000);
    TurnOn(Red);
    delay(15000);
    TurnOn(Amber);
    delay(5000);
}

use millis() function


text:
Passing a long string from SoftwareSerial to Serial
I'm currently playing around with a GPRS shield on an Arduino Uno, for which I have to write raw AT commands over the SoftwareSerial. At the moment, I just want to be able to talk to the GPRS from my PC, so I've written a really basic program to send serial in two directions:
#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);

void setup()
{
  GPRS.begin(19200);
  Serial.begin(19200);
}

void loop()
{
  if (GPRS.available())
  {
    Serial.write(GPRS.read());
  }

  if (Serial.available())
  {
    GPRS.write(Serial.read());
  }
}

So the communication looks something like this:
         HW               SW
+----+ Serial +-------+ Serial +------+
|    |        |       |        |      |
|    +-------->       +-------->      |
| PC |        |Arduino|        | GPRS |
|    <--------+       <--------+      |
|    |        |       |        |      |
+----+        +-------+        +------+

This seems to work fine for shorter commands:
AT+CPIN?

+CPIN: READY

OK

But I'm really interested in doing a NETSCAN to see what networks are available. When I try it, I get this:
AT+CNETSCAN

------MOST SUITABLE CELL------
Operator:"YES OPTUS",MCC:505,75

And that's all. I pulled out a logic analyser to spy on the serial pins themselves, and it appears that the complete message is being sent back to the Arduino from the GPRS module perfectly okay - but for some reason, it gets cut off before it reaches my PC.
This is what the logic analyser sees over the SW (top two tracks) and HW (bottom tracks) serial lines:

So it appears that the entire GPRS response is being read by the Arduino before it starts to send anything back to the PC, and I assume that some sort of buffer has been overrun and I only get the start of the message.
So - how should I go about passing through long strings between serial ports like this? I assumed that using if (X.available()) instead of while would alleviate any issues with long strings (because it appears that this way the two serial ports should take turns with one byte at a time), but is that assumption incorrect?

The output of the logic analyser is pretty clear. The problem will be a buffer overflow. One question is whether it is the receive buffer or the send buffer.
My best guess is the receive buffer: What could go wrong with your code is that the interrupts used by SoftwareSerial take precedence over the ones used by HardwareSerial. So maybe that's the reason why nothing is sent before the full message is received.
The SoftwareSerial library has a debug flag (_DEBUG) which you can enable to pulse a pin as an overflow indictator.
What I would try is to swap Software- and HardwareSerial (i.e. use SoftwareSerial for the communication with the PC). If the problem is as described above it should then vanish because the HardwareSerial does not block interrupts (nor the program flow) while receiving a byte.

Using software serial to PC appears difficult as far as I can tell! Is there a good guide somewhere? My other possibility is trying to get my hands on a Leo, or any other board with more hardware serials.


text:
My Computer Doesn't Realize ESP8266 ESP-05 is Connected or not
I wired ESP-05 to my usb-to-ttl as images below.
I connected it to USB #2 port, and my computer seems not knowing this.

I also tried to send "AT+RST" through Realterm but, it didn't work neither.

Can you try to describe what is happening and what the expected outcome of the action should be, maybe what you have tried. From what i can see everything looks fine, the RX/TX connection is where most people do wrong, but it looks like it is connected properly.

your problem is not with the ESP, but with the usb-ttl converter. You need to install manually the PL2303 driver.