text:
esp8266 not responding to the AT commands
I am integrating Arduino Uno with the WiFi module ESP8266.  I have already made the connections between the ESP8266 and the Arduino Uno which are :
txd uno -> rxd esp8266
rxd uno -> txd esp8266
gnd uno -> gnd esp8266

The VCC and chid pind of ESP8266 are connected to an external supply of voltage 3.3V and 160mA current. The code is getting uploaded onto the Arduino and the ESP8266 is also getting powered on.But i am facing a problem while i send the AT commands on the serial monitor. It is not responding even though the red led is on constantly and when i press enter after sending the command , the blue led blinks for a few seconds.
Do i have to update the firmware of the ESP8266?

possible duplicate of esp 8266 not getting programmed

It is not a duplicate of the above question.In that the led lights are not glowing but here the esp8266 is not responding to the AT commands.

It is a duplicate since you have made the same basic error in your wiring and are trying to incorrectly communicate in the same way.

Could you explain to me what is the basic error which i am making?

You cannot use the TX/RX pins both for communication with the PC AND communication with an external module at the same time. You've effectively got the ESP wired backwards for communication with the serial monitor, but if you turn it around it would be wired backwards for communication with the Arduino. If you want to communicate through the serial terminal you will have to connect the ESP through different pins and pass the data through using SoftwareSerial.

I don't think you should connect the TX of the arduino directly to the RX of the ESP, as the ESP only accepts 3.3v signals, while the Uno uses 5v signals.

160mA is barely enough to power the ESP.  That chip can draw up to 1A under the right conditions if i remember correctly.

Please save this chip from a horrible death!  Get your voltages down to 3.3v on the signal pins, or you will kill it!

I have brought down the voltages to 3.3V by using a voltage divider.It is still having the same problem.

I am facing the same problem. I used Arduino due for communicating with esp8266. I have used serial1 for communicating with esp. after booting , whatever I transmit to esp , the same characters are returned to me. The esp itself looks fine as its SSID appears and I manage to connect it through wifi. can any one help in this regard.

I had same problem. It helped to connect GNDs of both power supplies namely the one powering the arduino and the 3.3V one powering the ESP8266.

Okay, I'll just summarize the stuff I've seen in the comments and answers. It's quite a basic issue? You'll find a lot resources on it on the web.
Current (draw of chip too high?):
Wireless communication can take a lot of current. You should have a good power supply. Arduino usually can't supply enough current. Check the datasheet of the chip to see it max current draw.
Rx/Tx (Wiring):
Be sure you send through the Tx pin, into the Receive (Rx) pin of the other device.
Also, you can't use the same Tx pins for USB communication AND to connect to the ESP, that basically won't work.
Voltage (3.3V vs 5V):
The arduino runs on 5V, but, the ESP on 3.3V you shouldn't want to mix these up.
It'll do in some cases. Putting 3.3V (Tx of ESP) on the Rx of arduino (5V) won't damage it. But the other way around is strongly discouraged. Use a logic level shifter or voltage divider between it.
Chip might be broken
If the chip isn't doing anything at all, you should take in consideration that it's possible the chip is broken... I've spent too many hours on debugging my code while the chip simply wasn't working. Also after having applied 5V to the ESP8266, this becomes quite likely.

I have taken into consideration all your solutions and done these things : 1. i am using a battery pack as a power supply and not the arduino. 2. i am using different pins for communicating between the usb and for communicating with the ESP. 3.i have connected a voltage divider circuit and brought down the voltage to 3.3V while connecting the tx of arduino to rx of esp. But i am still not able to receive anything from the ESP.

If you used 5V logic on the ESP you might've killed it. Are you sure the chip works?

We had a similar issue and landed up spending a lot of time figuring out what was going wrong, the following certainly helped us resolve the issue:

We set the Baud rate of the Serial communication to 1200. This started showing the responses from ESP correctly with no / minimal junk
We set the baud rate of communication with ESP to 115200. This ensured that the ESP received correct commands.
We ensured that each command we send is terminated by a CR for e.g. ESP8266.println(espCmd + "\r"); // where ESP8266 is SoftwareSerial ESP8266 (rxPin, txPin);
Also, powering the ESP module with 5V gave no responses from ESP. When we powered it with 3.3V only then it started to provide any response - initially response looked like junk due to mismatched baud settings.

Hope this helps.
(Sometime you may need to use both \r\n....)
Regards

But surely supplying the correct voltage to the board (3.3v) and level shifting the rx and tx lines so the ESP gets 3.3v and the Arduino gets 5v would work much better.

Seems like you didnt used any type of voltage divider or level shifter between the Arduino Tx -> ESP8266 RX Line. The ESP8266 isnt really 5V friendly. Too Bad the Arduino outputs 5V on all of it Pins.
You could still try it With a Voltage Divider using 2 Resistors or a level Shifter in hope it works. Elsewise With a 3.3V USB-> UART Module or get a New ESP8266

I was thinking that we only need a supply of 3.3v.Dint know that there has to be a voltage divider between the pins also.Do we need the voltage divider only between the arduino tx-> esp 8266 rx pins and not between the arduino rx -> esp 8266 tx?

Nope. The TX pin sends data out. That means the voltage is given by the Microcontroller. That means the Arduino Transmit Pin is 5V, which is Bad for the ESP, while the Transmit Pin of the ESP is 3.3V, With which the Arduino has no Problem to work With. You also need to remember these things when you work With screens vor Sensors. Always read the dataheet and search for the maximum voltage in the io ( 90% of the time you can search for Vio)

I have taken into consideration your solutions and done these things : 1. i am using a battery pack as a power supply and not the arduino. 2. i am using different pins for communicating between the usb and for communicating with the ESP. 3.i have connected a voltage divider circuit and brought down the voltage to 3.3V while connecting the tx of arduino to rx of esp. But i am still not able to receive anything from the ESP.

You missed something bro!
Arduino          ESP8266
Rxd       ->     Txd
Txd       ->     Rxd
3.3 V     ->     VCC
GND       ->     GND
3.3 V     ->     CH_PD

All above is right! Few days back, it was working. Suddenly, it stopped working but red led on it still lights.

Even I faced a similar problem , I was Abel to communicate using AT until I uploaded another program on to the board ,that is initially all esp boards come with the AT response firmware Once you upload ur code or program if I'm not wrong I guess it replaces it so you won't get any response
That was my personal experience using all sorts of esp8266 boards (01, nodeMCU ) etc
As I'm still learning plz correct me if I have projected it in the wrong way
Thanks


text:
Intermittent wifi/hotspot connection
I have an Arduino Mega 2560 with a cc3000 Wifi shield that is sending messages to dweet.io. Here is the relevant portion of my code:

// Post data to dweetio
    char data[125];
    sprintf(data, "?t1=%i&t2=%i&t3=%i&t4=%i&t5=%i&t6=%i&t7=%i&t8=%i&t9=%i&t10=%i&t11=%i&t12=%i&t13=%i&p=%i",
            (int)(t1*10.),(int)(t2*10.),(int)(t3*10.),(int)(t4*10.),(int)(t5*10.),
            (int)(t6*10.),(int)(t7*10.),(int)(t8*10.),(int)(t9*10.),(int)(t10*10.),
            (int)(t11*10.),(int)(t12*10.),(int)(t13*10.)),(int)(0);
    Adafruit_CC3000_Client client = cc3000.connectTCP(dweetioIp, 80);
    if (client.connected()) {
      client.fastrprint(F("GET "));
      client.fastrprint(F("/dweet/for/blahblah"));
      client.fastrprint(data);
      client.fastrprint(F(" HTTP/1.1\r\n"));
      client.fastrprint(F("Host: https://www.dweet.io\r\n"));
      client.fastrprint(F("\r\n\r\n"));
      // client.println();
      // Serial.println(F("Sent dweet\n"));
    } else {
      Serial.println(F("Sending dweet failed"));
      return;
    }

/* Read data until either the connection is closed, or the idle timeout is reached. */
long lastRead = millis();
while (client.connected() && (millis() - lastRead < 1000)) {
  while (client.available()) {
    char c = client.read();
    Serial.print(c);
    lastRead = millis();
  }
}

client.close();
// Serial.println("Connection to dweet.io closed");

In addition to this code, the loop does about two seconds of data collection and setting outputs.
This works most of the time when I connect to a typical wireless router. However, I want to deploy it away from my wifi source so I got a T-Mobile hotspot. When I use the identical code with the hotspot, it only successfully sends the message about one out of ten tries (sporadically though, not on even intervals).
The code doesn't report any errors. Anyone have any suggestions on how to debug this?

Have you been able to verify that the hotspot is reliable in the location with a laptop or something?  The other thing that would be worth trying is bumping your timeout to 5000 or so.  Cellular data connections can be kind of slow, resulting in longer timeouts.

@Butters I checked the connection speed. My router does 15ms ping, 4.7Mbps download, 8.2Mbps upload and the hotspot does 35ms ping, 4.2 download, 2.2 upload. I don't have a good reference- is that a big enough difference to cause the problem? As for the timeout, I only really care about the upload so that timeout shouldn't be a big deal, right?

Ya, you're probably correct, and your speeds should be fine.  So you don't get any errors at all in the code, or you don't get any compile errors?  Do you see the Sending dweet failed in your serial monitor?

Code-wise, it appears to run fine. It reports that it sent the information.

Interesting.  You might have to run Wireshark to inspect the traffic on the network and see what is actually going on.  Good luck!

source: Stack Exchange

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

sort: votes


text:
Choosing wireless tech for lowest possible lag
I am drafting a pub quiz project, where the Referee gives a signal and multiple players push their buttons. The first to push wins the right to give an answer.
I want all buttons (referee's + X players) to be wireless. Since the best quiz players can click a button within 10ms of the signal, it is very important that there is a very, very little variance in ping between different buttons. I cannot have players shouting "my button is laggy!" On the other hand, I don't want to use more expensive/complex tech than needed.
SO, what would be the optimal wireless tech to use? Please share your experience from similar projects (or just theoretical knowledge :) Here's what I researched so far (correct me if I'm wrong):

Bluetooth 4 LE (as in RFduino)
Pros: 3-6ms latency (advertised), low energy
Cons: cost, not more than 7 buttons to the device
Wi-fi
Pros: 2ms latency (I justed pinged my wi-fi router), dozens of buttons if need be
Cons: cost, power-hungry
RF data tranceiver
Pros: dunno, cost seems to be a bit smaller
Cons: multiple buttons at the same frequency will probably create a lot of noise
Simplest "Radio remote"
Pros: zero lag since it's all electromechanical, no data
Cons: multiple buttons at the same frequency won't work

So, did I miss anything? I appreciate any guidance.

How many buttons in total?

The smallest possible requirement is 4, the normal case is 8, anything more would be welcome - I'd like it to be very flexible for some crowd entertainment.

Human reaction time is over 200ms. See https://www.humanbenchmark.com/tests/reactiontime/statistics,

@user31481 So what? Humans can perceive latency under 2ms. See links in the appendix: https://danluu.com/input-lag/

I've used NRF24L01+ chipset 2.4GHz wireless modules with Arduino before, and found them to be great, and super cheap (~$10 for 10 of them on ebay!). They have 3 modes of transmission: 250kbps, 1Mbps, and 2Mbps. The range decreases accordingly with higher bitrate, but the time spent sending a message does too. There are multiple Arduino libraries (e.g. RF24, Mirf, RadioHead) and tutorials for using the modules (see http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01). They also have built-in mesh networking modes which may or may not be of use.
Versions with an RP-SMA antenna connector and an advertised range of up to 1000m are also available for about $5 each. I would recommend using one of these for the referee's button at least, depending on the range you need.
According to Charles Hallard of hallard.me, The non-amplified chips can get 30m line-of-sight range in 250kbps mode, and I have verified this in my own testing.
According to user sporadic on diychristmas.org, sending a 32 byte payload in 250kbps mode takes 1432µs from the start of Tx mode on the transmitter to receiving the full message on receiver. This decreases to 444µs on 1Mbps mode and 283µs on 2Mbps mode.
Given these statistics, they fall well within 2ms latency for triggering, suitable for your application, and they use very little power. It's up to you to work out the best balance of latency, range and expense.

Thank you! What if multiple buttons are pressed at the same time? Will they collide and eg block each other out?

No, the networking of these chips is very sophisticated for their price, they can negotiate mesh networks and multiple Rx pipes at once happily, and automatically resend if the receiver doesn't acknowledge receipt of a message.

This EE.SE question details how you can have multiple nodes transmit to the same receive address, as in your situation. Then it's simply a matter of taking the sender's address to decide who 'won'.

More helpful examples: http://arduino-info.wikispaces.com/nRF24L01-RF24-Examples

Just a little heads up, those NRF24L01+ chips with antennas are not original, it might cause issues when you try to communicate between clone and original and if you try to use dynamic payloads or shockburst. Also, that wikispace article is outdated. One should use TMRh20 library instead.

Have you considered using real time clocks? You could synchornise them all ahead of time and then use any wireless protocol. Once a button is pressed, you'll look for the unit that reports the earliest time stamp and then once a window of a few seconds has passed let it know that it won. I'd consider using WIFI (802.11) with ESP8266s, RTCs and take a wireless access point along.
This isn't an answer to low lag wireless but eliminates the need for it.

Good idea, but you don't need a RTC. You can sync  Arduinos at start, so millis() - offset gives the same result (+/- some drift) for all Arduinos involved. The offset is the value of local millis() when an Arduino receive the sync signal from master Arduino. For a game that last one or two hours will be enough.

Using millis() for this may cause the devices to lose sync, as millis() does not increment when interrupts are disabled.

In my humble opinion it might be even cheaper if you use IR or some other type of light, assuming you can ensure line of sight.
You can use different wavelengths to ensure separation of the signals.

I'm afraid that "line of sight" and "pub quiz" don't go well together. But thanks for suggesting it, I will look into IR tech for other projects.

Low low tech solution.

The transmitter sends out its clock signal on command.
The receiver just needs to detect detect the prrsence of that signal.

The whole thing can be rf, or light based - for example one of the led lights can be configured as the transmitter.
Everything should be well within 1ms.

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


text:
digitalRead(A0) returns true when A1 is HIGH
I have an Atmega328P-AU with 16Mhz crystal(schematics). And its analog pins A0 to A3 are connected to button inputs.
All these pins are pulled-down(10K res). And in code, I have digitalRead(A0) to digtalRead(A3).
When I press button attached to A3 and A2. They works as they should. But when I press any button attached to A0 or A1, both their digitalRead() returns true.
I checked 3 times, all resistors and buttons wires are well connected and are not shorted.
Here is test code
void setup()
{
    Serial.begin(9600);
    pinMode(A0, INPUT);
    pinMode(A1, INPUT);
    pinMode(A3, INPUT);
    pinMode(A2, INPUT);
}

void loop()
{
if (digitalRead(A0))
    Serial.println("A0");
if(digitalRead(A1))
    Serial.println("A1");
if (digitalRead(A2))
    Serial.println("A2");
if (digitalRead(A3))
    Serial.println("A3" );
delay(400);
}

Here are outputs.
When pressed A0
A0
A1

When pressed A1(same result)
A0
A1

When pressed A2
A2

When pressed A3
A3

I'm wondering what could be causing this problem ?
Edit:
Test

When I press A1 button, the A1 pin is high with 4.8V as well as A0
pin is high with 2.6V to 3.8V.
When nothing is pressed, A1 has 180mV while A0 has -180mV.

simulate this circuit – Schematic created using CircuitLab

Have you actually checked the voltage on the A0 & A1 inputs when their switches are pressed, and only 1 of them goes high? Because this sounds like a short between A0 & A1...

Please post a wiring schematic for verification and please verify A0 stays Low and A1 goes High using a dmm or osciloscope as @Techy dude suggests

I've updated the question, please check.

Just to point this out too, but when both A0_SW, A1_SW are pressed R1, R2 go into parallel where they can be seen as a single 5k resistor.

Assuming you've not activated any ADC functionality in your Arduino code (i.e. assuming the sample code you've posted here is 100% what you've tried, and no analogReference(); statement), then I still think your problem is a partial short between AO & A1.  If my above assumptions are not the case, then there are other possibilities.
With a 5.0V Vcc rail, anything more than 0.5Vcc (i.e. 2.5V) will register as a high/1 (datasheet section 30 - Electrical characteristics, 30.2 DC Characteristics), so based on the measurements you posted to the edit of your question, your code is indeed correctly reporting a 1 on A0 when you push A1 button.
But it's only barely a 1/high, and as you've said, it varies from 2.6 to 3.8, another classic sign of a soldering or partial short circuit somewhere.
If you're able to remove the '328 from the circuit, use your multimeter to read resistance between A0 & A1.  Also try a new/different '328, maybe you damaged one of its input in the past.

Not using any ADC functionality. There is around 8.8K resistance between A0 and A1 on '328 soldered to PCB. While a new unsoldered chip shows no resistance between those pins. So yea, either there is little short or more likely the uC got damaged.

One more thing, seems not important but strange. On soldered '328 the resistance between A2 and A3 is around 20K while A0 and A1 is 8.8K max. Also, the pulldown resistors on A0 and A1 shows 6.6K to 7K reading on their ends. While its 10K on A2 and A3 each. It seems not a problem because they just pulling down the current, but still why different values.

I would have replaced the '328 but still waiting for hot air gun.

I recreated this experiment on my Arduino and it worked like it should. This should work the way you want it to. The only thing I can think of is maybe the chip possibly being partially fried or the pullup resistors not being adequet (not having a low enough resistance) for the job. The resistors I used are 1k. Other than that there is not much else I can think of.

I used 10K pulldown, but its not working as it needs to at my side.

Ok so it could be a number of factors.  You are sure that the pins are 5V tolerant in the mode you're using?  It's possible to burn out pins if they don't have internal current regulation.  You said analog pin which is weird since a button will cause lots of debouce, but it looks configured digital.  Debounce is still an issue on digital circuits with buttons.

Debounce can be solved very easily. Its not a problem to me. And according to datasheet of Atmega328P-AU, it can tolerate 5V.

Just because it can tolerate 5V doesn't mean it can sink the current off of a 5V bus without current regulation.  If you didn't think my answer was helpful it doesn't mean you need to mark it down.  All of what I said was true.  I shouldn't need to open your datasheet and spoon feed you answers about your own device.

The resistors you're using should be fine by the way.  Sock314 is not correct in that they may not be "low" enough.  In this situation being too "low" of resistance would cause the issue. You want large resistors to hold a voltage drop and reduce current consumption.  Also your pins are only 10uA tolerant.  Are you sure that you didn't burn up the pin by sinking/sourcing too much current?

This is what I think you may have done.  I'm work in EE on real time embedded systems by the way. http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino/

First of all, I did not down voted you. I never do, unless the answer is very stupid and needs to be deleted.

And how would I be sourcing current if pin is set to be INPUT only.

Yes, I've read those 10 ways. None of them are true in my case. I haven't done those things. Beside I do believe the uC has gone bad.

I mean the most common way for it to go bad is abuse of the specs.  At some point you probably exceeded the capabilities of the pin.  You are right that in "INPUT" mode the pin is a high-z so it shouldn't draw too much current.

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


text:
Detect a non-human moving object
I would like to design a system in which I am able to make a light flash when a motion sensor detects a movement of a non human object such as a car.
(The goal here being that when a car is moving behind me in my blind spot around the corner of a wall in my parking spot I don't back into it.)
I have looked into a few tutorials using arduinos to detect this motion but so far I have only read about the PIR (which only detects humans and animals).
http://www.instructables.com/id/DIY-Arduino-Motion-Sensor-Lighting-Control/?ALLSTEPS
What sensor would be best for this situation or do I need to rethink my system?
(I have no intention of harming anyone or anything :) )

Do you mean that you're trying to detect a moving car, or are YOU the moving object and you're trying to detect a static object that just happens to be a car? If it's the former, would a hot engine not trigger a PIR sensor?

Why the restriction on non-human, exactly? Is it OK if you back into a human? If so, why? If you want something that senses the difference between a moving inanimate object (like a car) and a human, then surely such a detection system would also detect things like dogs and cats. Unless you are going to Google for a "human detector" it seems to me that any sort of distance detector would do. Surely you don't want to reverse into anything, alive or not.

If your car is moving at the time, then relative to your car everything is moving.
Automotive companies have spent billions of dollars working on this problem.  There is no "sensor" that can differentiate one moving object from a background that is also moving.
All existing automotive systems that perform this task use cameras and computers, with software such as OpenCV.  This is not something that any Arduino could even come close to doing.
The closest you could get is "is there something in this area that is within a certain distance of me" which you may be able to do with an ultrasound "Ping" sensor.  It won't differentiate between a moving car or a bollard or a child or just the wall you are reversing towards.

I would try the PIR sensor before writing it off.  It detects changes in infrared radiation from an initial baseline that it reads, so whenever the ambient heat that it sees changes by some threshold, it notifies you.  They might be sensitive enough to see a car coming through, as suggested by others.
A more robust solution could be the ultrasonic proximity sensor, like Majenko mentioned.  Here's one as a starting point: ultrasonic distance sensor.  This will be best if you know that the car will be passing in front of where you point the sensor.  If it's hard to point the sensor to a point where you're sure the car will be coming through, then that's where a PIR would have advantages, as it "sees" a wider area.

I hate to be the wet blanket here but maybe the job is too simple for this much technology. Wouldn't a suitably placed curved mirror give you the information you need?
Or put a PIR sensor around the corner where it can see the car, and put the flashing light where you can see it while backing.

I am not sure why no one has suggested a Microwave Doppler sensor. I am not sure how it would work in an outdoor environment but it is designed to detect motion regardless of whether it is a human. This link has some information about using a cheap Microwave sensor with an Arduino.

I would use an ultrasonic distance sensor. They are quite accurate, and are common to use for this kind of problem. You will get all kinds of noise in your data, from all the different surfaces that the ultrasonic sound will bounce off from.
Another option would be infrared distance sensor. Make sure you find one with a long enough range, because the 'usual' one used with arduino examples goes to about 30cm. They are less precise, but very easy to use with arduino. And if I remember correctly they have less problems of getting interference if you have a bunch of them together.
Pir sensors are made to detect the difference in infrared heat coming off a human skin (comparing to when the person is not there). So I would not recommend that.

You can use the servo motor to rotate the ultrasonic sensor 180°:

In the setup() function of your code, store the distance for every 180° in an array;
In the loop() function, read the distance of each degree and compare with the one in the array.

If the value changes that means that the object has been moved

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


text:
Need help shrinking a code
I'am new to Arduino and c++
i get his code from the INTERNET
void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}
int f = 0, pos;
void loop() {
    boolean has_request = false;
    String in = "";
    if (Serial.available()) {
        in = "";
        while (true) {  // should add time out here
            while (Serial.available() == false) {}
            in += (char)(Serial.read());
            if (in.endsWith("\r\n\r\n")) {
                has_request = true;  break;
            }
        }
    }
    if (has_request) {
        int i1 = in.indexOf("GET /blink?f="), i2;
        if (i1 != -1) {
            i2 = in.indexOf(" ", i1+13);
            f = in.substring(i1+13, i2).toInt();
        }
        Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
        String sr = "<!DOCTYPE HTML>\n";
        sr += "\n";
        sr += "LED frequency: ";
        sr += f;
        sr += "Hz.";
        Serial.print("Content-Length: ");
        Serial.print(sr.length());
        Serial.print("\r\n\r\n");
        Serial.print(sr);
        has_request = false;
    }
    if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

see this link if you cant see the code formated here in the site
this code is used for the Arduino uno wifi shield
it is working perfectly except it is too complicated for me
while loop inside a while loop
and i don't want to do frequency i only need to send turn on or off
without any complexity
anyone could help me ?

The test if (millis() > t + 1000/f) will not work properly close to the millis() rollover. It should rewritten as if (millis() - t > 1000/f). See this answer to How can I handle the millis() rollover? for an extended discussion.

I would recommend starting out with some easy stuff you understand or making code yourself... Starting out with code you don't understand will backfire you.
I'll explain the code for you anyway.
This part will "set everything up". The serial connection and the direction (in/output) of the pin(s).
void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}

Somehow did the person who made this think it was logical to put this here instead of on the very top of code. There are 2 integer variables declared here of which one is initialized with 0. (f).
int f = 0, pos;

This part of the code (untill the very last bracket) will be ran continiously, in a "loop". Many, if not all, embedded systems will run "forever".
void loop() {

This is basically a "flag", it indicates if something has, or has not happened. At this point it's only initialized.
    boolean has_request = false;

Also we're keeping a buffer (text string) of the characters we receive.
    String in = "";

Check if there are characters in our serial buffer.
    if (Serial.available()) {

If so, we empty our own buffer.
        in = "";

And keep doing this code.
        while (true) {  // should add time out here

We wait until the next character is ready.
            while (Serial.available() == false) {}

And add it to our buffer.
            in += (char)(Serial.read());

But when we see our buffer ends with \r\n\r\n (carriage return, line break x2).
            if (in.endsWith("\r\n\r\n")) {

We're going to set te flag, indicating that we have received a message.
And we stop the: "Keep doing this code".
                has_request = true;  break;
            }
        }//(this is actually the parenthesis of the while(true) which we break out.

    }

So we had this message, right? Let's do the following:
    if (has_request) {

Parse the variable in the GET request (f=??) to an int.
        int i1 = in.indexOf("GET /blink?f="), i2;
        if (i1 != -1) {
            i2 = in.indexOf(" ", i1+13);
            f = in.substring(i1+13, i2).toInt();
        }

Send a 200OK (with body) back to the thing that sent the http request (actually pretty neat to do so.)
        Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
        String sr = "<!DOCTYPE HTML>\n";
        sr += "\n";
        sr += "LED frequency: ";
        sr += f;
        sr += "Hz.";
        Serial.print("Content-Length: ");
        Serial.print(sr.length());
        Serial.print("\r\n\r\n");
        Serial.print(sr);
        has_request = false;
    }

We also keep doing this blinking. (Fun fact: While receiving/sending stuff, your blinking will stop/desync. This is because the receive/send code is blocking the blinking code. Making the blinking hardware and/or receive/send interrupt based will improve the systems reaction time and efficiency.)
    if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

But how will we make this better? Or atleast easier to read?
By using functions, you can split up the code, and giving the functions a logic name, it all becomes quite obvious. The whole thing is doing 3 jobs:
Blinking a led on a given frequency.
Receiving requests/commands through serial (handling serial).
And handling these requests afterwards.
void BlinkLed(int f);
void HandleRequest();
void HandleSerial();

int f = 0, pos;//Pos doesn't have to be a global variable...

void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}

void loop() {
    boolean has_request = false;//Reset the flag every loop.
    String in = "";//Clear the string every new loop.
    if (Serial.available()) {
        HandleSerial();
    }
    if (has_request) {
        HandleRequest();
    }
    BlinkLed(f);
}

void BlinkLed(int f){
if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

void HandleSerial(){
        in = "";
        while (true) {  // should add time out here
            while (Serial.available() == false) {}
            in += (char)(Serial.read());
            if (in.endsWith("\r\n\r\n")) {
                has_request = true;  break;
            }
        }
}

void HandleRequest(void){

        int i1 = in.indexOf("GET /blink?f="), i2;
        if (i1 != -1) {
            i2 = in.indexOf(" ", i1+13);
            f = in.substring(i1+13, i2).toInt();
        }
        Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
        String sr = "<!DOCTYPE HTML>\n";
        sr += "\n";
        sr += "LED frequency: ";
        sr += f;
        sr += "Hz.";
        Serial.print("Content-Length: ");
        Serial.print(sr.length());
        Serial.print("\r\n\r\n");
        Serial.print(sr);
        has_request = false;
}

V2 (more likely to compile, but kinda changes the structure):
void BlinkLed(int f);
void HandleRequest();
boolean HandleSerial();

int f = 0;//Frequency of the led (blinking)

void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}

void loop() {
    String in = "";//Clear the string every new loop.
    if (Serial.available()) {
        if(HandleSerial()){
            HandleRequest();
        }
    }
    BlinkLed(f);
}

void BlinkLed(int f){
if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

boolean HandleSerial(){
        in = "";
        while (true) {  // should add time out here
            while (Serial.available() == false) {}
            in += (char)(Serial.read());
            if (in.endsWith("\r\n\r\n")) {
                return true;
            }
        }
        return false;
}

void HandleRequest(void){
    int i1 = in.indexOf("GET /blink?f="), i2;
    if (i1 != -1) {
        i2 = in.indexOf(" ", i1+13);
        f = in.substring(i1+13, i2).toInt();
    }
    Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
    String sr = "<!DOCTYPE HTML>\n";
    sr += "\n";
    sr += "LED frequency: ";
    sr += f;
    sr += "Hz.";
    Serial.print("Content-Length: ");
    Serial.print(sr.length());
    Serial.print("\r\n\r\n");
    Serial.print(sr);
}

We can even make it more nicer by:

using hardware (PWM) to toggle/time the led.
rewriting the serial handling code... (https://www.arduino.cc/en/Serial/ReadStringUntil)
Using printf() to format the serial.prints on one line...
Make the receive/send code interrupt based, so that it will only take short amounts of time of your code, instead of continously waiting in a while, you can do stuff in the meanwhile ;)
using classes.

The variable pos is not used at all.

In your “better” version, line 35: “error: ‘in’ was not declared in this scope”. Same for has_request (lines 40 and 62), in (line 47) and i2 (line 49).

Haha, indeed, edited the code on "answer" itself. And copied from the original code.
Pos indeed doesn't seem to do anything.
And yeah, by putting stuff in functions you're going to need to transfer the variables from one to another, or make them global :)
not sure about the  i2 though, it's in: int i1 = in.indexOf("GET /blink?f="), i2;?
I'll be editing the code (this time in Notepad++, don't have access to a compiler at the moment :l).

The syntax highlighting is actually very nice!
And you should consider the code in my answer as an example. With the explanation on the code it'd be fairly easy to roll your own (better) version of it (that will actually compile and work as you want ;) )
I believe that in V2 it's better, but I'm not sure if it still works as intended.

Just one compilation error remaining: in is declared in loop(), and used in HandleSerial() and HandleRequest(). Simplest solution would be to make it global.

You are awesome , appreciate your help bro !

There is only one "while loop inside a while loop" and that is hardly complex:
while (Serial.available() == false) {}

All that means is "Wait for something to become available on the serial".  That is ALL it does.
There is nothing even remotely complex there.  True, it may not be very well written (as is the case with lots of code on t'interwebs).  It's time to start learning how the code works so you can write your own.

+1, that code is extremely straightforward. Written like crap, but straightforward nonetheless.

Here is my take at this. I realize that I did not really make the
program simpler, but hopefully better in some respects, as it avoids
blocking reads and heap memory allocation. Be warned however that I did
not test it. It compiles fine though.
Preamble, hopefully simple enough that it requires no comments:
const uint8_t led_pin = 13;

void setup() {
    Serial.begin(57600);
    pinMode(led_pin, OUTPUT);
}

Next, here is a function to read the HTTP request. A few things are
worth noting in this function:

It is non-blocking: if there is not data in the serial buffer, it will
return NULL immediately. This is to prevent the whole program from
hanging if the client does not terminate its request.
It only saves the first 31 bytes of the request. This is because
browsers tend to add lots of useless headers, which can be unfriendly
to the memory of a small Arduino. And the only interesting piece of
data is at the very beginning anyway.
The request terminating sequence (CR LF CR LF) is detected without
having to store it in the buffer, just by counting how many
consecutive bytes of that sequence we have already received.
Declaring the function as static makes it possible for the compiler
to inline it, which it does as it is only called from one place. This
makes for a smaller executable.

/*
 * Non-blocking read. Returns the first bytes of the request in a static
 * buffer, or NULL if we do not have a complete request yet.
 */
static char * read_request() {
    static char buffer[32];
    static uint8_t pos;
    static uint8_t crlf_bytes;  // bytes of "\r\n\r\n" received

    while (Serial.available()) {
        char c = Serial.read();

        // Store the received byte if there is enough room.
        if (pos < sizeof buffer - 1)
            buffer[pos++] = c;

        // Update the count of consecutive CRLF bytes received.
        if ((c == '\r' && crlf_bytes % 2 == 0)
         || (c == '\n' && crlf_bytes % 2 == 1))
            crlf_bytes++;
        else
            crlf_bytes = 0;

        // Return the buffer if we have a complete request.
        if (crlf_bytes == 4) {
            buffer[pos] = '\0';  // terminate the string
            pos = 0;
            crlf_bytes = 0;
            return buffer;
        }
    }
    return NULL;
}

Parsing the request is done by a different function. Here, I do not
search for the "GET /blink?f=" string, because it must be at the very
beginning for the request to be valid.
/*
 * Returns the requested frequency, or 0 if nothing valid is found.
 */
static int parse_request(char *request) {

    /* The "GET" should be at the very beginning. */
    if (strncmp(request, "GET /blink?f=", 13) != 0)
        return 0;

    return atoi(request + 13);
}

Now we can send the response to the client, telling it how we parsed the
frequency. I avoid using String, as it involves heap allocation, and I
put the bulk of the response in PROGMEM (F() macro) to save RAM. I
also added a <title> to make it valid HTML.
/*
 * Tell the client how we understood the requested frequency.
 */
static void send_response(int freq) {
    char freq_str[12];
    itoa(freq, freq_str, 10);
    Serial.print(F("HTTP/1.1 200 OK\r\n"
                   "Content-Type: text/html\r\n"
                   "Content-Length: "));
    Serial.print(84 + strlen(freq_str));
    Serial.print(F("\r\nConnection: close\r\n\r\n"
                   "<!DOCTYPE html>\n"
                   "<title>Blink</title>\n"
                   "LED frequency: "));
    Serial.print(freq_str);
    Serial.print(F(" Hz.\n\n"));
}

The next function blinks the LED in a rollover-safe fashion. Storing the
current LED state in a static variable avoids a call to digitalRead().
static void blink_led(unsigned long toggle_time) {
    static uint8_t led_state;
    static unsigned long last_toggle;
    unsigned long now = millis();
    if (now - last_toggle > toggle_time) {
        led_state = !led_state;
        digitalWrite(led_pin, led_state);
        last_toggle = now;
    }
}

Putting it all together, the main loop() ends up being quite straight
forward:
void loop() {
    static unsigned long period = 1000;
    char * request = read_request();
    if (request) {
        int freq = parse_request(request);
        if (freq > 0) period = 1000 / freq;
        send_response(freq);
    }
    blink_led(period);
}

PS: My version is significantly larger than the original at the
source level (66 v.s. 44 source lines of code), but the compiled program
is smaller in both flash and RAM usage:
text    data     bss     version
5646     168     197     original
3316      40     218     my version

Hmm, I agree this code is probably way faster and better optimized. Though the variable last_toggle is only known in the "blink_led" function. And that basically means that in the if-statement (in blink_led function), you're testing the toggle_time against an uninitialized variable?

No, last_toggle is a local static variable. This means that, although it is only “locally visible”, it has “global duration”: it is initialized at program startup by the C runtime (in __do_clear_bss), before main() is called, and it keeps its value between successive calls to blink_led(). Static variables are always initialized. If not explicitly, they are implicitly initialized to zero. And this is the right initialization for this variable, just like blink_led(unsigned long)::led_state, read_request()::pos and read_request()::crlf_bytes.

Ah, yea, static in a function means something completely different as static in a variable?
Thanks for the extensive argumentation!
I just saw that indeed, it makes more sense to make it a static variable as global variable. As you won't need/want to access it anywhere, but you do want the "global" duration. It'll also be more efficient as just making it global?

@FuaZe: Yes, “static” has different meanings depending on whether it is used inside a function or in global scope. And no, it is not more efficient than a global variable, it's the same. You would not be able to tell the difference by disassembling the compiled program, except for the symbol table.


text:
Arduino Mega vs. RasPi Pro Cons in 3D Printing
Recently I tooked a look at cheaper China 3D Printers and noticed they're all based on RepRap (mostly using Ramps for the electronics part) and the next day i saw a 2d Plotter based in the pi. Then I asked myself why the Pi isnt used in 3d printers.
Question:
Why is the Arduino Mega/Due more used in 3D Printing than the RasPi? What are the Pro's and Con's for 3D Printing on the two systems?

Hard realtime is more difficult when you can't get the full specs for the main processor.

A mutli-tasking operating system such as the Linux normally run on the pi is not particularly suited to doing hard real-time control such as coordinated pulse generation for multiple stepper motor axis trying to move as quickly as the rigidity and motor power will permit.
It is possible to use realtime extensions to the Linux kernel to get reasonable performance.  And it is also possible to run something simpler than Linux on the pi.
However, it is also possible to use a far cheaper processor to get the actual G-code execution done (you don't really pay the Arduino cost premium when buying an ATmega on a dedicated board, so it's only a  dollar or three more expensive than it "should be").  If one were to design printer electronics from scratch today, there are probably better choices, such as as ARM Cortex M0, M3 or M4 - but most of the printer designs came out of the same community where Arduino was a familiar choice, and there are probably more people willing to try to make small personal customizations to an Arduino codebase than there are willing to install the toolchain for a perhaps technically better, but less familiar solution. .
People do use Raspberry Pi's with 3d printers quite frequently though - they just use them for a different job: that of slicing and motion planning and potentially functioning as a network print server, which then drip-feeds the G code to the simpler (ATmega or whatever) based realtime executive.  In effect, they use a pi as a cheap PC to host the ATmega-based printer, rather than dedicating an old PC to that job.
Ultimately, the rarely taken alternative of using a realtime Linux kernel extensions to control motion directly from a pi, vs the more common one of using an ATmega as a realtime motion delegate for the pi, are conceptually similar - it's just that in one case the realtime executive engine is a highest priority task on the main processor, and in the other it runs on a dedicated motion co-processor.

3D printers are not all that run GCode. In fact they are rather late comers. Real time Linux and other real time solutions have been used quite successfully for a long time. People use Arduinos on cheap 3D printer because they are cheap, as is most software written for them.


text:
Do I need a bubble sort or something easier?
I'm using an Arduino Leonardo and a GPSTiny++ library to parse NMEA strings from my GPS receiver. In this chunk of code I'm averaging all satellite SNR numbers for satellites which are locked (Being used for navigation). The avg value provides some general information on overall performance but I'm also really looking for the avg Top 4 values.
I believe I would need to do some sort of sorting algorithm. Increment through the top 4 and average those values.
Here's a snippet of my output window:
12/13 0.92 SNR=17 10 27 27 30 29 25 27 33 0 0 0 31 25.60 0.00
The second to last number is the average.
How do I get started?
int totalSNR = 0;
    float avgSNR = 0;
    int count = 0;
    Serial.print(F(" SNR="));
    for (int i = 0; i < MAX_SATELLITES; ++i)
      if (sats[i].active)
      {
        if (sats[i].snr > 0) {
          count++;
          totalSNR = totalSNR + sats[i].snr;
        }

        Serial.print(sats[i].snr);
        Serial.print(F(" "));
      }

    avgSNR = float(totalSNR) / float(count);
    Serial.print(avgSNR);

You could do a qsort. You haven't posted any data types so it is hard to answer with your specific code, however here is a sample of sorting numbers:
const int COUNT = 10;

int someNumbers [COUNT] = { 7342, 54, 21, 42, 18, -5, 30, 998, 999, 3  };

// callback function for doing comparisons
int myCompareFunction (const void * arg1, const void * arg2)
  {
  int * a = (int *) arg1;  // cast to pointers to integers
  int * b = (int *) arg2;

  // a less than b?
  if (*a < *b)
    return -1;

  // a greater than b?
  if (*a > *b)
    return 1;

  // must be equal
  return 0;
  }  // end of myCompareFunction

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) { }  // for Leonardo
  Serial.println ();
  // sort using custom compare function
  qsort (someNumbers, COUNT, sizeof (int), myCompareFunction);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someNumbers [i]);
  }  // end of setup

void loop () { }

Output:
-5
3
18
21
30
42
54
998
999
7342

Generic compare function with a template
Interestingly, you can make the compare function be a template which lets you compare any type -- that is, any type that supports direct comparisons. Change the compare function to:
// callback function for doing comparisons
template<typename T>
int myCompareFunction (const void * arg1, const void * arg2)
  {
  T * a = (T *) arg1;  // cast to pointers to type T
  T * b = (T *) arg2;
  // a less than b?
  if (*a < *b)
    return -1;
  // a greater than b?
  if (*a > *b)
    return 1;
  // must be equal
  return 0;
  }  // end of myCompareFunction

This change removes the reference to "a" and "b" being "int" and replaces them with T, which is the template type.
Now we can change the qsort line to be:
  // sort using custom compare function
  qsort (someNumbers, COUNT, sizeof (int), myCompareFunction<int>);
  // -------add this----------------------------------------^^^^^

That gives the same results, but now we can also compare float, long, unsigned long, byte, all that sort of thing.

Compare floats
For example to compare floats:
const int COUNT = 10;

float someNumbers [COUNT] = { 7342, 54, 21, 42, 18, -5, 30, 998, 999, 3  };

// callback function for doing comparisons
template<typename T>
int myCompareFunction (const void * arg1, const void * arg2)
  {
  T * a = (T *) arg1;  // cast to pointers to type T
  T * b = (T *) arg2;
  // a less than b?
  if (*a < *b)
    return -1;
  // a greater than b?
  if (*a > *b)
    return 1;
  // must be equal
  return 0;
  }  // end of myCompareFunction

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) { }  // for Leonardo
  Serial.println ();
  // sort using custom compare function
  qsort (someNumbers, COUNT, sizeof (float), myCompareFunction<float>);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someNumbers [i]);
  }  // end of setup

void loop () { }

The only change there was changing the word "int" to "float" (in two places) on the qsort line, and on the data declaration itself.

Compare String objects
You can even compare String objects (not C strings), for example the data is:
String someStrings [COUNT] = { "the", "quick", "brown", "fox", "jumped",
                               "over", "the", "lazy", "dog", "ZOMG"  };

And the sort is:
  // sort using custom compare function
  qsort (someStrings, COUNT, sizeof (String), myCompareFunction<String>);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someStrings [i]);

Compare C strings
We need to use strcmp in this case, but most of the work is done in that. We just have to dereference the pointer so strcmp gets the pointer to the string (not the pointer to the pointer to the string).
char * someStrings [COUNT] = { "the", "quick", "brown", "fox", "jumped",
                               "over", "the", "lazy", "dog", "ZOMG"  };

int myCompareFunction (const void * arg1, const void * arg2)
  {
  return strcmp (*(char **) arg1, *(char **) arg2);
  }  // end of myCompareFunction

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) { }  // for Leonardo
  Serial.println ();
  // sort using custom compare function
  qsort (someStrings, COUNT, sizeof (char *), myCompareFunction);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someStrings [i]);
  }  // end of setup

void loop () { }

I assume that by

I'm also really looking for the avg Top 4 values.

you mean that you will find the largest four numbers and report their average.
If so, you can sort all the values (as in previous answer) and then average the last four numbers (or first four, depending on sort order) from the sorted array.  This has complexity O(n lg n), that is, sort time grows with array size n as the product n times logarithm of n.
Or, you can keep track of the largest four values as you iterate through the array, via technique illustrated in code at the end of this answer.  This has complexity O(n lg k), that is, sort time grows with array size n and number k of high values as the product n times logarithm of k.

In using qsort, I prefer (in this edit) to write the comparator function more compactly, although possibly less transparently, by using *(int*)a to reference the value that a points to.   For example:
// Comparator function for integers
int compareInt (const void *a, const void *b) {
  // Return -, 0, or + if first value is <, =, or > second value.
  return *(int*)a - *(int*)b;
}

You can make the comparator sort descending (so that the largest four numbers appear in array's first four slots) by using return *(int*)b -*(int*)a; instead of the return that's shown.

Templated, the function looks as follows.
template<typename T>
// Comparator function for Numbers
int compareNumber (const void *a, const void *b) {
  // Return -, 0, or + if first value is <, =, or > second value.
  return *(T*)a -*(T*)b;
}

I called the routine compareNumber because it uses subtraction to find out which operand is larger.  But as explained in arduino.cc's String Comparison Operators page, for Arduino String-type objects, subtraction is bound to string comparison, so the above templated function works with String objects as well as numbers.
For C-type strings, which are character arrays terminated by a null character, ie of char* or char[] type, the strcmp() function can be used directly as qsort()'s comparator function:
qsort(arrayOfPointersToCStrings, elementCount, pointersize, strcmp);

That is, there is no reason to write a separate comparator function with a call to strcmp(); just reference strcmp() directly.

When you have a small, fixed number of values to process, just doing a sort is reasonable.  The algorithmic complexity is O(n*lg n), and if n is fixed, this is basically O(1). If, however, you were processing extremely large data sets and wanted to identify the largest four numbers without storing all the other numbers, you can track the largest four by keeping the four largest numbers so far seen in an array.  This has algorithmic complexity that is O(n*k) at worst, where k is the number of elements tracked; and for fixed k, this is O(n).  If k is large or variable, a tree method can be used to get complexity O(n*lg k).
Anyhow, suppose the array is int largestSoFar[4].    Initialize each entry in that array to some number smaller than any valid data item; eg, to INT_MIN from <limits.h>.
As each new data item arrives, compare it to largestSoFar[0].  If it's less or equal, go get the next data item.
Else, the new value is one of the largest values so far seen.  Store it in largestSoFar[0], then have a loop to do compare-and-swap steps to ripple the new number up to its appropriate level.  That is, compare elements [0] and [1]; break if largestSoFar[0]<largestSoFar[1], else swap[0] and [1] and go on to compare-and-swap for elements [1] and [2], etc.
The code below (shown as a standalone C program, rather than as an Arduino sketch) illustrates the technique.  Here is what it prints out:
Linear result:   2654  2720  2815  2961  2968  9662    Total: 23780
Sorting result:  9662  2968  2961  2815  2720  2654    Total: 23780

Here is the standalone C program illustrating a linear (O(1)) method:
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

// Comparator function
int intCompare(const void *va, const void *vb) {
  const int a = *(int*)va, b = *(int*)vb;
  // (a>b) is 1 if a>b, else 0.  (b>a) is 1 if b>a, else 0.
  // So the following expression has value 1, 0, or -1.
  return (b>a) - (a>b); // To sort descending
}

int main () {
  int someNumbers [] = { 481,  1041, 107,  279,  809, 2052,  2961, 557,
             2534, 2968, 89,   839,  2720,  85,  2115, 898,
             1931, 655,  2631, 1897, 2322, 1115, 2815, 674,
             2259, 176,  598,  525,  600,  1088, 1885, 313,
             1175, 2654, 915,  536,  978,  2052, 798, 1979,
             2571, 2154, 1138, 259, 9662  };
  enum { NumTop = 6, NumNum = (sizeof someNumbers)/sizeof(int) };
  int i, j, tot, largestSoFar[NumTop];

  for (i = 0; i < NumTop; ++i)
    largestSoFar[i] = INT_MIN;  // Init. largestSoFar[] to smallest numbers

  // Process all the numbers
  for (j = 0; j < NumNum; ++j) {
    if (someNumbers[j] <= largestSoFar[0])
      continue;
    // Install number into largestSoFar[] and bubble it up
    largestSoFar[0] = someNumbers[j];
    for (i = 1; i < NumTop; ++i) {
      if (largestSoFar[i] < largestSoFar[i-1]) {
        int t = largestSoFar[i];
        largestSoFar[i] = largestSoFar[i-1];
        largestSoFar[i-1] = t;
      }
      else break;
    }
  }
  printf ("Linear result:  ");
  for (i = tot = 0; i < NumTop; ++i) {
    printf ("%5d ", largestSoFar[i]);
    tot += largestSoFar[i];
  }
  printf ("   Total: %d\n", tot);

  // sort the array descending, for comparison
  qsort (someNumbers, NumNum, sizeof(int), intCompare);
  printf ("Sorting result: ");
  for (i = tot = 0; i < NumTop; ++i) {
    printf ("%5d ", someNumbers[i]);
    tot += someNumbers[i];
  }
  printf ("   Total: %d\n", tot);
  return 0;
}

Nice answer. I like the way you address the complexity of the various methods. :) The linear approach will be faster, although at the cost of RAM. If the OP wanted to average more numbers (eg. the top 100) then RAM might start to become an issue.

Since you only need to know the 4 largest values in the array you don't need to sort the array, you just need to iterate through it and find the four largest values. This can be done in O(n*k) which is faster than any sorting algorithm you could use. However there is an issue of space since you would use an array to hold the previous largest numbers. Fortunately we can get around this by swapping the current largest value to the end of the array and ignoring it. So you can find the k largest values in an size n array in O(n*k) time complexity with O(1) space complexity. For fixed values if n and k the time complexity is O(1).
 #include <stdio.h>

    void swap (int& a, int& b);

    int main () {

        int sum = 0;
        int max = -1; // I'm assuming your array will have non-negative numbers
        int maxIndex;
        int nums = 4; // we want the top "num" values in the array

        const int arrSize = 9;
        int arr[arrSize] = {36, 33, 19, 42, 47, 26, 50, 37, 38}; // random numbers

        for (int i = 0; i < num; ++i){
            // arrSize - i lets us ignore the previous max values
            for (int j = 0; j < arrSize - i; j++){
                if(arr[j] > max){
                    max = arr[j]; // store current max
                    maxIndex = j; // store the current max's index
                }
            }
            sum += max; // running total
            max = -1;   // reset max
            swap(arr[maxIndex], arr[arrSize-1-i]); // move current max to the end
        }

        float top4Avg = sum / 4.0;
        printf("\nTop 4 average: %f\n", top4Avg);

    }

    // swaps a and b without a temp variable
    void swap (int& a, int& b){
        a = a ^ b; // ^ is the bitwise xor
        b = a ^ b;
        a = a ^ b;
    }

First iteration: {36, 33, 19, 42, 47, 26, 38, 37, 50}
Second iteration: {36, 33, 19, 42, 37, 26, 38, 47, 50}
Third iteration: {36, 33, 19, 38, 37, 26, 42, 47, 50}
Fourth iteration: {36, 33, 19, 26, 37, 38, 42, 47, 50}
Also this was a really fun question I'd upvote but my rep isn't high enough.

Comment  “// arrSize - 1 lets us ignore the previous max values”  should instead refer to arrSize - i


text:
Getting random values on Arduino Duemilanove 328
I am using Arduino Duemilanove 328,and running the AnalogReadSerial example sketch.
Even when nothing is connected to the Arduino board it still shows a value of about 350 out of 1023. Ideally it should have shown 0 out of 1023 when nothing is connected to Arduino.
So how can I solve this problem?

Connect it to something. E.g. a pull-down resistor if you want to read zero when nothing else is connected.

Why do you think it should show 0 when not connected to anything?
Does the antenna of your radio give a zero signal just because the end isn't connected to anything?  An Arduino's input pin (either analog or digital) is just the same.  If it isn't connected to anything then it just picks up noise - be that radio transmissions, induction from nearby mains wiring, neutrinos from Alpha Centauri...  Basically if it's not connected to anything then there is no way you can possibly know what the value should be since there is no set value.
In order to read 0 on the ADC the ADC has to be connected 0V.  That means connect it to ground.


text:
How come people connect their arduinos to buzzers without any coil protection?
If you connect your arduino to a motor you use this schematic:

However, when it comes to buzzers, which also have a coil, no one protects the circuit:

What the hell is going on? Are these just buzzers "coiless"? How can I find the type of buzzer I have?

That kind of "buzzer" doesn't have a coil.  It is a "Piezo Transducer" and uses a crystal to produce the sound.
When you're using a real speaker and producing sound you are doing it very differently to switching a motor or a relay on and off.  You're generating a much smoother waveform and you don't have the sharp "ON-OFF" that causes a collapse of the magnetic field.  You're actually gradually reducing the power and then reversing it to remove the magnetic field then apply a new one in the opposite direction (if you have wired it right of course).
Also the currents involved in driving a speaker like that are minuscule compared to switching a relay, especially when driven direct from the Arduino.  For louder volumes you will use an amplifier, and that deals with the whole protection within itself since it is designed to drive a speaker.

This picture here states that buzzers have a coil http://1.bp.blogspot.com/-j-B5fWFwJVo/UQTewNIMC7I/AAAAAAAACzA/Y7WLCNIbUGs/s1600/buzzer%20coil.jpg so you are saying that this coil is harmless to arduino?

That is a specific component within a circuit within a stand-alone buzzer.  It is not a coil directly connected to an Arduino.  It is part of an oscillator circuit that drives the piezo transducer and thus is irrelevant to the Arduino.


text:
How to writte simple string compare?
I new to Arduino and I'm attempting to writte a simple string compare code like this:
void loop()
{
  distance(cm);
  delay(200);
}

void distance(char[3] unit)
{
  if (unit[] == "cm")
    Serial.println("cm");
}

Could somebody please advise me how to writte it correctly?
Thanks in advance!

Use strcmp().

Thank you for your answer.
I've written this statement: if (strcmp(unit, "cm") = 0) ,but I think I have a problem with void distance(char[3] unit) and "reading" the string.
IDE output: sketch_jul08a:15: error: 'unit' was not declared in this scope
expected ',' or '...' before 'unit'

It's char unit[3], or, better char * unit. And you call like distance("cm"), with the quotes.

I've written this statement: if (strcmp(unit, "cm") = 0) -- that should be == 0 to do a comparison.

if (strcmp (unit,"cm") == 0) {

    // matches cm

}

For syntax like this the intellisense in products such as Atmel Studio or Visual Studio can really help. Whilst you still need to understand what you might be looking for the intellisense makes all the available Arduino functions visible from the code. If you install the Arduino plugin then there will be an Arduino reference explorer in both ide's which explains everything.

Shameless plug!

@PhillyNJ Hi, not true. It is entirely correct, what users often doesn't realize will help most.  + I didn't post any links!

Shameless or not, Atmel Studio 7 Beta runs all the Arduino libraries with no plugin.

Sure you can use the import tool to convert some Arduino projects to cpp projects. they are then no longer Arduino compatible, no ability to easily take core upgrades from Arduino, no usb upload, only a debugger if you hack your board, only debug with optimization disabled, difficult to add new libraries and the list goes on. Great for some pro users but not for others. Have you tried it? maybe not?

Yes - Both Visual Macro and Beta 7.

Great then you will see that for pro users Atmel is fine but not for others. It's too rigid, different and complicated for most Arduino users but the publicity will surly bring new users :)

You seem to think shameless is bad.

Oops sorry. I am usually jumped on by linux people. Becoming paranoid in my old age.


text:
Hall Effect Sensor for POV Project
I'm making a POV project and need to count the RPM of the DC Motor.
I purchased a Hall Effect Sensor and it seems to work perfectly at slow speeds, however once the motor speeds up, the sensor doesn't pick up the magnet at all.
The datasheet for the sensor is at:
http://cdn.shopify.com/s/files/1/0045/8932/files/AH180.pdf?100744
This is one of my first projects and I'm not sure what I should be looking for on the datasheet.
The sensor came as part of this product:
http://www.freetronics.com.au/pages/hall-effect-magnetic-and-proximity-sensor-module-quickstart-guide#.VZ0Zs_meDGc
There doesn't seem to be a problem with the code:
int pin = 13;
volatile int state = LOW;
volatile int tcnt = 0;

void setup()
{
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, CHANGE);
  Serial.begin(9600);
}

void loop()
{
  digitalWrite(pin, state);
  Serial.println(tcnt);

}

void blink()
{
  tcnt = tcnt + 1;
  state = !state;
}

Thanks!

From the datasheet of the hall effect sensor, the thing is only checking for 125usec in every 125msec - so if your magnet whizzes by in <100msec it will miss it.
Obviously you haven't stated the speed your magnet passes your sensor, but as it's only active 0.1% of the time, this seems the likely reason to miss.
Can you put it nearer the shaft/axle ?

Wow, 125 milliseconds is way too long. I've put the magnet as close as I can to the sensor and it hasn't made a difference. From what I can tell, the motor is doing 12 revolutions a second. Should I be using another kind of sensor? Would something as simple as 2 wires touching be a better way of doing this?

There are faster hall effect sensors out there. Just check you regulator suppliers for hall effect sensors and check their datasheets. E.g. US1881 can handle 10kHz Switching Frequency (note that this is a latching sensor, so not ideal for you application (would require 2 magnets)).


text:
Using Arduino To Control Boot Sequence of PC
I want to know if it is possible to use an arduino to tell a pc which os to boot to. I know It is possible to turn on the pc by wiring it to the motherboard pins with the power switch, and I know the arduino I have (http://www.amazon.com/SainSmart-ATmega328P-Development-Compatible-Arduino/dp/B00E5WJSHK/ref=sr_1_1?ie=UTF8&qid=1436368217&sr=8-1&keywords=sainsmart+uno+r3) can act as a mouse or keyboard. Can that be done before the pc has booted however?

"can act as a mouse or keyboard" Do you know how to make it do so, or have you heard that others can do it?

There's a hackaday article on using the board's AT16u2 to emulate an HID device.

Injecting key events should be do-able, the question may be more if what needs to be injected and when is context- dependent.  Why not use a customizeable boot manager like grub, and modify it to talk to you over a serial port?

Arduino Micro, or Arduino Leonardo would be a lot easier to emulate a keyboard. Since you want the arduino to power up the PC you'd connect it to the 5v-standy (usb will power down in some PCs, so you can't usb to power it. I don't see how this would not be possible. You could use the old power button to control the arduino. Something like, one press=>Boot Windows, two presses =>Boot Linux etc.

Ignacio- I have never used an arduino for more than a motor and sensor controller, but the documentation says that It can emulate a HID device.

I see the issue with attempting to solve my issue with a keyboard now. There is no way to tell the arduino that the computer is waiting for an os selection. Grub control via serial port sounds like the only way to go.

So it might depend on how you implement it. With an Arduino Uno, your options for creating an HID device are limited to either reprogramming the 16u2 (which will require an ISP) or using a software USB implementation (like V-USB). If you go with the first method I'm pretty sure that will work as it will be a native USB connection. As for the second method, I'm not sure how well V-USB responds to having the USB host turning on while it is running. The best thing to do is just try it and see how well it works.
The bigger challenge you will run into is being able to select your PC operating system. Because this will be a one way connection, there is no way of knowing what state the computer is in and whether or not it is time to press a key yet or not. This means you will have to be timing things fairly accurately, which can be tricky unless you are careful. The internal oscillator is not very accurate (but probably still accurate enough) and interrupts used for communicating with USB can block the main loop. That is not to mention any variations the computer might have in its boot process.
A good alternative method would be to set up a bootloader on your PC that can be controlled via a serial port. GRUB2 is a popular one that does support a serial console. All you would need to do is add a level adjuster to adapt the Arduino UART to RS232, then set up the code to wait for the GRUB prompt and then send the command necessary to select which OS you wish to use.

Thanks for the information. This is very helpful and a great place to start. Grub sounds like the way to go. I have used grub in the past, but no more than using the arrow keys to select the os. The arduino's would send the power signal to the computers to boot, and then feed the bootloader the information telling it what to boot to? The serial console is via usb? How could I do this on two separate machines at the same time? Is it the same type of thing as using the serial console to monitor the arduino through the arduino++ software?

The arduino would listen to the serial port and wait for grub to be ready, usually it does this by printing a prompt (e.g. traditionally this has been "grub>" not super sure about newer versions though). If these computers have actual serial ports (i.e. 9 pin DSUB RS232) I would try and use that and connect to it via the UART port on the Arduino, using an adapter like I mentioned. Using the USB serial port might be possible, but it just depends on whether GRUB supports them.

As far as multiple computers go, you would pretty much have to go the UART route and get an Arduino that has more than one UART. For example the Due and the Mega 2560 have 4. Other Arduino-like boards like the Teensy 3.1 also offer extra UARTs.


text:
Programming an AVR using ISP
I am trying to program an atmega with arduino sketch using ISP only (mac user).
So I know how to burn a boot loader, and then to program the chip using the TX, RX. But I would like to program it directly using ISP, without a boot loader.
So I am using the UNO as a ISP programmer, and trying without success to program a chip on a PCB:

I upload to the UNO the ArduinoISP sketch
Connect the lines to the target board (target board have atmega328, crystal, capacitors, LED)
Choose the board "Arduino pro or pro mini" in the Arduino IDE.
Choose the programmer- "Arduino as ISP"
At the beginning I tried to upload a boot loader, to see if its going well, it DID boot loaded the chip,so I know the connections are good, and I am set to go.

Now, I am trying to just upload a sketch using the SAME ISP connection, I didn't touch anything(!) , so I opened the blinking example, hit the upload button, and it's just not working (not in sync).
Again, the goal is now to program a chip with ISP directly, without a boot loader. The reason I boot loaded it is to see it's all connected well.
I can't imagine how the exact same configuration can bootload the chip,and later can't upload a sketch directly using the ISP.
What am I missing here? Can't you use the Arduino IDE to upload a sketch directly as an ISP programmer?

Just buy something an like AVR ISP mk2. I think its silly to go tru the hassle of implementing your own ISP when you can buy one for 20€.

i have one , and have the same problem!

Try this: http://forum.arduino.cc/index.php?topic=118089.0

Agreed, this is off-topic for EESE.  But FWIW, what you're doing should of course be possible (program the device with just your sketch & no bootloader), and the fact that you can burn just a bootloader but not the sketch might mean your electrical connections are ok, so my next suggestion would be to confirm that your target hardware is in fact a Pro or Pro-Mini or very compatible to it. Fuse settings of course vary from one platform to another...

Usually I would recommend using Atmel Studio for development on AVRs because it's so easy to use; but I don't think you can install it for Mac. However I did use the avr-gcc toolchain in command prompt for Linux machines once. Maybe it'll help: http://www.instructables.com/id/Getting-Started-with-Embedded-Systems-using-Atmel/step5/Uploading-Code-to-the-MCU-with-Linux/

Uploading the bootloader probably changed the fuse settings. Try connecting a crystal to the chip.

Are you clicking "File>Upload using programmer" to upload?

You probably used a direct upload button that uses default Arduino programming using RX TX, not the programmer you had selected.
All wirings are perfect that's why you were able to burn the bootloader.
Now you just need to go under Sketch -> Upload Using Programmer.


text:
FIFO overflow - reading IMU MPU6090 and GPS uBlox NEO-6M at once
I am trying to read data from uBlox NEO-6m (I need just speed, just part of the code):
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 7, TXPin = 4;
static const uint32_t GPSBaud = 9600;

float gps_speed = 0;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup(){
ss.begin(GPSBaud);
}

void loop(){
if (ss.available())
    {
      gps.encode(ss.read());
      gps_speed = gps.speed.kmph();

    }
}

And in the same time I read data from MPU6090 using this code (gps code is integrated in it):
http://nevit.blogspot.de/2014/07/arduino-mpu-6050-pitch-roll-with-2.html
When I try to read data separately it works but together it stuck every second (probably reading of gps data) and MPU6050 serial monitor sending FIFO overflow error ..
I tried to lower MPU data rate to 20Hz from 100Hz but it didn't work. I use Arduino UNO.
I am not so much skilled.. Any idea? Is it even possible to do it like this?

It looks like the instant you have a single character received from the GPS, you will go off and wait until the full mesage is received from it in a blocking collection function where you may be unable to drain the MPU FIFO.  Instead, what you may want to do is collect characters one at a time from the GPS while continuing to monitor the MPU, and only deal with the GPS once you have a complete message from it.

When I try to read data separately it works, but together it stuck every second (probably reading of gps data) and MPU6050 serial monitor sending FIFO overflow error .

Yes, you have to be careful about the loop structure and "blocking" to "wait" for a new GPS speed report.  SoftwareSerial also blocks everything else during each received character time.
Just check for GPS characters and update the speed if a complete sentence was received, then do "other things" (e.g., use the IMU data).  Here is a NeoGPS version of your example:
#include "NMEAGPS.h"
#include <NeoSWSerial.h>

static const int RXPin = 7, TXPin = 4;
static const uint32_t GPSBaud = 9600;

float gps_speed = 0;

NMEAGPS gps;

// The serial connection to the GPS device
NeoSWSerial ss(RXPin, TXPin);

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

void loop(){

  // Read GPS characters and see if a new fix is available
  if (gps.available( ss )) {
    gps_fix fix = gps.read();

    //  A fix is available once per second, but the GPS may not know
    //  the speed value, perhaps because the satellite reception is
    //  poor or the unit is just starting.  Check the valid flag.

    if (fix.valid.speed) {

      // Update the gps_speed.  Other parts of your
      //   program can use it whenever they want.
      gps_speed = fix.speed_kph();
      Serial.println( gps_speed );
    }
  }

}

NeoGPS is smaller and faster than other libraries and can be configured to only parse the fields you really use.
Your original sketch uses 6884 bytes program space and 349 bytes of RAM.
The NeoGPS version can be as small as 4802 bytes program space and 150 bytes of RAM. Significant savings!
For the software serial library, I would suggest using AltSoftSerial on pins 8 & 9, if you can move the GPS.  It is much more efficient, and does not disable interrupts for long periods of time: SoftwareSerial will block for ~1ms, and eternity for a 16MHz Arduino.  This is probably interfering with the IMU interrupts.
If you can't move the GPS to pins 8 & 9, you might try another library I maintain, NeoSWSerial.  It is much more efficient than SoftwareSerial, and it works on any two pins.  NeoSWSerial will "play nicer" with the IMU interrupt code, but it can still be affected if the IMU interrupt code takes too long.  NeoSWSerial should not affect the IMU interrupt code.  I used it in the above sketch, along with a debug print.

A guess; Software serial is known for messing with interrupts, in fact I think the rule of thumb is do not use interrupts and software serial.
The MPU code you are using is classic Jeff Rowberg, and uses interrupts.
To be honest, there are things you can do, where an occasional overflow does not cause problems, but that is way too deep to explain here, sorry.
In my case I think I will end up using the arduino to handle the MPU, and attaching it and a GPS to a raspberry pi, and let it merge the two.  You might be able to accomplish something similar with a bigger Arduino if there is one with 2 (or more) uart serial ports, but I do not have experience with that.
If you can speed up the GPS serial rate, give that a try, it actually helps (which is counter intuitive).

Here is answer for you.
GPS keeps on sending data and fill the mcu input buffer . Use listen function and read one software serial at once ..
If you use listen then only one serial port will work at a time and you can swap accordingly .
I was having same problem and It solved my problem
Just open a dummy serial port and when ever you need gps then listen to GPS serial port and do listen to dummy after GPS reading .

Again, please do not add signatures to your post. I've edited these out. Thanks!


text:
PWM-FILTERS -DAC
I want to implement a digital controller C(z) on an Arduino Uno
(transfer function in the z domain) in order to control a plant
G(s) = 3750/[(s+10)(s+30)(s+100)].

I have implemented G(s) with electronics (op-amps, capacitors and
resistances). I want to realize C(z) on the Arduino Uno. The input to
the Arduino is the error signal (reference − output of G) and the
output of C(z) is the input of G(s). Finally, I will have a closed loop
system with negative unit feedback. The reference input is a unit step
signal (1 volt).
My problem is: how can I use PWM and filters in place of a DAC?

If you want to use PWM in place of a DAC, the normal thing to do is to
use some kind of analog low-pass filter. However, many people skip the
filter when the signal is meant for some system that inherently acts as
a low-pass. Example: dimming an LED, where the human eye is the filter.
In your case, since your plant looks like a third order low-pass filter
with cuts at 1.6, 4.8 and 16 Hz, you can probably skip the filter.
If you output on pins 5 or 6, the PWM frequency will be around
980 Hz
(exactly: fCPU/16384). At that frequency, your plant gain
relative to DC will be
G(j2π × 980 Hz) / G(0) ≈ 1.3 × 10−7 j
Probably low enough to not be an issue.

Generally have you  got any other information for this project;

No, and I guess you know the project better than I.

authors: Νίκος-Μάριος Κοκολάκης


text:
Arduino UNO with CD4510 Counter
I am new in Arduino but I have experience in electronics.
I was wondering how can I make a countdown timer using a CD4510 and an Arduino UNO. I know you would suggest that I should connect my seven segment display on the IO pins but I can't do that because I will use multiple seven segment displays.

A display driver, like the MAX7219, can allow you to control up to eight 7-segment displays (or 64 individual LEDs) while only using two pins on the Uno.

Thanks but I only have a limited amount of budget. Can you at least send me any link or tutorial that teaches how to use Arduino UNO and CD4510 counter? :)

What do you mean by  “countdown timer” ?  Do you mean a circuit that waits for some interval to elapse?  Why do you need any displays?  (Ie just use an LED to signal when done waiting)

I need to show the time left that is why I need displays :)

What's a typical range you will count down?  What frequency do counted events occur at?  How many digits does the display need?  Please edit question with answers to those items.  You can drive (eg) four 7-segment displays by using four bits to turn on high-side power and seven bits to pull down low-side segments -- ie just need some resistors, some transistors, four displays, and Arduino -- no need for CD4510 if input frequency isn't too high.  (I was assuming, due to your fixation on CD4510, that you have some external event to count; if just timing seconds, that's even simpler.)

I can use CD4510 to make a countdown timer, I just need to connect CLOCK INPUT to the Digital IO pins located in the arduino microcontroller and use pulse with modulation (pwm) for the code

The CD4510 does not seem at all appropriate for this task. It is a counter chip that counts up or down. You can do that with the Arduino. The output (of the CD4510) would be in "binary" and not suitable for driving a 7-segment display.
You can get 8 digit 7-segment displays on eBay for around $2. Surely that fits within your budget?

Ok, but i'm not sure if my local electronic shop has it :)) also I will use CD4511 to decode the binary and display it, i will only use the microcontroller for UP/DOWN and for CLOCKINPUT :))

@MiguelLorenzo: Why do you keep wanting to use extra chips to do what the Arduino can do on its own, or vice versa?

Because arduino uno has limited ports only and I would use multiple timers  and multiple sensors for my device :))

In that case see Is there a way to have more than 14 Output pins on arduino?


text:
Interrupt fires multiple times
I have a Photo Interrupter which I am using to count the RPM of a motor.
I am incrementing an integer to show the amount of interrupts there have been.
The issue is that there can be several interrupts fired for each time the "beam" of the Photo Interrupter is broken.
I have a 5mm length of plastic which breaks the "beam". If I make the plastic shorter than that, the Photo Interrupter doesn't pick up the break.
I am using the following, very basic code:
int pin = 13;
volatile  int tcnt = 0;
volatile int state = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, CHANGE);
}

void loop() {
  Serial.println(tcnt);
  digitalWrite(pin, state);
}

void blink() {
  tcnt = tcnt + 1;
  state = !state;
}

Why can there be several interrupts for each break?  Do you know for sure (eg via oscilloscope) that multiple  interrupts occur for each break?  Also, if you know how many  interrupts occur for each break, just divide by that number.

You appear to be asking a couple of different questions, Why does my interrupt fire multiple times? and Why won't my interrupter detect shorter than 5mm of plastic? I've tried to address both of them below, however, in the future please split them out and ask two separate questions.

How many is “several”? 2) How do you know there are several interrupts? You must have some independent means of knowing the motor speed.

@jwpat7, I don't have an oscilloscope however in the Serial Monitor I can see that the interrupt fires in clumps.

@JakeC, will do.

@EdgarBonet, several can be anywhere between 3 and 8. I think as JakeC mentioned, I should have the mode set as RISING.

What sensor are you using?

I would recommend adding a comparator with hysteresis so as to get a clean digital pulse, pictured below:

simulate this circuit – Schematic created using CircuitLab
This has the correct values.
I recommend the comparator with hysteresis as the phototransistors are prone to cause issues with interrupts even when used with pul-up/pull-down resistors, thus is as they very the voltage more than give a clean 0/1 digitally.
Here is your code, modified with the addition of RISING and of a 10mS delay.
int pin = 13;
volatile  int tcnt = 0;
volatile int state = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, RISING);
}

void loop() {
  Serial.println(tcnt);
  digitalWrite(pin, state);
   delay(10);
}

void blink() {
  tcnt = tcnt + 1;
  state = !state;
}

This method produces very reliable results. It is also accurate with objects moving rapidly because of the interrupt.

I would also say that the problem you have when you use a piece of plastic < 5mm is that the length of the slit in the sensor is 6.0±0.1(seen below). If the plastic is less you probably find that the phototransistor still has enough IR falling on it to allow voltage to flow, but enough to trigger and interrupt. With the comparator you could probably use a smaller piece of plastic and find the voltage swing with a DMM and modify the voltage divider (R1 and R2) to suite the needs.

Thanks for the advice! I'm going to do some reading on comparators first though!

Two other possible problems, apart from what Jake C has adressed in his answer are:
1. Hardware bounce
If your signal from the sensor isn't a clean transition from high to low but rather "bouncy" (see image below). The microcontroller will register multiple transitions in the meantime.

Solution to this would be to add a small capacitor (wil slow it down though) or add debouncing code... Best would be to get a "clean" sensor.
2. Floating contact

When I even move my finger close to the wire running to PIN2 the interrupt fires.

That kinda seems like it's a floating contact, where it's not really connected to anything.
This is usually solved by using a pullup/pulldown resistor. Or maybe there is something wrong with the connection.

Also:

Maybe due to the type of sensor?

You should note the part number of the sensor or link a datasheet, so we can see if it's typical behaviour for this type of sensor.

I've set the pin as a pull up. It does seem like it's a floating contact but I've noticed that when I detach the negative or positive lead, the sensor starts act completely like a floating point. The datasheet for the sensor is at: http://www.jaycar.com.au/medias/ZD1901-dataSheetMain?context=bWFzdGVyfGltYWdlc3wxMzk2OTh8YXBwbGljYXRpb24vcGRmfGltYWdlcy9oZTUvaGJlLzg4MTU3NDgwNTUwNzAucGRmfDJjZjE1NTk3Nzk3YTFlMmM5NjEzNTY5OWU0MjBmOTg0OGE3NzNkYWE5ZjFlMzc1ZWFjZjFkNjI2MzgxMGE0ZTc

I had this issue using buttons as interrupts. Adding a capacitor works like a charm!

As far as it firing multiple times, are you aware that you have the interrupt mode set to CHANGE? This means the interrupt will fire once when something enters the beam, and again when something leaves the beam. You will probably want to set it to RISING or FALLING so that it only fires on one of those events, not both.
As to the not detecting issue I can think of a few reasons why this could be:

Your motor is moving so fast that the sensor changes again before it has had the chance to finish the interrupt service routine and reset the interrupt on the pin.
The photo interrupter you are using is too slow to report the piece of plastic passing through it. Sensors like this usually indicate a rise time and a fall time, and if it moves through the beam faster than these times it will not register the interruption.
The piece of plastic isn't large enough to block the beam. Depending on the photo interrupter, the beam used could be laser like and very narrow, or it could be wide and more like a flashlight. If it is more like the latter, you will need to have enough material present to block enough light to set off the sensor.

Thanks for the response! I have set the mode to RISING with no luck. The sensor should be fast enough but it seems that the sensor doesn't work well with the pull-up pin. I've set the pin as INPUT_PULLUP but I still get the interrupt firing intermittently. When I even move my finger close to the wire running to PIN2 the interrupt fires. It's like it's not grounded. Maybe due to the type of sensor?

If you want to count RPM, maybe this link will help you:
http://rjbotics.blogspot.in/2015/07/counting-real-time-rpm-with-ir-sensors.html


text:
Arduino UNO with LMT86LP temperature sensor
I am trying to use the Arduino Uno with the LMT86LP temperature sensor, but I am getting strange output voltages from the sensor.
I have the pins (from left to right, flat side facing forward) as VDD, OUT, and GND. VDD is connected to 5V, GND to GND, and Vout to A0 (analog pin 0). The readings from the Arduino are consistently around 360 mV but should be somewhere around 1800 mV as I measured the output of the sensor using a multimeter and got a constant 1.8 V.
Right now the code is very simple. I am just doing analogRead() and printing to the Serial Monitor.

The result from analogRead() is in counts of full scale, not in volts. Since you are using a 10-bit ADC, full scale is 1024.
1.8V/5V⋅1024=368.64

Ah I see, thank you. However I seem to be getting negative values for the temperature. The calculations I am doing are like so,
int vin = analogRead(A0);
float mV = (vin/1024.0)*5000;
float tempC = (mV-500)/10;

@user1982824: Why are you subtracting 500?

Sorry sorry, this actually what I'm doing,
voltage = reading * (5.0 / 1024);
tempC = (voltage - 0.5) * 100;
and I'm getting values around 12.5 celsius

@user1982824: That equation doesn't match anything I can find in the datasheet.

should i be using the equation T = (10.888 - sqrt((-10.888)^2 +4*.0035*(1777.3-temp))/(2*-0.00347)) + 30

@user1982824: Eh, you could, but unless you need to support the entire temperature range of the device I'd look at using the approximation method just a bit lower down on the page.

thanks, i just made the modification and it works fine. :D


text:
Using nrf24l01 with mpu 6050 unstable
I am trying to connect the wireless module nrf24l01 with the gyro mpu-6050.  Each works perfectly on its own.  However, when connecting both to a single atmega328 (in order to send over wireless the gyro data), the code runs for between 30 seconds and 5 minutes.
I have seen many people have issues, none of the suggestions have worked, but it seems like it is more about the combination than the mpu itself.  I have not had any errors, in that all the attempts have uploaded fine.
Some things I have tried (If you have experience with this device, im sure you will know what i am referring to ):
Changing clock rates from 24 to 12, and 400 to 200
Changing the header file for mpu from 100 hz to 20 hz and back
Adding pullup and pulldown resistors on sla/sda
Using external variable power supply to make sure exact voltage
Powering devices off arduino 3.3 and external 3.3
Running code without using serial reader on computer and just transmitting data
Edit:
After more debugging, I reduced the issue (I think).  As each module works fine independently, i thought there could be a code issue.  It seems though, that the issue is the combination of buffers.  I don't think this is exactly right, but to us it seems like the gyro needs to run quickly to stop the risk of causing the arduino to hang(even though we clear the buffer).
The second part is the wireless.  It seems like the code is looking by default for an acknowledgment the package is received.  This slows down the broadcasting.  So, if we disable the ack requirement, the gyro becomes stable.  However, the receiver stops receiving any packets at all.  If someone knows why, please explain.
So what we thought would work is by sending only some packets as the write with ack on a particular pipe.  This way, the gyro will be able to run stably, and the data can sometimes be sent and we can see if this is really the problem.  Again, this does not get recognized by the receiver at all.
Questions:
Does it make sense that the buffers are working against eachother, and this is not solvable through hardware.
Is there a clear reason why the receiver can not find packets that are being sent, just without the ack requirement?

i'm trying to do the same but can't get the code right... i need to read the gyro gy-521 position and to transmit it to move servo's on the other side... i will happy to get help with that and move to the n
ext level (that is you problem now, i believe that changing the baud can help )

Correct me if I am wring, but the nrf24l01 is not a WIFI module. Its a RF Transceiver.

@PhillyNJ Thanks, just modified it. meant wireless

You only used the gyroscope for data transmission? please post the complete code that you used to communicate between the nrf24l01 and the mpu-6050. Thank you

I could not figure out what was wrong, but I changed to this library for NRF24: http://tmrh20.github.io/RF24/
and I started using the GY-85 with the FreeIMU Library : http://www.varesano.net/projects/hardware/FreeIMU
Following this advice:
http://forum.arduino.cc/index.php?topic=164222.msg1539961#msg1539961
It works now, so if it was SRAM as @Avamander suggested, it was not on my side.

It seems to me you are running out of memory (SRAM).  https://www.arduino.cc/en/Tutorial/Memory