message:
Interfacing an ATtiny85 with MIDI via Software Serial

In order to finish a synth project that I'm working on I built a MIDI interface. To test it, I drew up some code which (is supposed to) light up an LED when any key is pressed. The light turns off again when the key is released. This will later be merged with another branch of code [here](https://arduino.stackexchange.com/questions/13354/writing-midi-notes-more-quickly-to-a-shift-register-with-arduino/13362#13362) to tell me *which* note is playing. This sounds simple enough but the devil's in the details. Due to my project's size constraints I am using ATMEL's ATtiny85 chip instead of my Arduino Uno. The ATtiny doesn't support the Arduino Serial library and by extension the standard MIDI library. As I can't make use of simple functions like MIDI.read() I've opted to work with an alternative Software Serial technique I adapted from an [Instructable](http://www.instructables.com/id/Send-and-Receive-MIDI-with-Arduino/?ALLSTEPS). Unfortunately, the results have been less than exemplary. Simply put, the LED almost never lights up. I have conducted two test only 1 of which *somewhat* succeeded:

1)

    if(velocityByte > 0 ){digitalWrite(LED, HIGH);}
    if(velocityByte == 0 ){digitalWrite(LED, LOW);}

Initially, I had figured that would be the most successful of my options. My keyboard* is binary about its ouput velocity. There are no pressure sensors so "on" is on and "off" is off. Unfortunately, however, the code seems to think otherwise.

2)

    if(commandByte == noteOn ){digitalWrite(LED, HIGH);}
    if(commandByte != noteOff ){digitalWrite(LED, LOW);}

Though originally less sure of this one, I've found it to be better than the other at catching notes. noteOn is the integer 144. While it does in fact trigger it does so only very rarely - once every 10 presses or so.

I believe I have however, whittled down the possible number of problems to 2:

1) Something is up with one or more of my calls to Serial. I've never really felt super confident with the author's method of obtaining data from Serial. For one, I have no confidence that I can insure I have collected the correct byte. If the code were to somehow "miss" counting a byte would it not assign, say, a commandByte to a noteByte? Is a better method available?

2) My keyboard's MIDI protocol is incompatible with my if-statement cases.
At first I was under the assumption that my keyboard never sends a true "note off" message of any kind but instead a velocity = 0 message. But my test casts much doubt on this being the case and because of this, I don't *really* know how the keyboard handles note off messages. Does anyone else know?

*A Yamaha YPT-230

    //MIDI INPUT LED TEST
    //Adapted from code written
    //by Instructables user Amanda Ghassaei

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(0, 1);  //RX, TX

    #define LED 2

    byte commandByte;
    byte noteByte;
    byte velocityByte;

    byte noteOn = 144;
    byte noteOff = 128;

    void setup(){
      mySerial.begin(31250);
      digitalWrite(LED, LOW);
      delay(1000);
    }

    void checkMIDI(){
      do{
        commandByte = mySerial.read();//read first byte
        noteByte = mySerial.read();//read next byte
        velocityByte = mySerial.read();//read final byte

        if (commandByte == noteOn){
          digitalWrite(LED, HIGH);
        }
        if(commandByte != noteOn){
          digitalWrite(LED, LOW);
        }

      }
      while (mySerial.available() > 2);//when at least three bytes available
    }

    void loop(){
      checkMIDI();
    }
    /*
    void gotNoteOn(commandByte, noteByte, velocityByte){
      digitalWrite(LED,HIGH);
    }

    void gotNoteOff(commandByte, noteByte, velocityByte){
      digitalWrite(LED,LOW);
    }
    */

**UPDATE** Following a suggesting, I have replaced the do .. while loop with an ordinary while loop. Relevant changes below:

    void checkMIDI(){
      while(mySerial.available() > 2){
        commandByte = mySerial.read();
        if (velocityByte > 0x00){//if note on message
          digitalWrite(LED, HIGH);
        }
        if(velocityByte == 0x00){
          digitalWrite(LED, LOW);
        }
      }
    }

I'd like to think it's an improvement but if so only a slight one. Curiously, it almost works backwards - The default state of the LED is on while pressing a key produces no change pressing and *holding* causes the light to briefly shut off. But even this is sporadic. It may also be worth noting that I elected to use hex '0x00' as opposed to decimal '0'.

**UPDATE II / NOTE** Having slept on the problem I think I now understand why I am encountering this issue in the first place. The author of the Instructables code I adapted used an Arduino for both MIDI In as well as MIDI Out. Had they simply hooked one Arduino Uno to the other in an in/out configuration they could have perfectly ensured there were no running status issues by just never sending any running status messages. This would explain the lack of conformity to the actual realities of MIDI on the input side. If you can control exactly what data you are sending on one end (MIDI Out) it becomes fairly trivial to receive that data on the other end (MIDI In). Generalizing, the author may have assumed that a true keyboard behave the same thing and failed to actually verify this. Thoughts?

**UPDATE III** Following the lead of CL but deviating somewhat because I didn't fully understand what CL was doing, I have written up a highly derivative, new code. It is based around what I now know to be the highly fluid nature of MIDI messages and seeks to intelligently discriminate important messages from non-important messages based on content. It does not work (except for LED test at the beginning) but seems like a promising step nonetheless.

    //MIDI Input LED Test

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(0, 1);  //RX, TX

    #define LED 2  //Test LED

    void setup(){
      mySerial.begin(31250);
      digitalWrite(LED, HIGH); //Test
      delay(1000);
      digitalWrite(LED, LOW);
      delay(1000);
    }

    void loop(){
      checkMIDI();
    }

    void checkMIDI(){
    /*Two of the three independent types of bytes are always
    distinct and can be identified simply by their values.
    A Status byte (on channel 1 at least) is always either
    0x80 (off) or 0x90 (on). No other type of message
    (Note, Velocity) can ever take this value and so if
    this is the value of the byte received I can be
    assured it is a Status byte.

    The Note and Velocity bytes are a bit (haha) dicier.
    They have overlapping ranges with both taking values of
    anywhere between 0x00 to 0x7F. *Ordinarily*. A caveat
    is that my Yamaha YPT-230 is binary as far as velocity
    goes. A YPT-230 data is either 0x00 (full off) or 0x7F
    (full on). As long as a Note byte is never 0 or 127 I can
    use this to discriminate between these two types
    in this manner.
    */

      if(mySerial.available() > 0){
        byte b = mySerial.read();

        if(b == 0x80 || 0x90){
          byte commandByte = b;
        }else if(b == 0x00 || 0x7F){
          if(b == 0x00){
            digitalWrite(LED, LOW);  //If vel = 0 turn LED off
          }else if(b == 0x7F){
            digitalWrite(LED, HIGH); //If vel = 127 turn LED on
          }
          //velocityByte = b;
        }else{
          byte noteByte = b;  //Do nothing with this for right now.
        }
      }
    }

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

I suggest you first find what your Yamaha is sending you. I have a [sketch that decodes MIDI](http://www.gammon.com.au/forum/?id=12746) for the Uno (assuming you have a Uno lying around). Run that, and see if you got note on with velocity zero, or note off. Then you are a little closer to solving the problem.

---

This part is quite wrong:

      do{
        commandByte = mySerial.read();//read first byte
        noteByte = mySerial.read();//read next byte
        velocityByte = mySerial.read();//read final byte

      ...

      }
      while (mySerial.available() > 2);//when at least three bytes available

You are reading 3 bytes, even if none are available. At least change it to:

    while (mySerial.available() > 2)
      {
            commandByte = mySerial.read();//read first byte
            noteByte = mySerial.read();//read next byte
            velocityByte = mySerial.read();//read final byte

          ...

      }

The `do ... while` construct tests at the end of the loop. You must ensure you have 3 bytes "available" **before** reading 3 of them, not after.

---

## Example code for ATtiny85

The code below is an adaptation of the MIDI decoder in my link above. This one just reads the incoming MIDI and turns on the LED on a "note on" and turns it off on a "note off" (or note on with velocity zero). Tested, works perfectly.

    //  MIDI_decoder for ATtiny85
    //
    // ATMEL ATTINY 25/45/85 / ARDUINO
    // Pin 1 is /RESET
    //
    //                  +-\/-+
    // Ain0 (D 5) PB5  1|    |8  Vcc
    // Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
    // Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
    //            GND  4|    |5  PB0 (D 0) pwm0
    //                  +----+

    #include <SoftwareSerial.h>

    const byte LED = 0;   // pin 5 on ATtiny85

    // Plug MIDI into pin D2 (MIDI in serial) (pin 7 on ATtiny85)

    SoftwareSerial midi (2, 3);  // Rx, Tx

    const int noRunningStatus = -1;

    int runningStatus;
    unsigned long lastRead;
    byte lastCommand;

    void setup() {
      //  Set MIDI baud rate:
      midi.begin(31250);
      runningStatus = noRunningStatus;
      pinMode (LED, OUTPUT);
    } // end of setup

    void RealTimeMessage (const byte msg)
      {
        // ignore realtime messages
      } // end of RealTimeMessage

    // get next byte from serial (blocks)
    int getNext ()
      {

      if (runningStatus != noRunningStatus)
        {
        int c = runningStatus;
        // finished with look ahead
        runningStatus = noRunningStatus;
        return c;
        }

      while (true)
        {
        while (midi.available () == 0)
          {}
        byte c = midi.read ();
        if (c >= 0xF8)  // RealTime messages
          RealTimeMessage (c);
        else
          return c;
        }
      } // end of getNext

    const char * notes [] = { "C ", "C#", "D ", "D#", "E ", "F ", "F#", "G ", "G#", "A ", "A#", "B " };

    byte note;
    byte octave;
    byte velocity;

    // interpret a note in terms of note name and octave
    void getNote ()
      {
      note = getNext ();
      octave = note / 12;
      note %= 12;
      }  // end of getNote

    void getVelocity ()
      {
      velocity = getNext ();
      }

    // show a control message
    void showControlMessage ()
      {
       byte message =  getNext () & 0x7F;
       byte param = getNext ();
      }  // end of showControlMessage

    // read a system exclusive message
    void showSystemExclusive ()
      {
      int count = 0;
      while (true)
        {
        while (midi.available () == 0)
          {}
        byte c = midi.read ();
        if (c >= 0x80)
          {
          runningStatus = c;
          return;
          }

        } // end of reading until all system exclusive done
      }  // end of showSystemExclusive

    void loop()
    {
      byte c = getNext ();
      unsigned int parameter;

      if (((c & 0x80) == 0) && (lastCommand & 0x80))
        {
        runningStatus = c;
        c = lastCommand;
        }

      // channel is in low order bits
      int channel = (c & 0x0F) + 1;

      // messages start with high-order bit set
      if (c & 0x80)
        {
        lastCommand = c;
        switch ((c >> 4) & 0x07)
          {
          case 0:   // Note off
            getNote ();
            getVelocity ();
            digitalWrite (LED, LOW);
            break;

          case 1:   // Note on
            getNote ();
            getVelocity ();
            if (velocity == 0)
              digitalWrite (LED, LOW);
            else
              digitalWrite (LED, HIGH);
            break;

          case 2:  // Polyphonic pressure
            getNote ();
            parameter = getNext ();  // pressure
            break;

          case 3: // Control change
            showControlMessage ();
            break;

          case 4:  // Program change
            parameter = getNext ();  // program
            break;

          case 5: // After-touch pressure
            parameter = getNext (); // value
            break;

          case 6: // Pitch wheel change
            parameter = getNext () |  getNext () << 7;
            break;

          case 7:  // system message
            {
            lastCommand = 0;           // these won't repeat I don't think
            switch (c & 0x0F)
              {
              case 0: // Exclusive
                parameter = getNext (); // vendor ID
                showSystemExclusive ();
                break;

              case 1: // Time code
                parameter = getNext () ;
                break;

              case 2:  // Song position
                parameter = getNext () |  getNext () << 7;
                break;

              case 3: // Song select
                parameter = getNext () ;  // song
                break;

              case 4:    // reserved
              case 5:    // reserved
              case 6:    // tune request
              case 7:    // end of exclusive
              case 8:    // timing clock
              case 9:    // reserved
              case 10:   // start
              case 11:   // continue
              case 12:   // stop
              case 13:   // reserved
              case 14:   // active sensing
              case 15:   // reset
                 break;

              }  // end of switch on system message

            }  // end system message
            break;
          }  // end of switch
        }  // end of if
      else
        {
        // unexpected, ignore
        }

    }  // end of loop

---

## Suggested schematic

[![MIDI schematic][1]][1]

---

From a comment:

> the 4N35 is too slow to work reliably with MIDI signals

Below is an updated schematic that uses a faster opto-coupler.

[![MIDI schematic with 6N137][2]][2]

Admittedly the 4N35 is below spec for its rise time (it is supposed to be  less than 2 μs rise time, however the 4N35 is slower at between 3 µs and 7 µs). However during my testing it worked OK. It sounds like the faster rise time is specified to allow for multiple devices to be connected in series, a slow rise time will introduce distortion.

  [1]: https://i.stack.imgur.com/WZxOG.png
  [2]: https://i.stack.imgur.com/TNCq2.png


sender: user

sender: assistant

body:
This is not how the [MIDI protocol](http://www.blitter.com/~russtopia/MIDI/~jglatt/tech/midispec.htm) works.

The incoming stream can contain other commands than note-on or note-off, and with running status, it is impossible to predict the length of any single command.

You need at least some kind of state machine to remember where in the command you are:

<!-- language: lang-c -->

    byte nr;

    for (;;) {
        byte b = mySerial.read();
        if (b & 0x80) { // status byte
            if (b >= 0xf8) {
                // real-time command; ignore
            } else {
                commandByte = b;
                nr = 1;
            }
        } else { // data byte
            if ((commandByte & 0xf0) == 0x80 ||
                (commandByte & 0xf0) == 0x90) {
                if (nr == 1) {
                    noteByte = b;
                    nr = 2;
                } else if (nr == 2) {
                    velocityByte = b;
                    nr = 1;

                    if ((commandByte & 0xf0) == 0x90 &&
                        velocityByte > 0) {
                        // note on
                    } else {
                        // note off
                    }
                }
            }
        }
    }


body:
Got it! After doing the requisite amount of research... I've developed a *much* improved checking system which allows me to truly demarcate between messages during running status much like Nick Gammon's code. While the code seems to work perfectly now it was still a bit glitchy when I tried it the other day. Perhaps I accidentally fixed it, most likely it'll crop back up again. How does it look?

    //MIDI_Input_0x01
    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(0,1);

    const int LED = 2;

    int isStatus();
    int isAftertouch();
    int isRealTimeCategory();

    int dataByte;
    int velocityByte;
    int result;

    void setup()
    {
      mySerial.begin(31250);
      pinMode(LED, OUTPUT);

      digitalWrite(LED, HIGH);
      delay(1000);
      digitalWrite(LED, LOW);
      delay(1000);
    }

    void loop()
    {

      while(mySerial.available())
      {
        //This is the protocol for reading new stuff
        byte myByte = mySerial.read();
        if(isRealTimeCategory(myByte))
        {
          ;
        }
        else
        {
          if(isStatus(myByte))
          {

            result = (myByte | 0x80);  //0b10000000
            switch(result)
            {
              case 0b10000000:
                digitalWrite(LED, LOW);
                break;
              case 0b10010000:
                digitalWrite(LED, HIGH);
                break;
              case 0b10100000:
                break;
              case 0b10110000:
                break;
              case 0b11000000:
                break;
              case 0b11010000:
                break;
              case 0b11100000:
                break;
              case 0b11110000:
                break;
            }
          }
          else
          {
            byte myByte = mySerial.read(); //This is the protocol for reading new stuff
            if(isRealTimeCategory(myByte))
            {
              ;
            }
            else
            {
              if(myByte > 0)
         {
           digitalWrite(LED, HIGH);
         }
         else
         {
           digitalWrite(LED, LOW);
         }
            }
          }
        }
      }
    }  //END

    /**********************
    //function declarations
    **********************/

    int isStatus(int b)
    {
      if( (b & 0x80) == 0x80)
      {
        return 1;
      }
      else if( (b & 0x80) == 0)
      {
      return 0;
      }
    }

    int isAftertouch(int b)
    {
      if( (b & 0xf0) == 0xa0)
      {
        return 1;
      }
      else //if( (b & 0xf0) != 0xa0)
      {
        return 0;
      }
    }

    int isRealTimeCategory(int b)
      {
        if(b >= 0xF8)
        {
          return 1;
        }
        else
        {
          return 0;
        }
    }

On top of this, I managed to tweak the code to output particular values to a shift register as I had initially intended. The method I use to differentiate between note and velocity bytes is less than ideal but works on my keyboard. Because of certain limitations it only works over a range of 13 notes but that's fine for now. Code and flowchart below.

    //    MIDI_Input_0x02

    #include <SoftwareSerial.h>          //The Attiny does not natively support the Serial library so this
          //is the work-around.
    SoftwareSerial mySerial(0,1);

    const int latchPin = 2;
    const int clockPin = 3;
    const int dataPin = 4;

    const int gate = 1;    //Note that initially, this was the tx pin.
            //In this configuration absolutely every Attiny85 pin is used.
    int isStatus();
    int isAftertouch();
    int isRealTimeCategory();

    int result;
    int dataByte;
    int velocityByte;

    //int noteApprox[13] = {1,3,5,7,9,12,14,17,20,23,26,29,32};
    int noteApprox[13] = {32, 29, 26, 23, 20, 17, 14, 12, 9, 7, 5, 3, 1};
     //The above numbers are approximately 100 cents
     //apart from one another. This corresponds to notes of a scale.
     //They descend here because their corresponding
     //voltages will later become inverted in the circuit.

    void setup()
    {
      mySerial.begin(31250);

      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(gate, OUTPUT);  //'Gate' controls the level of the
         //envelope generators. The signal
         //becomes inverted later.

      digitalWrite(gate, HIGH);  //A simple test to ensure the
      delay(1000);    //circuit is wired correctly
      digitalWrite(gate, LOW);
      delay(1000);

    }

    void loop()
    {

      while(mySerial.available())
      {
        //This is the protocol for reading new stuff
        byte myByte = mySerial.read();  //Read the oldest byte in the buffer
        if(isRealTimeCategory(myByte))  //See Function Notes
        {
          ;
        }
        else
        {
          if(isStatus(myByte))           //See Function Notes
          {
            result = (myByte | 0x80);  //0b10000000
            switch(result)
            {
              case 0b10000000:
                digitalWrite(gate, LOW);         //0b10000000 is the note Off
                break;      //message
              case 0b10010000:
                digitalWrite(gate, HIGH);         //10010000 is the note On
                break;      //message
              case 0b10100000:   //Absolutely none of these are important.
                break;
              case 0b10110000:
                break;
              case 0b11000000:
                break;
              case 0b11010000:
                break;
              case 0b11100000:
                break;
              case 0b11110000:
                break;
            }
          }
          else                                     //This is the part where I assume it's a data byte.
          {                                        //this might be causing problems...
            if( (myByte > 48) && (myByte < 61) )         //<-- That's 13 notes. An octave and an extra
            {
              digitalWrite(latchPin, LOW);
              shiftOut(dataPin, clockPin, MSBFIRST, noteApprox[myByte - 48]); //Write to the shift
              digitalWrite(latchPin, HIGH);      //register.
            }
            else
            {
              digitalWrite(gate, LOW);
            }

            byte myByte = mySerial.read();
            if(isRealTimeCategory(myByte))
            {
              ;
            }
            else
            {
              if(myByte > 0)
         {
           digitalWrite(gate, HIGH);  //Velocity Byte
         }
         else
         {
           digitalWrite(gate, LOW);
              }
            }
          }
        }
      }
    }  //END

    /***************************
     function Declarations
    ***************************/

    int isStatus(int b)   //Determines if the incoming byte is a Status Byte of some sort.
         //Returns 1 if so and 0 if not.
    {
      if( (b & 0x80) == 0x80)
      {
        return 1;
      }
      else if( (b & 0x80) == 0)
      {
      return 0;
      }
    }

    int isRealTimeCategory(int b)         //Determines if the incoming byte is a Real Time Category byte
      {     //I'm not positive what these *are* but they are only 1 byte long
        if(b >= 0xF8)   //a piece and easily detected (they're all greater than 11111000).
     {
       return 1;
        }
        else
        {
          return 0;
        }
    }

    /*    Bit Math Notes

     if(b & 0x80) == 0x80)

    b   =  10000000
    0x80 = 10010000
       & ________
      10000000 =/= 10010000

      Not a Note On byte.
      Return 0.

    b   =  10010000
    0x80 = 10010000
       & ________
      10010000 == 10010000

      A Note On byte! Hooray!
      Return 1.
    */
[![Flowchart][1]][1]

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


message:
How to setup Arduino Wifi Shield with Red Bear Lab BLE Shield?

I'm new to Arduino shields.

I'm trying to stack these two shields on an arduino uno for a home automation project.

1 - Arduino Wifi Shield:

2 - Red Bear Lab BLE shield: http://redbearlab.com/bleshield/

I have pin contention, between the two shields:
The WiFi shield uses pins: 4, 7, 10, 11, 12, 13.
The BLE shield uses pins: 10, 11, 12, 13.

Is there a hardware or software way to allow the two shields to work together?

I saw in a similar thread, someone reccomended a go-between shield: https://www.sparkfun.com/products/11002, would this be something that I could use in this case?

If it's not possible, are there other shields that will work together?

Thanks

body:
The way the Arduino talks to each of the shields is by first telling the device that it wants to communicate with it, and then by exchanging information with that device. The Arduino uses 3 pins, 11, 12, and 13, to communicate to both the shields, and a 4th pin which it uses to select which of the devices it wants to use. This way the Arduino can use connect to two shields at once, by just selecting one at a time

I did some research, and found that the selection pin on the WiFi shield (which I believe is the same as yours: https://www.arduino.cc/en/Main/ArduinoWiFiShield) are pins 10 and 4; pin 4 for the SD card selection, and pin 10 for the WiFi selection. Now since pin 10 is used as a selection pin for both the WiFi shield and the BLE shield, you run into some problems: both the boards will be selected at the same time when pin 10 is used. In this case, you can use the Sparkfun go-between board you linked.

I've never used it myself, but it appears to be able to change what pin is attached where on the shield it's attached to. In this case, you want to put the WiFi shield on the bottom, then the Sparkfun go-between shield, then the BLE on the top. You want to set up the go-between shield to change pin numver 10 to another pin that's not being used (any pin but 11, 12, 13, 7, 4, or 10).

In the Arduino code you will at some point declare which pin is being used to select which board. In this case, set the WiFi selection to 10 (default), the SD card selection to 4 (default), and the BLE selection to whatever pin you changed pin 10 from with the go-between shield. This way, when you select the shield on pin 10, it will only select one shield, rather than two.


message:
MPU6050 or GY521/HMC5883 chips are burnt for no reason

I been trying to interface MPU6050 and HMC5883 with an Arduino Pro Mini/Nano. I²C scanner works just fine and identifies the device with no issues. I let the I²C scanner run like for 5 minutes and I see fumes coming out of the chips and sometimes the Arduino itself is burnt. I tried pull up resistors 2.2k, 7k without any luck. Has anyone got any inputs to this issue. Really frustrating to spend a weekend on this :(

To rule out the possibility of 5V supply causing the burn out I tried 3.3V from Nano and made promini 3.3V from 5V. Please see the pictures below.

Arduino Nano 3.3v was used to power up the I²C.

[![Arduino Nano Circuit][1]][1].

[![Pro Mini Circuit][2]][2].

Pro Mini jumper was desoldered from 5V to 3.3V to see if the I²C chips are saved from being burnt. In both these setup voltage accross the I²C chip was measured and it was 3.3V.

Still no luck!

If you guys are to make the same circuit how would you do it and where would you get the components from? I must be doing something wrong and hope we together can figure it out.

  [1]: https://i.stack.imgur.com/i4V9s.jpg
  [2]: https://i.stack.imgur.com/CSc0h.jpg

Components are bought from eBay and the links are here.
GY521 = goo.gl/Y4aDph
HMC5883 = goo.gl/DfrC9l
Arduino Nano = goo.gl/CaAykI
PROMINI = goo.gl/79PVOM

**This is some background of why this issue resolution is so important to me:**
Just give you a backgroud of why I am doing this: I am building a quadcopter myself. Infact built one using GY80, but the module was expensive also it eventually got burnt out for the same reason mentioned above. Here is the first successful test flight of my first quadcopter goo.gl/rn6xWG (add https:// since I am rookie there is limitation on how many links I can post). If I can make the same thing work using GY521 and HMC5883 it would be awesome and cheaper.

Update on 08/11 @12:45 PM CST
I think it is because of the Pro Mini, I²C chips are getting fried. When using Nano, I think it is because of the voltage level difference between the SDA/SCL lines causing the problem. With Pro Mini tripped for 3.3V, I was not able to see any serial data from the chip too. To end all these I placed an order for 3.3V 8 MHz Pro Mini from amazon goo.gl/FjgTGj Let see how that goes.

body:
[![enter image description here][1]][1]Fixed the issue with a dedicated 3.3V power supply.  I2C scanner is running for 30 minutes with no issues so far.

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


message:
Arduino Motor Shield

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

It seems that I can't get the DC Motor function to work while also having servos driven off the other ports :(

    #include "Arduino.h"
    #include <Servo.h>

    int pinI1=8;//define I1 interface
    int pinI2=11;//define I2 interface
    int speedpinA=9;//enable motor A
    int pinI3=12;//define I3 interface
    int pinI4=13;//define I4 interface
    int speedpinB=10;//enable motor
    int spead =220;//define the spead of motor

    Servo SteeringServo;  // create servo object to control a servo

    void setup()
    {
      // Steering servo pin setup
      SteeringServo.attach(5);  // attaches the servo on pin 9 to the servo object

      pinMode(pinI1,OUTPUT);
      pinMode(pinI2,OUTPUT);
      pinMode(speedpinA,OUTPUT);
      pinMode(pinI3,OUTPUT);
      pinMode(pinI4,OUTPUT);
      pinMode(speedpinB,OUTPUT);

      Serial.begin(9600);

    }

    void forward()
    {
         analogWrite(speedpinA,spead);//input a simulation value to set the speed
         analogWrite(speedpinB,spead);
         digitalWrite(pinI4,HIGH);//turn DC Motor B move clockwise
         digitalWrite(pinI3,LOW);
         digitalWrite(pinI2,LOW);//turn DC Motor A move anticlockwise
         digitalWrite(pinI1,HIGH);
    }
    void backward()//
    {
         analogWrite(speedpinA,spead);//input a simulation value to set the speed
         analogWrite(speedpinB,spead);
         digitalWrite(pinI4,LOW);//turn DC Motor B move anticlockwise
         digitalWrite(pinI3,HIGH);
         digitalWrite(pinI2,HIGH);//turn DC Motor A move clockwise
         digitalWrite(pinI1,LOW);
    }
    void left()//
    {
         analogWrite(speedpinA,spead);//input a simulation value to set the speed
         analogWrite(speedpinB,spead);
         digitalWrite(pinI4,HIGH);//turn DC Motor B move clockwise
         digitalWrite(pinI3,LOW);
         digitalWrite(pinI2,HIGH);//turn DC Motor A move clockwise
         digitalWrite(pinI1,LOW);
    }
    void right()//
    {
         analogWrite(speedpinA,spead);//input a simulation value to set the speed
         analogWrite(speedpinB,spead);
         digitalWrite(pinI4,LOW);//turn DC Motor B move anticlockwise
         digitalWrite(pinI3,HIGH);
         digitalWrite(pinI2,LOW);//turn DC Motor A move clockwise
         digitalWrite(pinI1,HIGH);
    }
    void stop()//
    {
         digitalWrite(speedpinA,LOW);// Unenble the pin, to stop the motor. this should be done to avid damaging the motor.
         digitalWrite(speedpinB,LOW);
         delay(1000);

    }

    void loop()
    {
      left();
      delay(15000);
      stop();
      right();
      delay(1000);
     stop();
     // delay(2000); Already commented out
      //forward();
     // delay(2000);
     // stop();
    // backward();
      delay(12000);
      stop();
    }

body:
Your code:

    int speedpinA=9;//enable motor A
    ...
    int speedpinB=10;//enable motor
    ...
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);

See <https://www.arduino.cc/en/reference/servo>

>  On boards other than the Mega, use of the library **disables analogWrite() (PWM) functionality on pins 9 and 10**, whether or not there is a Servo on those pins.

(My emphasis).

So, you can't do that, exactly. Perhaps choose other pins for the analogWrite, pins that analogWrite supports, that are not 9 and 10.


message:
Run an Arduino without a PC

I would like to use an Arduino to make tasks in my life automatic - maybe to rotate every morning a motor, or to open a door.

So, can I run an Arduino as solo with no pc needed? Can i connect it to the Internet and can I setup software like PHP and Apache on it to control it over the internet? Has it any protocols like SSH like a normal server?

As an example: I will send over any protocol a signal to my Arduino with a certification and then the Arduino would run a function...

Is that possible?

thanks ahead

body:
> I will use arduino to make tasks in my life automatic maybe to let rotate every morning a motor or to open the door.

That's the kind of thing it's designed for.

> So i will ask can i run arduino as solo so no pc needed,

Yes, you only need a PC to program it, once programmed it will run without the PC.

> Can I connect it to the internet

Yes, there are Ethernet and WiFi shields available for connecting it to a network.

> and can I setup PHP and Apache on it to control it over it; has it any protocols like SSH like an normal server ?

No.  The Arduino isn't powerful enough to run software like that.  You would normally connect it via the network / internet to a server to process data.  It would just receive simple instructions or send data to the server for processing.

> as example: I will send over any protocol a signal to my Arduino with a certification and then the Arduino is running a function...

I assume by "a certification" you want to run SSL on the Arduino. That's not going to happen since it's way too underpowered for that.  As I mentioned earlier, the Arduino would connect to a server on the internet to receive its instructions, or you could interface to it directly within your local network (say from a smart phone) through a simple web server interface (very simplistic due to lack of memory - a few buttons and text, that sort of thing).


message:
Which wireless technology should I use for my outside "check-if-door-is-open" project?

I want to connect a magnetic door open/closed sensor to a device that can transmit (or be queried for, whichever) the state of the door to a hub inside (probably RaspberryPi). The outside unit should...

1. Operate on as little power as possible (outside unit will consist of board, open/closed sensor, power, and transmitter)
2. Be able to transmit from my back yard to inside my house (~15 meters to house & 1 or 2 walls).

I am new to this and pretty **confused as to whether I should use BLE, Zig/xbee, or 2.4ghz rf** (is that different? I am not even sure...).

Other considerations are cost (of course) and ease of use. I am a novice with hardware & want something easy to get up and running.

body:
I agree with [@Gerben](https://arduino.stackexchange.com/users/2881/gerben) - the **nRF24L01+** would probably be the most suitable for your application.  It should have enough range to go 15m through a few walls, and the cost is about as cheap as you can get.

You can pick up cheap Chinese clone modules (not real nRF24L01+ but another chip that operates exactly the same) for around $2 each on eBay.  I by them by the bag full.

There are a few good libraries around for controlling them with an Arduino so programming really isn't much of a problem.

They even have the advantage that they can operate in a mesh network mode if you ever expand your system to incorporate other things.

The connection to the module is a simple 5-wire SPI interface - SDC, MOSI, MISO, Chip Enable and Command Select pins, so you don't even need to mess with lots of wires.

You can read more about using them here: http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01

The best library in existence is the RF24Network library: https://github.com/maniacbug/RF24Network

If you are looking for something more self-contained and stand-alone, you might look at the **ESP8266** modules which are a programmable WiFi module.  They can either interface with an Arduino to be controlled through *AT* commands, which is quite nasty, or they can be programmed directly using an Arduino-like API which can be obtained here: https://github.com/esp8266/Arduino

These modules are a little more expensive, but that cost is offset by not then needing an Arduino in the mix as well.  The [NodeMCU](http://nodemcu.com/index_en.html) is probably the easiest to work with since it contains the USB serial interface on board like an Arduino.  It also has its own *Lua* based programming environment if you don't mind learning another new language, but you can use it with the Arduino API for ESP8266 above.

The ESP8266 is also supported by the beta version of [UECIDE](http://uecide.org/beta)


message:
Sending A String from a Website to Arduino

I'm quite new to Arduino and have looked at many tutorials featuring an Arduino requesting data from a web server through a Wifi Shield, but haven't seen one featuring the sending of data from a website/server to an Arduino. I'm attempting to use a JavaScript then PHP script to send a string variable to the Arduino, which would then of course run its code at this point. Is this possible if I have a Wifi Shield and the Arduino's IP address?

body:
On the yun, this functionality is built-in via the bridge. [Here's an example.](https://www.arduino.cc/en/Tutorial/Bridge)

Via the shield, you now end up [writing your own webserver](https://www.arduino.cc/en/Tutorial/WiFiWebServer) and responding appropriately.

I'm guessing it makes more sense to use the client (the web browser) to make the calls than the backend php, but in either case, once the webserver is up and going on the arduino, you're just using it like any other server.


body:
If you really want the Arduino to be a **web server** (that is, you connect to it with your web browser) then I made a library a little while back to simplify processing the get/post/pathname/cookie arguments.

See [Tiny web server for Arduino or similar](http://www.gammon.com.au/forum/?id=12942).

Example code (that comes with the library) turns on various LEDs (presumably connected to pins on the Arduino) upon getting a "get" request like this:

    http://10.0.0.241/?on=4&off=5

That would turn on pin 4 and turn off pin 5. Obviously you change the IP address to suit your network, and use a suitable MAC address.

    // Tiny web server demo
    // Author: Nick Gammon
    // Date:  20 July 2015

    #include <SPI.h>
    #include <Ethernet.h>
    #include <HTTPserver.h>

    const int LOW_PIN = 3;
    const int HIGH_PIN = 5;

    // Enter a MAC address and IP address for your controller below.
    byte mac[] = {  0x90, 0xA2, 0xDA, 0x00, 0x2D, 0xA1 };

    // The IP address will be dependent on your local network:
    byte ip[] = { 10, 0, 0, 241 };

    // the router's gateway address:
    byte gateway[] = { 10, 0, 0, 1 };

    // the subnet mask
    byte subnet[] = { 255, 255, 255, 0 };

    // Initialize the Ethernet server library
    EthernetServer server(80);

    // derive an instance of the HTTPserver class with custom handlers
    class myServerClass : public HTTPserver
      {
      virtual void processPostType        (const char * key, const byte flags);
      virtual void processGetArgument     (const char * key, const char * value, const byte flags);
      };  // end of myServerClass

    myServerClass myServer;

    // -----------------------------------------------
    //  User handlers
    // -----------------------------------------------

    void myServerClass::processPostType (const char * key, const byte flags)
      {
      println(F("HTTP/1.1 200 OK"));
      println(F("Content-Type: text/html\n"
                "Connection: close\n"
                "Server: HTTPserver/1.0.0 (Arduino)"));
      println();   // end of headers
      println (F("<!DOCTYPE html>\n"
                 "\n"
                 "\n"
                 "<title>Arduino test</title>\n"
                 "\n"
                 "\n"));

      } // end of processPostType

    void myServerClass::processGetArgument (const char * key, const char * value, const byte flags)
      {

      int which = atoi (value);
      if (which >= LOW_PIN && which <= HIGH_PIN)
        {
        if (strcmp (key, "on") == 0)
          {
          digitalWrite (which, HIGH);
          print (F("
Turning on pin "));
          println (which);
          }
        else  if (strcmp (key, "off") == 0)
          {
          digitalWrite (which, LOW);
          print (F("
Turning OFF pin "));
          println (which);
          }
        else
          {
          print (F("
Bad action: "));
          fixHTML (value);
          println (F(""));
          }
        }
      else
        {
        print (F("
Bad pin number: "));
        fixHTML (value);
        println (F(""));
        }

      }  // end of processGetArgument

    // -----------------------------------------------
    //  End of user handlers
    // -----------------------------------------------

    void setup ()
      {
      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip, gateway, subnet);

      for (int i = LOW_PIN; i <= HIGH_PIN; i++)
        pinMode (i, OUTPUT);
      }  // end of setup

    void loop ()
      {
      // listen for incoming clients
      EthernetClient client = server.available();
      if (!client)
        {
        // do other processing here
        return;
        }

      myServer.begin (&client);
      while (client.connected() && !myServer.done)
        {
        while (client.available () > 0 && !myServer.done)
          myServer.processIncomingByte (client.read ());

        // do other stuff here

        }  // end of while client connected

      client.println(F("
OK, done."));

      client.println (F("\n"
                        ""));

      // give the web browser time to receive the data
      delay(1);
      // close the connection:
      client.stop();

      }  // end of loop

Library source on GitHub at [nickgammon/HTTPserver](https://github.com/nickgammon/HTTPserver).

The library is designed to allow you to receive cookies, POST data, pathnames (on the URL) and GET parameters.


message:
Can a shift register be used to extend the Arduino pins when an ethernet shield is mounted on the Arduino?

I am currently working on a wireless home automation system. The system is connected to a wireless network in the home via the ethernet cable connected the ethernet shield and router. Hence, I need more pins on the Arduino to connect the appliances to be controlled in the home.

body:
You can control a shift register with [shiftOut](https://www.arduino.cc/en/Reference/ShiftOut) or bit-banged SPI.

My page about [SPI](http://www.gammon.com.au/spi) has a small library that does bit-banged SPI.

It is also possible to control a shift register using the **same** pins (MOSI/MISO/SCK) that the Ethernet interface uses, as long as you use a different SS (slave select) pin for your shift register. This may not be practical if the Ethernet card is active all the time. It is probably easier to do the bit-banged SPI or use `shiftOut`.


message:
Is parity check hardware only or can I read it? ( Arduino Mega )

Maybe a simple question, but I can't seem to find it.

Parity check is simple error detection.

But is in done in hardware on the arduino and is the data discarded before i can read it from software?

The reason I ask this quote from Thomas

> 1  Command bit, set on the first character of each datagram. Reflected in the parity bit of most UARTs. Not compatible with NMEA0183 but well suited for the multiprocessor communications mode of 8051-family microcontrollers (bit SM2 in SCON set).

From http://www.thomasknauf.de/rap/seatalk1.htm#Dat which might have confused me. So I guess this is not an option ... after the feedback from users.

So i need to read the 9 bit and since the hardware support it. The Arduino team won't implement it, since it has a bigger overhead and it's really not used anymore ... I agree ... but the SeaTalk bus uses it ... so I'm stuck here.

But after more seaching I found this GitHub repo: https://github.com/rob42/FreeboardPLC_v1_2 which have made changes to the HardwareSerial.h and HardwareSerial.cpp but only for version 1.5.7

Think I will go for this version unless someone have done the mods to 1.6.x ... have searched the web. Later I will try to see if I can get it to work with 1.6.x ... but since this is all new. I'm taking small steps.

body:
AVR devices with a hardware USART have a real 9-bit mode; there is no need to "fake" it.

But to answer your question, it is done in hardware; the appropriate USART Parity Error bit is set and while the datasheet is vague about it, it is implied that the data is stored in the receive buffer.


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

This came up a while back on [the Arduino Forum](http://forum.arduino.cc/index.php?topic=91377.0) - talking about [Asynchronous SeaTalk](http://forum.arduino.cc/index.php?topic=54120).

I made a modified version of HardwareSerial which can be downloaded from <http://gammon.com.au/Arduino/HardwareSerial9bit.zip>

Changes are:

* The internal buffers have been changed from 8-bit characters to 16-bit characters (to hold the 9th bit). Thus the buffers double in size.

* There is a new argument to the Serial.begin() function, which is a boolean, whether or not you want 9-bit mode. It defaults to false.

* There is a new function `Serial.write9bit ()`. This takes an unsigned int argument, letting you supply a character with the 9th bit set. I didn't want to change the existing write function because it is used in the Print class.

* The read function, which already returns an int, now will return the 9th bit where required.

---

Example code:

    void setup ()
    {
     Serial.begin (115200);  // debugging prints
     Serial1.begin (115200, true);  // 9 bit mode
     Serial2.begin (115200, true);  // 9 bit mode
     Serial.println ("--- starting ---");
    }  // end of setup

    int i;

    void loop ()
    {

     Serial1.write9bit (i++);  // send another byte

     // display incoming on Serial2
     if (Serial2.available ())
       Serial.println ((int) Serial2.read (), HEX);

     // check if we have sent all possible characters
     if (i >= 0x200)
       {
       delay (100);
       while (Serial2.available ())
         Serial.println ((int) Serial2.read (), HEX);
       delay (5000);
       i = 0;
       }  // end of sent 512 bytes
    }  // end of loop

---

As Ignacio Vazquez-Abrams said, the hardware supports this 9-bit mode natively, it just takes a bit of fiddling around to make it work.

Because of the way that hardware serial is integrated into the IDE it is, unfortunately, necessary to find your existing files:

* HardwareSerial.cpp
* HardwareSerial.h

... and replace them with the ones in the download.

---

Note that this is for version **1.0.1** of the IDE. No guarantees are given that this will work with other versions. This was written a while back, I'm not sure what changes have been made to HardwareSerial in the meantime.

The actual changes are here: <http://gammon.com.au/Arduino/hardwareSerial_diffs.txt>

You could use those to guide your implementation on more recent versions, if the file download does not work "as is".


message:
Ethernet shield not have MAC address sticker

Hi everyone I recently bought an Arduino Mega and Arduino Ethernet Shield. There are lots of forum posts that say the shield should have a MAC address that is written on the back side of shield, but I don't have any sticker which has the MAC address. Does anyone know how I can get my MAC address or configure it with a new MAC address? Thanks

body:
According to [this documentation][1], you can just provide your own.

>mac: the MAC (Media access control) address for the device (array of 6 bytes). this is the Ethernet hardware address of your shield. Newer Arduino Ethernet Shields include a sticker with the device's MAC address. For older shields, choose your own.

  [1]: https://www.arduino.cc/en/Reference/EthernetBegin


message:
Usefulness of measuring 0v using ADC

I'm looking at the datasheet of the ATMega328, and I see the different channels you can select for AD conversion. ADC0..7, ADC8 (temperature), 1.1V (VBG), and lastly **0V (GND)**.

 - What would be the use of measuring 0V?
 - Would it ever result in a reading other than `0`? I find it very intriguing.

The datasheet doesn't seem to give any additional information about it.

[AVR126](http://www.atmel.com/Images/doc8444.pdf) seems to give a hint:
> configure 0V (GND) in ADC by setting Mux bitfield (MUX3:0) equal to 1111. This is done to discharge the capacitor of ADC.

Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz).

Is it to protect the ADC from to high a voltage in the ADC capacitor, when changing to a different (lower) reference voltage? Rather odd you need software to protect the IC, and it's not even mentioned in the datasheet. Also I've never seen anyone do this (e.g. when measuring the internal temperature of the ATMega).

body:
That quote you mention says it all really.  It's purpose is to discharge the Sample And Hold capacitor.

That capacitor is used (as I'm sure you are aware) to store the incoming voltage while it's being sampled by the ADC.  The ADC operated in two main phases:

1. Acquisition
2. Sampling

During acquisition the capacitor is connected to the incoming voltage.  During sampling it is disconnected from the incoming voltage and the voltage it stores is read into the internal registers.

It takes a certain amount of time for the voltage in the capacitor to equal that of the incoming voltage.    If you try reading at higher speeds then what voltage was in the capacitor from the previous sample can affect the new reading.  However, if you do each sample always from a known voltage in the capacitor (0V) then you get much more stable results.

Another good use for it is when using the ADC as a Charge Time Measurement Unit.  This is the proper way of performing capacitative sensing.  You apply a constant (tiny) current to an external capacitor (the sensing plates) for a specific period of time.  When that time is up you disconnect the constant current source and measure the voltage that has developed across that capacitance.  The capacitances and currents are small, and if there is a charge in your S&H capacitor at the time you do the sampling that will be back-fed into the touch sensor capacitative plates changing the voltage.  By ensuring that the S&H capacitor is at 0V before you sample the plates you won't be adversely affecting the voltage on the plates with successive readings (well, you will, but it will be consistently in the same way every time so it won't affect your overall results).


body:
> Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz).

The document actually says:

> The ADC can prescale the system clock to  provide an ADC clock that is between 50kHz and 200kHz **to get maximum resolution**.

(My emphasis)

It goes on to say:

>  If ADC resolution of less than 10 bits required, then the ADC clock frequency can be higher than 200kHz. At 1MHz it is possible to achieve eight bits of resolution maximum.

I did some testing on [this page](http://www.gammon.com.au/adc) with different prescalers. The results showed that reasonable results could be obtained even with a 1 MHz ADC clock:

    Prescaler 2

    Analog port = 0, average result = 1023
    Analog port = 1, average result = 1023
    Analog port = 2, average result = 1023
    Analog port = 3, average result = 1022
    Time taken = 26220

    Prescaler 4

    Analog port = 0, average result = 673
    Analog port = 1, average result = 718
    Analog port = 2, average result = 512
    Analog port = 3, average result = 193
    Time taken = 32780

    Prescaler 8

    Analog port = 0, average result = 842
    Analog port = 1, average result = 677
    Analog port = 2, average result = 509
    Analog port = 3, average result = 34
    Time taken = 46040

    Prescaler 16

    Analog port = 0, average result = 1022
    Analog port = 1, average result = 672
    Analog port = 2, average result = 509
    Analog port = 3, average result = 0
    Time taken = 73164

    Prescaler 32

    Analog port = 0, average result = 1022
    Analog port = 1, average result = 672
    Analog port = 2, average result = 508
    Analog port = 3, average result = 0
    Time taken = 128040

    Prescaler 64

    Analog port = 0, average result = 1022
    Analog port = 1, average result = 672
    Analog port = 2, average result = 508
    Analog port = 3, average result = 0
    Time taken = 240972

    Prescaler 128

    Analog port = 0, average result = 1022
    Analog port = 1, average result = 672
    Analog port = 2, average result = 508
    Analog port = 3, average result = 0
    Time taken = 448108

The four test voltages were, and their results *should have* been:

* 5V (should return 1023)
* 3.3V (should return 674)
* 2.5V (should return 511)
* 0V (should return 0)

---

The tests were done in rapid succession, no allowing for the ADC to recharge or anything:

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

     unsigned long startTime = micros ();
      for (int i = 0; i < ITERATIONS; i++)
        {
        for (int whichPort = lowPort; whichPort <= highPort; whichPort++)
           {
           int result = analogRead (whichPort);
           totals [whichPort - lowPort] += result;
           }
        }
      unsigned long endTime = micros ();


message:
CC3000 Wifi: Enable Debug

How do I enable debugging using Adafruit CC3000?

I am using the [Adafruit_CC3000_Library](https://github.com/adafruit/Adafruit_CC3000_Library).  I've followed the [WebClient.ino example sketch](https://github.com/adafruit/Adafruit_CC3000_Library/blob/master/examples/WebClient/WebClient.ino).  I'm able to make 300 to 400 HTTP requests, but eventually the connection will hang.

I have looked at the CC3000 [source](https://github.com/adafruit/Adafruit_CC3000_Library/blob/master/Adafruit_CC3000.cpp) and [utilities](https://github.com/adafruit/Adafruit_CC3000_Library/tree/master/utility) and found that the `Adafruit_CC3000_Library` has a `&Printer` reference in a local variable called `CC3KPrinter`.  I can't figure out how to enable or activate `CC3KPrinter`, as it is in a code block contingent on `CHECK_PRINTER`.  I thought that `#define`-ing some variables in my sketch would help:

    // None of these flags seem to enable debug within the CC3000 code.
    #define _CC3000_DEBUG  1
    #define DEBUG_MODE     1
    #define ENABLE_CC3K_PRINTER 1

An example code snippet within the CC3000 library that I'm trying to enable is at [line 916](https://github.com/adafruit/Adafruit_CC3000_Library/blob/master/Adafruit_CC3000.cpp#L916):

      CHECK_PRINTER {
        CC3KPrinter->println(F("Timed out waiting to connect"));
      }

body: Poor workaround: since I was trying to solve a connection hang, I opted to use a [watchdog timer](https://tushev.org/articles/arduino/5/arduino-and-watchdog-timer) solution, leveraging the lightly documented ```<avr/wdt.h>``` library.


body:
To enable debugging, you need to

 - uncomment `ENABLE_CC3K_PRINTER` in `Adafruit_CC3000.h`
 - If you want to pass in some debug stream other than the default `Serial`, you should pass a pointer to the object (which should inherit from `Print`, such as `SD` or `Client`) as the last argument to the constructor in your sketch:

        Adafruit_CC3000(uint8_t csPin, uint8_t irqPin, uint8_t vbatPin, uint8_t spispeed = SPI_CLOCK_DIVIDER, Print* cc3kPrinter = CC3K_DEFAULT_PRINTER);

 - In `utility/debug.h`, change the value of `DEBUG_MODE` to 1 (or any non-zero value)

I don't know what caused your issue but you shouldn't put this in your code:

    #define _CC3000_DEBUG  1

Because most of `utility/debug.h` is wrapped in the usual:

    #ifndef _CC3000_DEBUG
    .
    .
    .
    #endif

Your `#define`, depending on where it's placed, could cause most of the file to be skipped by the compiler and result in compilation errors. To be on the safe side, get rid of it and simply include `utility/debug.h` as needed.


message:
Yum as eth->wlan adaptor

Is there a way to make a yun an Ethernet-wifi bridge? Applications include giving wifi to raspberry pi and other Ethernet only devices and vice versa.

body:
Yes, you can.  I use one to connect my Sky box (Ethernet only) to my WiFi network,

It's not an easy task though and you have to have a good understanding of networking and routing.

Basically you have to set the Yun up as a router to route packets between the Ethernet and the WiFi interfaces.  You set the Ethernet interface up on a separate subnet to your existing WiFi network, and set a static route on your main router to send traffic destined to your new Ethernet subnet to the Yun's WiFi IP address.

Your Ethernet devices can then be allocated an IP address on the Ethernet subnet (turn on DCHP for that interface on the Yun) and will use the Yun as the default gateway.

There are probably ways you can enable bridging on the Yun to tie the Ethernet and WiFi interfaces together so it becomes transparent but I haven't investigated that yet.


message:
'AttachPinChangeInterrupt' was not declared in this scope

I am a beginner trying to upload the [SimpleExample328.ino sketch][1] on my Arduino Uno. When I verify my sketch however, I run into the error:

>'AttachPinChangeInterrupt' was not declared in this scope.

I would assume the header file `PinChangeInt.h` is not in the correct location; currently the `PinChangeInt` folder (that contains `PinChangeInt.h`) is placed in the `Arduino IDE libraries` folder, which I believe is the correct location.

Did I place the header file in the wrong location or does this error result from another cause? Thanks :)

  [1]: https://github.com/GreyGnome/PinChangeInt/blob/master/Examples/SimpleExample328/SimpleExample328.ino

body:
You don't have the library installed. To install:

 - Go to https://github.com/GreyGnome/PinChangeInt
 - Click the green `Clone or Download` button
 - Select `Download ZIP`

The .ZIP file will download to your computer. Take note of the location.

 - Open up the Arduino IDE
 - Go to `Sketch` > `Include Library` > `Add .ZIP library...`
 - Browse to the download location
 - Select the PinChangeInt ZIP file

Its done! Compile your program and all should work!


message:
LCD Display Flicker When Arduino Main Board Supply Voltage to GSM Shield Board

I have a 16x2 LCD display that is connected to an Arduino microcontroller.
It is working fine but the LCD display flickers when I connect the Vin and GND of the main board to its slave GSM Shield.

I used main board Vin and GND to power up the GSM Shield so I only have one power supply. I was able to power up GSM Shield by adding jumper to Vin and GSM +Vin.

In additional question, is there any other way to power up Arduino GSM Shield without connecting it to another power source to still keep having only one plug for power?

body:
This sounds like either your GSM Shield is drawing to much power (from time to time) and thus your Vin drops resulting in flickering or your GSM Shield induces ripple on top of your Vin.

To debug this I would recommed to have a look at Vin with an oscilloscope and see how stable Vin is. Additionally some capacitors between Vin and GND (100nF and 10-100µF) and a ferrit between Vin and the GSM Shields Vin might help.


message:
How to make C++ code compatible with Arduino IDE?

I wrote some code in C++ (Used libraries like fstream, vectors etc.) Now when I transferred the code to Arduino it wouldn't compile so I added the following library: https://github.com/maniacbug/StandardCplusplus I downloaded the IDE from here: https://www.arduino.cc/en/main/software

Now almost all my code works: All the libraries I've used work except for fstream which I've used to read a specific file.

Now is there a certain problem with the 'StandardCplusplus' library and how can I counter this problem.

Plus can someone give me an alternative for fstream that works with Arduino. Was reading a bmp image using C++. Now fstream works in a certain way (reads the file in a certain way). Is there some alternative to fstream.

body:
When you run that library on the Arduino and ask it to open a file, where do you imagine it would read the file from? Your Arduino has no hard disk or other file system.

One way to solve this is to include a library that emulates a read-only file system in the Arduino's flash. I dunno whether this exists (such libs do exist for for some other targets, for instance for the Nintendo DS), but it would be a bit of overkill IMO.

Another way is to include the data that is in the file in your program, as a const (expr) array of bytes, and read from that array instead of from the file. But if you have a library that is coded to use file read calls this would require some rewriting.

A third approach would be to do the reading and interpreting of the file on your host PC, output the *interpreted* content to a const (expr) byte array, and include that in your application. This frees you from having to include the bmp-read code in your image.


body:
If you want to write C++ for an Arduino, I'd recommend you cease using the Arduino IDE and instead use Atmel Studio. The microcontroller on board is an Atmel AVR, and you can write for that using the gcc-avr toolchain that comes with Atmel studio.

You'll lose the spiffy libraries that come with the arduino platform that abstract away a lot of the intricacies of the hardware, and you'll instead be looking at the AVR datasheet and the schematic of the arduino, but you'll learn quite a bit in the process and have direct control over the hardware.

With all that said though, the AVR does not have a file system so using fstream doesn't make any sense to begin with.


body:
The Arduino IDE *does* compile your code using the avr-g++ compiler. In other words, it *is* C++.

>  Was reading a bmp image using C++.

This isn't practical on the smaller Arduinos, at least, because they have so little RAM. They also don't have a file system. There is a [streaming](http://arduiniana.org/libraries/streaming/) library for output, which is very handy for streaming out things to Serial, LCDs, etc.

One of the replies here mentioned that if you switch to Atmel Studio you can look at the datasheet and get down to the intricacies of the hardware. Well, you can certainly do that as well with the IDE. All the hardware registers are available for use. I often use the "bare" registers for timers, watchdog, interrupts etc.

Also Atmel Studio only runs on Windows. You are out of luck if you use a Mac or Linux.

There is also a port of the [Standard Template Library](http://andybrown.me.uk/wk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/) for the Arduino, if you want to use vectors, lists, maps etc.

There is also [another port of the STL](https://github.com/maniacbug/StandardCplusplus) which may work better and be easier to install.


body: Are you using Arduino UNO? Look at the datasheet and see how much RAM the Arduino has. Assuming you are using Arduino Uno, it should be around 2kilobyte or less. So it is highly likely not to have enough memory to read the BMP file. Even if you are trying to read very small BMP file, the code reading the file would vary depending where you are reading the BMP file from (SD Card, SPI Flash memory, etc.) It cannot read files directly from your computer using just fstream.


body:
To answer your compile problem.. Are you using c++11? The issue could be that Arduino Compiler may not support entire C++11 features.

So if you cant find an alternative for fstream (I dont know any) then you have to find a different way compile the C++11 code and upload it. You can do this with a Makefile, avr-gcc. Its plenty of generators out there.


message:
How do I compile the Marlin firmware?

I have a folder of mostly .h and .cpp files for the Marlin firmware (3D Printing) from [here][1].

How do I compile that so I can upload it to my Arduino Mega with Ramps?

  [1]: https://nwreprap.com/software/

body:
You need to open the .ino file. that is the project file for the Marlin Firmware. then upload that. Also do some research about the settings for Marlin. It isn't just plug and play, you have to enter some information about your individual stepper motors.

http://solidutopia.com/marlin-firmware-user-guide-basic/ - heres a guide for Marlin.

the cpp and h files are c++ files that are apart of the project. the Arduino IDE cannot open these individually. the .ino file is the project file that will allow you to open up the entire project and not just one portion of it.


message:
Is it possible to accept multiple web requests at once?

I have an Arduino with ethernet shield and there are 8 different URLs that can be called to perform different actions.

The program loads and runs as expected for the most part, but, if it is busy doing an action, it won't accept the next one until the current action has finished.

Basically, the code's main loop listens for a client connection, then has a bunch of ifs that look in the URL that was called (for a query string) and then process the command.

I have looked at a few answers on here, but none deal with listening to HTTP requests. One recommended a library, but, I couldn't quickly get it to compile, and the other answer recommended a state machine - I do like this approach, however, I haven't had time to implement and it doesn't "feel" right as the listening for a HTTP request works on a `if(client)` basis.

I was wondering if anyone has done this before and/or has any advice?

body:
It can be done. The Arduino is a single tasking environment so you have to make sure your code is non-blocking.

BlinkWithoutDelay is a good starting point (thanks @Majenko) but you should also look at the [Timer1][1] library.

Basically your programs needs to do all the steps it can right away and whenever it does something that could block, it must do it asynchronously and during a later loop() run check if it's finished and continue with the next task. The alternative (if you know how long your task will take) is to use the timer interrupt with the library mentioned above.

  [1]: http://playground.arduino.cc/Code/Timer1


message:
Arduino for delivering a WoL signal over ethernet, when receiving a specific command over WiFi

I'd like to assemble a device that could accomplish the following:

 - Connect to my home [wifi][1] (WPA2-Personal)
 - Connect to my home PC with via Ethernet cable
 - Able to send [WoL][2] signal to the PC when getting a signal over wireless connection
 - The whole set up needs to be less than 45USD, desirably much less, otherwise I'd just buy a wireless bridge.

The goal is both to have a useful device (that will allow me to wake up my pc remotely) but also have fun learning something new (arduino).

I have no background in Arduino or Electronics in general. I program well though and learn fast.

Do you think Adruino is adequate for the above? Is soldering required (I'd rather not, or at least not a lot)?

  [1]: https://www.arduino.cc/en/Main/ArduinoWiFiShield
  [2]: https://en.wikipedia.org/wiki/Wake-on-LAN

body:
I doubt if you will do it in that price range. Buying genuine products (as opposed to clones from eBay) you would be paying something like:

* Arduino Uno: $US 25
* WiFi shield: $US 40
* Ethernet shield: $US 45

Prices from [Adafruit](http://www.adafruit.com/) - other suppliers would have the same or similar for similar prices.

I see there is a [Arduino Ethernet](http://www.adafruit.com/products/418) which combines the Uno and the Ethernet shield for $US 65.

> The whole set up needs to be less than 45USD, desirably much less ...

Maybe someone else can suggest a cheaper option, but I think you will be pushing it here.


body:
**The Arduino might not be a choice for you.** The reason why microcontroller boards(like Arduino) become popular is the simplicity and the easiness of control peripherals through GPIO pins, like output PWM signal to control motors, reading sensors through SPI or I2C, reading analog voltage, and etc. Most microcontrollers on Arduino boards itself, however, is not designed for networking features and does not have even enough performance for it. This means that it would cost you much more money on additional networking devices like WIFI shield, Ethernet shield and microprocessor for networking (Arduino Yun).

So, **if you are looking for just a pure networking device like what you have in mind, I would highly recommend you Raspberry Pi**(2 Model B for $39 and 1 Model B+ for $30), which has enough capability of networking itself. All you need is a USB WIFI dongle($9) with the Raspberry Pi, I guess. I am pretty sure you won't have a cheaper option using Arduino.

You can use the raspberry Pi as a web server, a NAS, a media server along with the features you mentioned.


body:
The Raspberry Pi is definitely the easiest way to do this, however it will use more power.

You can do it within your budget by using Arduino clone hardware from places like AliExpress.

If you don't mind the extra effort, it certainly can be done using the Arduino and a wireless and ethernet shield.

A WiFi shield is around $17, an ethernet shield is less than $6 and an Arduino Uno clone is around $3. Make sure you can combine these shields (I haven't checked). There's also a combined Linux, Ethernet + Wifi Yun shield for around $30.


message:
Is the Arduino library so slow?

I have a plan to operate 5MP camera module with the arduino Due. But I wonder if I can use the arduino libraries that include digitalRead, digitalWrite and so on. But some people said that it is a bad idea. Especially I found that people wrote values on registers instead of using the library, when they control ov7670 with Uno.

Contrary to this, ArduCam uses the libraries, even for OV5642!. Here is the link
https://github.com/ArduCAM/Arduino/blob/master/ArduCAM/examples/mini/ArduCAM_Mini_OV5642_Video_Streaming/ArduCAM_Mini_OV5642_Video_Streaming.ino

So could anyone please let me know, if it is okay to use such library and never to use register directly? With 'register' I mean arduino's register, not camera's.

I guess the system clock and existence of FIFO would affect the answer. But still I don't know how to evaluate their effect analytically.

body:
Unless you have a really large number of read/write operations and very tight time constraints, I doubt you are going to have any significant advantage in terms of speed.

Accessing the bits in a port together, rather than individually is certainly more efficient, both in terms of time and space, but it might cost in readability, depending on how comfortable you are with leaving the Arduino libraries behind.

You can have also a look at [this thread][1].

Notice that the maximum gain happens only when all the pins you have to read or write belong to the same register.

  [1]: http://forum.arduino.cc/index.php?topic=86060.0


body:
You can use ANY and ALL libraries (if their LICENCies allows it) you want, or none library at all.

More important is, if the result does what you need.

 For some kinds of problems even very slow library is fast enought. For some kinds only highly optimized library can do. Some problems are so complex, that any Arduino cannot do it even with the best effort and total optimization of code and HW resources. (Well, for some problems even todays best supercomputers are not good enough)

Lot depends on what exactly you plan to do with such camera - if you need some simple controls (like START, STOT, change sesitivity ...) maybe anything is good. If you want to make some autonomous system navigated by vison system which would learn from experience and will recognize all your face expression, than there is no Arduino with needed computing power at all.

Just try find any project vaguelly similar to yours, look, what they are using and what they say about it (excelent, barely usable, we found it impossible) and try library/approach based on that. If it works somehow, make it better and be celebrity too :) If it does not work at all and does not yeld any usable results, maybe try something different.

A lot can be done, if you enhance Arduinos capabilities with external modules (commercial or home made) be it in form of shield or in form of totally different platform.


message:
Why are my sensors not working (the reaction time is so slow)?

[![enter image description here][1]][1]

    //testing the light sensor;
    int sensor=A0; // setting as input is by default;
    int sensorval;
    int pin=13;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(pin,OUTPUT);
      pinMode(sensor,INPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      sensorval=analogRead(sensor);
      Serial.println(sensorval);
      if(sensorval>900)
        digitalWrite(pin,HIGH);
      else  digitalWrite(pin,LOW);
        delay(1000);
    }

I am using a photocell, a temperature sensor and a potentiometer with an Arduino Uno and it always gives me `1023 0 1023 0 1023 0 1023 ......`. All my wires are connected properly and I tried all this stuff online and they are working correctly.

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

body:
Have you tried with a different trimmer?

I dont seem to be able to find any issue with your code or your schematic, so can you please cross verify that the trimmer is not spoilt.

Can you also check if, when A0 is left floating (nothing connected) it give a random value.


body:
you should internalize value of sensorval equal to zero.
You do not require set analog pin.
you want get data quickly then reduce delay time because 1 second quite high.So, make it **500** mili second.


message:
Arduino digitalWrite 1 or 0 instead of HIGH or LOW

Is it ok to use

    digitalWrite(pin, 1) instead of digitalWrite(pin, HIGH)

or

    digitalWrite(pin, 0) instead of digitalWrite(pin, LOW)

I want it that way to make the coding lesser because I save values on EEPROM with 1's and 0's. So if I want to use EEPROM value, I can call it this way

    digitalWrite(pin, EEPROM.read(1))

body:
Yes, that is fine.  LOW is 0 and HIGH is 1.  `digitalWrite()` sets the output to off if it receives a 0 and on if it receives anything of 1 or more.

That means that these are all equivalent:

    digitalWrite(pin, HIGH);
    digitalWrite(pin, 1);
    digitalWrite(pin, 69);

It's especially useful when you are examining a variable for, say, a certain bit being set:

    digitalWrite(pin, bytevar & 0x80);

That will set the pin to high on any value from 128 to 255 in the byte variable, and low for anything below 128.


body:
From the [arduino source code](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Arduino.h#L40-L41):

    #define HIGH 0x1
    #define LOW  0x0

So `HIGH` is **exactly** the same as `1`. And `LOW` exactly the same as `0`.


body:
When you look at the source code of Arduino, HIGH is defined as 1 and LOW is defined as 0 using #define.

You may heard about **Preprocessor, Compiler, and Linker**. When you build the project, preprocessor do its job before the code is compiled. What the preprocessor does is basically converting defined words into corresponding value.

For example when you write a syntax like:

    digitalWrite(1, HIGH);
When you build your project, the preprocessor converts the above like into this:

    digitalWrite(1, 1);
Then the code is compiled. Therefore, there is no difference between HIGH and 1.
So, if the result of `EEPROM.read(1)` is either 0 or 1, there should be no problem.


message:
Will 12.6v really damage my arduino?

I'm using a 12v fan and 12v LED modules in my project, so I need about 400mA by their combined specs. I have a 12.6v dc regulated power source that can give ~700mA I wish to use, and since it has a rather small form factor I would also like to power my Arduino Diecimila with it. I'm using PWM from pins 10 and 6 to go through N-channel MOSFETs in order to control both the LEDs and the fan. Anyway, in the Arduino Diecimila board page it says the recommended voltages are between 7-12v, and beyond that it can handle 6-20v, but it might cause the voltage regulator to heat too much, which might damage the board. So, my question is that: will 12.6v really damage my board, or is it within some margin of error? The actual voltage I got when I checked my power supply was 12.55V. Can I maybe just dial it down a bit somehow?

Thanks in advance,

UriSh.

body:
As you have already noticed, it may cause the 5V regulator to get hotter than would be normally considered reasonable.  However, how hot depends entirely on how much current your board is drawing (not including the 12V devices)- the more current you draw the hotter it will get.

Even at 12V it can get uncomfortably hot.

For running off voltages greater than about 9V I usually recommend using an external 5V switching regulator.  These can be easily and cheaply obtained under the name "UBEC" (Universal Battery Elimination Circuit) and are used extensively in the model aircraft arena.  They don't get hot, can handle large currents, and don't waste power like the on-board linear regulator does.

So you'd connect that to your 12.6V supply, then the 5V output of the UBEC (make sure you get a 5V one) would go straight to the 5V pin of the Arduino, and you wouldn't connect the barrel jack or Vin to anything.

You can also pick up cheap switching regulators on eBay - some are adjustable, so you'd want to make sure you adjust it to 5V first before connecting the Arduino, or if you can adjust it to around 7V then you could power the Arduino through the barrel jack (or Vin) with it and avoid too much heat from the on-board linear regulator.


message:
NODEMCU vs AT for esp8266

I have recently started working on esp8266 wifi module and arduino uno.
I am a little confused.

I have created a small Web page with esp8266 AT commands.
Now I want use it for receiving data such as changes on the Arduino inputs.

I have seen many similar implementations using jQuery for that purpose,
but I don't know where to place that jQuery file.

Furthermore, is it possible to use NODEMCU firmware and still toggle arduino pins and transmit data to esp8266?

I want to use Arduino for:

  * reading voltage levels
  * publish the values read to the Web page
  * toggle a relay when a button on the Web page is pressed.

Please kindly help me out or point me in the right direction to search

body:
This is quite a huge topic to cover in one answer, but I will do my best.

The NodeMCU can be used in three distinctly different ways.  First is the *AT* mode, where you have installed the *AT* firmware.  In this mode the NodeMCU is purely a slave device to the Arduino.  Once you have got the Arduino to configure the NodeMCU in the right way to receive data on a socket it will send that data back to the Arduino verbatim through the serial port with special tags added (indicating what the data is, and which socket it arrived on, etc).  It is then up to you to receive that data, interpret it in whatever way you desire (as a HTTP GET request most likely) and craft the correct response (if any) and send it to the NodeMCU to send back (again using the *AT* commands).

What you send through the socket is entirely up to you.  By the sounds of things you will be making a simple GET request from a web browser to perform an operation, and maybe respond with some data to display in the web page.  That can be easy, or it can be hard - it's as hard as you want to make it.  The simplest way is to rely on an external web server to serve the main content and structure of the page, then use jQuery or Prototype to make an AJAX call to your NodeMCU and receive back any data there may be.  In this case everything will be on your external web server except the single (or few) URL(s) that perform operations and return data.  That includes the jQuery (which is just Javascript, it's loaded from your web server into the browser and executed), any code for buttons, images, HTML, everything (on the web server, that is).

The other two ways the NodeMCU can operate are both very different to that.  They differ mainly in the language that is used with them.  You can use the NodeMCU with its own LUA language to get it to do almost anything you want.  That includes receiving the HTTP GET request and serving the data for it, all without the help of the Arduino.  In fact, doing that, there is little need for the Arduino any more - the NodeMCU has an analog input and multiple digital IO lines - it also has SPI available for interfacing with external ADC chips if you want more than one analog input.  So you can have everything internal to the NodeMCU without needing the Arduino at all.  If you do want to keep the Arduino then you can interface to it through the serial port (as you would in *AT* mode) but using your own custom protocol in whatever way you see fit.

The third way is to program the NodeMCU as if it were itself an Arduino.  There is an ESP8266 core for the Arduino IDE (and for [UECIDE Beta](http://uecide.org/beta) as well) which allows you to program the NodeMCU in the same language and with a similar API, as the Arduino.  This even more removes the need for the Arduino.  You can get the Arduino core from Github here: https://github.com/esp8266/Arduino

Incidentally, the Xtensa core in the ESP8266 is considerably more powerful than your typical Arduino, being 32-bit, having its own DSP, and with much more RAM and Flash memory.  It kind of makes the Arduino redundant.


message:
Delay workaround needed for RTC and LCD-shield buttons

Following configuration:

- Arduino UNO R3
- Real Time Clock DS1307RTC
- LCD1602 Shield with buttons
- Photo resistor
- DHT11 (Temp & Humidity Sensor)

I need the function delay(1000) to display the seconds properly from the RTC to the LCD.
But, that way I always have to keep the buttons pressed for up to 1 second until they react.

How can I workaround or solve this problem?

Idea 1: Multitasking would come in handy here :-) pseudocode:

    task 1: listen for LCD buttons
    task 2: display seconds with a delay of 1000ms

But there isn’t a way Arduino could multitask, isn’t it?

Idea 2: As far as I saw in the header files for the RTC, the smallest readable unit is seconds. Otherwise I could have used something like a millisecond reader in a while condition to listen for the buttons; pseudocode:

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

    while (RTC-millisecond < 1000ms) {
     // listen for buttons
        // so a second passes, which gives the RTC time to display the seconds values
    }

-

**EDIT**

updated code, thanks to @NickGammon and Gerben:

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

    #include <LiquidCrystal.h>
    #include <Wire.h>
    #include <Time.h>
    #include <DS1307RTC.h>
    #include <DHT.h>

    // initialize the library with the numbers of the interface pins
    //                RS  E  D4 D5 D6 D7 (maybe wrong order)
    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    // pins on which the sensor is connected
    #define DHTPIN A1
    #define PHOTOPIN A2

    // initialize DHT sensor
    #define DHTTYPE DHT11
    DHT dht(DHTPIN, DHTTYPE);

    // define some values used by the panel and buttons
    int lcd_key     = 0;
    int adc_key_in  = 0;
    //#define btnRIGHT  0
    //#define btnUP     1
    //#define btnDOWN   2
    //#define btnLEFT   3
    //#define btnSELECT 4
    //#define btnNONE   5

    // FSM
    unsigned long previousMillis1 = 0;
    unsigned long previousMillis2 = 0;
    const long interval = 3000;

    // prototypes
    void print2digits(int number);
    int read_LCD_buttons();

    void setup() {
      // open a serial connection to display values on PC
      Serial.begin(9600);

      // set up the number of columns and rows on the LCD
      lcd.begin(16, 2);

      // start DHT sensor
      dht.begin();
    }

    void loop() {
      // set variable from struct tmElements_t
      tmElements_t tm;

    /********* Reading from sensors *********/
      /*** DHT sensor ***/
      // Reading temp or RH takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float humid = dht.readHumidity();
      float tempC = dht.readTemperature();
      // Check if any reads failed and exit early (to try again).
      if (isnan(humid) || isnan(tempC)) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("DHT reading failed!");
        Serial.println("DHT reading failed!");
        return;
      }
      // Compute heat index in Celsius (isFahreheit = false)
      float hiC = dht.computeHeatIndex(tempC, humid, false);

      /*** Photo resistor ***/
      int lightReading = analogRead(PHOTOPIN);

    /********* Print to PC over serial connection *********/
      // ...

    /********* Print values to LCD *********/
      /* --- first line on LCD --- */
      /*** RTC ***/
      // set the cursor to LCD column 4, line 0 to center the clock
      lcd.setCursor(4, 0);

      // starts RTC reading and checks if it's working
      if (RTC.read(tm)) {
        static byte oldSecond = 60; // 60, because there is no 60'th second in a clock
        // display only if time changes
        if (tm.Second != oldSecond) {
          oldSecond = tm.Second;
          print2digits(tm.Hour);
          lcd.print(':');
          print2digits(tm.Minute);
          lcd.print(':');
          print2digits(tm.Second);
        }
      }
      else {
        lcd.clear();
        lcd.setCursor(0, 0);
        if (RTC.chipPresent()) {
          lcd.print("Please run SetTime function");
        } else {
          lcd.print("DS1307 read error!");
        }
        delay(9000);
      }

      /* --- second line on LCD according to button --- */
      lcd_key = ((lcd_key + read_LCD_buttons()) %3);  // call button function, modulo 3 to cycle through
        /** // Test buttons:
        lcd.setCursor(1, 1);
        lcd.print("lcd var:");
        lcd.print(lcd_key); */

      unsigned long currentMillis = millis(); // FSM used for displaying DHT and photo values without flikering

      switch (lcd_key) {
        case 0:
          /*** Weekday and Date ***/
          // display only if day changed
          static byte oldDay = 99;
          if (tm.Day != oldDay) {
            oldDay = tm.Day;
            lcd.setCursor(0, 1);
            lcd.print("                "); // 16 spaces to clear second line before printing
            lcd.setCursor(0, 1);
            //lcd.print(dayShortStr((weekday() + 1) % 7 )); // (day+1)%7 calculation for Swiss layout
            lcd.print(tm.Wday); // TEST
            lcd.print(weekday()); // TEST
            lcd.print(", ");
            print2digits(tm.Day);
            lcd.print('.');
            print2digits(tm.Month);
            lcd.print('.');
            lcd.print(tmYearToCalendar(tm.Year));
          }
          break;

        case 1:
          /*** DHT Sensor ***/
          if (currentMillis - previousMillis1 >= interval) {
            previousMillis1 = currentMillis;
            lcd.setCursor(0, 1);
            lcd.print("                "); // 16 spaces to clear second line before printing
            lcd.setCursor(1, 1);
            lcd.print(hiC);
            lcd.print("*C ");
            lcd.setCursor(10, 1);
            lcd.print(humid);
            lcd.setCursor(12, 1);
            lcd.print("%RH ");
          }
          break;

        case 2:
          /*** Photo resistor ***/
          if (currentMillis - previousMillis2 >= interval) {
            previousMillis2 = currentMillis;
            lcd.setCursor(0, 1);
            lcd.print("                "); // 16 spaces to clear second line before printing
            lcd.setCursor(0, 1);
            lcd.print("Light ");
            lcd.setCursor(6, 1);
            lcd.print(lightReading);
          }
          break;
      }
    }

    // used to print 2 digits in the time values
    void print2digits(int number) {
      if (number >= 0 && number < 10) {
        lcd.print('0');
      }
      lcd.print(number);
    }

    // read the buttons
    int read_LCD_buttons() {
      adc_key_in = analogRead(0);
      //if (adc_key_in > 1000) return btnNONE; // 1st option since it will be the most likely result (speed reasons)
      //if (adc_key_in < 50)   return btnRIGHT;
      //if (adc_key_in < 195)  return btnUP; // replaced by below one
      if (adc_key_in < 195)  return 1; // my button up !
      //if (adc_key_in < 380)  return btnDOWN;
      //if (adc_key_in < 555)  return btnLEFT;
      //if (adc_key_in < 790)  return btnSELECT;
      //return btnNONE;  // when all others fail, return this...
      return 0;
    }

body:
You need to learn a different way of programming.

Two things you need to understand:

1. Non-blocking code.  Read and understand the BlinkWithoutDelay example sketch (in the Arduino IDE's File -> Examples menu)
2. Finite State Machines.  Stop thinking purely linear, and start thinking about the different states your program can be in at any one time.

Once you have those cracked you'll be an Elite Arduino Programmer (EAP™).


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

      // clean up screen before printing a new reply
      lcd.clear();

      /* --- first line on LCD --- */
      /*** RTC ***/
      // set the cursor to LCD column 4, line 0 to center the clock
      lcd.setCursor(4, 0);

Straight away, that will cause flicker, right? For a few milliseconds the screen will go blank, and then get gradually redrawn. Why not omit the clear? You could put it in if you are changing display types (eg. from date to temperature) but you don't need to clear the screen every time. So:

* Don't call `delay()`

* Don't clear the screen unless changing to displaying a different type of thing

* Only update the display at all if the new number (or time, or temperature, etc.) is **different** from what you just displayed.

* Just do the `setCursor()` to position the cursor and **overwrite** the information there previously.

* Preferably follow by a space or two in case a large number is replaced by a smaller one.

---

Side-benefit: Since you have removed the delay, your project will now be much more responsive to key presses. Win win!

---

## References

* [State machines](http://www.gammon.com.au/statemachine)

* [How to do multiple things at once ... like cook bacon and eggs](http://www.gammon.com.au/blink)

---

>  I am not quite sure how to do it

     if (RTC.read(tm))
      {
      static byte oldSecond = 99;
      // display if time changes
      if (tm.Second != oldSecond)
        {
        oldSecond = tm.Second;
        print2digits(tm.Hour);
        lcd.print(':');
        print2digits(tm.Minute);
        lcd.print(':');
        print2digits(tm.Second);
        }
      }

Similarly further down where you display the date / sensor.


message:
Need help understanding how RF communication works with 2 arduinos

I have two arduinos (uno) and I would like to send the results of a key press on a 5X4 matrix pad to the other arduino. The matrix keypad works great. I can identify which key was pressed with a switch function.

    switch (keypad())
    //switch used to specify which button
         {
          case 0:
            Serial.print("Key A Pressed");
            Serial.print(keypad());
            messageToSend = 0;
          break;
            case 1:
            Serial.print("Key B Pressed");
            Serial.print(keypad());
            messageToSend = 1;
          break;
            case 2:
            Serial.print("Key C Pressed");
            Serial.print(keypad());
            messageToSend = 2;
          break;
           }

My RF units are both nrf24l01. I have tried working with the sample code and I think the issue is I don't understand how the unit works well enough.

 1. What is the nature of the data sent between units? I want to send
    integers, possibly even text. Is that possible? Do I need to convert
    to binary or something?

 2. My understanding of "ping" and "pong" is that ping sends a message
    then pong sends that same message back to ping... is this correct?

 3. Are RF units very different? Is this one particularly difficult?

 4. If I just want to send with one receive with the other shouldn't
    this simplify the code?

 5. What are pipes? How many can I open?

 6. If I have 3 or more of these what changes will I need to make to the
    code?

Thanks!

body:
Many questions so broad answers, but hopefully informative for your research

 1. >What is the nature of the data sent between units? I want to send integers, possibly even text. Is that possible? Do I need to convert to binary or something?

It depends broadly on what you use. If you use an ethernet peripheral then the communications will be entire ethernet packets with whatever protocol stack you have above it in payload. For simple RF communication modules it may be as simple as a serial stream delivered 8 bits at a time. The simplest rf (buzzer-style) would simply interrupt (or drive a pin high) when the transmitter is sending a signal.

In Your case the transmitter uses an addressed protocol with a payload packet of between 1 and 25 Bytes of data. This means that you will need code to read and store the necessary payload, maintain configuration data and keep track of addresses of the other systems to message. You also need to poll (or handle interrupts from) the rf module to make sure there aren't messages from the transmit node.

How you convert the data is up to you, a string can be represented by a sequence of bytes and can be send and read as a string on the receivers end. Your rf module will deliver you data in 1-25 byte chunks, what you send in that chunk and how to encode it is entirely up to you.

On the low level,the way this module is configured, the MCU sends data into the rf ic using a serial protocol, the module incorporates a buffer to allow the MCU (slow - 8 bit) to send the data and not have to keep up with the 1Mbps throughput of the rf. On a physical level the signals of the chip look thus:

[![enter image description here][1]][1]

2. >My understanding of "ping" and "pong" is that ping sends a message then pong sends that same message back to ping... is this correct?

Ping Pong is a game and not a well defined technical term. For precision you can define ping-pong as an ``echo`` where the transmitter effectively acknowledges the message by re-transmitting it back to you.

3. >Are RF units very different? Is this one particularly difficult?

RF units can be very different depending on what high level protocol they offer. This unit is somewhere half way between full blown wifi and simple and modulated RF communications. It gives you addressing and error correction as well as a robust communication scheme

This particular unit is made to be relatively "modern", it uses [GFSK](https://en.wikipedia.org/wiki/Gaussian_frequency-shift_keying) - a frequency modulation scheme -to transmit and receive data to uniquely addressable nodes on a number of channels. At 2.4 GHz it is high throughput, [legal](https://en.wikipedia.org/wiki/ISM_band).  It is not the simplest toy.

In terms of simplicity, this module has a lot of examples and documentation, given that it has an arduino library it has a high likelihood of working and succeeding, but you will need to use more advanced microcontroller features to fully utilize the device (e.g. interrupts, DMA).

For other RF options there are lots of things to consider. Going up to wifi requires you to maintain a much more complex stack, meaning more processing power and code, if you want to offer TCP/IP services (say webserver) it is even more code but can be done on an 8 bit arduino. Going down to simpler protocol may win you less power and simpler code but a headache to expand.

 4. >If I just want to send with one receive with the other shouldn't this simplify the code?

You will still need to implement both a receiving and a transmitting application so the work is still all there, it will simplify the higher level logic into separate application which is easier.

5. >What are pipes? How many can I open?

I see nothing about pipes from a cursory glance at the docs, perhaps you can illuminate more on what you are confused about?

In general pipes are a "hole" where an application (in the broadest sense) can stream data and it will be consumed by whoever is on the other end, a black hole of a serial data stream. You can implement a pipe as a high level software construct that will buffer and consume data from peripherals and wait to send it out the RF transmitter, it may also be implemented on a hardware level with discrete buffers and additional logic around the rf transmitter etc. As a conceptual element you can probably use a "pipe" concept for communication between the different devices in your code (e.g. move byte to pipe 1 for device 1, move byte to pipe 2 for device 2, let the "driver" handle order), this is a design paradigm that makes software development easier.

6. >If I have 3 or more of these what changes will I need to make to the code?

The rf module is fully capable of addressing up to 65,536 unique hosts, so the device is fully ready to talk to 3 of your hosts, however the software logic needs to track the addresses and other comms data about each host as well as process the data for them (if its different) in enough time.

If you are expecting this in advance, good design decisions early on (e.g. small API or library) will make this much easier on yourself to add features in the future.

***Final Thought***

If you need a simple echo, this may be a bit overkill for your system, however it is relatively powerful and may make it easier for you to program since you can work with "real-world" data units and send multiple byte packets easily.

I would **highly recommend** you read and understand the [datasheet](https://www.sparkfun.com/datasheets/IC/nRF2401A.pdf) for the RF chip, be thankful that the nice library takes care of the messy details for you, but understanding how it works will certainly help you understand how to use it best.

An 8 bit Atmega may not be powerful enough to process and transmit 3 separate streams together (if they are identical its less difficult) if you require a constant high rate transmission or if you do a significant amount of processing on the arduino before sending you will feel the limitations of the chip and a 32 bit board may be worth looking at.

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