body: I have quite a lot of experience with Arduino but have recently been faced with a challenge that has stumped me. The project is to create a robot that can be controlled from a separate network than it is on. I had the idea of using the Yun board to receive the values. Does anyone know a way I could have a computer send data to a Yun on a different network? (Maybe through a website?)

title: Sending values to an Arduino Yun across different networks

Answers: 3

body:
You havent mentioned what exactly your robot does, for now I am going to assume it is something as simple as switching on a light etc and not something like a rover.

The easiest way would be to make the YUN read from a db (like mysql, etc.) and depending on the value perform a task.

For example, you could have a row called **light**, if the value of it is **1** then turn on the light else turn off the light

The problem you are going to face is the power consumption as you will constantly be polling from the database. You could also look into push notifications ( I am not sure if it is applicable here)

You could also look into creating a private VPN and connecting the YUN and your other devices to it and then control it.

body:
I have accomplished this, first by reading [this article](http://babaawesam.com/2014/11/06/control-input-output-of-arduino-yun-with-ajax/) on controlling a Yun through a web-browser *on the same network*. From there it was a matter of allowing my Yun to be accessed *externally* (setting up port-forwarding on my router) and changing a few lines of code to reflect the new location reference.

All the necessary files and code are included under the heading "Project Files" in the above link and no modification is needed to get it working within the same network. That said, I had to convert the two `.jpg` files to `.png` (and change the filenames in `index.html`) - I don't know why they wouldn't show up in my browser.

## In brief: ##

The Yun hosts a webpage (index.html) which contains some indicators and control inputs. These objects are linked to the 32u4 using [Bridge](https://www.arduino.cc/en/Tutorial/Bridge) and the REST API - nothing special. The bulk of the html code is for visual purposes, and the actual REST calls are nice and simple.

What is good is that the webpage can be accessed from anywhere with the right jiggery-pokery, and with a little more determination can be *hosted* from anywhere.

## External Access ##
Once you have that working, you need to do the following to allow access externally. I tested this using my smartphone - disconnected from my home WiFi of course - to ensure the link was over the Internet, not intranet.

1) Set up port forwarding and a static IP for the Yun. This is the fundamental step if you simply want to control your Yun over the Internet. However, I can't actually tell you how to do this because I don't know what equipment you have! Information is all over Google for setting up both DHCP static IP and port forwarding.

2) Get a static IP from your ISP for your home/work, or set up a Dynamic DNS service ([these people](https://www.dnsdynamic.org/) offer it free, but I've never actually needed to use an external service). Most commercial ISPs tend to dish out static IPs, but that's no guarantee that yours will.

3) Access your Yun with a browser via: `http://YOUR.IP.ADD.RES:PORT/arduino/<SketchName>`.

## External Hosting ##
If you want to host the webpage on something other than the Yun, you can! You will of course need a server to host this, either your work's central server or an external hosting service. You'll need to change some more lines in the code:

1) <s>In the Yun sketch change `server.ListenOnLocalhost();` to `server.noListenOnLocalhost();` - the subtle difference is the 'no', and is essential for external control.</s> *Sorry, that's incorrect without a little more explanation than is required at the moment to answer your original question.*

2) In the `.html` file, you need to change each instance of:

    server = "/arduino/<SOMETHING>";
to

    server = "YOUR.IP.ADD.RES:PORT/arduino/<SOMETHING>";
If you have the REST password set to ON then you have to incorporate the username/password in there too:

    server = "username:password@YOUR.IP.ADD.RES:PORT/arduino/<SOMETHING>";
There are *three* occurences in the original file, so be sure to catch them all.

3) When making changes to the `.html` file, make sure you re-upload it to the external host, not the Yun - that mistake took me hours to figure out.

## A little more... ##
While searching for the URL of the article in the opening paragraph I found [this atricle on a similar theme](https://grallator.wordpress.com/2014/01/13/json-and-the-arduino-yun/). It looks to have plenty of information although I haven't read it yet fully yet; I've been busy writing an answer on Stack Exchange. External Access should be no different, and if you want the 'External Hosting' version you just need to find any line that references the 'server' as `"/arduino/..."` and change it to `"YOUR.IP.ADD.RES:PORT/arduino..."`.

body:
Basically your yun is a linux box with a arduino connected to it on port /dev/ttyATH0.
If you know linux that should answer all your questions about what is possible.
I have setup my own bridge and communicate via html to my robot using cgi script and lua.
I have demoed this on a web contest and you can see it in action on this video from 15:25 onwards https://www.youtube.com/watch?v=q0CnB7Yzpfg&index=3&list=PLCSjf7QmP3TCOLIw0lMPbwHtKrO-nwfKG


body:
I faced a problem to send 1 SMS if an input is HIGH and if it is LOW no SMS will be sent. The code not working, just sends SMS when I turn the GPRS on and after that nothing happens.

Please check this link to see the code : [the code][1]

Thank you for helping in advance.

  [1]: https://stackoverflow.com/questions/29818894/send-sms-for-1-time-with-arduino-gprs-sim900-if-an-iput-is-high

title: Sending SMS once with arduino GPRS SIM900 if an input is HIGH

Answers: 1

body:
You need to attach an interrupt to the pin which is getting HIGH and then the function connected to the interrupt will have the code to send the SMS.

Just init the GPRS with connecting to the network then just wait for the interrupt to send anything.


body: Without declaring the pin 2 as INPUT or OUTPUT, it remains constantly HIGH. Can anyone explain why is it so?

title: Why does the pin 2 of arduino Mega stay always HIGH?

Answers: 1

body:
Pin 2 connects to the controller's PE4, which is a GPIO pin, which can also be used for PWM. You should be able to use it either as input or output, and both high and low. It could be that setup initializes it as output high, while you would usually have uninitialized pins as input.

![enter image description here][1]

Have you tried to make it low, or make it input?

    digitalWrite(2, LOW);

should make it low, while

    pinMode(2, INPUT);
    int pin2Status = digitalRead(2);
    digitalWrite(13, pin2Status);

will copy the status of pin 2 to the on-board LED.

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


body: I have a friend who is just getting started with Arduino UNO.  He downloaded a sketch and is using a UNO on Mac OS.  He loaded the sketch and verified.  it comes up with errors.  He sent me the same sketch and i opened it under Win7 arduino software.  verified, and it says it is fine.  i made an arduino file and emailed it back to him.  he is still getting the same errors.  can anyone help and let me know what is wrong?  i am not a MAC expert and wonder why  this works in win and not MAC????????  appreicate any help anyone can give me

title: arduino sketch on Win7 vs. MAC op system?

Answers: 1

body: I've had the same issue with Mac OSX 10.6.8 vs Windows XP SP3 using the same IDE version. I don't have a definitive answer for you, but I know that Microsoft has more frequent updates compared to Apple, which could be the reason. I suspect my issue and your friend's issue is the GCC compiler we're using. The compiler would be updated on OSX only when you update your entire OSX version. To get around that, there are third-party package managers: Homebrew and MacPorts that would allow you to just update the GCC compiler for example.


body: I am looking into building a robot with my Arduino Nano but I don't want to shell out more then 50 bucks. Does anyone have any suggestions for a four wheel robot chassis at this price that I could use to make my robot mobile?

title: Arduino Robot Chasis

Answers: 1

body:
There's plenty of [options on ebay][1], you will have to add a DC motor [driver][2] and optionally, sensors, but these are a good starting point.

[1]: http://www.ebay.com/itm/Hot-sale-4WD-Robot-Smart-Car-Chassis-with-Speed-Encoder-DC-3V5V6V-for-Arduin-EEW-/291423639383?pt=LH_DefaultDomain_3&hash=item43da33d757

[2]: http://www.ebay.com/itm/L9110S-H-bridge-Stepper-Motor-Dual-DC-motor-Driver-Controller-Board-New-GA-/181650502852?pt=LH_DefaultDomain_15&hash=item2a4b36b4c4


body:
I'm building a lathe that will be powered by a 3-phase 750w AC motor (4 pole, max unloaded RPM of 1400 RPM). I want to be able to control the RPM using a potentiometer attached to an Arduino mega which I can figure out how to do.

Under load, I'm guessing the motor is going to want to draw more current across each of the phases, the cabling can take the extra current draw but I don't want to damage the motor.

Could I use AnalogueRead (using current transducers) to tell the Arduino to increase the resistance with a servo-potentiometer setup or cut the power momentarily (using transistors on each phase) if the current rose above a certain level? If so, is there any code that would be good to steal/adapt?

Thanks all!

title: Arduino-controlled current limiter for lathe

Answers: 0


body: I have been awaiting the release date for some time for the Arduino TRE.  So, my question is simple does anyone know the release date or any hints about when it might come out?  Also, what do you think the cost will be?

title: Arduino TRE Release Date and Cost

Answers: 0


body:
I am trying to code something for fun using an Arduino Due and a LED matrix. The led matrix has a [backpack controller](https://www.sparkfun.com/datasheets/Components/rgbmatrixbackpack_userguide.pdf). This device is using SPI. So I connect MOSI and SCLK to their respective pins and SS to pin 10 on the Due. So far so good.

The problem I have is that when i run my rudimentary code nothing happens.
this is the current code I am using. I thought this should be enough, but it clearly isn't.

    #include <SPI.h>
    void setup() {
      SPI.begin(10);
      SPI.transfer(10, 0x26, SPI_CONTINUE); //setup the matrix
      for (int i = 0; i<64; i++){
        SPI.transfer(10, 0x00, SPI_CONTINUE); //set all pixels to black...
      }
    }

Output:

     Erase flash
     Write 10444 bytes to flash
     [                              ] 0% (0/41 pages)
     [=======                       ] 24% (10/41 pages)
     [==============                ] 48% (20/41 pages)
     [=====================         ] 73% (30/41 pages)
     [============================= ] 97% (40/41 pages)
     [==============================] 100% (41/41 pages)
     Verify 10444 bytes of flash
     [                              ] 0% (0/41 pages)
     [=======                       ] 24% (10/41 pages)
     [==============                ] 48% (20/41 pages)
     [=====================         ] 73% (30/41 pages)
     [============================= ] 97% (40/41 pages)
     [==============================] 100% (41/41 pages)
     Verify successful
     Set boot flash true
     CPU reset.

![Image of the ever unchanging LED-matrix][1]

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

So my question is: am I doing something wrong? what?
Or is the Led matrix broken?

Hoping for good answers.
regs
KB

title: Arduino DUE and a ledmatrix with issues

Answers: 0


body:
Suppose I have a number with 2 digits, 42.
It is an integer, received from my RTC

Now for my 7 segment displays, I will need 2 separate numbers:
* 4 on display 1.
* 2 on display 2.

How do I slice this number in 2?

title: 2 digit number to 2x 1 digit

Answers: 1

body:
Numbers retrieved from an rtc are usually returned as a char or integer.

On this basis, you want

    ones_column = bytefromrtc % 10;
    tens_column = (bytefromrtc / 10) % 10;
    hundreds_column = (bytefromrtc / 100) % 10;

the `%` operator returns the modulus - if you divide 42 by 10, the answer is 4, with a remainder of 2. % returns the remainder, in this example, 2.

To do the tens column, first get rid of the last digit by dividing by 10, then do the modulus as above. Since bytefromrtc is not a float, if you divide it, you lose the remainder - 42 / 10 = 4, not 4.2.

If the output is a word, or integer, or long integer, the method is exactly the same, except for the number of digits you can get out.


body:
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);
        }
    }

title: Multiple interrupt lines connection

Answers: 2

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

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.


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

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

Answers: 1

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.


body:
I've been working on a project (Arduino Uno: Atmega328) that implements a gyroscope (which is used with the LSM9DS0 spark-fun library) that is communicated with through I2C and uses a Servo library. Due to a timer conflict with the standard Servo library and another library I've been using, I am now using the ServoTimer2 library which obviously uses timer 2. This is when the problem started.

When I call the attach() function of the ServoTimer2 library, it allows the gyroscope to be read a few times and then the gyroscope feed cuts out. I am using the serial monitor (115200 baud) to read the gyroscope data. The Serial monitor is not the problem because it uses a UART interrupt for Serial.

To fix this error, I modified the ServoTimer2 library to run on Timer0 (Yes I know this handles the delay functions, but they are not needed in my case), which is now called ServoTimer0. This modified version of the library works perfect except for when I attempt to use it with the gyroscope. The same problem still arises though. I've traced what causes this failure down to one line of code that sets up the interrupts:

    TIMSK0 =  _BV(OCIE0A) //This is in my own modified version of the library.
That is what causes it to fail. I believe the AtMega328 can run I2C natively, and my thought is that this native running somehow uses these timers.

Any solutions?
Thanks

title: Unexpected Timer Conflicts (Uno)

Answers: 0


body:
I'm doing a project using the ADXL335 accelerometer from SparkFun. The actual project I'm using P5 and it's working great. I'm running workshops in parallel and want to demo the chip in real-time but am currently out of time to build something from scratch. I'm desperate for a simple processing (or something else) sketch that takes my x, y, z values being printed to the serial port from Arduino and visualizes them in some way. Can anyone point me to anything that won't need a lot of coding time and effort just now?

Thank you!
Claudia

title: Need a simple accelerometer visualization example!

Answers: 1

body:
A simple and fast solution would be implement a chart using a JavaScript library called Chart.js. it is simple and you can visualize your data in realtime.

Try node.js to make the back-end by communicating via serial (serialport package is good) and send the data using socket.io.

It is simple and you can set everything in less than 2 hours.

[Chart.js][1]

I recently made some video tutorials about this and you see them [here][2]. The audio is in Portuguese but you can just skip and go directly to coding sections.

  [1]: http://Chart.js
  [2]: https://youtu.be/LNtmLapUSzw


body: I acquired a Seeed studio Arduino motor shield V.2 and wanted to start using it. The problem is that there is like no good example code. The library for the shield on the seeed website has one example and doesn't really explain anything. Does anybody know where I could get a good guide for this thing?

title: Coding for Seeed Arduino motor shield

Answers: 0


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

title: Proportional water flow control

Answers: 2

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.


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

title: The code of ISR executes twice

Answers: 1

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.


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

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

Answers: 1

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


body:
I faced a problem to send 1 SMS if an input is HIGH,and if it is LOW==> no SMS to send,if LOW to HIGH==> send 1 SMS. this code not working,just sent SMS when I turn the GPRS on,and after nothing is happened.
Thank you for helping in advance.

     #include <SoftwareSerial.h>
     #include "TimerOne.h"

     const int DI = 2;
     const int DT = 3;
     const int DGP1 = 4;
     const int DGP2 = 5;
     const long interval = 100000; // in microseconds

     int value1 = 0;
     int value2 = 0;
     int value3 = 0;
     int value4 = 0;

     int value1_old = 0;
     int value2_old = 0;
     int value3_old = 0;
     int value4_old = 0;

     boolean changed1 = false;
     boolean changed2 = false;
     boolean changed3 = false;
     boolean changed4 = false;

     SoftwareSerial SIM900 (7, 8);

     void SIM900power(){
       digitalWrite(9, HIGH);
       delay(1000);
       digitalWrite(9, LOW);
       delay(5000);
     }

     void initia(){
       SIM900.print("AT+CMGF=1\r");
       delay(100);
       SIM900.println("AT + CMGS = \"xxxxxxxxxx\"");
       delay(100);
      }

     void Send_SMS(){
        SIM900.println((char)26);
        delay(100);
        SIM900.println();
        delay(5000);

      }

      void isr_timer(){
        if (changed2) {
          initia();
          SIM900.println("Station 85: Defaut electrique");
          delay(100);
          Send_SMS();
          value2_old = value2;
          changed2 = false;
       }

       if (changed3) {
         initia();
         SIM900.println("Station 85: DefautGP1");
         delay(100);
         Send_SMS();
         value3_old = value3;
         changed3 = false;
       }

       if (changed4) {
         initia();
         SIM900.println("Station 85:DD>1000");
         delay(100);
         Send_SMS();
         value4_old = value4;
         changed4 = false;
       }
     }

     void setup() {
        pinMode(DI, INPUT);
        pinMode(DT, INPUT);
        pinMode(DGP1, INPUT);
        pinMode(DGP2, INPUT);

        SIM900.begin(19200);
        Timer1.initialize(interval);
        Timer1.attachInterrupt(isr_timer);
      }

      void loop() {
        value1 = digitalRead (DI);
        value2 = digitalRead (DT);
        value3 = digitalRead (DGP1);
        value4 = digitalRead (DGP2);

        if (value1 != value1_old && value1 == HIGH) changed1 = true;
        if (value2 != value2_old && value2 == HIGH) changed2 = true;
        if (value3 != value3_old && value3 == HIGH) changed3 = true;
        if (value4 != value4_old && value4 == HIGH) changed4 = true;

        value1_old = value1;
        value2_old = value2;
        value3_old = value3;
        value4_old = value4;

      }

title: send SMS for 1 time with arduino GPRS SIM900 if an iput is HIGH (4 Digi inputs)

Answers: 0


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

title: Multiplexing help for relay and pwm

Answers: 1

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


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

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

Answers: 1

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


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

title: Nano destroyed?

Answers: 1

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


body:
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);
      }
      }
    }

title: How to clear FIFO buffer on MPU6050?

Answers: 3

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.


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

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

Answers: 2

body:
    long int currentMillis;
    void setup() {
        pinMode(motorPin, OUTPUT);
        digitalWrite(motorPin, LOW);
    }
    void loop() {
        if(condition is met){
            startOfMotor = millis();
            while(millis() != (startOfMotor+180000)){
                digitalWrite(motorPin, HIGH);
            }
        digitalWrite(motorPin, LOW);
        }
    }

This `motorPin` is the pin to which the motor is connected. `millis()` gets the milliseconds after the board is started. 3 min = 180 seconds = 180000 ms.

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;
      }
    }


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

title: Making my own libraries

Answers: 2

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


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

title: Arduino 16x2 LCD Black Boxes

Answers: 5

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.


body:
I'm using the I2C library to connect to a GY-521 board and, when executing the getAcceleration() methods I get gyro values and viceversa..

This is my setup (I'm using a proto shield but that shouldn't change anything as far as I understand):

![enter image description here][1]

It follows this schematic:

![enter image description here][2]

And this is the code I'm testing:

    #include "Wire.h"

    #include "MPU6050.h"

    MPU6050 accel;

    int16_t ax, ay, az;

    void setup() {
        Wire.begin();
        Serial.begin(9600);
        Serial.println("Initializing I2C devices...");
        accel.initialize();
        Serial.println("Testing device connections...");
        Serial.println(accel.testConnection() ? "Connected" : "Connection failed");
    }

    void loop() {
        accel.getAcceleration(&ax, &ay, &az);
        Serial.print("acc x:    ");
        Serial.println(ax);  // This prints the gyro value of the Y axis!
        delay(1000);
    }

I don't think it has to do with the wiring since inverting the 4 and 5 analog pins yields zero values.

Is this a problem with the library? Or with my chip?

  [1]: https://i.stack.imgur.com/H0UV4.jpg
  [2]: https://i.stack.imgur.com/Chs6l.jpg

title: Getting inverse values of acceleration and tilt for the MPU 6050

Answers: 1

body: There are a lot of libraries, I wouldn't use the accelerometer library in wire, download and add the I2Cdev library, you can get it on a variety of different sites like github.com


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

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

Answers: 1

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


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

title: Is my Arduino Ethernet Shield broken?

Answers: 1

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


body:
I want to build a program that will seek audio file inside a USB DOK (DisK On Key/Pen Drive) when it is inserted to the Circuits@Home USB Host shield. After a specified file will be found i want it to be played via the Audio library and the Teensy 3.1 12 Bit Analog Output.

Alternatively, I can use an Arduino MEGA with the shield and the TMRpcm library: [https://github.com/TMRh20/TMRpcm/wiki][1]

I've saw that there's a sample with SD card and I've fiddled a lot to get the USB Host Shield 2.0 library to work and succeeded. However I've found a simpler implementation of it in the UsbFat library: [https://github.com/greiman/UsbFat][2]

Now basically I need to connect between these two libraries but sadly I've failed to understand how to convert "play_sd_wav.h" to use the UsbFat Library.

Or, more simply put, how do I command a USB pen drive like it is a SD card and pull an audio file from it?

Anyone can help please?

Thank You,

Ziv

  [1]: https://github.com/TMRh20/TMRpcm/wiki
  [2]: https://github.com/greiman/UsbFat

title: Trying to play audio files on arduino via Usb Host Shield

Answers: 0


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

title: Speed sensors for sport

Answers: 6

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:
Your best bet would be to use a module of Gyro, Accelerometer and Magnetometer much like MPU-9150. These devices communicate using I2C and you can log in data about the direction and the change in direction as well as acceleration. Using this data you can easily find out the speed in a particular direction and even overall data like the average speed, distance travelled, etc.

Another idea is using the accelerometer to measure a jerk.A jerk can be taken as a footstep and using appropriate calculations you can find out how much a person has moved throughout the sprint.

You can use ultrasonic sensors too which would tell you the position of the sprinter from a point but they have their disadvantages like small pressure changes due to air will affect the readings and you won't get accurate reading.

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.


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

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

Answers: 3

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.


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

title: Microphone Data on Arduino to Wav File on RaspPi

Answers: 2

body: It's difficult to answer this without seeing any code, but I will take a wild guess and assume you are not using any sort of FFT processing on the input. You could try looking into [this](http://wiki.openmusiclabs.com/wiki/ArduinoFFT?action=AttachFile&do=view&target=ArduinoFFT2.zip) library. Alternately, people seem to have good luck with [this](http://elm-chan.org/works/akilcd/report_e.html) one too.

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.


body:
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);
      }

title: Turn on led by phone and phone contacts

Answers: 1

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


body:
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);
        }
    }

title: My button control working in reverse

Answers: 4

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