message:
Multiple interrupt lines connection

In my project I need to connect more then 10 I2C sensors(MPU-6050) to Arduino Mega and an interrupt line for each sensor is essential.
Since the Arduino Mega only has several interrupt slots (digital 2, 3, 21,29,19,18), how can it be achieved? Is that using a multiplexer every time I switch sensors and also switching interrupt lines solve the problem?

The code I'm using is Jeff Rowberg's MPU-6050 DMP example, which means interrupt line is essential and important, also very sensitive (a wrong change can cause sudden stop)..

<!-- language: lang-cpp -->

    // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
    // 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
    // Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
    //
    // Changelog:
    //      2013-05-08 - added seamless Fastwire support
    //                 - added note about gyro calibration
    //      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
    //      2012-06-20 - improved FIFO overflow handling and simplified read process
    //      2012-06-19 - completely rearranged DMP initialization code and simplification
    //      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
    //      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
    //      2012-06-05 - add gravity-compensated initial reference frame acceleration output
    //                 - add 3D math helper file to DMP6 example sketch
    //                 - add Euler output and Yaw/Pitch/Roll output formats
    //      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
    //      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
    //      2012-05-30 - basic DMP initialization working

    /* ============================================
    I2Cdev device library code is placed under the MIT license
    Copyright (c) 2012 Jeff Rowberg

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    ===============================================
    */

    // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
    // for both classes must be in the include path of your project
    #include "I2Cdev.h"

    #include "MPU6050_6Axis_MotionApps20.h"
    //#include "MPU6050.h" // not necessary if using MotionApps include file

    // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
    // is used in I2Cdev.h
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif

    // class default I2C address is 0x68
    // specific I2C addresses may be passed as a parameter here
    // AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
    // AD0 high = 0x69
    //MPU6050 mpu;
    MPU6050 mpu(0x69); // <-- use for AD0 high

    /* =========================================================================
       NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
       depends on the MPU-6050's INT pin being connected to the Arduino's
       external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
       digital I/O pin 2.
     * ========================================================================= */

    /* =========================================================================
       NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
       when using Serial.write(buf, len). The Teapot output uses this method.
       The solution requires a modification to the Arduino USBAPI.h file, which
       is fortunately simple, but annoying. This will be fixed in the next IDE
       release. For more info, see these links:

       http://arduino.cc/forum/index.php/topic,109987.0.html
       http://code.google.com/p/arduino/issues/detail?id=958
     * ========================================================================= */

    // uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
    // quaternion components in a [w, x, y, z] format (not best for parsing
    // on a remote host such as Processing or something though)
    //#define OUTPUT_READABLE_QUATERNION

    // uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
    // (in degrees) calculated from the quaternions coming from the FIFO.
    // Note that Euler angles suffer from gimbal lock (for more info, see
    // http://en.wikipedia.org/wiki/Gimbal_lock)
    //#define OUTPUT_READABLE_EULER

    // uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
    // pitch/roll angles (in degrees) calculated from the quaternions coming
    // from the FIFO. Note this also requires gravity vector calculations.
    // Also note that yaw/pitch/roll angles suffer from gimbal lock (for
    // more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
    #define OUTPUT_READABLE_YAWPITCHROLL

    // uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
    // components with gravity removed. This acceleration reference frame is
    // not compensated for orientation, so +X is always +X according to the
    // sensor, just without the effects of gravity. If you want acceleration
    // compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
    //#define OUTPUT_READABLE_REALACCEL

    // uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
    // components with gravity removed and adjusted for the world frame of
    // reference (yaw is relative to initial orientation, since no magnetometer
    // is present in this case). Could be quite handy in some cases.
    //#define OUTPUT_READABLE_WORLDACCEL

    // uncomment "OUTPUT_TEAPOT" if you want output that matches the
    // format used for the InvenSense teapot demo
    //#define OUTPUT_TEAPOT

    #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    bool blinkState = false;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

    // ================================================================
    // ===               INTERRUPT DETECTION ROUTINE                ===
    // ================================================================

    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }

    // ================================================================
    // ===                      INITIAL SETUP                       ===
    // ================================================================

    void setup() {
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        // initialize serial communication
        // (115200 chosen because it is required for Teapot Demo output, but it's
        // really up to you depending on your project)
        Serial.begin(115200);
        while (!Serial); // wait for Leonardo enumeration, others continue immediately

        // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Arduino
        // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
        // the baud timing being too misaligned with processor ticks. You must use
        // 38400 or slower in these cases, or use some kind of external separate
        // crystal solution for the UART timer.

        // initialize device
        Serial.println(F("Initializing I2C devices..."));
        mpu.initialize();

        // verify connection
        Serial.println(F("Testing device connections..."));
        Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

        // wait for ready
        Serial.println(F("\nSend any character to begin DMP programming and demo: "));
        while (Serial.available() && Serial.read()); // empty buffer
        while (!Serial.available());                 // wait for data
        while (Serial.available() && Serial.read()); // empty buffer again

        // load and configure the DMP
        Serial.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        // supply your own gyro offsets here, scaled for min sensitivity
        mpu.setXGyroOffset(220);
        mpu.setYGyroOffset(76);
        mpu.setZGyroOffset(-85);
        mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

        // make sure it worked (returns 0 if so)
        if (devStatus == 0) {
            // turn on the DMP, now that it's ready
            Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);

            // enable Arduino interrupt detection
            Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(0, dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();

            // set our DMP Ready flag so the main loop() function knows it's okay to use it
            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            dmpReady = true;

            // get expected DMP packet size for later comparison
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {
            // ERROR!
            // 1 = initial memory load failed
            // 2 = DMP configuration updates failed
            // (if it's going to break, usually the code will be 1)
            Serial.print(F("DMP Initialization failed (code "));
            Serial.print(devStatus);
            Serial.println(F(")"));
        }

        // configure LED for output
        pinMode(LED_PIN, OUTPUT);
    }

    // ================================================================
    // ===                    MAIN PROGRAM LOOP                     ===
    // ================================================================

    void loop() {
        // if programming failed, don't try to do anything
        if (!dmpReady) return;

        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {
            // other program behavior stuff here
            // .
            // .
            // .
            // if you are really paranoid you can frequently test in between other
            // stuff to see if mpuInterrupt is true, and if so, "break;" from the
            // while() loop to immediately process the MPU data
            // .
            // .
            // .
        }

        // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();

        // get current FIFO count
        fifoCount = mpu.getFIFOCount();

        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            // reset so we can continue cleanly
            mpu.resetFIFO();
            Serial.println(F("FIFO overflow!"));

        // otherwise, check for DMP data ready interrupt (this should happen frequently)
        } else if (mpuIntStatus & 0x02) {
            // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            // track FIFO count here in case there is > 1 packet available
            // (this lets us immediately read more without waiting for an interrupt)
            fifoCount -= packetSize;

            #ifdef OUTPUT_READABLE_QUATERNION
                // display quaternion values in easy matrix form: w x y z
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                Serial.print("quat\t");
                Serial.print(q.w);
                Serial.print("\t");
                Serial.print(q.x);
                Serial.print("\t");
                Serial.print(q.y);
                Serial.print("\t");
                Serial.println(q.z);
            #endif

            #ifdef OUTPUT_READABLE_EULER
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetEuler(euler, &q);
                Serial.print("euler\t");
                Serial.print(euler[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(euler[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(euler[2] * 180/M_PI);
            #endif

            #ifdef OUTPUT_READABLE_YAWPITCHROLL
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                Serial.print("ypr\t");
                Serial.print(ypr[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(ypr[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(ypr[2] * 180/M_PI);
            #endif

            #ifdef OUTPUT_READABLE_REALACCEL
                // display real acceleration, adjusted to remove gravity
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                Serial.print("areal\t");
                Serial.print(aaReal.x);
                Serial.print("\t");
                Serial.print(aaReal.y);
                Serial.print("\t");
                Serial.println(aaReal.z);
            #endif

            #ifdef OUTPUT_READABLE_WORLDACCEL
                // display initial world-frame acceleration, adjusted to remove gravity
                // and rotated based on known orientation from quaternion
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
                Serial.print("aworld\t");
                Serial.print(aaWorld.x);
                Serial.print("\t");
                Serial.print(aaWorld.y);
                Serial.print("\t");
                Serial.println(aaWorld.z);
            #endif

            #ifdef OUTPUT_TEAPOT
                // display quaternion values in InvenSense Teapot demo format:
                teapotPacket[2] = fifoBuffer[0];
                teapotPacket[3] = fifoBuffer[1];
                teapotPacket[4] = fifoBuffer[4];
                teapotPacket[5] = fifoBuffer[5];
                teapotPacket[6] = fifoBuffer[8];
                teapotPacket[7] = fifoBuffer[9];
                teapotPacket[8] = fifoBuffer[12];
                teapotPacket[9] = fifoBuffer[13];
                Serial.write(teapotPacket, 14);
                teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
            #endif

            // blink LED to indicate activity
            blinkState = !blinkState;
            digitalWrite(LED_PIN, blinkState);
        }
    }

body:
One possible solution is to use a "global" interrupt pin which all the sensors use, and also normal GPIO pins to work out which interrupt has occurred.

Feed the interrupt signals into a multiple-input OR gate (if they are active HIGH) or a multuple-input AND gate (if they are active LOW).  The output of that AND gate goes to a single INT pin.  Each interrupt signal also goes to a normal IO pin.  When the interrupt pin triggers the ISR can then look at the IO pins to determine which of the interrupt signals that triggered the interrupt.

![enter image description here][1]

For fastest operation use IO pins that are on the same port and use direct register reading for that port to see which bits are on and which are off.

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


sender: user

sender: assistant

body:
Just FYI, the interrupt is not essential. If you can write efficient code you can read an MPU(DMP) without it (UNO, been there, done that). But that is only for one MPU. I doubt if an UNO can keep up with 10, no idea about the faster processors. In any case, even with interrupts, I doubt if an UNO could keep up with 10. Keep googling and you will find a note how to change the sampling rate to slow the MPU down.

The code you referenced provides AHRS (Attitude Heading Reference System) - I would be real curious to see what projects needs 10 of those :) Sounds like fun.


message:
Stuck in a small confusion about Infrared leds and receivers?

I have a very simple idea I want to implement. I am making a home automation using an Arduino Uno. I am familiar with Arduino programming but the problem is what kind of IR receiver I need to buy if i want my TV remote (or similar) to communicate with my Arduino.

Can you suggest me any example (low cost, and available in India)?

body:
Element14 has an India based store, and they carry these IR devices.
Here is one for 66 rupees:
http://in.element14.com/vishay-semiconductor/tsop38238/ir-receiver-45m-38khz-th/dp/2395954?MER=MER-BPR-4PPM-SP-VSHY-OD&

You may want to do research into what the carrier frequency of your remote is also. Most are generally around 35 - 40khz, and the receiver I provided a link to is 38khz. It should work, but if you want to be safe I suggest you look it up. Or, if you have an old TV lying around, you can pull one out of that.

Hope this helps.


message:
Proportional water flow control

I've been looking at water flow control with Arduino and I'm finding a huge difficulty in managing to do an 'analog' control on water flow. The mainstream solution seems to be the well known solenoid valve, however those seem to be binary (full flow, no flow), and I'm looking for a more variable answer.

Is it possible to get middlegrounds with solenoids? Maybe actuating them with less voltage or amperage will cause it to partially actuate? If not, does anyone know of embedded solutions using servos or steppers maybe?

body:
> Is it possible to get middle grounds with solenoids?

No.  The solenoid will be all or nothing.  If you have used a magnet, you have seen that the force decreases rapidly with distance.  As you move something closer, it will typically snap to a magnet at one point.  The same thing happens in a solenoid valve: once you apply enough voltage to start motion, the motion will complete.

Side note: that is actually a common trick to saving much power with solenoid valve.  You might apply 12 V to actuate, but then you can reduce the voltage very low (maybe 2 V or lower) and the valve will still say actuated.

So if you want flow, you need a flow control valve.  A common 1/4 turn ball valve will provide the fractional flow you seek.  You should be able to hook a servo or gear motor to that.

A typical ball valve will not provide a constant change of flow with angle.  That means the change in flow between the first 5 degrees opening will be large while the last 5 degrees of motion will have little effect.  If the application is not critical, that would be fine.

If you want more precise flow control, valves are made with a particular cutout in the ball that makes the flow control more linear.  You can get a commercial type valve with motor attached in cost range of 100 $US.  For hooking up to an Arduino, a Belimo flow valve ([one example vendor][1]) only seems appropriately named

![enter image description here][2]

These are commercial type valves used to control water in heater systems and such.  They take a 0 - 10 V input signal as control and will rotate the vale.  The keyword search is "motorized flow control valve" and that will find you many.  These are not exotic, you will find many in all sorts of sizes.  You may even find from a local plumbing supplier where you can pick one up at will call.

  [1]: http://www.belimo.us/americas/ccv.html
  [2]: https://i.stack.imgur.com/EHiKa.jpg


body: Do you use a pump to circulate the water flow, if so maybe you have a better result with a variable pump speed (PWM), in state of a variable valve opening.


message:
The code of ISR executes twice

i am using Arduino Mega.. ANd this is the code:

    void bump(void);

    void setup()
    {
        pinMode(19,INPUT);
        attachInterrupt(4,bump,HIGH);
        pinMode(13,OUTPUT);
    }

    void loop()
    {

    }

    void bump()
    {
       for(float i = 0; i < 90000; i++){
       digitalWrite(13,HIGH);
       }
       for(float i = 0; i < 10000; i++){
       digitalWrite(13,LOW);
       }

    }

Although i give +5 V to it once, the LED will blink twice...!
What is the solution?

body:
After wondering over it for quite a long time, I finally came to the conclusion, that the interrupt should be made to trigger at RISING edge, **if I want it to go into ISR the moment it gets HIGH.**

Hence the setup line was change to

    attachInterrupt(4,bump,RISING);

And the cod e works well.
I suppose that is because, when it receives a HIGH signal, than the period for which it receives HIGH is a bit long, during which it adds another interrupt into the queue, and so the ISR is executed once again.


message:
Is it harmful to write to unused bits in PORT registers?

Background:
I'm looking at writing a library to drive an LED matrix panel (one of these:http://www.adafruit.com/product/607) from my newly acquired Arduino Due.  My background is C++ programming, not electronics.

I'm planning to experiment with various optimisations of the code for memory and speed, but one constant is that I would like to be able to send the data to the matrix with single memory writes to port registers without having to use masking operations to leave certain bits unaffected.  As I need to send 6 bits of data with a clock signal, I figured this could be easy with an 8 bit write to one byte of a port register.  The 8th bit/pin could be used as the latch or some other used line.

Looking at the nice pinout diagram that someone has kindly put together (http://forum.arduino.cc/index.php/topic,132130.0.html), I was pretty shocked to discover that my plans weren't going to be as easy as I would have liked.  There are only two circumstances where there are whole bytes of port registers that connect to digital pins (Port A byte 1 and Port D byte 0).  All other bytes have "holes" in them, for example Port C byte 0 has no connection for bit 0, but has bits 1-7;

While two complete bytes is enough (I actually only need to use 13 pins to control the display, plus ground connections), the pins of the available two are spread out in a way that would make it a little awkward for me to make a stripboard shield as I intended due to the pins on the Arduino boards not being evenly spaced (why is that?) and I'm guessing that since most of the digital pins in Port A byte 1 are used for communication pins (including RX0 and TX0) I would lose my ability to print to the debug log.  As a result, I've ruled out using those port registers.

That leaves me with bytes 0 and 1 of Port C.  There are just enough pins available with those bytes and they are grouped nicely on the double connector at the bottom of the board (Digital pins 33-40 and 48-51), however some bits in those bytes are not mapped to Arduino IO pins.

Would it be bad if I were to write to bits of a port register that do not have Arduino IO pins assigned to them?  Would the answer depend on whether I had set those bits to be inputs or outputs using the Output Write Enable Registers?  I'm assuming that these bits are used for IO pins on the SAM3X8E chip but just not made available to the Arduino boards.

body:
If the pins have no connection to the outside world (i.e., they don't have any actual pin associated with them on the SAM3X chip) then writing to the PORT (or indeed any other register associated with them) will have no effect whatsoever.

If they have a pin but that pin is not connected to anything, then there will be little effect.  There may be slightly increase current draw as the pin switches on/off, or you enable/disable the internal pullup resistor, but that's all.

If the pin exists and is connected to something on the board - maybe a button or LED, then you will basically be providing an output to that item.  If it's an LED it will flash.  However, if it's a button, and you provide an output opposite of its active state (i.e., provide a HIGH when it normally connects to ground when you press it) and that button lacks any current limiting resistance, then you could risk burning out that IO pin if the button gets pressed.

If the pin just goes straight to a header, then as long as nothing gets connected to that header then there will be no effect other than as detailed in the "pin present on the chip but not connected".


message:
Multiplexing help for relay and pwm

I have to control with an Arduino UNO and xbee shield:

- 9 5V relay
- 9 RGB LED

What kind of multiplexing can you advice me? Do I have to use external power supply (like 12V DC external from arduino or from vcc)? Is there any kind of already ready-to-use shield?

### EDIT
I'm planning to use a [8 relays shield][1] plus one single relay

  [1]: http://tinyurl.com/peagrd5

body:
You can use shift registers to control the relays. This will only use 3 pins and allow you to use the xbee.

For the RGB LEDs you can use the [TLC5940][2] to control 16 channels, so you will need two, giving you 32 channels. This is a PWM chip with serial interface.

Considering you will be using the board linked. It is driven by transistors, so you can use the shift registers.

For the power supply, if you will be operating all of the relays at the same time it will draw about 650 mA (9x72mA), you will need a separate 5V power supply for the relay board, as I believe drawing that much current will heat the board and regulator a lot. If one at a time it will not draw too much, so its possible you can run it all off the Arduino.

A [forum][1] post of someone running 360 relays with shift registers.

  [1]:http://forum.arduino.cc/index.php?topic=94255.0
  [2]: https://www.sparkfun.com/products/10136


message:
How can I best control various high power LEDs without using PWM

I want to be able to dim various high powered (20mA) LEDs in an array (8X12 LEDs). I do not need individual control, but would like to be able to dim each row (or two rows together) so that I can create gradients.

An important caveat is that I can't use pulse width modulation (PWM) as there should be no flashing whatsoever, even if it is invisible to humans.

**How can I best achieve this?**
(I do not care about energy efficiency)

The fist thing I found which seemed to be the right solution in the beginning is using digital potentiometers as explained in [this tutorial][1]. However they only support low currents so I can't use one channel for 8 or 16 LEDs.
Maybe I could use various digipots in parallel with one Arduino, each powering 1 LED per channel? But that sounds overcomplicated and a nightmare to wire up. Is there a more elegant solution?

  [1]: http://www.arduino.cc/en/Tutorial/SPIDigitalPot

body:
The figure below illustrates a method of current control.  It shows four LEDs in a 2x2 arrangement; one  would adapt the number of LEDs in series or parallel in accord with how one's array is wired, what voltages are available, LED current requirements, transistor power limitations, etc. *[Edit: See transistor-power example calculation at end.]*

Each separately-controlled group of LEDs would need one such circuit.  Each circuit needs one control voltage (eg, from a DAC or a digital potentiometer voltage divider circuit) and needs one transistor per series chain.

![figure 1, cc circuit][1]

**Circuit Operation:**

Suppose the following conditions hold.

- Q1 and Q2 are equivalent transistors and Vbe is 0.7 V typ. (one diode drop)
- D1, D2, D3, D4 are equivalent LEDs
- Resistors R1, R2 are small and equal (eg 1–30Ω)
- V1 is some fixed DC voltage, eg about 1 V
- V > 2*Vf + Vbe + VR where Vf = typical forward voltage of D1...4

Under these conditions, V1 will drive current into the bases of Q1 and Q2, causing transistor-amplified current to flow through R1 and R2 and maintain the condition V1 = Vbe + VR1 = Vbe + VR2.

Here is a concrete example:  Suppose we want 23 mA through each LED and that R1=R2=17Ω. VR = IR = 0.023 mA · 17 Ω = 0.391 V.  If Vbe is about 0.7 V, then we set V1 = 0.7 + 0.391 V or about 1.09 V to get 23 mA through each LED.  More generally, to get current I through the LEDs we solve V1 = Vbe + VR = 0.7 + IR = 0.7 + I·17.

**Base current:**

The amount of current required from the V1 voltage source depends on transistor [hFE or β](http://en.wikipedia.org/wiki/Bipolar_junction_transistor#h-parameter_model).
Eg, if β is about 100 and ILED is 20 mA then each transistor will need about 20/100 mA or about 200 μA of base drive.  This amount of current probably could be delivered by a voltage divider based on an AD5206 (the digital potentiometer chip that's used in the [SPIDigitalPot](http://www.arduino.cc/en/Tutorial/SPIDigitalPot) tutorial mentioned in the question).

**Power Dissipation:**

The AD5206 digital potentiometer datasheet shows an absolute maximum rating for Package Power Dissipation of  (TJMAX-TA)/θJA.  If ambient TA is 25℃ and θJA is 70°C/W (as for a SOIC package) this gives (150-25)/70 = 1.8 W max package power.  However, it would be reasonable to limit dissipation to under half a watt.  In the 10 KΩ version of the AD5206, that means a little less than 2.9 mA maximum per channel.  [I = √(0.5 W /(6 channels * 10000Ω)).]  If several low-beta transistors are used to drive several strings of LEDs, 2.8 mA might be marginal.

**Voltage-divider Linearity:**

Only a small fraction of the current through a voltage divider can be drawn off without upsetting the division ratio.  A [unity gain buffer](http://en.wikipedia.org/wiki/Buffer_amplifier#Voltage_buffer_examples) amplifier [as in the following figure] can be used to increase linearity of voltage-divider output by providing a high-impedance connection to the divider.

![figure 2, unity gain buffer with voltage divider input][2]

(In the figure above, R1 and R2 are not related to R1 and R2 of the previous figure.  Here, R2 represents a digitally-variable resistor.  Choose R1 and R3 so that V1's range is from slightly below Vbe to slightly above  Vbe + ImaxR, where Imax is the maximum LED current desired.  For example: Suppose V=5 V, that R2's total resistance is 10 KΩ, that R is 15Ω, that Vbe is 0.7 V, and Imax is 25 mA.  Let RT = R1+R2+R3.  Now R3/RT = Vbe/V = 0.7/5 = 0.14, and R1/RT = (V - Vbe - ImaxR)/V = (5 - 0.7 - 0.025·15)/5 = 3.925/5 = 0.785.  Thus R1+R3 = 0.925·RT, whence 0.075·RT = R2 = 10 KΩ, giving RT = 133 KΩ, R1 = 105 KΩ, and R3 = 19 KΩ.  With these R1 and R2 values, each digital pot step should give a change in LED current of 25/256 mA, or about 98 μA.)

*[Edit:  When V1 is set to less than VBE, no current will flow through the LEDs.  That is, to turn off the controlled LEDs, set V1 to VBE or less.]*

**PWM with RC filter:**

It may be worthwhile to experiment with using a PWM-driven low pass [RC filter](http://en.wikipedia.org/wiki/RC_circuit) to supply V1, possibly avoiding need for buffer amplifiers and digital potentiometers.  See eg “Arduino’s AnalogWrite – Converting PWM to a Voltage”
by Scott Daniels at [provideyourown.com](http://provideyourown.com/2011/analogwrite-convert-pwm-to-voltage/), and also see the [filter-calculation page](http://sim.okawa-denshi.jp/en/PWMtool.php) it refers to.  You might need an oscilloscope to verify the design and its quality of results, and might need to use several RC filter stages in a row to adequately filter out ripple, but it can be done, at the cost of slower response to control changes.

**Transistor-power example calculations:**

Letting  VCE, ICE, VBE, and IBE represent collector-to-emitter and base-to-emitter voltages and currents, transistor power dissipation is VCE·ICE+VBE·IBE.  Because VBE·IBE is likely to be sub-milliwatt, we ignore it in following, taking P ≅ VCE·ICE.

In the LED-driving circuit,  VCE = V – VLEDs – Vsense, where VLEDs is the series voltage across the chain of LEDs the transistor controls, and Vsense is the voltage across the sense resistor (ie, across R1 or R2 in the top figure).

In general, it is a good idea to keep Vsense small (under a volt) to allow a wider compliance range – ie, so that LED current is the same over a wider range of variation of supply voltage V.  Thus, the approximation  VCE ≅ V – VLEDs is reasonable.

Here is a concrete example: Suppose we have eight LEDs in series, and they are white LEDs with about 3.6 V forward drop at 20 mA. [LEDs of different colors may have different drops; eg see [LED color chart](http://www.oksolar.com/led/led_color_chart.htm) at oksolar.com.]  Then VLEDs = 8·3.6 V = 28.8 V. We need V(BR)CEO > V > VLEDs + VBE + Vsense, where  V(BR)CEO = collector-emitter breakdown voltage (which is 40 V min. for 2N3904 or 2N2222).  Allowing a volt for Vsense and 0.7 V for VBE we have V > 28.8 + 0.7 + 1 = 30.5 V.  Let's suppose V=32 V.  Then P < (32–28.8)·0.020 W = 64 mW.  Thus a small general purpose NPN transistor will work, for example a 2N3904 (rated at 350 mW to 1 W, depending on package, before derating for ambient and heatsinking) or a 2N2222 (similarly rated).

For a second example, suppose VLEDs = 8·1.7 V = 13.6 V (for, eg, eight infrared LEDs at 50 mA) and V=32 V.  Then P ≅  (32–13.6)·0.050 W = 920 mW, so a larger (and heatsinked) transistor would be needed.  Or, V could be decreased, say to 16 V, giving  P ≅  (16–13.6)·0.050 W = 120 mW, allowing use of a small transistor.

For a third example, suppose eight LEDs are paralleled (rather than seriesed), that VLEDs = 2.0 V at 20 mA, that Vsense is about 0.4 V at desired operating point, and that V=5 V.  The transistor will need to drop 5-2-0.4 V = 2.6 V at 160 mA, which is 416 mW, probably large enough to require a heatsink.  [Note:  if LEDs are placed in parallel and driven by a single transistor, some of them probably will be dimmer than others; “current hogging” may occur in some of the LEDs, making them brighter than the others.  However, many cheap flashlights connect LEDs in parallel without individual current control.]

  [1]: https://i.stack.imgur.com/9vx8w.jpg
  [2]: https://i.stack.imgur.com/rZykZ.jpg


message:
Nano destroyed?

Board: OE Gravitech Nano
Is it possible to destroy the board if there are a voltage on a Analog pin while the board is not powered?
I have a application that use a analog (speed) voltage 0-4,9 from a GPS module, this worked very nice for a hour of 10, after that the voltage seems to be not constant available.
Maybe the user have powered off the Arduino while driving the machine.

Regards,
Rien

body:
Assuming you're talking about the device with [this schematic][1] (or similar), the "analog" pins go directly to Atmel AVR I/O pins with no series resistance, so yes, it's quite possible to damage the microcontroller. Add some series resistance of a few K and you'll have a better chance of the part surviving such an event.

The voltage on any pin should not, under any circumstances exceed Vcc+ 0.5V as the [datasheet][2] specifies, however it's usually okay under non-operational conditions if the current is limited to much less than the 40mA. A 4.7K resistor would limit the current to less than 1mA with a 5V input.

 ![enter image description here][3]

  [1]: http://www.mouser.com/pdfdocs/ArduinoNano30_schematic.pdf
  [2]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [3]: https://i.stack.imgur.com/lBahq.png


message:
How to clear FIFO buffer on MPU6050?

my MPU6050 works very unstable , the problem is unable clear excessed FIFO buffer on MPU6050, I am using Jeff Rowberg's MPU library and according to his DMP example but without using interruptions,here is my modified code but I've tried several method listed in the library to clear buffer but doesn't work..

Thanks very much!

    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"
    #include "Wire.h"

    MPU6050 mpu(0x69); //AD0=High

    //MPU control/status vars
    bool dmpReady = false;
    uint8_t mpuIntStatus;  //actual interrupt status byte
    uint8_t deviceStatus; //device status , 0 = success ,
    uint16_t packetSize; //expected DMP packet size (defult 42) -- ?
    uint16_t fifoCount; //count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO buffer storage

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    volatile bool mpuInterrupt = false;
    //void dmpDataReady() {
    //  mpuInterrupt = true;
    //}

    // put your setup code here, to run once:
    void setup() {
      //join I2C bus
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 48; // 400kHz I2C clock (200kHz if CPU is 8MHz)
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif
      //initialize serial communication
      Serial.begin(115200);
      while(!Serial); //common for Leonardo issues

      //initialize the mpu
      Serial.println("Call MPU6050 Lib to initialize devices...");
      mpu.initialize(); //initialize I2C device by using MPU6050 library

      //verify connection
      Serial.println("Tesing device connections");
      Serial.println(mpu.testConnection() ? F("MPU6050 connection test successed ") : F("MPU6050 connection test failed"));

    //  //wait for begin , uncomment if we need wait user interruption
    //  Serial.println("Press any button to begin");
    //  while (Serial.available() && Serial.read()); // empty buffer
    //  while (!Serial.available());                 // wait for data
    //  while (Serial.available() && Serial.read()); // empty buffer again

      //load and configure DMP
      Serial.println("initializing DMP");
      deviceStatus = mpu.dmpInitialize(); //use MPU6050 library to inilisalize the dmp

     //feed offsets
      mpu.setXGyroOffset(220);
      mpu.setYGyroOffset(76);
      mpu.setZGyroOffset(-85);
      mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

      //make sure it works
      if (deviceStatus == 0) {
        Serial.println("DMP initialization success, now enable DMP for use");
        //turn on DMP
        mpu.setDMPEnabled(true); //use MPU6050 library to enable DMP)

        //wait for first interrup . currently just leave it false automatically
        mpuInterrupt == false;

        //let main llop know it's ok to use DMP, set dmpRead flag to ture
        dmpReady = true;
        Serial.println("DMP is ready to use.");

        //get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
      } else {
        //ERROR! , device status !=0 when initializing DMP
        Serial.print("DMP initialization failed when using MPU6050 library:");
        if (deviceStatus == 1) {
          Serial.println(" intial memory load failed");
        } else if (deviceStatus == 2) {
          Serial.println(" failed to update DMP configuration");
        } else {
          Serial.print(" unknow error with code: ");
          Serial.println(deviceStatus);
        }
    }
    }

    int ticket = 1;
    void printOnlyOnce (String message){
      if (ticket == 1){
       Serial.println(message);
       ticket = 0 ;
      } else {
        return;
      }
    }

    void loop() {
      //if DMP not ready don't do anything
      if (!dmpReady) {
        printOnlyOnce("MAIN LOOP: DMP disabled");
        return;
      } else {

        //testing overflow
        if (fifoCount == 1024) {
          mpu.resetFIFO();
          Serial.println("FIFO overflow");
        } else {

        //wait for enough avaliable data length
        while (fifoCount < packetSize) {
          //waiting until get enough
          fifoCount = mpu.getFIFOCount();
        }

        //read this packet from FIFO buffer
        mpu.getFIFOBytes(fifoBuffer,packetSize);

        //track FIFO count here is more then one packeage avalible

        //reset fifo count
        fifoCount -= packetSize ;
        Serial.println(fifoCount);

        if (fifoCount > 2) {
            ////// clear fifo buffer
        }
        //display stage
                    // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                Serial.print("ypr\t");
                Serial.print(ypr[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(ypr[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(ypr[2] * 180/M_PI);
      }
      }
    }

body:
Yank,
I ended up clearing the buffer after every read.  In your code it would be following the line

    //read this packet from FIFO buffer
    mpu.getFIFOBytes(fifoBuffer,packetSize);

I added

    mpu.resetFIFO();

I came to this conclusion after watching when the over flows occurred. The fifo buffer is adding on to the end of the buffer, and when it gets full, rather than wrap, it over flows. Reading does not seem to remove data from buffer in any way.  By clearing the buffer you might be discarding data, but the DMP is doing the integration for AHRS for you, so you really do not need to worry about dropping data since you are only interested in the current pitch,roll,yaw or Euler or whatever, at least that was my case.
I am running it on an Arduino UNO shield prototype and it is rock solid stable (at the default 100 hz rate). See spiked3.com PiPlate / Pilot.


body:
To prevent overflow problems, please, go to MPU6050_6Axis_MotionApps20.h and modify that line:

    0x02,   0x16,   0x02,   0x00, **0x01**                // D_0_22 inv_set_fifo_rate

The value in bold is the objective! Change it to `0x03` or `0x04` or `0x05` to reduce the Hz of rate. I am using `0x03` and not getting error values, junk data, or overflows anymore.


body:
What if we can increase the size of the FIFo Buffer.

    uint8_t fifoBuffer[64]; // FIFO storage buffer

What if I change it to lets say:

    uint8_t fifoBuffer[1024]; // FIFO storage buffer

and then change :

    if ((mpuIntStatus & 0x10) || fifoCount == 16384) { // I changed 1024 -> 16384
        // reset so we can continue cleanly
        mpu.resetFIFO(); // Resets the FIFO buffer when set to 1 while FIFO_EN equals 0.
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    }

Please check these changes.


message:
Activate a DC motor for a fixed amount of time

I have a single simple DC motor that upon a condition I wish to let it run for 3 minute. How can I do it in Arduino? a simple addition to the code will be great help.

As I use Adafruit motor shield this is my current code:

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_PWMServoDriver.h"

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Adafruit_DCMotor *myMotor = AFMS.getMotor(1);

    void setup() {
       Serial.begin(9600);           // set up Serial library at 9600 bps
       AFMS.begin();  // create with the default frequency 1.6KHz
    }

    void loop() {
    IOvalue = 1000

    if (IOvalue = 1000) {

     //this is the motor I wish to run for 3 min
       myMotor->setSpeed(25);
       myMotor->run(FORWARD);
       delay(100);
     }
    }

Thanks a lot

body:
    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_PWMServoDriver.h"

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
    boolean motorRunning = false;
    unsigned long motorStartMillis;
    unsigned long motorRunMillis = 180000;

    void setup() {
       Serial.begin(9600);           // set up Serial library at 9600 bps
       AFMS.begin();  // create with the default frequency 1.6KHz
    }

    void loop() {
      IOvalue = 1000

      if (IOvalue = 1000) {
        //this is the motor I wish to run for 3 min
        myMotor->setSpeed(25);
        myMotor->run(FORWARD);
        motorStartMillis = millis();
        motorRunning = true;
      }

      // check if motor is running and time-to-run has elapsed
      if( motorRunning && (millis()-motorStartMillis > motorRunMillis) )
      {
        myMotor->setSpeed(0);
        myMotor->run(RELEASE);
        motorRunning = false;
      }
    }


message:
Making my own libraries

Does anyone know of a site or book where you can learn how to create, or for first reed, libraries. Because I think the libraries I use are sometimes unnecessary complicated, or have similar features, for example [Wire][1] and [OneWire][2].

I think, these make my sketch unnecessary big, when I need both of them.

  [1]: http://www.arduino.cc/en/Reference/Wire
  [2]: http://playground.arduino.cc/Learning/OneWire

body:
Arduino has a library tutorial here: http://www.arduino.cc/en/Hacking/LibraryTutorial

and a formal specification here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

these explain the specifics to making arduino libraries, like the propeties files, the keywords file, and the directory structure. Most of that is unnecessary though.

Anyway, there are not many differences between the actual code in an arduino library and the normal code you write for arduino sktech. The only major ones being that

 - The arduino preprocessor doesn't generate function declarations - you have to make your own header file
 - You can't use setup or loop

Other than that, its just normal c++ code that exposes a particular interface and provides an implementation. If you want the library to work well for a lot of users, you will need to put in the extra work to make it run on all the different arduino hardware variants.

Making libraries for c++ often involves creating .a, .so, .dll etc. files of compiled code that new programs can link against, but arduino compiles everything from source for every sketch so you don't need to worry about that here.


body:
To address your query about libraries making sketch code too big...

I have recently completed (or rather, am in the process of completing) my first library, [SevenSegmentSL1255][1]. I too was concerned about the growing size of the library, as I incorporated more and more ideas. So I decided to plan for a "Lite" version, [SevenSegSL1255Lite][2], so that the casual user would not feel to overwhelmed and also to reduce the memory footprint, for simple sketches.

However, after reading the [Arduino page on the build process][3], I discovered that the whole library is not necessarily included in all sketches:

> The .c and .cpp files of the target are compiled and output with .o
> extensions to this directory, as is the main sketch file and any other
> .c or .cpp files in the sketch and any .c or .cpp files in any
> libraries which are #included in the sketch.
>
> These .o files are then linked together into a static library and the
> main sketch file is linked against this library. *Only the parts of
> the library needed for your sketch are included in the final .hex
> file, reducing the size of most sketches.*

So you see, from a memory footprint point of view, no matter how big the library may be, the resultant compiled sketch can still be quite small, depending on the amount of the library that is called for the sketch. From my point of view, this makes the "Lite" version of my library now somewhat redundant. Although, the argument for a simpler, more user friendly library may still exist.

As an aside, the resources that I used in creating the library are listed below:

 - [Writing a Library for Arduino][4]
 - [Arduino Style Guide for Writing Libraries][5]
 - [error in using overloaded constructor][6]
 - [Memory][7]
 - [Style Guide][8]

  [1]: https://github.com/greenonline/SevenSegmentSL1255
  [2]: https://github.com/greenonline/SevenSegmentSL1255Lite
  [3]: http://www.arduino.cc/en/Hacking/BuildProcess
  [4]: http://www.arduino.cc/en/Hacking/LibraryTutorial
  [5]: http://www.arduino.cc/en/Reference/APIStyleGuide
  [6]: http://forum.arduino.cc/index.php?topic=36935.0
  [7]: http://www.arduino.cc/en/Tutorial/Memory
  [8]: http://www.arduino.cc/en/Reference/StyleGuide


message:
Arduino 16x2 LCD Black Boxes

I hooked up a 16x2 Arduino compatible LCD yesterday and made sure all the connections were according to the program and the schematics provided all over the web. My contrast is adjusted perfectly but the problem is that there are black boxes on the top line while the lower one is empty.

[![Black boxes on top row only of LCD][1]][1]

I know this question has been asked many times but no one has answered the question other than saying, "Check your contrast pin". I'm using the default sample code provided in the Arduino IDE.
HELP!

Regards.

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

body: Connect your RW pin to Ground.


body:
Are you using an LCD driver board that has 4 connections between it and the arruino, or do you have the LCD directly connected?

If using a driver board, download Liquid Crupystal Library [here][1]

Ten make sure to have the library running in that startup code.

  [1]: http://playground.arduino.cc/Main/LiquidCrystal


body:
I have done some Googling across the web and it turns out that this can be caused by a couple of things:

 - Incorrect wiring.
 - Wiring of LCD backwards (ie 1 to 16 and 16 to 1).
 - Faulty wiring (ie broken cables & dry joints).
 - Incorrect initialization of the LCD.
 - Buggy software.
 - Damaged screen.

The LCD screen that you have is a based on the Hitachi HD44780 chipset. It is the most common interface for text-based LCDs. It can be identified by the 16-pin interface. I2C is the next most common interface and is distinguishable as it has a 4-pin (sometimes 5-pin) interface.

Lets assume that your screen isn't damaged. From the details in your question, it sounds like your contrast is working just fine. The list above can be shrunk to just 2 things: bad wiring and/or bad code. Lets eliminate both of those by using known working software and known working circuit.

Arduino has an LCD library with example programs. Details for this library, including a **wiring diagram**, can be found over at the [Arduino site in the Reference section][1]. I use these example sketches to test my wiring connections before I write my own program. I recommend using the [Autoscroll][2] example.

[![Wiring Diagram][3]][3]
Schematic:
[![Schematic][4]][4]
These diagrams are from the [Arduino Autoscroll page][2]. **I highly suggest that you read this page thoroughly.**

The code can be easily uploaded into your Arduino, through the IDE, by going into `File` > `Examples` > `LiquidCrystal` > `AutoScroll`, then `Sketch` > `Upload`.
You should see the sketch print the characters 0 to 9 on the top line (with autoscroll off), then moves the cursor to the bottom right (turns autoscroll on,) and prints the characters 0 to 9 on the bottom line, but as it prints each character the display should move one to the left.

If you get this example program to work then you know that you have a working LCD and also that your wiring is OK as well.

  [1]: https://www.arduino.cc/en/Reference/LiquidCrystal
  [2]: https://www.arduino.cc/en/Tutorial/LiquidCrystalAutoscroll
  [3]: https://i.stack.imgur.com/w3zqN.png
  [4]: https://i.stack.imgur.com/kBqxP.png


body: Your contrast is just fine. The black boxes indicate that your LCD isn't correctly initialized. Poor connections and / or bad code is to blame. So focus your debugging there.


body: Alright guys thanks for everything! I've found the solution. It was a bad solder.


message:
Do I have to use an external power supply when connecting an ultrasonic sensor to Arduino?

This might be a very stupid question but please bear with me. So I am using an HC-SR04 Ultrasonic sensor model (5 V) and I want to connect it to Arduino Uno. Do I have to use an external power supply for the ultrasonic sensor (just like with the motors) in order to connect it to the Arduino? Or can I just use the 5 V pin?

body:
From the question I assume you power your Arduino via USB in which case you don't need an external supply. The HC-SR04 draws 15 mA with is far below the specifications for USB. I did this myself some time ago:

![enter image description here][1]

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


message:
Is my Arduino Ethernet Shield broken?

I have an Arduino setup from which I can control my RGB LED strip from my computer using LAN.

It worked like a charm in the start, but after two days, my Ethernet Shield W5100 for Arduino Uno stopped working, and I can't figure out why.

When I connect the Ethernet Shield, the red LED "pwr" is solid red and the "FULLD" flashes orange every second.

**The setup:**

I have followed an Adafruit guide, connecting the Arduino as such: ![Image from Adafruit.com][1]

On top of the Arduino, I have the Ethernet Shield. All this is powered by an 12V/4A power supply connected to the Arduinos 2.1mm jack.

As I said, this setup worked fine for a few days. While it was on, I noticed the Arduino getting somewhat hot, but some google searches assured me that Arduino Uno can handle high temperatures, so I did not pay any attention to it.

The LED strip is not too long - about 2 meters with about 150 LEDs.

**What I have tried:**

 - When I detach the Arduino from my breadboard, the Ethernet Shield
   will still not connect
 - I have tried connecting the Shield to another Power Supply (Computer USB) using another Arduino, but the Shield would still not connect.
 - I have added a debugging Serial.print message in the Arduino loop function. When using serial monitor, this message is printed over and over again (as if it is stuck in a reset loop)
 - I have verified for MAC address collisions, even changed the MAC address of the Shield multiple times.

Have I somehow burned the Ethernet Shield? Why won't it work anymore?

  [1]: https://i.stack.imgur.com/VOa9Y.gif

body:
I'm sorry to tell you but i think you damaged your board severely that's because you took more energy from the pins than an arduino can handle.

150 LEDs takes way too much power for the arduino to handle as you can see [here][1].

So you likely burnt something on your board and might have to replace it :/
make sure which board is damaged(the arduino itself or the shield) before replacing it.

If the ATmega328P(The chip on the arduino) is damaged then this should be an easy fix.

Instead of what you did, you shoud have powered the LED strip from another power supply(not from the arduino pins) and used the arduino to turn "this power supply" on and off(probably using transistors).

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardUno


message:
Speed sensors for sport

Fair warning: I'm a newbie when it comes to Arduino, so if I'm not too great at describing things, let me know so I can learn!

I have recently built a fairly accurate laser timer to time sprinters through a section of a soccer pitch, giving a nice reading of their average speed through the zone.

The limitation is that we would love to be able to see their speed as a progressive measurement throughout the sprint.

My problem? I have NO idea where to start. Google has so far come up empty...

All I have is the following link, [Best of the 2015 NHL All-Star Skills Competition][1], illustrating the sort of thing we would like to accomplish. The bit in question starts at around 0:35 when they are talking about sensors in the players' jerseys.

Any one able to point me in the right direction?

  [1]: http://youtu.be/uPQgAdP14Ck

body: I would use an ultrasonic sensor pointed at them it will give you a list of distanced at the rate that the sensor collects information (e.g. 5Hz) this could be used to plot a graph of distance over time then a graph of speed over time, then acceleration over time ect.


body:
An option would be to use a GPS module which would give you actual speed accurately, this data can be logged to EEPROM or SD and downloaded later or it can be sent wirelessly to a base station.

There is a [wearable GPS module][4] from adafruit, there are a few tutorials on getting started with it. You can the make a jacket or something light that can go onto the sprinters with the system attached.

----------

You could use an [IMU][1](Inertial measurement unit), this uses an Accelerometer, Gyro and Magnetometer. There is an article on using IMUs for measuring velocity of an object with basic modules and not using the expensive systems.

[This article][2] by CH Robotics covers a starting point, also [googling][3] this should give a whole load more of links. As the article says:
>It depends entirely on how much accuracy is needed. In general, accelerometer-based position and velocity estimates from low-cost sensors ... are very poor and are simply unusable.

  [1]: http://en.wikipedia.org/wiki/Inertial_measurement_unit
  [2]: http://www.chrobotics.com/library/accel-position-velocity
  [3]: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=measuring velocity with accelerometer
  [4]: http://www.adafruit.com/product/1059


body:
You will likely need to buy a relativly high quality GPS for each runner. Alternatly, if you could get a camera mounted so it could see large portions on track from a good angle it could probably perform pretty well with the right optical recoginition code.

IMU's are not going to be capable of tracking a runners velocity. Even constrained to linear motion the position and velocity measurements from integrating a consumer accelerometer become garbage in a few seconds because of accumulated error. Once you add the fact that the sensor will not be level all the time and your angle estimation is at best within 1 degree, I'd estimate the velocity and position of a runner recorded by a normal 9-dof IMU would be irrelevent after at most 5 seconds.

Have a look at the table on this page for a detailed analysis of orientation based errors:http://www.chrobotics.com/library/accel-position-velocity


body:
[Kinovea][1] is good but this would be post processing not live. You need record video and then you can track each runner on time. Another one is Typhon program but it involves programming and calibrating (then you can track live).

[1]: http://www.kinovea.org


body:
You can use photo cells. Just get some light sensors and direct lasers on to them. I got 100 lasers for £10 from eBay. You don't need to connect them to any controller, just connect them to a power supply to provide light for sensors. The sensors I got from eBay were, I think, 100 for about £5 or £10, then you can use an Arduino Mega and connect sensors to it.

When you cross the sensor, light will trigger and send a signal to Excel (you can use parallax program) and use Arduino code for interrupts when the sensor is triggered, you will get data to Excel (time and triggered sensor). If you call sensors like: first one 1 millisecond, 2 milliseconds, and so on, so you know what distance and what speed. But I think would be tricky if you need to measure a few guys simultaneously. It should work for single one though.


message:
Why does my LED turn off automatically after about 18 seconds on its own?

I am using the Arduino Due and I am programming it with Atmel Studio 6.2. I have had a HUGE learning curve using this IDE and the Atmel ASF. Nothing is straightforward as it is in the Arduino IDE. Nonetheless, I want to toggle an LED on and off with a simple interrupt on a pull-up configured tactile button. This is my code:

    #include <asf.h>
    #include "pio.h"

    // Define the LED pins
    #define BLUE_LED2 PIO_PC28 // Arduino Due pin 3
    #define BLUE_LED3 PIO_PC26 // Arduino Due pin 4
    #define BLUE_LED4 PIO_PC25 // Arduino Due pin 5
    #define BLUE_LED5 PIO_PC24 // Arduino Due pin 6
    #define BLUE_LED6 PIO_PC23 // Arduino Due pin 7

    // Define the button pins
    #define BUTTON_1 PIO_PC22
    #define BUTTON_2 PIO_PC21

    // Define function prototype for button interrupt
    void button_press_handler(uint32_t, uint32_t);
    void toggle_LED(uint32_t);

    int main (void)
    {
     /* Initialize the SAM system. */
     sysclk_init();

     // Initialize input/out
     ioport_init();
     pmc_enable_periph_clk(ID_PIOC);
     pmc_enable_periph_clk(ID_PIOB);

     // Set LED pins as outputs and set there default values (off)
     pio_set_output(PIOC, BLUE_LED2, LOW, DISABLE, ENABLE);
     pio_set_output(PIOC, BLUE_LED3, LOW, DISABLE, ENABLE);
     pio_set_output(PIOC, BLUE_LED4, LOW, DISABLE, ENABLE);
     pio_set_output(PIOC, BLUE_LED5, LOW, DISABLE, ENABLE);
     pio_set_output(PIOC, BLUE_LED6, LOW, DISABLE, ENABLE);

     // Set button pins as pull-up inputs
     pio_set_input(PIOC, BUTTON_1, PIO_PULLUP);
     pio_set_input(PIOC, BUTTON_2, PIO_PULLUP);

     // Configure button input pin interrupt mode and handler (Falling Edge)
     pio_handler_set(PIOC, ID_PIOC, BUTTON_1,  PIO_IT_RISE_EDGE, button_press_handler);
     pio_handler_set(PIOC, ID_PIOC, BUTTON_2,  PIO_IT_RISE_EDGE, button_press_handler);

     // Enable the interrupts
     pio_enable_interrupt(PIOC, BUTTON_1);
     pio_enable_interrupt(PIOC, BUTTON_2);
     NVIC_EnableIRQ(PIOC_IRQn);

     while(1){
       // Doing stuff in here...
     }
    }

Then this is my interrupt routine:

    // Interrupt handler for button press
    void button_press_handler(uint32_t a, uint32_t b)
    {
     // Turn the LED's on or off
     toggle_LED(BLUE_LED2);
     toggle_LED(BLUE_LED3);
     toggle_LED(BLUE_LED4);
     toggle_LED(BLUE_LED5);
     toggle_LED(BLUE_LED6);
    }

    // Function to toggle LED on/off
    void toggle_LED(uint32_t LED){

     if (pio_get(PIOC, PIO_TYPE_PIO_OUTPUT_0, LED))
     pio_clear(PIOC, LED);
     else
     pio_set(PIOC, LED);
    }

Things work normal and as expected up until about 18 seconds in. After 18 seconds, the LED turns off if it is on. I tested this by setting LED 2 HIGH by default and removing the interrupt all together:

    pio_set_output(PIOC, BLUE_LED2, HIGH, DISABLE, ENABLE);

In this case, the LED will stay on forever, but about every 18 seconds, the LED will flash off then back on once quickly. Why is this happening?

body:
The symptoms you describe are consistent with your program crashing after 18 seconds.  I expect you will find something in this that is the problem:

    while(1){
         // Doing stuff in here...
    }

To debug this, add something to the startup that is unique or clearly identifiable:

 - a print "reset" to a serial port if you have one
 - in your case, blink the led's in sequence 2,3,4,5,6

Once you confirm that your program is resetting, strip out everything in the

    // Doing stuff in here...

With the program stripped down, it should keep the LED's lit.

If the LED's still do not stay lit, but you see your reset indicator, consider power.  Microcontrollers will reset when the voltage droops too low.  The LED's might be consuming enough power to reduce the voltage below the trip point.  Connect a voltmeter to the supply voltage to see if it is stable.

The time delay can be associated with the power supply heating at higher current.  The LM2734 chip on the Due has a thermal shutdown, same as most voltage regulators.  If your hardware draws enough current to overheat, the chip will shutoff, cool down and turn back on.


body:
Again, figured this out. I simply forgot to put in `board_init();` Also, since `board_init()` already calls `ioport_init()`, I had to disable that.

Now I have this:

    int main (void)
    {
     /* Initialize the SAM system. */
     sysclk_init(); // Initialize the System Clock
     board_init();  // Initialize the board

....


body:
This may be because the ATSAM3X8E chip has a watchdog: from the datasheet section 15.1,

> The Watchdog Timer can be used to prevent system lock-up if the software becomes trapped in a deadlock. It
features a 12-bit down counter that allows a watchdog period of up to 16 seconds (slow clock at 32.768 kHz). It
can generate a general reset or a processor reset only. In addition, it can be stopped while the processor is in
debug mode or idle mode.

`board_init()` almost certainly disables the watchdog.


message:
Microphone Data on Arduino to Wav File on RaspPi

Working on an Arduino + Raspberry Pi project and hoping that this question fits into this category. I'm recording audio using a MEMS microphone on the Arduino and transmitting it over to the Pi to store in a playable file (WAV).

What I currently have setup is TCP transmission from the Arduino to the RaspPi. This part is fine and dandy for the purpose of seeing the data transmission that I am looking for.

Where my issue lies, is the audio data being recorded on the Arduino.
At the moment, I see data from my `analogRead()` function displaying like the following:

    2035
    2046
    2030
    2031
    2044
    2038
    2034
    2031
    2034
    2019
    2028
    2030
    2024
    2032
    2028

My question is, what does this mean? How would I translate this, preferably on the Pi, as usable data that I can store in a WAV file?

Any libraries or hints/clues that can steer me in the right direction would be great.

body: Why use the arduino, when you can use the Pi directly? I would get a high quality ADC, connect the mic to it, and then make the Pi write the value from the ADC directly to file. The arduino simply isn't fast enough for good quality audio recording - the ADC is 10-bit, 9.6 khz. At best you could get a stereo 8-bit 8khz wav file. With a good ADC on the Pi, you would be able to go up to stereo, 16-bit(maybe even 24-bit), 44.1 khz. Also, the Arduino would be massively slowed down by sending the data, so the actual sample rate would be much lower.


message:
Turn on led by phone and phone contacts

I would like ask for help. Can you give me an advice how to create (contacts) nubers who can turn on led.

    #include <GSM.h>
    #define PINNUMBER ""
    GSM gsmAccess;
    GSMVoiceCall vcs;
    char numtel[20];

    void setup()
    {
     pinMode(13, OUTPUT);

    Serial.begin(9600);
    while (!Serial) {
    ;
    }

    Serial.println("Receive Voice Call");

    boolean notConnected = true;

    while (notConnected)
    {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
    }

    vcs.hangCall();

    Serial.println("Waiting for a call");
    }

    void loop()
    {

    switch (vcs.getvoiceCallStatus())
    {
    case IDLE_CALL:

      break;

    case RECEIVINGCALL:

      Serial.println("RECEIVING CALL");

      vcs.retrieveCallingNumber(numtel, 20);

      digitalWrite(13, HIGH);

      vcs.answerCall();
      vcs.hangCall();
      digitalWrite(13, LOW);

      break;

      }
      delay(1000);
      }

body:
So, `retrieveCallingNumber` is documented in [here][1]. It "retrieves the calling number, and stores it" in a character array passed as second argument.

The simplest solution to check if this number is among the allowed ones is to [construct][2] a [string][3] from this and [compare][4] it against a predefined string for equality. (If you have more than one allowed number, repeat for all.)

Something like this:

    vcs.retrieveCallingNumber(numtel, 20);
    String s = String(numtel);
    if (s == "allowed number goes here") {
        // toggle LED etc.
    }

  [1]: http://www.arduino.cc/en/Reference/GSMVCSRetrieveCallingNumber
  [2]: http://www.arduino.cc/en/Tutorial/StringConstructors
  [3]: http://www.arduino.cc/en/Reference/String
  [4]: http://www.arduino.cc/en/Tutorial/StringComparisonOperators


message:
My button control working in reverse

I built this circuit to learn button control.

![My setup][1]

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

But my code (or button) is working in reverse. I want to initialize led flash effect when the button is pressed with this code

    buttonState = digitalRead(8);
    if (buttonState == HIGH)
      doFlash();

Instead the effect runs continuously and pauses if I push and hold the button. If change the condition as `if (buttonState == LOW)` code is working as expected. (Effect starts when I push the button.)

This is just the opposite of what I read in tutorials. What is wrong in my circuit or code?

Full code:

     void setup(){
      for(int i=2;i<=6;i++)
      pinMode(i,OUTPUT);
      pinMode(8,INPUT_PULLUP);
     }

     void loop(){
      int buttonState;

      buttonState = digitalRead(8);
      if (buttonState == LOW)
        doFlash();
     }

    void doFlash() {
        int i;
        for (i=2;i<=6;i++) {
            digitalWrite(i,HIGH);
            delay(100);
            digitalWrite(i,LOW);
        }
        for (i=6;i>=2;i--) {
            digitalWrite(i,HIGH);
            delay(100);
            digitalWrite(i,LOW);
        }
    }

body:
This behavior is expected: INPUT_PULLUP means the pin is pulled up via the internal pull up, i.e. it will read as high if not connected externally.

With your push button you connect it to ground (0 volts), thus bringing it to low level and it will read as low. Therefore, in your code, you need to check for low level (LOW) to check if the button is pressed (as you found out by changing the code).


body:
Most tutorials will make the code more "intuitive" by adding additional components to the circuit. E.g.

![enter image description here][1]

Here you can see one end of the button is connected to 5 volt, will the other end is connected to a digital input, and via a (pull-down) resistor to ground.

If the button isn't pressed the pull-down resistor will make the input read LOW. If the button is pressed the input will go to 5v (overpowering the pull-down resistor) and the input will read HIGH.

Like you I found the pull-up version a bit weird. But once I figured out how both versions worked, I now prefer the pull-up one. For once, because you don't need an addition resistor. <strike>(And secondly because I don't like to use unrestricted 5v signals. If in the above example you accidentally set the input to an output, and press the button, you create a short, and could blow up the micro controller.)</strike>

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


body:
There are two kinds of logic: "active high" and "active low". (At least that's one way to characterize it.) Your circuit is "active low", and there's nothing wrong with it. If fact, when you use the internal pull-up resistors of the microcontroller you're bound to use active low logic. (More modern microcontrollers have configurable pull-up or pull-down resistors.)

If this confuses you you can use a #define in your code:

    #define ACTIVE LOW

    if (buttonState == ACTIVE)
      doFlash();


body:
i had the same problem and no body solved it for me.but i got the solution and it works.[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/4Nn1L.gif


message:
Arduino Java SerialEvent not being called (Rasberry PI) XPOST from stack overflow

I am following a simple example [found here (example one)][1], to have an Arduino connected to a Raspberry Pi and read some data from the Arduino on the Pi in Java.

The issue is that the SerialEvent method is never called, which implies that no data is coming in. However, when I open the Serial Monitor I can see that data is being read correctly.

The correct serial port is being used as well.

Here is the Java code.

    //This class:
    // - Starts up the communication with the Arduino.
    // - Reads the data coming in from the Arduino and
    //   converts that data in to a useful form.
    // - Closes communication with the Arduino.

    //Code builds upon this great example:
    //http://www.csc.kth.se/utbildning/kth/kurser/DH2400/interak06/SerialWork.java
    //The addition being the conversion from incoming characters to numbers.

    //Load Libraries
    import java.io.*;
    import java.util.TooManyListenersException;

    //Load RXTX Library
    import gnu.io.*;

    class ArduinoComm implements SerialPortEventListener
    {

       //Used to in the process of converting the read in characters-
       //-first in to a string and then into a number.
       String rawStr="";

       //Declare serial port variable
       SerialPort mySerialPort;

       //Declare input steam
       InputStream in;

       boolean stop=false;

       public void start(String portName,int baudRate)
       {

          stop=false;
          try
          {
             //Finds and opens the port
             CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName);
             mySerialPort = (SerialPort)portId.open("my_java_serial" + portName, 2000);
             System.out.println("Serial port found and opened");

             //configure the port
             try
             {
                mySerialPort.setSerialPortParams(baudRate,
                mySerialPort.DATABITS_8,
                mySerialPort.STOPBITS_1,
                mySerialPort.PARITY_NONE);
                System.out.println("Serial port params set: "+baudRate);
             }
             catch (UnsupportedCommOperationException e)
             {
                System.out.println("Probably an unsupported Speed");
             }

             //establish stream for reading from the port
             try
             {
                in = mySerialPort.getInputStream();
             }
             catch (IOException e)
             {
                System.out.println("couldn't get streams");
             }

             // we could read from "in" in a separate thread, but the API gives us events
             try
             {
                mySerialPort.addEventListener(this);
                mySerialPort.notifyOnDataAvailable(true);
                System.out.println("Event listener added");
             }
             catch (TooManyListenersException e)
             {
                System.out.println("couldn't add listener");
             }
          }
          catch (Exception e)
          {
             System.out.println("Port in Use: "+e);
          }
       }

       //Used to close the serial port
       public void closeSerialPort()
       {
          try
          {
             in.close();
             stop=true;
             mySerialPort.close();
             System.out.println("Serial port closed");

          }
          catch (Exception e)
          {
          System.out.println(e);
          }
       }

       //Reads the incoming data packets from Arduino.
       public void serialEvent(SerialPortEvent event)
       {

          //Reads in data while data is available
          while (event.getEventType()== SerialPortEvent.DATA_AVAILABLE && stop==false)
          {
             try
             {
                //-------------------------------------------------------------------

                //Read in the available character
                char ch = (char)in.read();

                //If the read character is a letter this means that we have found an identifier.
                if (Character.isLetter(ch)==true && rawStr!="")
                {
                   //Convert the string containing all the characters since the last identifier into an integer
                   int value = Integer.parseInt(rawStr);

                   if (ch=='A')
                   {
                      System.out.println("Value A is: "+value);
                   }

                   if (ch=='B')
                   {
                      System.out.println("Value B is: "+value);
                   }

                   //Reset rawStr ready for the next reading
                   rawStr = ("");
                }
                else
                {
                   //Add incoming characters to a string.
                   //Only add characters to the string if they are digits.
                   //When the arduino starts up the first characters it sends through are S-t-a-r-t-
                   //and so to avoid adding these characters we only add characters if they are digits.

                   if (Character.isDigit(ch))
                   {
                      rawStr = ( rawStr + Character.toString(ch));
                   }
                   else
                   {
                      System.out.print(ch);
                   }
                }
             }
             catch (IOException e)
             {
             }
          }
       }

    }

And here is the Arduino Sketch

    //Arduino code for Part 01

    //First we will define the values to be sent
    //Note: The java code to go with this example reads-
    //-in integers so values will have to be sent as integers
    int valueA = 21;
    int valueB = 534;

    void setup()
    {
       Serial.begin(115200);
       Serial.println("Start");
    }

    void loop()
    {

       //We send the value coupled with an identifier character
       //that both marks the end of the value and what the value is.

       Serial.print(valueA);
       Serial.print("A");

       Serial.print(valueB);
       Serial.print("B");

       //A delay to slow the program down to human pace.
       delay(500);

    }

I have read that changing `Serial.print()` to `Serial.write()` is the new way to do this, but changing this had no result.

  [1]: http://openenergymonitor.org/emon/javaexamples

body:
So the reason for no events being triggered was due to the program exiting and ending before it had the chance to.

To solve this i added a thread with a loop inside it inside the main thread.

    public static void main(String[] args) throws Exception {
     ArduinoComm = new ArduinoComm ();
     main.start("/dev/ttyUSB0",115200);
     Thread t=new Thread() {
     public void run() {
     try {
     //Messy implementation but it works for this demo purpose
        while(true){
          //optional sleep
          thread.Sleep(500);
        }
     } catch (InterruptedException ie) {}
     }
     };
     t.start();
     System.out.println("Started");
     }

Bit of an oversight on my part.


message:
need help for saving the millis function when arduino was rebooted

I have two questions want to ask

1. I'm using Arduino Uno with 16*2 LCD Blue ( also I have temp. sensor and two motors also 3 limit switches) ,, my code is working good, but sometimes my lcd stop printing the values of Temperature and time [print nothing i.e. print all the leds on] \\\ then when I reboot it everything works good .... why this problem happened ?

2. Is there any way to save the value of millis function when the arduino was rebooted ?

thanks for your help
regards

---

My code is for an egg incubator , it consists of

1. Dht22 sensor [humidity + Temp]
2. three limit sw.
3. one motor
4. 16*2 lcd
5. lamp [acting as  heaters]

As I said previously,  millis function  that I'm using is for controlling the motor movement every 3 hours and stop the movement after 18 days of working

The main problem I faced is POINT 1 that I mentioned previously (I don't need to lose the time when I reboot the LCD)

If any one can help by giving me a short code as an example who to deal with EEPROM or any other idea.

Here is my code

    #include "DHT.h"  //includes lib for the temperature-humdity sensor
    #include <LiquidCrystal.h> //lcd lib

    #define DHTPIN 13 //pin that DHT is connected to
    #define DHTTYPE DHT22 //Sensor we are using

    DHT dht(DHTPIN, DHTTYPE); //defines location for DHT

    int sw1,sw2,sw3;
    const int LM1=0;
    const int LM2=1;
    const int LM3=6;
    const int LAMP=8;
    const int CW=10;
    const int CCW= 9;
    const int Buzzer=7;
    long previousMillis = 0;        // will store last time LED was updated
    unsigned long RealTime = 0;
    float MOTORTime =0;// This is the real time that present on LCD now.
    unsigned long MOTORSTOP = 0;// store the valve after 18 days of ranning ,,

    // the follow variables is a long because the time, measured in miliseconds,
    // will quickly become a bigger number than can be stored in an int.
    long interval = 10800000;           // interval at which to blink (milliseconds)(3 hours waiting)

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {

      lcd.begin(16, 2);   // set up the LCD's number of rows and columns: [LCD that we have (Colomn,Row)]
      pinMode(LAMP,OUTPUT);
      pinMode(LM1,INPUT);
      pinMode(LM2,INPUT);
      pinMode(LM3,INPUT);
      pinMode(CW,OUTPUT);
      pinMode(CCW,OUTPUT);

     }
    void loop() {
      sw3=digitalRead(LM3);
          unsigned long currentMillis = millis();
    MOTORSTOP = currentMillis;
    if (MOTORSTOP < 1555200000){ // 18 days
      float h = dht.readHumidity(); //defines the variable for humidity
      float t = dht.readTemperature(); //defines the variable for temperature
      // set the cursor to column 0, line 0
      lcd.setCursor(0,0);
      // print the humidity
      lcd.print("H ");
      lcd.print(h);
      lcd.print("% ");
      //move line down
      lcd.setCursor(0,1);
      lcd.print("T ");
      lcd.print(t);
      lcd.print("C ");

      lcd.setCursor(10,0);
      lcd.print("MOTOR"); // to print motor working time

    if (t==37.65)digitalWrite(LAMP,LOW);// Lamp OFF
    else if (t>37.65)digitalWrite (LAMP,LOW); // Lamp OFF
    else { digitalWrite(LAMP,HIGH);}// Lamp ON

      delay(2000); //wait two sec. before taking another reading.
      ///////////////stepper motor control and delay time 2.45 hours.
     sw1= digitalRead(LM1);
      sw2= digitalRead(LM2);

      RealTime = currentMillis - previousMillis;
      MOTORTime=((RealTime/(1000))/60); ////////////////////////////////////////////
      MOTORTime = 180 - MOTORTime;

      if (MOTORTime >= 1){
       lcd.setCursor(10,1);
      lcd.print(MOTORTime); }// this will print the ACTUAL Time Remaining on LCD
      else {
        lcd.setCursor(10,1);
       lcd.print("<1 MIN");}

      if(RealTime > interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

      if (sw1==LOW && sw2==HIGH){
        digitalWrite (CW,LOW);
        digitalWrite (CCW,LOW);
        do {
          digitalWrite(Buzzer,HIGH);
          digitalWrite (CW,HIGH);// change the direction of rotation (DOWN Movement)
          digitalWrite (CCW,LOW);

          sw2= digitalRead(LM2);}
          while(sw2==HIGH);}

          else if (sw1==HIGH && sw2==LOW){

          digitalWrite(CW,LOW);
          digitalWrite(CCW,LOW);

            do {
              digitalWrite(Buzzer,HIGH);
              digitalWrite(CW,LOW);// change the direction of rotation (UP Movement)
              digitalWrite(CCW,HIGH);

              sw1= digitalRead(LM1);}
              while(sw1 == HIGH);}}
    }
    //----------------------------------------------------------------------------------------------------------------------
    else if (((MOTORSTOP/10800000)>= 144 )&& (LM3== LOW)&&(MOTORSTOP >= 1555200000)){
      digitalWrite (CW,LOW);
        digitalWrite (CCW,LOW);

       float h = dht.readHumidity(); //defines the variable for humidity
      float t = dht.readTemperature(); //defines the variable for temperature
      // set the cursor to column 0, line 0
      lcd.setCursor(0,0);
      // print the humidity
      lcd.print("H ");
      lcd.print(h);
      lcd.print("% ");
      //move line down
      lcd.setCursor(0,1);
      lcd.print("T ");
      lcd.print(t);
      lcd.print("C ");

      lcd.setCursor(10,0);
      lcd.print("MOTOR"); // to print motor working time
      lcd.setCursor(10,1);
      lcd.print("OFF");

    if (t==36.70)digitalWrite(LAMP,LOW);// Lamp OFF
    else if (t>36.70)digitalWrite (LAMP,LOW); // Lamp OFF
    else { digitalWrite(LAMP,HIGH);}// Lamp ON

      delay(2000); //wait two sec. before taking another reading.

    }
    }

body:
1. You could be running out of memory. Posting your code would be helpful.

<strike>2. Not without some external memory such as an SD card.</strike>

2. As David points out in the comments the Arduino does have EEPROM memory (512bytes or 1024bytes depending on which version you have). See here for the library: http://www.arduino.cc/en/Reference/EEPROM


body: You might try a real-time clock module instead of the `millis()` function. They keep time in external hardware and are battery backed so continue through a power down, you get calendar date and clock time instead of milliseconds since restart, and they don't overflow every 50 days.


body:
**Summary:**

You have an incorrect variable type assignment for previousMillis ('long' instead of 'unsigned long') resulting in illegal mixing of types in a subtraction.

It is not certain that this is causing your problems but, if not, it will cause problems at some stage if millis() is never reset  - if only when millis() passes its halfway point.

It is not possible to prove with certainty that the mixing of types is not causing a problem without examining the compiled code as the action is 'illegal' and so no assurance is possible.
(We **hope** that the compiler writer 'got it right' :-) ).

____________________

**Details:**

Where you now use
>long previousMillis = 0;

You should use

>unsigned long previousMillis = 0;

Both 'long' and 'unsigned long' are 32 bit data types but long is signed and effectively "wraps around" at half value.

Apart from having funny things happen after about 25 days, if you mix data types in a calculation as you do in
>   RealTime = currentMillis - previousMillis;
where

 - RealTime = unsigned long
 - currentMillis = unsigned long , but
 - previousMillis = long

then there is no certainty as to what the code will do when subtracting a long' from an 'unsigned long'.

We know what we would like it to do, and we hope that the compiler writer made the same assumptions as we do, but there is no guarantee.

Interestingly, while it does no harm for RealTime to be of type 'unsigned long', this is usually not essential, as we know that

>up to about 25 days the result will fit in the lower 31 bits of a 'long' and
up to 65.535 seconds the result will fit in the 16 bits of an unsigned int and
up to 32.767 seconds the result will fit in the lower 15 bits of an int.

So, if your period between millis() tests is guaranteed to fit in the above ranges then the lower range variables may be used.

While the mixing of types in the actual subtraction produces a technically undefined result, the use of a different type for the result than is used in the calculation is acceptable as the calculation result is well defined as long as the subtraction is performed correctly.

___________________

millis() wrap-around - **NOT** a problem:

People have expressed concern about incorrect results when millis() overflows after about 50 days, but this need not be a concern if correct data typing is used.   When two variables or 'counters' (in this case eg millis() and previousMillis), both of type 'unsigned long' are subtracted or compared, the result is arithmetically valid, even if the "upper" variable ( millis() ) has reached the top of its range and 'wrapped around'. This result is true for any two unsigned integer counters which are both of the same length.
ie the result of eg

> delay = millis() - previousMillis

will ALWAYS be valid if millis() and previousMillis are both 'unsigned long's.
This result is not intuitively obvious to most people and there are many "solutions" to this "problem" on web which seek to correct a problem that does not exist. If you are interested in making use of this fact in other situations it is worth taking pencil and paper (or your favoured equivalent) and using eg 3 or 4 bit variables, working through how this works and why. What happens is that the overflowing / wrapping around higher counter (millis() in this case) "looks like" a longer unsigned variable with additional bits above its MSb. When the subtraction is carried out an MSb "bowwow" may occur  - this is being "borrowed" from data bits that do not exist but this matters not when only the lower N bits (32 in this case) are of importance.

___________________________

Variable (including the state of millis() ) can be saved in EEROM memory prior to a reboot. IF the data has to be validly written when a power outage occurs the system must detect the outage and continue to run long enough to validly write to EEROM. This requires proper design of power supply holdup time - without which EEROM corruption may occur due to power loss while writing to memory. As well as internal EEROM, it is possible to use low cost I^2C EEROM memory if non volatile storage requirements exceed uC EEROM capacity.

__________________

More detail on any of the above available if required.


body:
It has been suggested to you to save the millis value in the EEPROM.
Although this can work, there is a big issue with the frequency at which
you save it. If you save too often, you will burn your EEPROM, as it is
only rated to 105 writes. If you do not save often enough,
you will have most of the time a very outdated value in EEPROM. The
problem can be mitigated by adopting a wear-leveling strategy, but this
adds significant complexity.

There is a simpler solution to this problem: instead of using the
EEPROM, save the value in RAM. Actually, the millis value already lives
in RAM, and since the RAM is not initialized by hardware on reset, you
will find, when your program starts, that the last millis is right where
you left it! It is then cleared by your program, in a function called
`__do_clear_bss` that belongs to the C runtime and runs before
`setup()`.

In order to preserve millis across a reset, you can do the following:

* Write a function that copies the millis value into some other global
  variable. This function must run early in the startup sequence, before
  `__do_clear_bss` clears millis. This can be achieved by putting
  the function in the _.init3_ section of the program, as explained in
  [the avr-libc documentation on memory
  sections](http://www.nongnu.org/avr-libc/user-manual/mem_sections.html).
  And the global variable must be in the _.noinit_ section in order for
  the C runtime not to mess with it.
* In `setup()`, restore the millis value from that global variable.

This way you will have a continuous millis across resets, with one
caveat: on a cold boot, it will start with an unpredictable value. This
should be no issue if you take care to never rely on absolute time but
only on time differences, which is a good practice if only to avoid
issues when millis rolls over. If you nevertheless want to reset millis
on a cold boot, you have several options:

1. Connect a "reset time" button to your Arduino and hold the button
   pressed when you power it up. `setup()` would then know it should not
   restore the millis value.
2. Write some [magic
   number](https://en.wikipedia.org/wiki/Magic_number_(programming))
   in RAM. If you find this number at startup, it is extremely likely
   that the program is starting from a warm reset.
3. If your Arduino has a fairly recent version of optiboot, you
   will find the reset flags in the CPU register r2 when your program
   starts. These flags tell you whether you come from a cold boot or a
   warm reset.

The program below is an example that implements strategy 2. It prints
the millis value on the serial port roughly every second. On reset, it
prints “-- starting --” and continues from where it left.

    // If this is in RAM at startup, we come from a warm reset.
    volatile const unsigned long magic = 0x12345678;

    // This is where Arduino core keeps the millis() value.
    extern volatile unsigned long timer0_millis;

    // Here we will save a copy of timer0_millis.
    unsigned long __attribute__((section(".noinit"))) savedMillis;

    // Save the millis value at startup.
    void __attribute__((section(".init3"),naked)) saveMillis()
    {
        if (magic == 0x12345678)  // very likely a reset
            savedMillis = timer0_millis;
        else                      // cold boot
            savedMillis = 0;
    }

    void setup()
    {
        // DO THIS FIRST: Restore the saved value of millis.
        noInterrupts();
        timer0_millis = savedMillis;
        interrupts();

        // Other initializations can be done now.
        Serial.begin(9600);
        Serial.println("-- starting --");
    }

    void loop()
    {
        Serial.println(millis());
        delay(1000);
    }


message:
Arduino UNO + Arduino GSM Shield + Sparkfun Venus GPS

I am using an Arduino UNO that is connected to an Arduino GSM shield (<http://www.arduino.cc/en/Main/ArduinoGSMShield>).

Now, I want to connect the SparkFun Venus GPS module to this combination. (*unfortunately due to my rep I can only post two links)

The Venus GPS works fine with the Arduino UNO by itself, but I am having some trouble getting the GPS module to communicate with the Arduino when the GSM shield is stacked on top.

The GPS powers on and begins blinking (which means it has a lock), but the serial monitor is not showing any information.

Coming from the programming side of things, I really don't understand much about electronics, so please pardon me if I am missing something basic here.

Based on what I've managed to figure out so far, I think it has something to do with the shield requiring 5V operating voltage and the Venus operating at 3.3V.

I think that when the GSM shield is plugged in, its expecting a 5V input, but the Venus GPS is only capable of sending a 3.3V signal.  Furthermore, any other 5V sensors that I am currently using don't have any problems communicating with the UNO through the GSM shield.

So, I actually have two questions:

 1. Is this assumption correct or could something else be the cause of my issue?
 2. If this is correct, could I use something like this logic level converter (https://solarbotics.com/product/50550/) to step up the Venus GPS input signal?

Thank you in advance for any help and guidance you are able to provide.

body:
I received my logic level converter today and wired it in between the Venus GPS and the Arduino GSM shield.

The issue seems to be resolved and I'm able to properly receive information from the TX on the Venus GPS.  It would seem that my assumption was correct and I needed to "step-up" the 3.3V TX signal from the Venus GPS in order to use it with the GSM shield.