body:
<!-- language-all: lang-C++ -->

## How the IDE organizes things

First thing, this is how the IDE organizes your "sketch":

* The main `.ino` file is the one of the same name as the folder it is in. So, for `foobar.ino` in `foobar` folder - the main file is foobar.ino.
* Any other `.ino` files in that folder are concatenated together, in alphabetic order, at the end of the main file (regardless of where the main file is, alphabetically).
* This concatenated file becomes a `.cpp` file (eg. `foobar.cpp`) - it is placed in a temporary compilation folder.
* The preprocessor "helpfully" generates function prototypes for functions it finds in that file.
* The main file is scanned for `#include <libraryname>` directives. This triggers the IDE to also copy all relevant files from each (mentioned) library into the temporary folder, and generate instructions to compile them.
* Any `.c`, `.cpp` or `.asm` files in the sketch folder are added to the build process as separate compilation units (that is, they are compiled in the usual way as separate files)
* Any `.h` files are also copied into the temporary compilation folder, so they can be referred to by your .c or .cpp files.
* The compiler adds into the build process standard files (like `main.cpp`)
* The build process then compiles all the above files into object files.
* If the compilation phase succeeds they are linked together along with the AVR standard libraries (eg. giving you `strcpy` etc.)

A side-effect of all this is that you can consider the main sketch (the .ino files) to be C++ to all intents and purposes. The function prototype generation however can lead to obscure error messages if you are not careful.

---

## Avoiding the pre-processor quirks

The simplest way of avoiding these idiosyncrasies is to leave your main sketch blank (and not use any other `.ino` files). Then make another tab (a `.cpp` file) and put your stuff into it like this:

    #include <Arduino.h>

    // put your sketch here ...

    void setup ()
      {

      }  // end of setup

    void loop ()
      {

      }  // end of loop

Note that you need to include `Arduino.h`. The IDE does that automatically for the main sketch, but for other compilation units, you have to do it. Otherwise it won't know about things like String, the hardware registers, etc.

---

## Avoiding the setup/main paradigm

You don't have to run with the setup/loop concept. For example, your .cpp file can be:

    #include <Arduino.h>

    int main ()
      {
      init ();  // initialize timers
      Serial.begin (115200);
      Serial.println ("Hello, world");
      Serial.flush (); // let serial printing finish
      }  // end of main

---

## Force library inclusion

If you run with the "empty sketch" concept you still need to include libraries used elsewhere in the project, for example in your main `.ino` file:

    #include <Wire.h>
    #include <SPI.h>
    #include <EEPROM.h>

This is because the IDE only scans the main file for library usage. Effectively you can consider the main file as a "project" file which nominates which external libraries are in use.

---

## Naming issues

* Don't name your main sketch "main.cpp" - the IDE includes its own main.cpp so you will have a duplicate if you do that.

* Don't name your .cpp file with the same name as your main .ino file. Since the .ino file effectively becomes a .cpp file this also would give you a name clash.

---

> Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);

Yes, this compiles OK:

    class foo {
      public:
    };

    foo bar;

    void setup () { }
    void loop () { }

However you are probably best off to follow normal practice: Put your declarations in `.h` files and your definitions (implementations) in `.cpp` (or `.c`) files.

### Why "probably"?

As my example shows you *can* put everything together in one file. For larger projects it is better to be more organized. Eventually you get to the stage in a medium to large-size project where you want to separate out things into "black boxes" - that is, a class that does one thing, does it well, is tested, and is self-contained (as far as possible).

If this class is then used in multiple other files in your project this is where the separate `.h` and `.cpp` files come into play.

* The `.h` file *declares* the class - that is, it provides enough detail for other files to know what it does, what functions it has, and how they are called.

* The `.cpp` file *defines* (implements) the class - that is, it actually provides the functions, and static class members, that make the class do its thing. Since you only want to implement it once, this is in a separate file.

* The `.h` file is what gets included into other files. The `.cpp` file is compiled once by the IDE to implement the class functions.

### Libraries

If you follow this paradigm, then you are ready to move the entire class (the `.h` and `.cpp` files) into a library very easily. Then it can be shared between multiple projects. All that is required is to make a folder (eg. `myLibrary`) and put the `.h` and `.cpp` files into it (eg. `myLibrary.h` and `myLibrary.cpp`) and then put this folder inside your `libraries` folder in the folder where your sketches are kept (the sketchbook folder).

Restart the IDE and it now knows about this library. This is really trivially simple, and now you can share this library over multiple projects. I do this a lot.

---

A bit more detail [here](http://www.gammon.com.au/forum/?id=12625).


sender: user

message:
Classes and objects: how many and which file types do I actually need to use them?

I have no previous experience with C++ or C, but know how to program C# and am learning Arduino. I just want to organize my sketches and am quite comfortable with the Arduino language even with its limitations, but I really would like to have an object-oriented approach to my Arduino programming.

So I have seen that you can have the following ways (not exhaustive list) to organize code:

 1. A single .ino file;
 2. Multiple .ino files in the same folder (what the IDE calls and displays like "tabs");
 3. An .ino file with an included .h and .cpp file in the same folder;
 4. Same as above, but the files are an installed library inside Arduino program folder.

I have also heard of the following ways, but have not got them working yet:

 - Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);
 - __[preferred approach]__ Including a .cpp file where a class is declared, but _without_ using a .h file (would like this approach, should that work?);

Note that I only want to use classes so that code is more partitioned, my applications should be very simple, only involving buttons, leds and buzzers mostly.

sender: assistant

body:
I'm posting an answer just for completeness, after finding out and testing a way of declaring _and_ implementing a class in the same .cpp file, without using a header. So, regarding the exact phrasing of my question "how many file types do I need to use classes", the present answer uses two files: one .ino with an include, setup and loop, and the .cpp containing the whole (rather minimalistic) class, representing the turning signals of a toy vehicle.

Blinker.ino

    #include <TurnSignals.cpp>

    TurnSignals turnSignals(2, 4, 8);

    void setup() { }

    void loop() {
      turnSignals.run();
    }

TurnSignals.cpp

    #include "Arduino.h"

    class TurnSignals
    {
        int
            _left,
            _right,
            _buzzer;

        const int
            amberPeriod = 300,

            beepInFrequency = 600,
            beepOutFrequency = 500,
            beepDuration = 20;

        boolean
            lightsOn = false;

        public : TurnSignals(int leftPin, int rightPin, int buzzerPin)
        {
            _left = leftPin;
            _right = rightPin;
            _buzzer = buzzerPin;

            pinMode(_left, OUTPUT);
            pinMode(_right, OUTPUT);
            pinMode(_buzzer, OUTPUT);
        }

        public : void run()
        {
            blinkAll();
        }

        void blinkAll()
        {
            static long lastMillis = 0;
            long currentMillis = millis();
            long elapsed = currentMillis - lastMillis;
            if (elapsed > amberPeriod) {
                if (lightsOn)
                    turnLightsOff();
                else
                    turnLightsOn();
                lastMillis = currentMillis;
            }
        }

        void turnLightsOn()
        {
            tone(_buzzer, beepInFrequency, beepDuration);
            digitalWrite(_left, HIGH);
            digitalWrite(_right, HIGH);
            lightsOn = true;
        }

        void turnLightsOff()
        {
            tone(_buzzer, beepOutFrequency, beepDuration);
            digitalWrite(_left, LOW);
            digitalWrite(_right, LOW);
            lightsOn = false;
        }
    };


message:
Triggering the push button on the analog input of the L293D motorshield

I'm trying to drive a **12v dc motor** using three push buttons, one to turn clockwise, the other counter-clockwise and the other to stop the motor completely.

However the code below is not working, apparently it feels like I'm doing something wrong in the code on the connect buttons on the analog part of the engine shield L293D.

The Arduino is powered by a **9v** battery and **motor shield **L293D** with an external power.

    #include <AFMotor.h>

        AF_DCMotor motor(1);

        int val;

        #define btnleft A0
        #define btncenter A1
        #define btnright A2

        void setup()
        {
          pinMode(btnleft, INPUT);
          analogWrite(btnleft, HIGH);
          pinMode(btncenter, INPUT);
          analogWrite(btncenter, HIGH);
          pinMode(btnright, INPUT);
          analogWrite(btnright, HIGH);
        }

        void loop()
        {
         val=digitalRead(btnleft);
           if(val!=1)
            {
            Serial.print("LEFT: ");
            motor.setSpeed(255);
            motor.run(FORWARD);
            delay(3800);
            }

         val=digitalRead(btncenter);
           if(val!=1)
            {
            Serial.print("CENTER");
            motor.setSpeed(255);
            motor.run(BACKWARD);
            delay(3800);
            }

         val=digitalRead(btnright);
           if(val!=1)
            {
            Serial.print("RIGHT");
            motor.run(RELEASE);
            delay(3000);
            }
        }

body:
<strike>As noted in Nick Gammon's comment, `digitalWrite(btnleft, INPUT)` (etc.) would make a lot more sense than does `analogWrite(btnleft, INPUT)` (etc.).</strike>

***
*Edit:* `INPUT` is a constant defined in `wiring.h` (as in following extract), and is intended for use in [`pinMode()`](https://www.arduino.cc/en/Reference/PinMode) calls that set an IO pin's mode to one of `INPUT`, `OUTPUT`, or `INPUT_PULLUP`.  It's inept to use it in a call of either [`digitalWrite()`](https://www.arduino.cc/en/Reference/DigitalWrite) or `analogWrite()`.

        #define HIGH 0x1
        #define LOW  0x0
        #define INPUT 0x0
        #define OUTPUT 0x1
        #define INPUT_PULLUP 0x2

***

Note that [`digitalWrite`](https://www.arduino.cc/en/Reference/DigitalWrite) to an input-mode pin leaves the pin in input-mode, while an [`analogWrite`](https://www.arduino.cc/en/Reference/analogWrite) to an input-mode pin changes the pin to output-mode.

When you want a pin to be input-mode with pullup, it is simpler to use `INPUT_PULLUP` as the mode parameter, rather than using two separate calls.  That is, instead of saying [`pinMode(pin, INPUT);`](https://www.arduino.cc/en/Reference/pinMode) followed by `digitalWrite(pin, HIGH);`, just say

    pinMode(pin, INPUT_PULLUP);


message:
Reading iBeacon Data using HC-05 bluetooth module

I have bought a HC-05 bluetooth module for Arduino.

My requirement is to read data transmitted from iBeacon, is it possible using HC-05 or I have to shift to HM-10?

body: The HC-05 doesn't support BLE, which is used for iBeacons.


message:
esp8266 not getting programmed

I am working on an esp8266 and I am connecting it with Arduino Uno. I have programmed the Arduino but when I write AT command on the serial monitor it doesn't show anything.The connections which i have made are:

    tx uno - rx esp
    rx uno - tx esp
    gnd uno -gnd esp
    vcc and ch_pd - 3.3v supply

I am using an external supply and not the 3.3v from the Arduino.
I need help with this.

body:
Be careful, you could fry your ESP like that.  You need to get the signal lines down to 3.3V, not the 5V used by the Arduino Uno.  There are many ways to do this, from voltage dividers, to transistors, or you can use a 3.3v Arduino Pro Micro.  I would also recommend starting out with just a 3.3v FTDI board, and interface that directly to the ESP to remove the Arduino and its code from the picture.

I would also make sure that your grounds on the external supply and the Arduino are tied together, or just power the ESP from the 3.3v out of the Arduino.

Other than that, double check your baud rate, some come shipped at 9600, some at 115200, and i'm sure that there are others out there too shipping at different baud rates.


body:
Sorry if these are stupid questions but these are the things I would check.

 1. Why are you connecting to an Arduino, why not connect directly to the
   HOST and use a terminal emulator program?
 2. What ESP8266 are you using?
 3. Are you connecting the Vcc connector of the ESP8266 to 3.3v?
 4. I think you need to pull the RST pin high to enable normal running,
    is it high?


message:
Arduino Micro and MPU-9150

I'm trying to connect an Arduino Micro to MPU-9150 using the  MPU6050_DMP6 example.
It runs for couple of seconds then the board Hangs, I sometimes see the "FIFO overflow" message.
The same code runs well when i connect the MPU-9150 to Arduino UNO and Arduino Duemilanove.
I tried to lower the serial baud rate but no success with that. I even tried connecting an external 12V to the Micro but it's the same.

should I lower the i2c clock (not sure how to do it)?

another interesting thing i have noticed is that with the Duemilanove i can use a longer line for the i2c (5m of cat5e), with the Uno it only works with less then 2m cables, can anyone tell why?

body:
I have seen a lot of variations with the 6050.  Code I know works fine for me, will not run on someone else's system.  Code fixes suggested by others has zero effect for me.  My understanding is the DMP code is a reverse engineered sample that the manufacturer will not release actual documentation on. So it is a gamble to begin with.

That being said, I usually reset the FIFO buffer after every read.  I get an occasional over flow (1-2 per minute) with a lot of other code running at the same time, and NOT using interrupts.  The resulting AHRS data is reliable and solid (UNO) at default rate (100hz).  Ive lowered the AHRS rate (you have to modify data tables in a .H file) and I get the same error rate, it seems to have no effect.

As far as line lengths go, it is I2C. It is some magical combination of wire size and length, internal pull up resistors plus external ones.  I have usually heard people have success adding some pull-up resistors  I2C is a ground sink signal - so it doesn't care if it is 5 volts or 3.3 - only that everything on the bus be the same.  Obviously you will do better at 5V on a longer line vs 3.3V.  Some will argue the pull ups need to be at termination, some say it doesn't matter. I don't know anything other than the spec is very hard to understand and I have not had problems, especially the kind that require some of the elaborate schemes some people come up with (replacing caps and resistors).

Anyhow, 2 meters would seem to be pushing an Integrated circuit to Integrated circuit spec beyond what it was intended for, communication within a board. You might get it to work, but you also might rethink it.


message:
Arduino IRremote stops working

I'm using a standard 38kHz receiver with [Arduino-IRremote library][1] and it works fine for a while but then it stops working. The loop function is running time after time as expected but at some point the library decode function starts returning false until I reset the board.

This example code works for me with any arduino nano or bare atmega328p at 8Mhz but for both of them it freezes after some receptions.

The code is the library example itself:

    #include <IRremote.h>

    int RECV_PIN = 11;

    IRrecv irrecv(RECV_PIN);

    decode_results results;

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

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

Some times this happens fast and other times it is after 20 or more receptions.
I only added a led blink later to test if the board is frozen or is only the infrared that stops receiving and it was the second case.

  [1]: https://github.com/shirriff/Arduino-IRremote

body:
Arduino tutorials I've seen don't mention it but the datasheets from the ir receptors manufacturers advice to stabilize vcc with a resistor and a capacitor.

![circuit][1]

It seems without that the receptor fail to correctly report the received wave so the library may decode it wrong. In my case the problem started to happen when I added RGB leds controlled by PWM on the same (stabilized) power supply.

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


body:
I was having similar problem (but not the same )
And it was due to software serial pins which keep on filling the buffers of MCU.

Some times it happen that pwm pins keep on receiving data e.g. GPS also keep filling the buffer and due to that arduino freeze .

To solve this problem I open new dummy software serial port.( select any pins which is free ) and do listen to your software serial pins when you want to read it otherwise make dummy listen.


body:
In short: The IRremote Library has bugs that lead to unresponsiveness of the board.
There were some updates and now IRremote.h library 3.01 runs about a day with a FastLED.h WS1211 led stripe connected to it.

My approach to make it run reliable more than 24h with the latest library you could connect a digital pin to the reset pin on the Arduino.
Then use `EVERY_N_HOURS` to occasionally pull that pin low.

The Software reset via timer (watchdog timer library) every 2 seconds f.e. worked occasionally but not reliable.

That should even make every 2USD board clone run as reliable as it could/hardware allows it.

Have fun :)


message:
0 value integer does not enter If

I'm sure this is a very basic coding mistake...

I'm picking up a reading from A0. If the value is 0, I want the value of the serial to be written to the Serial Monitor.

I also want it only to write to the Serial Monitor for the first time that the value falls to 0.

I don't understand why, when the value for SensorValue = 0, the if is not performed.

This is my code:

    boolean must_print = true;
    int sensorValue = 0;

    // the setup routine runs once when you press reset:
    void setup() {
    // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      sensorValue = analogRead(A0);

      if (sensorValue = 0) {

         if (must_print = true)
        {
         must_print = false;
         Serial.println(sensorValue);
        }
      else
        must_print = true
      }

       delay(500);        // delay in between reads for stability
    }

Thanks!

body:
      if (sensorValue = 0) {

That assigns zero to sensorValue, which then tests false. You want:

      if (sensorValue == 0) {


message:
Counting revolutions of a DC motor with a Photo Interrupter

I have a DC motor which is rated at 11 200 RPM.

I would like to count the actual RPM (it seems to be maybe 1500 RPM from what I can tell manually.)

I bought a Photo Interrupter, and have connected it to pin A0. When the beam of the Photo Interrupter is broken, the reading drops to zero.

All seems to work well when using a delay of 100, but as soon as I drop the delay to less than about 50, I get multiple reads.

This is my code:

    int must_print = 1;
    int sensorValue = 0;

    //the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      sensorValue = analogRead(A0);

      if (sensorValue > 0)
        {
          if (must_print == 1)
          {
            must_print = 2;
            Serial.println(sensorValue);
          }
        }

      if (sensorValue == 0) {
        must_print = 1;
      }

      delay(100);        // delay in between reads for stability
    }

At delay(100) the Serial Monitor looks like this for a single interrupt of 10 seconds:

    354

At delay(50) the Serial Monitor looks like this for a single interrupt of 10 seconds:

    298
    312
    328
    336
    349
    360
    366
    371

Thanks!

body: You shouldn't use an analog pin with a photointerruptor.  The photointerruptor is a digital device.  Connect it to, preferably, an interrupt pin and use an interrupt to count your revolutions at high speed.


message:
Sodaq Moja — Accessing SW2/SW3 user switches

I have a Sodaq Moja, from supporting the project on Kickstarter, and I didn't have much time until now to play with it. Unfortunately, the online documentation for the Moja has disappeared, and only the docs for the new version, the Mbili, is accessible. And nowhere can I see where to access the user switches. Which, to boot, have been reordered in the Mbili, can cut down from 3 to 2.

Would anyone have an idea?

Cheers,

body:
According to [the schematics](https://github.com/SodaqMoja/SodaqMojaBoard) and pictures of the Moja, the Sodaq Moja has no "User Switches".

There are 2 buttons and 1 switch.  The switch is a general power on-off switch.  One button (SW2) is the master reset button for the ATMega328P.  The other button, SW3, is the reset for the X-Bee daughter board.

None of those can be used programmatically.


message:
Sending a double message for action to occur

I'm currently designing a system for my GCSE coursework. For the coursework, I am making a bollard system, controlled by the internet / traffic lights.

I've been experimenting with an Arduino Uno and Ethernet shield, in order to fulfill the control by the internet.

When I telnet into my Arduino, and send it the command "S#UP", the red LED comes on, and stays on for 30 seconds. If I send the command again, the Arduino does not turn on the LED, unless the command was send twice, consecutively. Also, if I were to send a different command, for example "S#DOWN", the LED does not even turn on, no matter how many times I send it.

Does anyone have any ideas for my? Anything I've blatantly missed or got myself confused on?

    #include <SPI.h>
    #include <Ethernet.h>
    String authcode, newstatus, command;
    bool UP, DOWN, EMERGANCY;
    long UPTime, DOWNTime, EMERGANCYTime, LastFlash;
    bool NextFlash;

    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

    IPAddress ip(192, 168, 1, 177);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);

    EthernetServer server(1265);

    char serverHost[] = "LambdaLaptop";
    EthernetClient phpClient;

    int R = 8;
    int G = 9;

    void setup() {
      Ethernet.begin(mac, ip, gateway, subnet);
      server.begin();
      Serial.begin(9600);
      Serial.println("=----------------------=");
      Serial.println("=- Traffic Management -=");
      Serial.println("=-    System Loaded   -=");
      Serial.println("=----------------------=");

      Serial.println("");

      authcode = String("4b4fec50eaa13b98934c36863293b5cf");
      LastFlash = millis();
      NextFlash = HIGH;

      pinMode(R, OUTPUT);
      pinMode(G, OUTPUT);
    }

    void loop() {
      EthernetClient client = server.available();
      if (client) {
        if (client.available() > 0) {
          char thisChar = client.read();
          command += thisChar;
          ProcessCMD( command );
        }else{
         if(command.length() > 0 ){
           command = String("");
         }
        }
      }
      if( UP ){
        if( UPTime > millis() ){
          digitalWrite(G, HIGH);
        }else{
          UP = false;
          digitalWrite(G, LOW);
        }
      }else if( DOWN ){
        if( DOWNTime > millis() ){
          digitalWrite(R, HIGH);
        }else{
          DOWN = false;
          digitalWrite(R, LOW);
        }
      }else if( EMERGANCY ){
       if( EMERGANCYTime > millis() ){
         if( LastFlash + 100 < millis() ){
           digitalWrite(R, NextFlash);
           if(NextFlash == LOW){
             NextFlash = HIGH;
           }else{
             NextFlash = LOW;
           }
         }
        }else{
          EMERGANCY = false;
          NextFlash = HIGH;
          digitalWrite(R, LOW);
        }
      }
    }

    void ProcessCMD( String CMD ){
      if(CMD == "S#UP"){
        UP = true;
        UPTime = millis() + 30000;
        if(CMD.length() > 11){
          command = String("");
        }
      }else if(CMD == "S#DOWN"){
        // Make the thing go DOWN.
        // GREEN LIGHT
        DOWN = true;
        DOWNTime = millis() + 30000;
        if(CMD.length() > 11){
          command = String("");
        }
      }else if(CMD == "S#EMERGANCY"){
        // Make the thing go DOWN.
        // Flash RED beacon.
        EMERGANCY = true;
        EMERGANCYTime = millis() + 15000;
        if(CMD.length() > 11){
          command = String("");
        }
      }else if(CMD == "TEST"){
        UP = true;
      }else if(CMD == "TEST2"){
        UPTime = millis() + 30000;
      }else{
        if(CMD.length() > 11){
          command = String("");
        }
      }
    }

    void SetStatus( String newstatus ){
      if (phpClient.connect(IPAddress(192,168,1,10), 80)) {
        phpClient.println(String("GET /setstatus.php?authcode=") + authcode + String("&status=") + newstatus + String(" HTTP/1.1"));
        phpClient.println("Host: LambdaLaptop");
        phpClient.println("User-Agent: arduino-ethernet");
        phpClient.println("Connection: close");
        phpClient.println();
        phpClient.stop();
      }
      else {
        Serial.println("Couldn't connect to the system!");
        phpClient.stop();
      }
    }

body:
I do not have and ethernet shield at this moment to test on it your code but hopefully the next observations will help to solve your issue.

> If I send the command again, the Arduino does not turn on the LED,
> unless the command was send twice, consecutively.

It seems that your string is not correctly processed, probably caused by "garbage" from previous received string or incomplete string. I think is from this part of the code

     if (client.available() > 0) {
      char thisChar = client.read();
      command += thisChar;
      ProcessCMD( command );

You are trying to append a char (one byte) to your command string; by doing this you are not getting the received string necessarily because the "+=" is for retrieve char by char (for example, inside a while loop). First try to print thisChar variable to ensure what are you getting and also you can print client.available() to see how many bytes you got.

Second, for your `ProcessCMD` function it could be better to use pointers to handle the `command` variable, meanwhile you must clean `command` variable always (and not only when `CMD.lenght > 11` ), i.e,

    if(CMD.length() > 11){
      command = String("");
    }

must be at the end of the ProcessCMD function

      command = String("");

Also you can ensure that when you set `UP=true`, also set `DOWN=false` and so on. I prefer the Switch-Case structure to handle commands.

Try to follow arduino examples to better understand.

Cheers.


body:
It would be far better to use char arrays instead of the String class (perhaps 11 bytes, if that is the largest command?).

eg.

const int MAX_COMMAND = 11;

char command [MAX_COMMAND];

----

     if (client.available() > 0) {
          char thisChar = client.read();
          command += thisChar;
          ProcessCMD( command );

You appear to be processing the command for every received byte. This means you will process "S", "S#", "S#D", "S#DO" etc. You need to wait until the whole command has arrived.

Then, once the command has been processed, empty out the command ready for next time.

---

    void ProcessCMD( String CMD ){

Also all upper-case is usually reserved for constants, not variables like CMD.

---

  Finally, your detection of end-time by addition will fail when millis() wraps. This might not matter in a small test, but you may as well teach the right way. Instead of adding an interval, remember the start time and detect when the interval is up, eg. instead of:

    if( UPTime > millis() ){

You would write:

    if (millis () - UPTime >= 30000) {

Where UPTime is now the *start* of the interval (that is, you remember when the interval starts, and do the above subtraction to find the end of it).

---

## References

* [Processing incoming serial data](http://www.gammon.com.au/serial) - the same techniques apply to Ethernet

* [millis() overflow ... a bad thing?](http://www.gammon.com.au/millis) - how to handle millis() wrap-around

* [State machines](http://www.gammon.com.au/statemachine) - managing events happening on the fly


message:
Arduino can't see any library I have installed for nrf905?

nrf905\
nRF905-All-In-One-Shield\
RadioHead-master\
RadioHead\

None any of them are compiled with their examples without getting errors.

*Error message:*

    nRF905_RX.ino:4:20: fatal error: NRF905.h: No such file or directory
    compilation terminated.
    Error compiling.

Libraries used:

[Elechouse][1]
[RadioHead Github][2]
[RadioHead Doxygen][3]
[zkemble/nRF905][4]

[1]: http://www.github.com/elechouse/nRF905
[2]: http://www.github.com/PaulStoffregen/RadioHead
[3]: http://www.airspayce.com/mikem/arduino/RadioHead
[4]:http://www.github.com/zkemble/nRF905

body:
The errors you were getting when you compiled was because if the libraries were extracted straight to the Arduino library folder from the .zip, the file path becomes too long for the compiler to find it.

So what you need to do is to create a new folder in the libraries folder for each library.

**Note**: you cannot do the standard `libraryName\src\foo.cpp` as this seems to give errors for these libraries (in that it does not find them).

What you need to do is to make a file in the `libraries` directory; for the *zkemble* one you can create a main folder called `nRF905`, then take the files under `nRF905/arduino/nRF905` from github and place them in the folder created earlier. It should look like this:
![enter image description here][1]

You should repeat this for the Elechouse one as well as it solved the problem too. i.e.

 - `C:\\...\libraries\NRF\examples\`
 - `C:\\...\libraries\NRF\NRF905.cpp`
 - `C:\\...\libraries\NRF\NRF905.h`
 - `C:\\...\libraries\NRF\keywords.txt`

Also of importance is that once you have the library from Elechouse compiling you need to open up the .cpp file and go to line 16, where there is

    PROGMEM unsigned int freq_tab[10] = {

 and to this add `const`, like so:

    PROGMEM const unsigned int freq_tab[10] = {

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


message:
Arduino Mega XBee Limited inputs

I'm currently using an Arduino Uno with the Wireless SD shield with an XBEE attached so I can wirelessly send voltages from sensors to a computer. This works great but I am limited to 5 analog inputs. I am thinking of using a Mega but the Wireless SD Shield is the same for both models. Are there any shields/techniques were  I can wirelessly transmit up to 15 analog inputs to a PC using XBEE or otherwise,

Many Thanks,

AH

body:
<!-- language-all: lang-C++ -->

See [74HC4051 multiplexer / demultiplexer](http://www.gammon.com.au/forum/?id=11976). That describes how you can use a multiplexer chip to multiplex analog inputs.

The 74HC4051 multiplexes 8 inputs into one, and the 74HC4067 multiplexes 16 inputs into one. Thus you would only use one analog input, plus 3 or 4 pins to tell the chip which input you want at a particular moment.

The general way a multiplexer works is like this:

![Multiplexer example][1]

By outputting a binary pattern to the A/B/C pins you select which input you want active at a particular moment. That is then copied to the output pin (pin 3 in this case). You would connect that to your analog port on the Arduino.

The code would rotate between each of the 8 pins (or 16 pins with the bigger chip), and then do an analogRead.

---

## Example wiring

![Connect 4051 chip to Arduino Uno][2]

---

## Example code

    // Example of using the 74HC4051 multiplexer/demultiplexer

    // Author: Nick Gammon
    // Date:   14 March 2013

    const byte sensor = A0;  // where the multiplexer in/out port is connected

    const byte addressA = 5; // the multiplexer address select lines (A/B/C)
    const byte addressB = 6;
    const byte addressC = 7;

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ("Starting multiplexer test ...");
      pinMode (addressA, OUTPUT);
      pinMode (addressB, OUTPUT);
      pinMode (addressC, OUTPUT);
      }  // end of setup

    int readSensor (const byte which)
      {
      // select correct MUX channel
      digitalWrite (addressA, (which & 1) ? HIGH : LOW);
      digitalWrite (addressB, (which & 2) ? HIGH : LOW);
      digitalWrite (addressC, (which & 4) ? HIGH : LOW);
      // now read the sensor
      return analogRead (sensor);
      }  // end of readSensor

    void loop ()
      {
      // show all 8 sensor readings
      for (byte i = 0; i < 7; i++)
        {
        Serial.print ("Sensor ");
        Serial.print (i);
        Serial.print (" reads: ");
        Serial.println (readSensor (i));
        }
      delay (1000);
      }  // end of loop

---

That only does 8 ports, but the 16-port chip would be conceptually similar.

  [1]: https://i.stack.imgur.com/w8dRV.png
  [2]: https://i.stack.imgur.com/UFNL4.png


message:
What is the use of decoupling capacitor?

I dont understand what does the word "decoupling" mean? Where and Why it is used? Can anyone give me a brief idea>?

body:
Quite simply put, it's a little reservoir of energy for a chip or other device to dip into when it needs to get a little extra power.

In Electronics *nothing* happens instantly.  When a chip needs more power it has to get it from the power source.  The power source then has to respond to that by providing more energy, and that then has to make its way down the wires or traces to where it needs to be.

By placing a small capacitor near where the power is consumed the capacitor can respond to that call for more power much faster than the power supply.


body:
Every time a logic circuit switches from a 0 to a 1 or a 1 to a 0, the 1 and 0 transistors are on at the same time for a short period of time.  In MOS circuits, this is combined with the need to charge the gate of the 1 or 0 transistor (Charge is what capacitors store, gates of MOS transistors are capacitors!).

Since all wiring is inductive, the faster the current, the higher the impedance from the main power supply and the switching device (Your processor or sensor etc).  The terms bypass and decoupling mean the same thing:  You are providing a local charge well to supply fast current demands by bypassing the main power system, i.e. supplying current via a different path and thus decoupling the switching device from the inductively isolated main supply.

This is also why we used to use two types of capacitors for decoupling: A 0.1uF ceramic and a 1uF electrolytic for instance...  You couldn't get the whole 1uF in a low resistance ceramic to cover both the Low and High speed transients without paying a lot so you used two or more parts, each covering a portion of the spectrum.  Nowadays a single SMT ceramic with low ESR, low ESL and no lead wires can do the whole job and is usually pretty economical.

Another factor is radiation:  A ringing voltage transient current through inductive wiring acts just like an antenna.


message:
What changes I have to take care while coding from Atmel Studio instead of Arduino IDE?

-Are there any changes in Bootloader?
-Why is the coding different for same chip in different softwares?
-How to upload the program from Atmel Studio?

body:
Atmel cpp projects do not currently provide an option to upload using Arduino bootloader. Atmel only provides upload using hardware programmers.

The bootloader is deleted when you upload using a hardware programmer either from Atmel Studio or from the Arduino ide.

The underlying Atmel toolchain is not very different from the latest Arduino toolchain however Atmel does not know about the Arduino hardware/cores. You have to copy the Arduino core sources to your Atmel project if you want to compile for Arduino compatibility but that still does not give you bootloader upload.

It is not clear from your question if you have the Arduino sources in your cpp project already. If you do have the sources in your project then you can use avrisp mkII or other programmer to upload but the Arduino libraries might be an issue for you if you are using them.

There is another option in Atmel Studio however it might not be what you require ...

You can install the Visual [Micro plugin for Arduino][1] from the Atmel Gallery and work with standard Arduino sketch projects inside Atmel Studio.

The Visual Micro plugin provides full Arduino compatible sketch build and bootloader upload in Atmel Studio. Because of the nature of Arduino, the Visual Micro plugin automatically manages the include paths and Atmel project properties so that intellisense works in projects that contain .ino source code files. If the project does not contain .ino files then Visual Micro sleeps (does not interfere with cpp projects)

The plugin also provides other features such as a serial usb debugger, library manager, board manager, Arduino examples etc.

More about Visual Micro is [here][2]

Tutorials are [here][3]

Debugger overview is [here][4]

![enter image description here][5]

Update:

There is no difference in program execution between uploading using a physical hardware programmer or using a usb cable via bootloader.

The Arduino libraries sources can be more complicated to include/compile in a project because they often include additional folders with private source code. This is more of an issue with older Arduino libraries that have a sub folder called \utility.

  [1]: https://gallery.atmel.com/Products/Details/c7a74708-c128-42fb-b670-29f501e85937?
  [2]: http://www.visualmicro.com/
  [3]: http://www.visualmicro.com/page/User-Guide.aspx
  [4]: http://www.visualmicro.com/page/Debugging-for-Arduino.aspx
  [5]: https://i.stack.imgur.com/PKBjO.png


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

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


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


body:
You missed something bro!

Arduino          ESP8266
Rxd       ->     Txd
Txd       ->     Rxd
3.3 V     ->     VCC
GND       ->     GND
3.3 V     ->     CH_PD


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


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

1. We set the Baud rate of the Serial communication to 1200. This started showing the responses from ESP correctly with no / minimal junk
2. We set the baud rate of communication with ESP to 115200. This ensured that the ESP received correct commands.
3. 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);
4. 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


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


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

 1. Bluetooth 4 LE (as in RFduino)
Pros: 3-6ms latency (advertised), low energy
Cons: cost, not more than 7 buttons to the device

 2. Wi-fi
Pros: 2ms latency (I justed pinged my wi-fi router), dozens of buttons if need be
Cons: cost, power-hungry

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

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

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


body:
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](https://hallard.me/nrf24l01-real-life-range-test/), 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](http://www.diychristmas.org/vb1/showthread.php?3564-nRF24L01-OTA-Timing-Measurements), **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.


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


body:
Low low tech solution.

1. The transmitter sends out its clock signal on command.

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


message:
digitalRead(A0) returns true when A1 is HIGH

I have an Atmega328P-AU with 16Mhz crystal([schematics][1]). 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.

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

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

<!-- End schematic -->

  [1]: https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Pro-Mini-v14.pdf

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


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


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

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


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


body:
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](http://www.amazon.com/dp/B00E0NXTJW/ref=wl_it_dp_o_pC_nS_ttl?_encoding=UTF8&colid=2F4U8JG4G0EM2&coliid=I1J6R2FQCYYKZ2).  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.


body:
I would use an [ultrasonic distance sensor][1]. 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][2]. 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.

  [1]: http://playground.arduino.cc/Main/UltrasonicSensor
  [2]: https://encrypted.google.com/search?q=infrared distance sensor arduino


body:
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][1] has some information about using a cheap Microwave sensor with an Arduino.

  [1]: http://jpnelson.com/post/37623468093/microwave-motion-sensors-for-fun-and-profit-hb100


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


message:
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 += "<html>\n";
            sr += "LED frequency: ";
            sr += f;
            sr += "Hz.</html>";
            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][1]

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 ?

  [1]: http://pastebin.com/mNQQamUg

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


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


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


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

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


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

body:
<!-- language-all: lang-C++ -->

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 () { }


body:
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](https://www.arduino.cc/en/Tutorial/StringComparisonOperators) 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 ("] ", 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 ("] ", someNumbers[i]);
        tot += someNumbers[i];
      }
      printf ("   Total: %d\n", tot);
      return 0;
    }


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


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

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


message:
How come people connect their arduinos to buzzers without any coil protection?

If you connect your arduino to a motor you use this schematic:

![enter image description here][1]

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

![enter image description here][2]

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

  [1]: https://i.stack.imgur.com/ibbFi.png
  [2]: https://i.stack.imgur.com/JMqnY.png

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


message:
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!

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


message:
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!

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


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

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

  [1]: https://wiki.archlinux.org/index.php/Working_with_the_serial_console


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

1. I upload to the UNO the ArduinoISP sketch
2. Connect the lines to the target board (target board have atmega328, crystal, capacitors, LED)
3. Choose the board "Arduino pro or pro mini" in the Arduino IDE.
4. Choose the programmer- "Arduino as ISP"
5. 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?

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


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

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


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


body:
> 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](https://github.com/SlashDevin/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.<br>
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](https://github.com/SlashDevin/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.