message:
Why are LED's receiving different voltages connected to Arduino

I have four LED's all connected the exact same way to four pins via four 150OHM resistors. (ignore the sensors, they are doing nothing currently) The code is very simple in the loop:

      digitalWrite(blue1, HIGH);
      digitalWrite(green1, HIGH);

      digitalWrite(blue2, HIGH);
      digitalWrite(green2, HIGH);

Here's a photo of the setup, notice how the LED's all light up differently. They are receiving the following voltages from left to right (2.48, 1.72, 3.02, 2.15):

![enter image description here][1]

Why is this happening and how do I get them all to light up the same?

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

body: After trying another Arduino I realized the problem. I did not use `pinMode` in the setup for all of the pins. Darn.


sender: user

message:
Serial.println Sensor Value and text in one line

**How do I put the sensor value and text on the one line in the serial monitor.**

I just want Pot Value 30 to show in the serial console. What am I doing wrong?

    Serial.println("POT value ")(sensorValue);

sender: assistant

body:
You just do two Serial prints:

    Serial.print("POT value ");
    Serial.println(sensorValue);

The `.print` prints without moving to a new line, the `.println` moves to a new line.

If you want to be more fancy and don't mind the processing and memory overhead, you can use `snprintf` to format the string:

    char temp[15];
    snprintf(temp, 15, "POT value M", sensorValue);
    Serial.println(temp);

You can read more about `sprintf` and formatting here:

* http://www.cplusplus.com/reference/cstdio/snprintf/ (function parameters)
* http://www.cplusplus.com/reference/cstdio/printf/ (formatting options)

**Note that there is no floating point support in the standard library for the Arduino - so you can't use %f etc.**


message:
Arduino Ethernet Shield 2 stuck on EthernetServer::begin()

I am currently trying to get the Ethernet Shield working on my Mega. I was trying to run the Webserver example but the program seems to stuck at one point, so I tried to start from scratch.

This is my test code:

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

    byte mac[] = {
      0x90, 0xA2, 0xDA, 0x0F, 0xF6, 0x3D
    };
    byte subnet[] = { 255,0,0,0 };
    byte gateway[] = { 2,0,0,1 };
    IPAddress ip(2, 0, 0, 1);

    EthernetServer server(80);

    void setup() {
      Serial.begin(9600);
      Ethernet.begin(mac, ip, gateway, subnet);
      Serial.println("Ethernet started");
      server.begin();
      Serial.println("Server started");
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println("Loop");
    }

The output I get from the serial console is:

    Etrted
    Ethernet started

So I think the program gets stuck inside the EthernetServer::begin() function.
I am aware that there are earlier versions of ethernet shields which are not compatible to the mega, but the vendor of my shield says it is.

Also I don't understand, why it outputs the first line.

Thanks for your hints!

body:
    // fill in your Domain Name Server address here:
    IPAddress myDns(192,168,1,1);

    // initialize the library instance:
    EthernetClient client;

    char server[] = "www.arduino.cc";

    unsigned long lastConnectionTime = 0;
    // last time you connected to the server, in milliseconds
    boolean lastConnected = false;
    // state of the connection last time through the main loop
    const unsigned long postingInterval = 14*1000;
    // delay between updates, in milliseconds

    void setup() {
      pinMode (pin, OUTPUT);
      digitalWrite (pin, LOW);

      // start serial port:
      Serial.begin(9600);
      // give the ethernet module time to boot up:
      delay(1000);
      // start the Ethernet connection using a fixed IP address and DNS server:
      Ethernet.begin(mac, ip, myDns);
      // print the Ethernet board/shield's IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      // if there's incoming data from the net connection.
      // send it out the serial port.  This is for debugging
      // purposes only:
      if (client.available()) {
        Serial.println ("1"); delay(500);
        char c = client.read();
        Serial.print(c);
        } else {Serial.println ("11");delay (500);}
      // if there's no net connection, but there was one last time
      // through the loop, then stop the client:
      if (!client.connected() && lastConnected) {
        Serial.println(2); delay(500);
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();
      } else {Serial.println ("22");delay (500);}

      // if you're not connected, and ten seconds have passed since
      // your last connection, then connect again and send data:
      if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
        Serial.println(3); delay(500);
        httpRequest();
        Serial.println ("4");delay (100);
      } else {Serial.println ("33");delay (500);}
      // store the state of the connection for next time through
      // the loop:
      lastConnected = client.connected();
      Serial.println ("end loop");
    }

    // this method makes a HTTP connection to the server:
    void httpRequest() {
      // if there's a successful connection:
      Serial.println ("httpRequest"); delay(500);
      if (client.connect(server, 80)) {
         Serial.println ("H1"); delay(500);
        Serial.println("connecting...");
        // send the HTTP PUT request:
        client.println("GET /latest.txt HTTP/1.1");
        client.println("Host: www.arduino.cc");
        client.println("User-Agent: arduino-ethernet");
        client.println("Connection: close");
        client.println();

        // note the time that the connection was made:
        lastConnectionTime = millis();
      } else {
        Serial.println ("H11"); delay(500);
        // if you couldn't make a connection:
        Serial.println("connection failed");
        Serial.println("disconnecting.");
        client.stop();
      }
    }

I inserted debug lines.  all I get are the faileure "if" comments.  after 15 seconds, I get debug #3 and then "HTTP Request" then nothing but crickets....


body:
You must use these libraries:

    #include <Ethernet.h>  -->  #include <Ethernet2.h>
    #include <EthernetUdp.h>  -->  #include <EthernetUdp2.h>

More info at this link [Arduino Ethernet Shield2][1]

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


body: Just to get this answered (see comments): It was a weird "bug" in my case. After days of research I found people with the same issue and in their cases it helped to cut all of the pin headers but the ICSP header by 2mm so the ICSP header had better contact. I tried it on my shield and it worked.


message:
control Arduino board using Android sensors and wifi?

i am thinking about building a Quadcopter that can be controlled with a computer via Wifi . but the problem is that with a lack of components and limited resources , i have been thinking of using my available components ( Arduino uno + smart phone + quadcopter frame with 4 brush-less motors and 4 speed control )
so i am asking you guys if it is possible to read smartphone sensor values using Arduino usb and control the quadcopter using smartphone wifi ??

body:
Is it possible?  Yes, it's certainly possible.  You can read the sensor values from within an Android program. It's possible to get Android to communicate with the Arduino through the USB.  The Arduino can be programmed to respond to what it gets through the serial.

Is it easy? Well, that depends on how good you are at Android programming.

One good place to start might be the [ArduinoFirmata-Android](http://shokai.github.io/ArduinoFirmata-Android/) project.  Don't worry about programming the Arduino, just install Firmata on it.  Then it's all down to how you program the Android device.  The Arduino just becomes a peripheral to your phone.


message:
How to write data in RAM memory using Arduino Uno or Arduino Due?

I know that it is possible to write data in [ROM][1](Read Only Memory).
But what about if I want to write data in [RAM][2](Random Access Memory)?
Can I do it using "Arduino Uno R3"?
RAM is normally associated with [volatile][3] types of memory.

There are several examples about writing data in [EEPROM][4] as in a (Read Only Memory) which may have 8 pins.
In order to store values read from analog input 0 into the EEPROM we need to use the "EEPROM.write()" function.
These values will stay in the EEPROM when the board is turned off and may be retrieved later by another sketch.
ROM is a [Non-volatile][5] type memory.
SD card is also Non-volatile type of memory.
We know that there are few SD card shields for "Arduino Uno" and it is possible create your own shields.

But what about volatile types of memory?
what about if I want to write data in RAM like a "[DDR SDRAM][6]" or in a DDR3 memory which may have 240 pins instead of 8 pins?
So my question is is it possible to write data in "DDR SDRAM" using "Arduiono Uno R3"?
How? Where should I connect those 240 pins?

  [1]: https://en.wikipedia.org/wiki/Read-only_memory
  [2]: https://en.wikipedia.org/wiki/Random-access_memory
  [3]: https://en.wikipedia.org/wiki/Volatile_memory
  [4]: https://en.wikipedia.org/wiki/EEPROM
  [5]: https://en.wikipedia.org/wiki/Non-volatile_memory
  [6]: https://en.wikipedia.org/wiki/DDR_SDRAM

body: DRAM of any kind requires a memory controller which is not present in any AVR device. Larger AVR devices such as the ATmega64A and ATmega128A do have an external memory bus that can be used for SRAM and MMIO.


body:
Your program is already using the on board RAM:

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

    int a = 5; // This is RAM. Where did you think it goes? (This might go to a CPU Reg)
    int a[5000]; // This is RAM

**DDR3 RAMs** require (typically) `1633 MHz` clocks, and store gigabytes of data, not something you use with Arduino, which has a `16 MHz` CPU.

If you need **EXTRA** (emphasis on extra) `RAM`, my first advice would be to refactor your project, and reduce processing on *Arduino*.

However, if must have more `RAM`, get `SRAM`. In most cases, `DDR3` trade high maintenance for cost. Have a look [here][1].

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


body:
The easiest way to read and write DDR SRAM would be to install it in a PC and write a serial server that allowed the Arduino to access the data by requesting it over the serial port.

Now although that is possible to do, the performance probably won't be great.  So it might be worth looking into memory that interfaces over SPI or IIC, there are several ICs that you could use.  Most of them would have libraries already available and you would be looking at about £1 per 256kbits.

But like it has been said above if you are looking at storing multi-GBs of data then you probably want SD cards.  If the write speed is going to be a problem then look at multiplexing the data over many SD cards.


message:
Aduino 7 segment dice project

I am struggling with the code that I should write for my project. I finished my breadboard but I have never learnt programming before so I cannot write the program for the dice.
My project is to make the dice output random numbers when the button is pressed.
This is what I have completed already. I just want to know how to complete the program to make it work for my arduino.
![enter image description here][1]

This is the code so far:

    int leda = 2;
    int ledb = 3;
    int ledc = 4;
    int ledd = 5;
    int lede = 6;
    int ledf = 7;
    int ledg = 8;
    int ledh = 9;
    int leda1 = A0;
    int ledb1 = A1;
    int ledc1 = A2;
    int ledd1 = A3;
    int lede1 = A4;
    int ledf1 = A5;
    int ledg1 = A6;
    int ledh1 = A7;

    void setup()
    {
        Serial.begin(9600);
        pinMode(leda, OUTPUT);
        pinMode(ledb, OUTPUT);
        pinMode(ledc, OUTPUT);
        pinMode(ledd, OUTPUT);
        pinMode(lede, OUTPUT);
        pinMode(ledf, OUTPUT);
        pinMode(ledg, OUTPUT);
        pinMode(ledh, OUTPUT);
        pinMode(leda1, OUTPUT);
        pinMode(ledb1, OUTPUT);
        pinMode(ledc1, OUTPUT);
        pinMode(ledd1, OUTPUT);
        pinMode(lede1, OUTPUT);
        pinMode(ledf1, OUTPUT);
        pinMode(ledg1, OUTPUT);
        pinMode(ledh1, OUTPUT);

        pinMode(12, INPUT);

        digitalWrite(12, HIGH);
    }

    if (number == 1)
    {
        digitalWrite(2, HIGH);
        digitalWrite(7, HIGH);
    }

    else if (number == 2)
    {
        digitalWrite(3, HIGH);
        digitalWrite(2, HIGH);
        digitalWrite(5, HIGH);
        digitalWrite(9, HIGH);
        digitalWrite(8, HIGH);
        delay(200);
    }
    else if (number == 3)
    {
        digitalWrite(3,HIGH);
        digitalWrite(2,HIGH);
        digitalWrite(5,HIGH);
        digitalWrite(7,HIGH);
        digitalWrite(8,HIGH);
        delay(200);
    }

    else if (number == 4)
    {
        // do number 4
    }

    else if (number == 5)
    {
        // do number 5
    }

    // ... etc
    // Additional 'numbers' have been removed for brevity

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

body:
I made it so at least it compiles. It should loop through the numbers.

As for the circuit; you really should add a resistor to every segment, instead of just one the the common cathode. Otherwise the brightness will be different if more segments are on.

    int number = 1;
    int number1 = 1;

    int leda = 2;
    int ledb = 3;
    int ledc = 4;
    int ledd = 5;
    int lede = 6;
    int ledf = 7;
    int ledg = 8;
    int ledh = 9;

    int leda1 = A0;
    int ledb1 = A1;
    int ledc1 = A2;
    int ledd1 = A3;
    int lede1 = A4;
    int ledf1 = A5;
    int ledg1 = A6;
    int ledh1 = A7;

    void setup() {
     Serial.begin(9600);

     pinMode(leda, OUTPUT);
     pinMode(ledb, OUTPUT);
     pinMode(ledc, OUTPUT);
     pinMode(ledd, OUTPUT);
     pinMode(lede, OUTPUT);
     pinMode(ledf, OUTPUT);
     pinMode(ledg, OUTPUT);
     pinMode(ledh, OUTPUT);

     pinMode(leda1, OUTPUT);
     pinMode(ledb1, OUTPUT);
     pinMode(ledc1, OUTPUT);
     pinMode(ledd1, OUTPUT);
     pinMode(lede1, OUTPUT);
     pinMode(ledf1, OUTPUT);
     pinMode(ledg1, OUTPUT);
     pinMode(ledh1, OUTPUT);

     pinMode(12, INPUT);
     digitalWrite(12, HIGH);
    }
    void loop() {

     // turn off all leds
     digitalWrite(leda, LOW);
     digitalWrite(ledb, LOW);
     digitalWrite(ledc, LOW);
     digitalWrite(ledd, LOW);
     digitalWrite(lede, LOW);
     digitalWrite(ledf, LOW);
     digitalWrite(ledg, LOW);
     digitalWrite(ledh, LOW);

     digitalWrite(leda1, LOW);
     digitalWrite(ledb1, LOW);
     digitalWrite(ledc1, LOW);
     digitalWrite(ledd1, LOW);
     digitalWrite(lede1, LOW);
     digitalWrite(ledf1, LOW);
     digitalWrite(ledg1, LOW);
     digitalWrite(ledh1, LOW);

     if (number == 1)
     {
      digitalWrite(leda, HIGH);
      digitalWrite(ledf, HIGH);
      delay(200);
     }
     else if (number == 2)
     {
      digitalWrite(ledb, HIGH);
      digitalWrite(leda, HIGH);
      digitalWrite(ledd, HIGH);
         digitalWrite(ledh, HIGH);
         digitalWrite(ledg, HIGH);
      delay(200);
     }
     else if (number == 3)
     {
      digitalWrite(ledb,HIGH);
      digitalWrite(leda,HIGH);
      digitalWrite(ledd,HIGH);
      digitalWrite(ledf,HIGH);
      digitalWrite(ledg,HIGH);
      delay(200);
     }
     else if (number == 4)
     {
      digitalWrite(ledc,HIGH);
      digitalWrite(ledd,HIGH);
      digitalWrite(leda,HIGH);
      digitalWrite(ledf,HIGH);
      delay(200);
     }
     else if (number == 5)
     {
      digitalWrite(ledb,HIGH);
      digitalWrite(ledc,HIGH);
      digitalWrite(ledd,HIGH);
      digitalWrite(ledf,HIGH);
      digitalWrite(ledg,HIGH);
      delay(200);
     }
     else if (number == 6)
     {
      digitalWrite(ledb,HIGH);
      digitalWrite(ledc,HIGH);
      digitalWrite(ledd,HIGH);
      digitalWrite(ledf,HIGH);
      digitalWrite(ledg,HIGH);
      digitalWrite(ledh,HIGH);
      delay(200);
     }

     if (number1 == 1)
     {
      digitalWrite(A4, HIGH);
      digitalWrite(A1, HIGH);
      delay(200);
     }
     else if (number1 == 2)
     {
      digitalWrite(A5, HIGH);
      digitalWrite(A4, HIGH);
      digitalWrite(A7, HIGH);
      digitalWrite(A0, HIGH);
      digitalWrite(A2, HIGH);
      delay(200);
     }
     else if (number1 == 3)
     {
      digitalWrite(A5,HIGH);
      digitalWrite(A4,HIGH);
      digitalWrite(A7,HIGH);
      digitalWrite(A1,HIGH);
      digitalWrite(A2,HIGH);
      delay(200);
     }
     else if (number1 == 4)
     {
      digitalWrite(A6,HIGH);
      digitalWrite(A7,HIGH);
      digitalWrite(A4,HIGH);
      digitalWrite(A2,HIGH);
      delay(200);
     }
     else if (number1 == 5)
     {
      digitalWrite(A5,HIGH);
      digitalWrite(A6,HIGH);
      digitalWrite(A7,HIGH);
      digitalWrite(A1,HIGH);
      digitalWrite(A2,HIGH);
      delay(200);
     }
     else if (number1 == 6)
     {
      digitalWrite(A5,HIGH);
      digitalWrite(A6,HIGH);
      digitalWrite(A7,HIGH);
      digitalWrite(A0,HIGH);
      digitalWrite(A1,HIGH);
      digitalWrite(A2,HIGH);
      delay(200);
     }

     number = (number%6) + 1;//show next number the next loop
    }


body:
## About random numbers ##

What you are trying to achieve is actually not that easy. An Arduino is
basically a computer, and as any computer, it is designed to execute
instructions in a very _deterministic_ fashion. Computers are not good
at randomness and, unless fitted with dedicated hardware, they _cannot_
generate random numbers. Given this, you are left with two options:

 1. [pseudo-random number generators](https://en.wikipedia.org/wiki/Pseudorandom_number_generator)
 2. [entropy](http://en.wikipedia.org/wiki/Entropy_(computing)) gathering

The first is the easiest:

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

    int first_dice  = random(1, 7);  // 1 (inclusive) to 7 (exclusive)
    int second_dice = random(1, 7);

and voilà! You have two random-looking numbers. They are random-looking
in the sense that you will find no obvious pattern in any sequence of
numbers you draw. However, if you reset your Arduino, either with the
reset button or by power-cycling it, it will give you the _exact same
sequence_ as in the first run. Thus, pseudo-randomness in useless unless
you commit to never unpower your circuit. It is a good starting point,
however, if your main goal is to get started with Arduino programming.

Entropy gathering means getting some randomness from outside the
Arduino: you would connect it to some source of randomness and perform
some measurement that has unpredictable outcome. A human being is a good
source of randomness: if you require the user to press a button before
displaying the dice value, the timing of the button press is a good
random source. The `micros()` function can be used to get the current
time with 4 µs resolution, which is more than enough for this
purpose. Entropy gathering is usually used in tandem with pseudo-random
number generators, as a way to _seed_ them, like this:

    wait_for_the_user_to_press_a_button();
    randomSeed(micros());
    int first_dice =  random(1, 7);
    int second_dice = random(1, 7);

If you cannot have human interaction, you could try to get some
electromagnetic noise by performing an `analogRead()` on a floating pin.
Ideally you would connect that pin to an analog noise source. See the
first comment to this answer for more information on this option.

## About arrays and loops ##

You should definitely try to find a good tutorial about arrays and
loops. Whenever you find yourself writing tons of almost-identical lines
of code, you should wonder whether you can replace that repetition with
a loop. For example, for displaying the digit `1`, you may write:

    if (number == 1) {
        digitalWrite(leda,  LOW);
        digitalWrite(ledb, HIGH);
        digitalWrite(ledc, HIGH);
        digitalWrite(ledd,  LOW);
        digitalWrite(lede,  LOW);
        digitalWrite(ledf,  LOW);
        digitalWrite(ledg,  LOW);
    }

(I am using the "canonical" A–G letter assignments, and yes, you should
also take care of setting to `LOW` the segments you want to be off).
This code is an obvious candidate for being replaced by a loop:

    if (number == 1) {
        for (int segment = 0; segment < 7; segment++)
            digitalWrite(leds[segment], digit1[segment]);
    }

This requires that you first define the following arrays:

    //                A     B     C     D     E     F     G
    int leds[]   = {  2,    3,    4,    5,    6,    7,    8 };
    int digit1[] = { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW};

This logic can be pushed one level further by using a two-dimensional
array (an array of arrays): instead of defining six arrays `digit1`,
`digit2`... `digit6`, you create an array of arrays like this:

    int digits[][7] = {
             /*          A     B     C     D     E     F     G  */
             /* 1 */  { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW},
             /* 2 */  {HIGH, HIGH,  LOW, HIGH, HIGH,  LOW, HIGH},
             ...
    };

and you use `digits[number]` instead of `digit1`, etc. This way you get
rid of the whole `if () ... else if ()` chain, replaced by:

    for (int segment = 0; segment < 7; segment++)
        digitalWrite(leds[segment], digits[number-1][segment]);

Take care though that in C++ arrays are indexed from zero, which is why
you need to use `number-1` as the index in `digits`. If you have more
than one die (which is your case), you can also put their pin
assignments in a two-dimensional array. Then all the dice updating code
would be wrapped inside a loop indexed by the die number. Putting all
this together you end up with something like this:

    // Pin assignments.
    int leds[][7] = {
       /*                A     B     C     D     E     F     G  */
       /* 1st die */  {  2,    3,    4,    5,    6,    7,    8 },
       /* 2nd die */  { A0,   A1,   A2,   A3,   A4,   A5,   A6 }
    };

    // 7-segment "font".
    int digits[][7] = {
             /*          A     B     C     D     E     F     G  */
             /* 1 */  { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW},
             /* 2 */  {HIGH, HIGH,  LOW, HIGH, HIGH,  LOW, HIGH},
             /* 3 */  {HIGH, HIGH, HIGH, HIGH,  LOW,  LOW, HIGH},
             /* 4 */  { LOW, HIGH, HIGH,  LOW,  LOW, HIGH, HIGH},
             /* 5 */  {HIGH,  LOW, HIGH, HIGH,  LOW, HIGH, HIGH},
             /* 6 */  {HIGH,  LOW, HIGH, HIGH, HIGH, HIGH, HIGH}
    };

    void setup()
    {
        for (int die = 0; die < 2; die++) {
            for (int segment = 0; segment < 7; segment++) {
                pinMode(leds[die][segment], OUTPUT);
            }
        }
    }

    void loop() {
        for (int die = 0; die < 2; die++) {
            int number = random(1, 7);
            for (int segment = 0; segment < 7; segment++)
                digitalWrite(leds[die][segment], digits[number][segment]);
        }
        delay(200);
    }

This is still lacking the entropy gathering phase discussed above.


message:
What's wrong with my Arduino board?

When I connect the Arduino to my PC the Led "ON" lights for a second then turns OFF. I wonder if the Arduino has a fault?

body:
Most likely a short between VCC (5 volt) and GROUND. When there is a short the fuse will kick in after a second, and disable the whole board, including the ON-led.

When you disconnect the board, the fuse will reset.

So either the board is faulty of the connection you made to it are.


message:
Arduino Protothreads by Example

I am trying to get Arduino working with [Protothreads](http://dunkels.com/adam/pt/) and wanted to confirm I have the basic setup correct. If I have understood the API correctly, then the following code should be what I need to start 2 concurrent threads from inside an Arduino program:

    #include <pt.h>

    static struct pt t1, t2;

    void setup() {
        PT_INIT(&t1);
        PT_INIT(&t2);
    }

    void loop() {
        doSomething(&t1, 500);
        doSomethingElse(&t2, 500);
    }

    static int doSomething(struct pt *pt, int interval) {
        PT_BEGIN(pt);
        sleep(100);
        PT_END(pt);
    }

    static int doSomethingElse(struct pt *pt, int interval) {
        PT_BEGIN(pt);
        sleep(250);
        PT_END(pt);
    }

Does anyone see anything that jumps out at them as missing or wrong?

body:
Check [this example][1]: rather than sleep(), it uses PT_WAIT_UNTIL

      while(1) {
          PT_WAIT_UNTIL(pt, millis() - timestamp > interval );
          timestamp = millis();
          doSomething();
      }

That should be the proto-thread way of waiting: PT_WAIT_UNTIL will make sure that your thread sleeps in a way that allows other threads to run.

The rest looks fine, but I have not tried to run the code.

  [1]: http://harteware.blogspot.de/2010/11/protothread-and-arduino-first-easy.html


body:
Why reinvent the wheel? There are libraries that can do just that for you.
For example
**[ArduinoThread][1]**. I tried it out and did not need to keep looking further. There are also [Wiring][2] and [SoftTimer][3] but I did not try those.

  [1]: https://github.com/ivanseidel/ArduinoThread
  [2]: http://wiring.org.co/download/
  [3]: https://github.com/prampec/arduino-softtimer


message:
analogRead-ing Potentiometer Values in void setup()

I've run into a problem while coding a speedometer meant for bicycles. The speedometer would require the diameter of the wheel in inches for maximum accuracy, so I'd like to have an adjustable (by potentiometer) numerical prompt appear on two 7 segment LEDs. So, for example, the device would be turned on, it would display "16," the user would turn the potentiometer knob until the 7 segment LED displays "24," then the user would push a button [indicating the beginning of the loop()], and the speedometer would begin measuring and displaying his or her speed.

This would be an easier task to accomplish in the loop section of the code, but, because I only want this series of potentiometer analogReads to occur once, it gets a bit trickier.

Some clarification: Every other component of the speedometer works (such as the 7 segment LEDs via shift register and the actual measurements), so I'm only looking for help with the code for the potentiometer.

Thanks!

body:
You presumably know that:  The easiest and usual way to read a potentiometer is to connect the "track" between V_pot (often = Vcc) and ground and to connect the pot "wiper" to an analog input pin. You then use analogRead(Ax) to read the pot value in the range 0-255.

The use of analogRead() is valid in setup.

However a more "real" method would be to have a "flag" variable that indicates that the speedo initialisation code has or hasn't been run.
Set this flag to false in setup, detect and action it in loop and then set the flag to true so that the code is not repeatedly actioned.

________________________

eg

void setup()
{

...
boolean initialised = false ;
...
}

void loop()
{
if (initialised == false) {
// initialise speedo
//  ....
   initialised = true;
}

...

} // end of loop()

}


body:
If you really want to use this feature in the setup() then you can do like this:

    #define BUTTON 2
    boolean not_done = true;

    void stopDiameterSetup() {
        // some button debounche code
        ...
        // we are done with setting up the diameter.
        not_done = false;
    }
    void setup() {
        ...

        // POT reading
        interrupts();
        attachInterrupt();
        while(not_done) {
           attachInterrupt(BUTTON, stopDiameterSetup, CHANGE);
        }
    }
    void loop(){
    // your loop code
    }

If you can't or afraid to use interrupts then just check for a button pressed inside the while loop.


message:
Light sensor acting up when used with other code

I have a light sensor that works fine and outputs the correct data to the serial monitor when I only upload the following code to the nano:

    const int lightSensorPin = A0;
    int lightSensorValue = 0;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      lightSensorValue = analogRead(lightSensorPin);
      delay(100);
      Serial.println(lightSensorValue);
    }

Now when I upload it with all of my other code, which includes lighting up about 6 LED's at one time and getting readings from two rangefinder sensors, the light sensors no longer output expected data, instead spewing out a bunch of random numbers, 0 to over 3000.

Could sharing the ground with all the LED's and rangefinders be causing interference for the light sensor? Or could it be a code optimization issue? Here's my entire code if it helps at all:

    int trigPin1 = 5;
    int echoPin1 = 6;
    int blue1 =  7;
    int green1 = 8;

    int trigPin2 = A3;
    int echoPin2 = A4;
    int blue2 =  A2;
    int green2 = A1;

    int redLED = 10;
    int greenLED = 3;
    int yellowLED = 9;
    int blueLED = 4;

    const int lightSensorPin = A0;
    int lightSensorValue = 0;

    int securityLength1 = 28;
    int securityLength2 = 28;

    int frontEyes(11);
    int backEyes(12);

    const char* front = "front";
    const char* back = "back";

    void setup()
    {
      Serial.begin(9600);

      pinMode(trigPin1, OUTPUT);
      pinMode(echoPin1, INPUT);
      pinMode(trigPin2, OUTPUT);
      pinMode(echoPin2, INPUT);

      pinMode(blue1, OUTPUT);
      pinMode(green1, OUTPUT);
      pinMode(blue2, OUTPUT);
      pinMode(green2, OUTPUT);

      pinMode(frontEyes, OUTPUT);
      pinMode(backEyes, OUTPUT);

      pinMode(redLED, OUTPUT);
      pinMode(greenLED, OUTPUT);
      pinMode(yellowLED, OUTPUT);

    }//end setup

    void loop(){

      digitalWrite(redLED, HIGH);
      digitalWrite(greenLED, HIGH);
      digitalWrite(yellowLED, HIGH);
      digitalWrite(blueLED, HIGH);

    eyeballs(trigPin1, echoPin1, securityLength1, green1, blue1, front);
    eyeballs(trigPin2, echoPin2, securityLength2, green2, blue2, back);

      lightSensorValue = analogRead(lightSensorPin);
      delay(100);
      Serial.println(lightSensorValue);

    }//end loop

    void eyeballs(int trigPin, int echoPin, int securityLength, int green, int blue, const char* frontOrBack){
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      long duration = pulseIn(echoPin, HIGH);
      long distance = (duration/2) / 29.1;

      Serial.println(distance);

     if (distance >= securityLength || distance <= 0) {
      digitalWrite(green,HIGH);
      digitalWrite(blue,LOW);
      if (frontOrBack == "front") {
        digitalWrite(frontEyes, LOW);
      }//end if
      else if (frontOrBack == "back") {
        digitalWrite(backEyes, LOW);
      }//end else
      }//end if

      else if(distance < securityLength) {
      digitalWrite(blue,HIGH);
      digitalWrite(green,LOW);

      if (frontOrBack == "front") {
        digitalWrite(frontEyes, HIGH);
      }//end if
      else if (frontOrBack == "back") {
        digitalWrite(backEyes, HIGH);
      }//end else

     }//end else if

    }//end function

body:
There's no `pinMode(lightSensorPin, INPUT);` in either of your codes. In the original code this probably doesn't matter because you set no other pins to In or Out.

As a side note, instead of declaring all your pin number as `int` then defining them, make use of *preprocessor directives*:

    #define trigPin1  5;
    #define echoPin1  6;
    #define blue1     7;
    #define green1    8;

When you hit Verify or Upload the *preprocessor* sweeps through your code and replaces all instances of a defined term with whatever comes immediately after it in the definition. You can't use it for variables of course, but it's perfect for designating pins.

This will cut down on unnecessary memory usage. Not a huge saving in your case, but I don't see why people don't do it more often.


body: I'd prefer to delete this question because I'm so embarrassed by the answer. I didn't notice I had `Serial.println(distance);` in my function. The odd numbers were coming from my rangefinders and being printed in between my light readings.


message:
Connecting battery and LED to Arduino Due

I am brand new to Arduino/robotics and am trying to take baby steps. First I'd like to just power an Arduino and an LED from a 9V battery like so:

![enter image description here][1]

No programming, just simple circuitry. The battery powers the Due, and the Due in turn powers the LED.

A few concerns here:

* Will the 9V battery fry the Due, which I *believe* is expecting 3.3V? If so, what can I do to reduce the voltage/amps?
* Will the 9V battery fry the resistor and/or LED?
* As you can see by my question marks, I'm not real sure *where* to connect the battery to the Due (both positive & negative terminals) as well as the *where* to connect the breadboard to the Due (again, both terminals).

Any ideas?

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

body:
What you want is something like this (ignore the fact that my mini breadboard is stuck to a shield):
![Simple LED example with no software.][1]

My starter Arduino kit came with the connector for the 9 volt battery into the power socket on the Arduino, you may need to make one.  You cannot connect the 9V battery to any other part of the Due that I am aware of (without damaging it!).

It is perfectly safe to power your Arduino with 9V this way, there is circuitry to step the voltage down to the 5V and 3.3V that the board requires.

In the connector strip nearest this power socket (labelled Power on my board) there are a couple of Gnd connections and 5V and 3.3V connectors perfect for what you want to do.  I have used the 3.3V connector in my photo, but the 5V one should also be fine with the right resistor.

In your picture you don't appear to have anything connecting the LED to ground, but other than that, if you were to connect the battery up as I have shown and the red and black LED connectors to 3.3V and Gnd respectively, it should work as desired.

As a next step, you could load the sample sketch Examples->01Basic->Blink, write it to your Due, move the red LED connecting wire to pin 13 on the opposite side and your LED would flash (along with one of the LEDs on the Due board itself).

Edit (to specifically address your concerns):

 - The 9V battery will not fry the Due if it is connected through the power socket, which has circuitry to drop the voltage to safe levels.
 - The 9V battery will not damage the LED or resistor as they are connected to 5V or 3.3V that the Due outputs, not the 9V from the battery.
 - Only connect the battery through the power socket.  If you have a good quality steady 5V power supply, you can power the board through a 5V pin (at least I have been able to), but you bypass the voltage regulation circuitry that way and it is not recommended.  Connect the black wire from your LED to any Gnd pin, connect the red wire from the LED to 3.3V or 5V.

Additional edit:
You can connect the battery directly to the Arduino Due board without needing a plug to connect to the power socket.  Connect the red battery wire to the Vin pin and the black battery wire to a Gnd pin.

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


message:
Will writing to serial when no serial is available cause problems?

I have an Arduino UNO, and use the serial for debugging purposes. What happens if I run the arduino on batteries and try to write to serial? Will the code stop running until a serial connection is availible?

body:
No, that will not cause any problem.

What might hurt you is the fact that if you want to leave your Arduino in low power mode, but keep the serial potr disconnected _and_ the serial port is a wakeup source, it might pick up sporadic (but frequent enough to cause be noticeable) noise that will trigger wakeups and spam with meaningless data your RX.

This, however, is not specific to the serial port, but it can happen to any wake up source that is enabled and left dangling.


message:
How to count the number of times a changing variable reaches a peak value

I am recording a varying distance with an Ultrasonic sensor and Arduino but my problem is I want to display the number of times this variable reaches peak (at an instance the value will be increasing and the next instance decreasing in that order) on an LCD.

So far this is my code:

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

    //Libraries
    #include <Ultrasonic.h>
    #include <LiquidCrystal.h>

    //Setup connection with LCD and HC-SR04
    LiquidCrystal lcd(12, 10, 5, 4, 3, 2);
    Ultrasonic ultrasonic(A0,A1);

    void setup() {
      //Lcd init
      lcd.begin(16, 2); //16 rows, 2 columns
    }

    void loop()
    {
      lcd.clear();
      lcd.print("  Ardumotive ;)  "); // You can change this message.
      lcd.setCursor(0, 1);
      lcd.print("Distance: ");
      lcd.print(ultrasonic.Ranging(CM));
      lcd.print("cm");

      delay(300); // 1sec delay
    }

body:
The counting portion of what you want to achieve is simple - you just increment a variable.  The hard part is knowing *when* to count.

You need to remember what your value has been doing in the past in order to know if you have had a peak or not.  Also you have to define exactly what a peak is.

The simplest method (I'm not going to spoon feed you code, just help you understand the concepts) is to set a couple of thresholds, and maintain a flag.

You decide upon a value "above which the value enters the peak zone", and another "below which the value leaves the peak zone".  They could be the same value, but don't need to be.

You then have a flag which remembers if you are in the peak zone or not.

If you're not currently in the peak zone and the new value is above the peak zone entry threshold then you have entered the peak zone.  Set the flag to remember that fact.

If you are currently in the peak zone and the new value is below the peak zone leaving threshold then you have just left the peak zone.  Clear the flag to remember the fact that you're not in the peak zone and increment your peak counter now you have left the peak.

![enter image description here][1]

It can be very good to have the leaving threshold lower than the entering threshold so that the value has to drop significantly out of the peak zone before it will register another peak.  This is known as [hysteresis](http://en.wikipedia.org/wiki/Hysteresis) and is great for getting rid of the noise you may get if the value is hovering around the peak zone entry threshold.

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


body:
If ((current distance - previous distance) < 0)
Max = previous distance;

Current distance = previous distance;


message:
Coding Debugging

This program is supposed to act as a Decimal To Binary Converter, the LeD's acting as output.
The problem is that this function returns Garbage Value
<pre>
const int LED1 =1, LED2 =3, LED3 =5;
void setup()
{
  Serial.begin(9600);
  pinMode (LED1, OUTPUT);
  pinMode (LED2, OUTPUT);
  pinMode (LED3, OUTPUT);
}
void loop()
{
  int x = 0;
  x = Serial.read();
  x = x-48;
  switch(x){
    case 0:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, LOW);
      break;
    case 1:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, LOW);
      break;
      case 2:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, LOW);
      break;
      case 3:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, LOW);
      break;
      case 4:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, HIGH);
      break;
      case 5:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, HIGH);
      break;
      case 6:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, HIGH);
      break;
      case 7:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, HIGH);
      break;
  }
 Serial.write(x);
}
</pre>

body:
That massive program can be compressed into just a handful of lines:

    const int LED1 = 1,
              LED2 = 3,
              LED3 = 5;

    void setup() {
        Serial.begin(9600);
        pinMode (LED1, OUTPUT);
        pinMode (LED2, OUTPUT);
        pinMode (LED3, OUTPUT);
    }

    void loop() {
        if (Serial.available()) {
            int x = Serial.read();
            x = x - '0';
            digitalWrite(LED1, x & 0x01);
            digitalWrite(LED2, x & 0x02);
            digitalWrite(LED3, x & 0x04);
            Serial.print(x);
        }
    }

Note the use of Serial.print() not Serial.write().  If you use Serial.write() then it prints the ASCII character associated with the number you feed it - in your case characters 0 to 7 (none of which are printable).

Also, unless you check for there actually being something available for you to read from the serial you'll only get a brief flicker of something meaningful (too fast for the eye to see) and then it will just return -1, which with 48 subtracted from it would be -49, which would be "complete garbage".


body:
There are a couple of issues:

 - The function `loop()` doesn't return anything, by definition. Functions that do return a value return it with a statement like `return(someValue); Did you mean to say that it *prints* garbage on the terminal?

 - If you want to print a value on the terminal, you need to use the the `Serial.print(someValue)` function; `Serial.write()` sends a binary value and that is probably not what you wanted. The binary values 0 - 9 represent non-printing characters so I'm not surprised that the terminal printed some odd graphic characters.

-


message:
Leonardo Serial1 enable internal pull-up for removable Bluetooth module

I would like to have a serial Bluetooth module thats completely removable, leaving nothing connected to the arduino.

My code would freeze up whenever the Bluetooth module was removed. I eventually tracked down the issue to an overwhelming amount of garbage being received from the disconnected serial pins.

I enabled the internal pull-up resistor on pin 0 (serial rx) in the setup() function which appears to have solved all my problems but is that correct? I found barely any information on removable serial devices, floating serial connections and pull-up resistors.

I suppose it's important to enable the pull up before calling serial1.begin() or maybe flushing the serial buffer once before reading any input to ensure there's no garbage?

body:
Yes, what you have done is good.

It is important to tie all unused inputs to a stable state (normally low) to reduce current consumption from floating inputs.  When those inputs are actively used but not connected it is even more important to stop things happening that shouldn't.

As I mentioned, normally you'd use a pull-down, not a pull-up, but the UART is actually a special case where you would want to use a pull-up (as you have) not a pull-down.

UART is "Idle High", which means that when there is no data being transmitted on a line it is held high by the transmitter.  By adding a pull-up you are making it appear as if there is something connected but that something isn't actively transmitting at the moment.

The internal pullups aren't very strong, so in a noisy environment you may still get some spurious data on the UART.  If that happens then you want to add an external stronger (lower resistance) pull up.

Another thing to think about with your disconnected pins is to protect them from ESD.  You should have some TVS diodes on those pins to absorb spikes, and some small inline resistors to limit any overcurrent conditions.


message:
Controlling 2WD car chassis with PS3 controller

I'm having trouble with controlling my car with the PS3 joystick, and there hasn't been any example codes out there. I'm using;

 - PS3USB library from USB_Host_shield_2.0 library
 - Freetronics H Bridge shield http://www.freetronics.com.au/collections/shields/products/hbridge-dual-channel-h-bridge-motor-driver-shield#.VXMqXUJJmgM

This is my code;

    include <PS3USB.h>

    // Satisfy the IDE, which needs to see the include statment in the ino too.
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #include <SPI.h>
    #endif

    USB Usb;
    /* You can create the instance of the class in two ways */
    PS3USB PS3(&Usb); // This will just create the instance
    //PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

    bool printAngle;
    uint8_t state = 0;

    int motora1 = 4;
    int motora2 = 7;
    int motoraspeed = 6;
    int motorb1 = 3;
    int motorb2 = 2;
    int motorbspeed = 5;

    void setup() {
      Serial.begin(115200);
    #if !defined(__MIPSEL__)
      while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
    #endif
      if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
        while (1); //halt
      }
      Serial.print(F("\r\nPS3 USB Library Started"));
      pinMode(motora1, OUTPUT);
      pinMode(motora2, OUTPUT);
      pinMode(motoraspeed, OUTPUT);
      pinMode(motorb1, OUTPUT);
      pinMode(motorb2, OUTPUT);
      pinMode(motorbspeed, OUTPUT);
      delay(5000);
    }

    void loop() {
      Usb.Task();

      if (PS3.PS3Connected || PS3.PS3NavigationConnected) {

        //go forward
         if (PS3.getAnalogHat(LeftHatY) == 0) {
           Serial.print(F("\r\nLeftHatY: "));
          Serial.print(PS3.getAnalogHat(LeftHatY));
             digitalWrite(motora1, HIGH);
              digitalWrite(motora2, LOW);
              digitalWrite(motoraspeed, 255);
            digitalWrite(motorb1, HIGH);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 255);
    }

    //go backward
    if (PS3.getAnalogHat(LeftHatY) == 255) {
           Serial.print(F("\r\nLeftHatY: "));
          Serial.print(PS3.getAnalogHat(LeftHatY));
               digitalWrite(motora1, LOW);
      digitalWrite(motora2, HIGH);
      digitalWrite(motoraspeed, 255);
      digitalWrite(motorb1, LOW);
      digitalWrite(motorb2, HIGH);
      digitalWrite(motorbspeed, 255);
    }

    //turn left
    if (PS3.getAnalogHat(RightHatX) == 0) {
           Serial.print(F("\r\RightHatX: "));
          Serial.print(PS3.getAnalogHat(RightHatX));
               digitalWrite(motora1, HIGH);
      digitalWrite(motora2, LOW);
      digitalWrite(motoraspeed, 200);
      digitalWrite(motorb1, LOW);
      digitalWrite(motorb2, HIGH);
      digitalWrite(motorbspeed, 200);
    }

       //turn right
       if (PS3.getAnalogHat(RightHatX) == 255) {
           Serial.print(F("\r\RightHatX: "));
          Serial.print(PS3.getAnalogHat(RightHatX));
              digitalWrite(motora1, LOW);
      digitalWrite(motora2, HIGH);
      digitalWrite(motoraspeed, 200);
      digitalWrite(motorb1, HIGH);
      digitalWrite(motorb2, LOW);
      digitalWrite(motorbspeed, 200);
    }

As of now, when I look at my code in the serial monitor, I get the following;

    LeftHatY: 131
    RightHatX: 127
    LeftHatY: 130
    RightHatX: 127
    LeftHatY: 130
    RightHatX: 127
    LeftHatY: 130
    RightHatX: 127
    LeftHatY: 130
    RightHatX: 127
    LeftHatY: 131
    RightHatX: 127
    LeftHatY: 131
    RightHatX: 127
    LeftHatY: 131
    RightHatX: 127
    LeftHatY: 131
    RightHatX: 127
    LeftHatY: 131
    RightHatX: 127
    LeftHatY: 131
    RightHatX: 127
    LeftHatY: 131
    RightHatX: 127
    LeftHatY: 131
    RightHatX: 127
    LeftHatY: 130
    RightHatX: 127
    LeftHatY: 130
    RightHatX: 127
    LeftHatY: 130
    RightHatX: 127
    LeftHatY: 130
    RightHatX: 127
    LeftHatY: 131
    RightHatX: 127
    LeftHatY: 131
    RightHatX: 127
    LeftHatY: 131
    RightHatX: 127

The numbers adjust as I'm moving the joystick around but just keeps going even though I'm not moving the joystick around. Any help would be appreciated, thanks

body:
I found three issues:

 1. You don't have a `#` before the include on line 1.
 2. There is no `}` at the end of the `void loop()`.
 3. You forgot to include an if statement for when the joystick is idle.

Try this code:

    #include <PS3USB.h>

        // Satisfy the IDE, which needs to see the include statment in the ino too.
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #include <SPI.h>
    #endif

    USB Usb;
    /* You can create the instance of the class in two ways */
    PS3USB PS3(&Usb); // This will just create the instance
                      //PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

    bool printAngle;
    uint8_t state = 0;

    int motora1 = 4;
    int motora2 = 7;
    int motoraspeed = 6;
    int motorb1 = 3;
    int motorb2 = 2;
    int motorbspeed = 5;

    void setup() {
        Serial.begin(115200);
    #if !defined(__MIPSEL__)
        while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
    #endif
        if (Usb.Init() == -1) {
            Serial.print(F("\r\nOSC did not start"));
            while (1); //halt
        }
        Serial.print(F("\r\nPS3 USB Library Started"));
        pinMode(motora1, OUTPUT);
        pinMode(motora2, OUTPUT);
        pinMode(motoraspeed, OUTPUT);
        pinMode(motorb1, OUTPUT);
        pinMode(motorb2, OUTPUT);
        pinMode(motorbspeed, OUTPUT);
        delay(5000);
    }

    void loop() {
        Usb.Task();

        if (PS3.PS3Connected || PS3.PS3NavigationConnected) {

            if (PS3.getAnalogHat(LeftHatY) == 0) { //go forward
                Serial.print(F("\r\nLeftHatY: "));
                Serial.print(PS3.getAnalogHat(LeftHatY));
                digitalWrite(motora1, HIGH);
                digitalWrite(motora2, LOW);
                digitalWrite(motoraspeed, 255);
                digitalWrite(motorb1, HIGH);
                digitalWrite(motorb2, LOW);
                digitalWrite(motorbspeed, 255);
            } else if (PS3.getAnalogHat(LeftHatY) == 255) { //go backward
                Serial.print(F("\r\nLeftHatY: "));
                Serial.print(PS3.getAnalogHat(LeftHatY));
                digitalWrite(motora1, LOW);
                digitalWrite(motora2, HIGH);
                digitalWrite(motoraspeed, 255);
                digitalWrite(motorb1, LOW);
                digitalWrite(motorb2, HIGH);
                digitalWrite(motorbspeed, 255);
            } else if PS3.getAnalogHat(RightHatX) == 0) { //turn left
                Serial.print(F("\r\RightHatX: "));
                Serial.print(PS3.getAnalogHat(RightHatX));
                digitalWrite(motora1, HIGH);
                digitalWrite(motora2, LOW);
                digitalWrite(motoraspeed, 200);
                digitalWrite(motorb1, LOW);
                digitalWrite(motorb2, HIGH);
                digitalWrite(motorbspeed, 200);
            } else if (PS3.getAnalogHat(RightHatX) == 255) { //turn right
                Serial.print(F("\r\RightHatX: "));
                Serial.print(PS3.getAnalogHat(RightHatX));
                digitalWrite(motora1, LOW);
                digitalWrite(motora2, HIGH);
                digitalWrite(motoraspeed, 200);
                digitalWrite(motorb1, HIGH);
                digitalWrite(motorb2, LOW);
                digitalWrite(motorbspeed, 200);
            } else { //stop moving
                Serial.print(F("\r\RightHatX: "));
                Serial.print(PS3.getAnalogHat(RightHatX));
                Serial.print(F("\r\nLeftHatY: "));
                Serial.print(PS3.getAnalogHat(LeftHatY));
                digitalWrite(motora1, LOW);
                digitalWrite(motora2, LOW);
                digitalWrite(motoraspeed, 0);
                digitalWrite(motorb1, LOW);
                digitalWrite(motorb2, LOW);
                digitalWrite(motorbspeed, 0);
            }
        }
    }


message:
How to communicate with arduino uno when arduino motor shield connected to arduino uno?

I'm using this Dual Motor Shield
![L293D Arduino Dual Motor Shield][1]

 when I plug Arduino Dual Motor Shield into Aruino uno can't seen any way to communicate with Adruino uno.how can I communicate with uno ?

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

body:
Communicate with what? A PC? The usb serial port should still work fine, and anything connected to the RX/tx pins (D0 and  D1)
If your concern is that there is no longer a socket on the top of this shield that you can plug wires into, well you can solder on some wires to the top of the board, or you could get a screw shield board to go between the arduino and motor shield which would make all the pins available. I have also use small gauage wire wrapped around the shield pins and then just insert the shield onto the arduino making kind of a wire wrap connection between the boards.


message:
Is there such a thing as an "Always" loop?

I seem to remember somewhere somebody making an "Always" loop between Setup() and Loop().

But I can't find any documentation on it. Does such a thing exist, or am I imagining it?

body:
There's nothing officially called an "always" loops as such. However, you can make a loop which goes on forever like this:

    while (true)
    {
        // this bit repeats forever
    }

A `while` loop checks the condition before every iteration of the main body. If it detects that the condition equals boolean `false` then it will stop the loop and move on to the next bit of code.

Normally, the condition would be some kind of expression, like `(x < 10)`. However, in the example above, the condition is hard-coded as `true`, meaning it will never be `false` so it will never stop.


body:
You *might* be thinking of the *Serial Event* system.

This is a specially defined function which runs whenever `loop()` finishes *if there is anything to read from the serial port*.

* http://www.arduino.cc/en/Reference/SerialEvent

Basically it is implemented as a function call after `loop()` in the `main()` function, which looks like this:

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

As you can see there is only `setup()`, `loop()` and the *serial event* system.


message:
Non line of sight radio and arduino uno

I've been using a pair of arduino uno and nrf24l01 and found it wasn't really suitable due to low range when it comes to obstacles.

Essentially I'd like to use it in country areas where it would ideally transmit through dense trees and over hills at around 500 meters.

I've spotted the [SI4432][1] and the [sx1272][2] (which seems ideal but it doesn't seem popular despite it's high NLOS range capabilities?)

I was just wondering if anyone had any recommendations on which would be the best radio module to try? Any help would be really appreciated. Many thanks in advance.

  [1]: http://www.banggood.com/SI4432-470MHz-1000M-Wireless-Module-Wireless-Communication-Module-p-920484.html
  [2]: https://www.cooking-hacks.com/documentation/tutorials/extreme-range-lora-sx1272-module-shield-arduino-raspberry-pi-intel-galileo)

body:
General rule is, the lower the frequency, the longer the range (but lower bandwidth). So both should have a better range at 433Mhz and 137MHz instead of the 2.4Ghz of the NRF. Antennas also affect the range.

The "over the hills" part I think will be problematic. The RF won't be able to penetrate through the hill. So the signal has to bounce of the ionosphere to get over the hill, which is to long a distance. So you probably have to have some kind of repeater on top of the hill to accomplish this.


body: Since you already have the uno+nrf24 working, it might be worth trying a better nrf24 module before trashing the work you've already done. You can buy nrf24 modules with an integrated LNA, PA, and external antenna port. Just do a search for NRF24L01+LNA+PA. You can find them on amazon for < $10 and usually come with an external antenna.


message:
Use of Resistor in PinWheel Exercise

I'm working on project 9 of the Arduino starter kit - the motorized pinwheel.

Here is the schematic:

![enter image description here][1]
(if img not showing: https://goo.gl/tqZmKD)

My question is, why is the 10k resistor needed after the switch? Why can't it just go straight to ground? The switch's output just connects to a digital pin, it doesn't care how much voltage there is, correct?

Thank you!

EDIT**: Additional help from the arduino forums:
The resistor is needed so when the switch is closed you don't short the supply
to ground.  Switch open the resistor pulls the signal to ground and no current
flows, when the switch is closed it forms a resistive divider with the 10k
(switch contacts might have 0.01 to 0.1 ohms resistance or so), thus pulling
the signal to Vcc, but with only 0.5mA flowing through the 10k resistor.

Replace the 10k with a wire and you'd simply overload the supply completely and
perhaps weld the switch contacts shut.
[Arduino Forums][2]

  [1]: https://i.stack.imgur.com/wKxI0.jpg
  [2]: http://forum.arduino.cc/index.php?topic=328353.new#new

body:
It's a pull-down resistor.

A pull-up or pull-down resistor is used the make sure that the input of a digital device is confined to strict logic levels, i.e +Vdd (positive, or HIGH) or GND (Ground, or LOW).

With the switch open and no resistor present, the Arduino pin is neither high nor low. It will *probably* read as low if you tried `digitalRead()`, but there's no guarantee. The probability of the pin being one or the other changes according to the layout of the PCB and other external factors; the pin is termed 'floating' because it could be at any voltage between Vdd and GND.

However, if you apply a pull-(somewhere) resistor you force the Arduino pin to one of either Vdd (up) or GND (down) *until you press the switch*, at which point the Arduino pin switches state.

If you removed the resistor and joined the switch directly to ground, what happens when the switch contacts close?

Think about it...

One side of the switch connected to Vdd.

The other side is connected to the Arduino and GND.

Close the switch, *I dare you.*

**Vdd is now connected to GND**


message:
w5100 and nrf24l01 - SoftSPI - Radio not starting

I had posted some questions about this project earlier this week. Arduino uno + w5100 ethernet shield + nrf24l01 transeiver.

The w5100 is running a webserver to accept GET requests and parse out the variables - Works all the time

The nrf24l01 is acting as a transmitter and sending data out to other nodes - Only works with no Ethernet code.

What doesn't work is both at the same time. With everything hooked up it parses get fine, gets the variable but I can't transmit it since the radio never seems to fire up. Remove all the ethernet code and leave just the radio code it sends fine.

Code here. http://pastebin.com/SMWC9x4F it errors at 146. Which I assume is the radio never starting since the:

    radio.printDetails();

does nothing.

I'm using manicbug's library.

I use the EXACT same send bits in that file to test wireless communication, it works. I only need it to transmit wirelessly when it get data from the network.

Pinouts:

CSN -> 10
CE   ->  9
MISO -> 12
MOSI -> 11
SCK   -> 13
VCC   ->  Separate 3.3 source, not the arduino
GND  -> GND

My guess is this is because both are using SPI.

Tried the softspi method http://pastebin.com/4mv612B7 .

Same thing. I can post GET to it, parse out variables but nothing on the radio side. And I still get no output from radio.printDetails() so it just must not be starting. Commence hair pulling..

EDIT: Bloody hell, printDetails() relies on printf...... that would have been handy to figure out an hour or two ago.  I can get details now. still having communication issues.  Will post more debugging information in a bit.

body:
Issue one:  .printDetails(); uses printh.  If you don't have that included you won't get the information.

Issue two:  The ide gets confused when you have two libraries with the same file.  I compiled my receiver with the softspi file. Once I put the right library in it works.


body: The issue here is that the Ethernet chip locks the SPI bus thus making it impossible for NRF24L01+ to communicate with the arduino properly. Please use softSPI to fix this.


message:
How is the diode here effective?

I'm working on project 9 of the arduino starter-kit - the motorized pinwheel.

Here is the schematic:
![enter image description here][1]

The diode in question (and the only one here) is toward the bottom right of the breadboard. It is to prevent the back-voltage from the motor from harming the circuit.

According to the above img, would the backvoltage travel back down the motor's supply of energy (the red wire)?

If so, what is the diode preventing here? That whole energy strip will just have current running through it and the diode's cathode will prevent it from running to the transistor - which would also happen fi we just didn't connect anything to that power strip.

If not, and the back-voltage is running through the black wire (our ground), then I still do not see how the diode is helping. The diode seems to want to pull the extra energy back to our power strip (which is why the anode is facing toward the left, where the motor's output is. But this doesn't prevent the current from still hitting the green wire which leads to the transistor's 'source'.

So how is this diode working?

Thanks!

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

body:
Under normal operation the + connection of  any inductive component (motor, relay, etc) is at a higher potential than the - connection.

During a "back EMF" event (the collapsing of the magnetic field) a large voltage *of the opposite potential* is generated.  That means that the - connection suddenly becomes a much higher potential than the + connection.

That is very bad for anything connected to the - pin of the inductive load.

With the diode connected backwards like that across the inductive load, under normal operation, it does absolutely nothing.  However, when the - pin becomes a higher potential than the + pin the diode will become *forward biased* and start to conduct.  That allows a very low resistance path for all the energy stored in the coil of the inductive component to flow from the high potential to the low potential, which is what it wants to do.

Without it, the only way for that energy to get from the high potential to the low potential is through the rest of your circuit, which it won't like.

The excess energy at the - side of your motor wants to get to the + side. That's the only place it wants to go.  It'll (crudely speaking*) take the shortest, quickest, route to get there.  That means it goes through the diode and nowhere else.  Straight from the black wire to the red wire of your motor.

----
<sub>* Note: In actuality the energy will take all possible routes at once, but in varying proportions depending on the resistance of the route.  The lower the resistance the greater the proportion. Because the diode is such low resistance it gets the majority of the energy and only a very negligible proportion takes the other possible routes through your circuit. Unless your circuit is incredibly sensitive it won't even notice it's there.</sub>


body:
Flywheel Diode.

When the transistor shuts off, the stopping of the motor generates *back EMF (ElectroMotive Force)* . This manifests itself as negative potential difference (voltage) across the motor. In plain English the collector of the transistor, connected to the -Ve side of the motor, is raised to a damagingly high voltage. If you include the diode, this voltage is siphoned immediately back to the positive rail, so the damage is averted.


message:
How to interface arduino nano with sim900A?

I have arduino nano and sim900a modem.
![My arduino pinout][1]

![SIM900A Modem][2]

![Modem Backside][3]

Rx(pin30) and Tx(pin31) pins of **arduino** shows 3.8VDC respectively and Rx and Tx of **SIM900a** shows 3.6VDC and 2.8VDC respectively. Could i connect the SIM900a modem directly to the arduino? Since Should i use level shifter between arduino TX(3.8v) and SIM900A modem(3.6v)? Any suggestions?

Thanks..

  [1]: https://i.stack.imgur.com/Ze9I6.jpg
  [2]: https://i.stack.imgur.com/wpPOc.jpg
  [3]: https://i.stack.imgur.com/kXEOE.jpg

body:
The bottom of your board shows a chip that gives every hint of being a charge-pump logic-level to RS232 inverting level shifter, to translate from the SIM900A's levels to the RS232 D-Sub connector.

It would appear that the 3 pin header just inside the D-sub would allow you to communicate at these levels.

However, a quick look at the SIM900A docs I could find **suggests that these logic levels may be 2.8v, NOT 3.3v, and 3.3v is actually outside absolute maximum rating!**

Essentially, you have two problems:

 1. You need to drive and read signals with 2.8v logic, either by modifying your arduino to run at that voltage, or by using a level shifter.  It's possible that a resistor would protect the SIM900A, but that is going to be the most expensive component and so short of finding solid evidence of input protection diodes I'd be more hesitant to do that here than I would in other cases.

 2. You need to make the level shifter not drive a signal into the SIM900A, so you don't fight with it.  You could do this by looking in the documenation (if any) for your board and seeing what accommodations they made for this, looking up the level shifter's  data sheet and finding the enable pin, or merely desoldering it.

Another option would be to make your Arduino talk at RS232 levels using its own shifter board.

Finally, there's a sort of hackish option:  Connect the *transmit* data from the SIM900A to a 3.3v Arduino, but connect the transmit from the Arduino through a simple inverter (tinylogic, whatever) to the RS232 *receive* pin.


message:
PID control for Motor Speed control

I was trying to apply PI controller to a motor using Arduino. I have somewhat achieved the task but the problem is that it oscillates too much. Also i couldn't figure out what to do when pwm signal are calculated as negative

      int counter = 0;
      double end_time=0;
      double ini_time=0;
      double rpm=0;
      double my_time=0;
      double temp = 0;
      int pid_speed=0;
      float kp=2.25;
      float ki=.01;
      float kd=0.005;
      int prev_error=0;
      double pwm_sig=0;
      int integrator  = 0;
      int motor_sig_pin= 5;
      int error=0;
      int absolute = 0;
      float desired_rpm=1000; //my desired RPM value
      double zero_time=0;
      double i_time=0;
      double f_time=0;
      int rpm_tacho=0;
      int previous_error=0;
      int derivative=0;

      void setup() {
        pinMode(2,INPUT);
        digitalWrite(2,HIGH);
        pinMode(motor_sig_pin,OUTPUT);
        pinMode(9,OUTPUT);
        pinMode(10,OUTPUT);
        digitalWrite(9,HIGH);
        digitalWrite(10,LOW );
        attachInterrupt (0,Count,RISING);
        ini_time = micros();
        i_time=micros();
        Serial.begin(115200);
      }

       void Count(){ //calculating time for one round using encoder

          counter++;
          if (counter>=100){
            end_time=micros()-ini_time;

            ini_time=micros();
            counter=0;
          }
       }
      void loop() {
          rpm = ((1000000*60)/(end_time));
          rpm = abs(rpm);
          rpm_tacho = ((1000000*60)/(zero_time));
          if (rpm <10 || rpm>5000){
            rpm=0;
          }
          error=desired_rpm-rpm;

          integrator += error;
          pid_speed = kp*error; + ki*integrator;

          pid_speed=(int)pid_speed;

          Serial.print(pid_speed);
          Serial.print("       ");

          if (pid_speed> 0){
            if (pid_speed>255)
              analogWrite(motor_sig_pin,255);
            else
              analogWrite(motor_sig_pin,pid_speed);
          }
          if(pid_speed<0){
            if(pid_speed<-255)
            {
                analogWrite(motor_sig_pin,0);
            }
            else
           {
              pid_speed=abs(pid_speed);
              analogWrite(motor_sig_pin,255-pid_speed);
           }
          }
          Serial.print ("      ");
          Serial.println(rpm);
      }

body:
Instead of thinking of the PID output as pid_speed, think of it as motor_power, and what the PI controller is doing is translating errors in rpm into a motor power setting.

You are probably getting oscillation because of integral windup.  If your loop is fast relative to your system, each loop worth of error adds to integrator quickly/quicker than the system can adjust.   For example, if a loop takes 1ms, an error of 100rpm could overflow the "int integrator" past 32768 in only 0.327 seconds, and past the threshold where the integrator could peg the output 25500 (=255/Ki) in only 0.255sec  If the integrator is faster than the system, it can easily cause overshoot.  You might consider slowing the loop down to 10ms, 100ms or 1000s to match the physical process and make the kI term be a sane conversion of the integrator's rpmError*seconds/100, rpmError*seconds/10, or rpmError*seconds into output power.

To handle the numerics and constraints better, like overflowing integrators and negative output values, it would probably be best to use the Arduino PID library from http://playground.arduino.cc/Code/PIDLibrary as in Edgar Bonet's comment.


body:
I do not know if this question still exists or you managed to solve it. Regardless, I was (still am) working on a [self balancing robot](https://github.com/NischalSehrawat/Self-Balancing-Segway-Robot) where I also faced such an issue and I came to this forum. The way I tackled it was to set PID outputs (assuming you are using Arduino 's PID library) 0 - 255 instead of -255 to 255. Now for my project I needed to change direction of the motor depending upon the inclination angle of the robot. So, each time I need to change the motor rotation direction, I do the following

-  I first reset the Iterm (or make it zero).
- Change the direction of rotation.
- Begin PID computation again.

Earlier I was also trying to achieve this by -255 to 255, but it was very jerky and I was not sure if that was the correct way to do it. With my current approach, I have managed to solve my problem.


message:
What is the diffrence between following arduino boards and which should i buy?

# Arduino UNO R3 Compatible Board ATmega328P ATmega16U2 #
http://www.ebay.in/itm/UNO-R3-ATmega328P-ATmega16U2-Compatible-Board-For-Arduino-with-USB-Cable-/201367107680?pt=LH_DefaultDomain_203&hash=item2ee26a3860
# Arduino UNO R3 ATmega328P USB Development Board CH340G
http://www.ebay.in/itm/UNO-R3-Development-Board-SMD-Chip-Arduino-Compatible-/301653217776?pt=LH_DefaultDomain_203&hash=item463beed1f0

### I will be working on a windows 7 32 bit pc.

body:
The first is an unofficial clone of an R3 using the same schematic as the real R3.  The second is a rough copy using a cheaper USB serial interface chip.

Neither of them are real Arduino boards.  The first one is closer to the real UNO and should do the same things that a real UNO should do (assuming it works at all).  The second one - well, who knows?  You certainly can't do any of the fancy things to the USB interface that you can with a real UNO R3.

Which should you buy? Well, really, you shouldn't buy either of them - but if you *must* go for one I'd pick the first one.  Better to buy a real UNO from Arduino though, at least then you know what it is you're getting, and you expect it to work.  With these cheap Chinese clones (Chinduinos) you may just get a bunch of counterfeit chips selotaped to a piece of cardboard.


message:
MPU6050 causing arduino not to run sketch

I have a mpu6050(which I got from here http://www.sainsmart.com/sainsmart-mpu-6050-3-axis-gyroscope-module.html) and I have connected it to special ports on a sensor shield made for the mpu6050(http://www.amazon.co.uk/SainSmart-InstaBots-SS-SBR-1-0-Sensor-Shield/dp/B00N1YANH2) which is on a Arduino uno. I have a sketch which is meant to print stuff out to the serial monitor, however when the mpu6050 is attached nothing is printed out and when it is not attached the Arduino does print out things to the serial monitor. I attached other things to the sensor shield and things were printed out on the serial monitor, so I know it is the mpu6050 that is the problem.

This is my code

    #include <Wire.h>
    #include <SPI.h>
    #include <Mirf.h>
    #include <nRF24L01.h>
    #include <MirfHardwareSpiDriver.h>
    #include <I2Cdev.h>
    #include <MPU6050.h>

    MPU6050 accelgyro;
    int16_t ax, ay, az;
    int16_t gx, gy, gz;

    #define Gry_offset 0
    #define Gyr_Gain 0.00763358
    #define Angle_offset 4
    #define RMotor_offset 20
    #define LMotor_offset 20
    #define pi 3.14159

    long data;
    int x, y;
    float kp, ki, kd;
    float r_angle, omega;
    float f_angle;
    float Turn_Speed = 0, Turn_Speed_K = 0;
    float Run_Speed = 0, Run_Speed_K = 0, Run_Speed_T = 0;
    float LOutput,ROutput;

    unsigned long preTime = 0;
    float SampleTime = 0.08;
    unsigned long lastTime;
    float Input, Output;
    float errSum, dErr, error, lastErr;
    int timeChange;

    int TN1=3;
    int TN2=4;
    int ENA=9;

    int TN3=5;
    int TN4=6;
    int ENB=10;

    void setup() {
      Wire.begin();
      accelgyro.initialize();
      pinMode(TN1,OUTPUT);
      pinMode(TN2,OUTPUT);
      pinMode(TN3,OUTPUT);
      pinMode(TN4,OUTPUT);
      pinMode(ENA,OUTPUT);
      pinMode(ENB,OUTPUT);

      Mirf.spi = &MirfHardwareSpi;
      Mirf.init();
      Mirf.setRADDR((byte *)"serv1");
      Mirf.payload = sizeof(long);
      Mirf.config();
      Serial.begin(115200);
      Serial.print("Hello");
    }

    void loop() {
      Recive();
      accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
      r_angle = (atan2(ay, az) * 180 / pi + Angle_offset);
      omega =  Gyr_Gain * (gx +  Gry_offset);
      //Serial.print("  omega="); Serial.print(omega);
      if (abs(r_angle)<45){
        myPID();
        PWMControl();
      }
      else{
        analogWrite(ENA, 0);
        analogWrite(ENB, 0);
      }
    }

    void Recive(){
      if(!Mirf.isSending() && Mirf.dataReady()){
        Mirf.getData((byte *)&data);
        Mirf.rxFifoEmpty();

        y = data >> 16;
        x = data & 0x0000ffff;
        //Serial.print("  x="); Serial.print(x);
        //Serial.print("  y="); Serial.println(y);
        if(x >= 520){
          Run_Speed_K = map(x, 520, 1023, 0, 100);
          Run_Speed_K = Run_Speed_K / 50;
          Run_Speed = Run_Speed + Run_Speed_K;
        }
        else if(x <= 480){
          Run_Speed_K = map(x, 480, 0, 0, -100);
          Run_Speed_K = Run_Speed_K / 50;
          Run_Speed = Run_Speed + Run_Speed_K;
        }
        else{
          Run_Speed_K = 0;
        }
        if(y >= 520){
          Turn_Speed = map(y, 520, 1023, 0, 20);
        }
        else if(y <= 480){
          Turn_Speed = map(y,480,0,0,-20);
        }
        else{
          Turn_Speed = 0;
        }
      }
      else{
        x = y = 500;
      }
    }

    void myPID(){
      kp = analogRead(A0)*0.1;
      //kp=17;
      Serial.print("  kp=");Serial.print(kp);
      kd = analogRead(A2)*1.0;
      //kd=840;
      Serial.print("  kd=");Serial.print(kd);
      //ki = analogRead(A3)*0.001;  Serial.print("  ki=");Serial.print(ki);

      //kp = 0;  Serial.print("  kp=");Serial.print(kp);
      //kd = 0;  Serial.print("  kd=");Serial.print(kd);
      ki = 0.08;
      Serial.print("  ki=");Serial.print(ki);

      unsigned long now = millis();
      float dt = (now - preTime) / 1000.0;
      preTime = now;
      float K = 0.8;
      float A = K / (K + dt);
      f_angle = A * (f_angle + omega * dt) + (1 - A) * r_angle;

      Serial.print("  f_angle=");Serial.print(f_angle);

      timeChange = (now - lastTime);
      if(timeChange >= SampleTime){
        Input = f_angle;
        error = Input;
        errSum += error * timeChange;
        dErr = (error - lastErr) / timeChange;
        Output = kp * error + ki * errSum + kd * dErr;
        LOutput = Output + Run_Speed + Turn_Speed;  Serial.print("  LOutput=");Serial.print(LOutput);
        ROutput = Output + Run_Speed - Turn_Speed;  Serial.print("  ROutput=");Serial.println(ROutput);
        lastErr = error;
        lastTime = now;
      }
    }

    void PWMControl(){
      if(LOutput > 0){
        digitalWrite(TN1, HIGH);
        digitalWrite(TN2, LOW);
      }
      else if(LOutput < 0){
        digitalWrite(TN1, LOW);
        digitalWrite(TN2, HIGH);
      }
      else{
        digitalWrite(TN1, HIGH);
        digitalWrite(TN2, HIGH);
      }
      if(ROutput > 0){
        digitalWrite(TN3, HIGH);
        digitalWrite(TN4, LOW);
      }
      else if(ROutput < 0){
        digitalWrite(TN3, LOW);
        digitalWrite(TN4, HIGH);
      }
      else{
        digitalWrite(TN3, HIGH);
        digitalWrite(TN4, HIGH);
      }
        analogWrite(ENA, min(255, abs(LOutput) + LMotor_offset));
        analogWrite(ENB, min(255, abs(ROutput) + RMotor_offset));
    }

and this is a picture of the mpu6050 on the sensor shield

![enter image description here][1]

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

body:
The shield you linked to is no longer sold.

The current version is
![enter image description here][1]

But it has no special connection for an MPU6050 breakout (and BTW that same 6050 board is $6 about everywhere else).  A shield serves no purpose for just the 6050 really.

If you connected the 6050 to the I2C lines (aka A4 & A5), Then you also need to connect an additional interrupt line.  If you are using unmodified example code, it depends on the interrupt being connected.

Here is a post made a while back using the 6050

[http://www.spiked3.com/very-cool-imu-demo/][2]

It is possible to use the 6050 without interrupts but you would have to (understand and) modify the standard example code.

Update: I knew you had a different board, and it had a connector for the 6050, the comment was that the link you provided, since it was 'no longer available', did not link to any documentation. Without a schematic it can not be known how it is hooked up beyond simple I2C. As you are using other devices I am not familiar with, I would expect some sort of conflict on the i2C bus maybe. Are all i2c bus devices using the same reference voltage? It does not matter if they are all 5v or all 3.3V as long as they are all the same.

Since you say 'nothing is printed' and your second line of setup is 'initialize' gyro, odds are good it is not getting past that. Simple (archaic) debugging, put a print (and a small delay) before and after the call to initialize.

My code uses the following for Wire.begin

    #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

I dont know if your Arduino is different and if it would make any difference.

I have a line after initialize

    mpu.testConnection();

That may or may not help you.

FYI PI is already defined, as is DEG_TO_RAD and RAD_TO_DEG

    if (abs(RAD_TO_DEG * headingDelta) > .1F)
  poseChanged = true;

Update: I just looked quickly at the code, and the only thing initialize does is write to i2c, it never waits really. And that means writing to I2C is hanging.  I ran into this once when I had an unpowered device on the bus. I thought it would not harm, but I was wrong.  Does the power light on the mpu come on? (is it really getting power?)  I have run them at 3.3v and 5V so I do not think that would be a problem, but  if you can, switch it to 3.3V to be sure. Getting down to the nitty gritty, you could check if the default pullup resistors are still on the board and did not get accidentally knocked off. Even better would be to try it with a known good MPU.  I have about 10 of them within reach :P (spiked3.com)

  [1]: https://i.stack.imgur.com/F7ccO.jpg
  [2]: http://www.spiked3.com/very-cool-imu-demo/


message:
Which Arduino Board should I start with?

I am interested in Arduino projects. I want to learn to develop my own Arduino based system. The problem is I am not sure which Adruino board must I start with. Any ideas are appreciated, I have searched many discussion forum but could not find a satisfactory answer.

My questions are:

1. Which Arduino Board should I start with?
2. Is it possible to work on Arduino based projects without the board; like having a simulation of the board? If so how?

body:
Depending on your budget you could start with an Arduino Uno starter kit that will include the Arduino, breadboard and wires plus different sensors (like [this one](http://www.amazon.com/The-Ultimate-Kit-Arduino-oddWires/dp/B00K6PYGQ8) - but there are others with less peripherals and cheaper).

If you have a lower budget you can still buy the arduino and many separate sensors/LEDs etc from eBay.

By googling you'll find a lot of tutorials about getting started with the hardware that you bought.


body:
My advice:
 - get a model with USB port (some do not have one)
 - the DUE might seem attractive, but you have less libraries available and less examples, I'd recommend it more as follow up
 - you will get frustrated if you do not know how to code, at least a bit, so if you have not programmed before, you might want to spend some time trying simple stuff just with your PC
 - same about electronics: if you do not have previous experience, it might be preferable to play a bit with a breadboard and some components (LEDs, resistors, switches, etc.); this will reduce the likelyhood that you fry your Arduino. Remember to buy some cables MM/MF/FF, you will end up needing all of them, sooner or later. For powering the board, you can find nice power supplies that cn be powered by a USB cable.

I have bought UNOR3 clones at $4-$5 on ebay, so if you can afford it, I'd suggest you buy a couple, that will enable you playing with I2C master slave and similar configurations.


message:
Can we control an Arduino with voice commands?

I'm looking for some method to control an Arduino with voice commands.

Could this work on this platform?

body:
Yes possible on some of the high end Arduinos, but I know of no example where it has been done. The quality of recognition will be proportional to the processing power provided. In the case of an Arduino, probably not at an acceptable level.

You would be much better off looking at the multitudes of PC solutions, and using the Arduino as an interface to what ever it is you plan on controlling.

FYI: [https://www.sparkfun.com/products/13316][1]

  [1]: https://www.sparkfun.com/products/13316


message:
Sending serial commands to yourself

Is it possible to "send" a serial command to the device itself to see the response?
I have written a little routine based on a couple of serial sends and receives and want to see if that works out like I want.

EDIT:

I have a device (an AVR with arduino boot loader) and as part of my program, the device exchanges phrases with peripheral devices over a serial connection. Since I have right now just the arduino itself and can't really test, if at least the logic behind the serial part of works out, I would like to get serial commands from somewhere and trigger 'continuous talking', so I want to monitor the response behavior of my module, if it gets a certain command (stability reasons). Instead of waiting for a second device, is it possible to "link the TX/RX line to itself" internally or externally to test my program with itself?

body:
Yes, you can do that by cross-connecting the transmit and receive pins on the Arduino. But then your devices sits there silently murmuring to itself (or not...) and you can't really tell what it's saying, or if it's doing anything unless you can observe some other hardware - LEDs, a 'scope, f/ex.

But why not hand-type or script some messages to it on your PC? If the Arduino sketch would make some brief, coherent replies you could confirm what it's doing and debug it if necessary.

I've done just this in your situation: Two of us defined a serial protocol - the ASCII (for human readability!) commands and replies that either end could make or expect. Then each of us wrote the communication code for one of the two devices and proved that it met the protocol. Once both of us had finished and were confident in our respected communication code, we plugged the two devices together, and - they played! Nicely! :)  And if they hadn't we could have eavesdropped on the serial line and printed their attempted conversation to discover where it went wrong.


message:
Analog pins all reading same value

I'm trying to read 5 analog inputs, but all the pins are reading the same as pin A0, plus or minus a couple points. I tried using pulldown resistors on all 5 pins and it made no difference. The board is a Leonardo. Thanks for any ideas/help!

    void setup() {
        Serial.begin(115200);
        analogReference(EXTERNAL);
    }

    void loop() {
        int A0, A1,A2,A3,A4;
        delay(200);
        A0= analogRead(A0);
        A1= analogRead(A1);
        A2= analogRead(A2);
        A3= analogRead(A3);
        A4= analogRead(A4);

        Serial.print(A0);
        Serial.print(" ");
        Serial.print(A1);
        Serial.print(" ");
        Serial.print(A2);
        Serial.print(" ");
        Serial.print(A3);
        Serial.print(" ");
        Serial.print(A4);
        Serial.print("\n");
    }

body:
>     int A0, A1,A2,A3,A4;
    delay(200);
    A0= analogRead(A0);
    A1= analogRead(A1);
    A2= analogRead(A2);
    A3= analogRead(A3);
    A4= analogRead(A4);

Your local variables (`A0` through `A4`) are shadowing the global variables for the pins (`A0` through `A4`). Give your local variables different names.


message:
Arduino Due and Vin, 3.3V and 5V power inputs

I just want to confirm something before I wire up my first ever Arduino project and fry all the stuff I just spent money on.

It is my *understanding* that the `Vin` power input will tolerate a 9V battery and use voltage regulators to pare it down to either 3.3V or 5V (as different parts of the board require). So it is then my *assumption* that if I have a 9V battery running to `Vin`, that I could then connect a power wire to the `3.3V` connector, and reliably get a 3.3V signal (and ditto for 5V), **yes?**

Or, is it that they are *input* jacks *expecting* either 3.3V or 5V signals? I guess I'm confused over this:

* Will `Vin` then power the 3.3V and 5V inputs, giving me access to voltage at that level; or
* Do I have to choose between 3.3V, 5V or `Vin`, and only use one of those to power my board (with the appropriate voltage level)

body: Yes your assumption is correct you can power 3.3v and 5v items from those pins as long as you don't take more current than the onboard regulator(s) can supply


body:
`DC Jack` is connected, through a diode, to `Vin`.

`Vin` is stepped down to `5V` on-board.

`5V` is stepped down to `3V3` on board.

Thus you can do any one of the following numbered items.

 1. Connect a 7-12V supply to the `DC Jack`; thus:
- use `Vin` as a supply @ DC - 0.7V for off-board peripherals, and
- use `5V` as a supply for off-board peripherals, and
- use `3V3` as a supply for off-board peripherals.

 2. Connect a 6-12V supply to `Vin`; thus:
- use `5V` as a supply for off-board peripherals, and
- use `3V3` as a supply for off-board peripherals.

 3. Connect 5V supply to the `5V`; thus:
- use `3V3` as a supply for off-board peripherals.

The above is only guaranteed for boards that **follow the reference schematic**, as plenty of clone/compatible boards do. If you buy a cheap Chinarduino and something doesn't work, or the thing breaks, after following anything above then that's your tough luck.


message:
Arduino Due Pinout with Explanations?

I am trying to understand what each pin on my Arduino Due is and what it is used for, and so I have been searching for things like "*Arduino Due pinout*", "*Arduino Due pin mapping*" and similar.

The best I could find was [this table](http://www.arduino.cc/en/Hacking/PinMappingSAM3X), however it doesn't help you out at all if you are completely new to electronics and have no idea what `TX2`, `SDA` or `NPCSO` mean, etc.

Does anybody know of Arduino/Due documentation that explains what each I/O pin is?

body:
The Arduino Due is backed by an Atmel SAM3X8E ARM Cortex-M3 microprocessor and most of the pins on the Due are connected directly to this chip. Therefore, you can refer directly to the chip's datasheet for descriptions of these hardware features.

[Atmel SAM3X8E ARM Cortex-M3 datasheet][1]

  [1]: http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf


message:
How to increment and decrement an output voltage by using two buttons?

I'm trying to create a code using an Arduino Uno board to increment and decrement the output voltage of the Arduino Uno which is 5 volts and I need to step it up to 10 volts which I have done below.

The things that are missing on the schematic are two buttons. I want to be able to increment 0.5 volts with each press of Button-A until the Arduino is at 5 volts. With Button-B I want to be able to lower the voltage by 0.5 volts with each press of the button till value is 0.

I can do the calculations and the circuit design but I'm not much of a programmer. I just want to know if anyone can point me in a good direction of where I can get the right code. I have already looked at all the tutorials on the Arduino Website. I do know I have to work with the PWM functions as well as `attachinterrupt()` and `Debounce()` functions. Also, how do I set the increments so that I don't go over, say it takes 10 presses to get to 5 volts on the 11th press have it not do anything so I don't break anything. So can anyone please help me with any suggestions?

I have a low pass filter on the circuit for noise handling and like I said I need to add in the buttons to my schematic.

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

Here is my code I have made. I'm using an LED to test the Vout aspect. So far I can only get my LED to flicker from 2 to 4 volts and my buttons A and B don't work. Can someone look over my code and see how bad I made this?

    int PWMPin = 6; // output pin supporting PWM
    int buttonApin = 9; // buttonA to pin 9 PWM
    int buttonBpin = 10; // buttonB to pin 10 PWM
    float value = 0; // read the value at 0
    int fadeValue = value;

    void setup()
    {
      Serial.begin(9600); //initialize serial communication at 9600 baud
      pinMode(buttonApin, INPUT_PULLUP);
      pinMode(buttonBpin, INPUT_PULLUP);
      pinMode(PWMPin, OUTPUT);
    }
    void loop()
    {
      {
        int port = analogRead(0);
        port = map(port, 0, 10, 0, 255);
        analogWrite(6, port);
      }

      {
      if (digitalRead(buttonApin) == LOW, fadeValue)
      {
      // fade from min to max in increments of 25.5 points: basically (0.5 volts)
      for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5)

        digitalWrite(PWMPin, fadeValue);

        // sets the value (range from 0 to 255):
       Serial.println(PWMPin);
       analogWrite(PWMPin, fadeValue);
      }
      }

      {
        if (digitalRead(buttonBpin) == LOW, fadeValue)
      {
      // fade from max to min in increments of 25.5 points:
      for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=25.5)

        digitalWrite(PWMPin, fadeValue);

      // sets the value (range from 0 to 255): basically (0.5 volts)
      analogWrite(PWMPin, fadeValue);
      }
      }
    }

body:
If all you have to do is to read those 2 buttons, you could just forgo the interrupts and simply poll in the main loop.
The [Bounce2 library][1] does basically the same.

Also, about the PWM, why not an R-2R?

10V/0.5V + 1 => 21 steps < 32 => 5 bits => 6 resistors.

But it could be more precise, as you would not depend on the oscillator, rather on the precision of the resistors.

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


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

I suggest you to use debounce to detect if a pin has been definitely pressed. You could also test using interrupts (hint: interrupts can happen multiple times even if you "only" pressed once). So either use Arduino's example of debounce or take a look at the [Bounce2 library][1] found on their website.

Now that you can check whether or not either button A or B has been pressed, how do you keep track of the voltage to be output? You should use a `counter` variable that will be incremented when button A is pressed and decremented when button B is pressed. Here is a pseudocode:

    if(ButtonA == pressed)
      counter++;
    else if(ButtonB == pressed)
      counter--;

This `counter` variable can be used to control the output voltage. Remember that the argument for `analogWrite()` function on the Arduino Uno is the duty cycle which takes in values from 0 to 255. So `analogWrite(0)` ≣ 0 Volt and `analogWrite(255)` ≣ 5 Volt. So at the moment, you couldn't just do `analogWrite(counter)` because you would need to press 255 times button A!

Instead, you would need a way to convert your counter to reflect the increment you need. You mentioned that it should require 10 presses to reach 5 Volt at the Arduino output, and the easiest way to accomplish this is to use Arduino's [Map function][2]. The pseudocode would look like this:

    Output = map(counter, 0, 10, 0, 255);
    analogWrite(Output);

Now there is one last step! The map function will limit the output voltage from 0 to 5 Volt so everything will be safe; however, the counter is not limited to 0 to 10. This means that even if the counter is at 15 (because you pressed button A too many times) the voltage will be 5 Volt and you would need to press button B at least 6 times to see the voltage go down! So to limit the counter you could easily implement your own function:

    if(counter >= 10)
      counter = 10;
    else if (counter<= 0)
      counter = 0;

You could also use Arduino's `constrain()` function which more information can be found on their website.

Hopefully this points you in the right direction.

  [1]: http://playground.arduino.cc/Code/Bounce
  [2]: http://www.arduino.cc/en/Reference/Map


message:
how to make an led turn on when something gets close to an ultrasonic sensor

Hey I just started using arduino and so far can't get any help with how to write a code for an led to turn on when someone gets in range of a three pin ultrasonic sensor, and off when they are out of a specific range.

Any help?

body:
Try with this and check that at least you can reproduce the desired effect:
http://www.arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor

Then you can refer to this for the part related to driving the LED:
http://www.arduino.cc/en/Tutorial/Blink?from=Tutorial.BlinkingLED

Since the ultra sound demo already calculates the distance, you can do the test on that to decide when to turn ON/OFF the LED.


message:
Can Bus Shield Not Receiving Data

I am trying to connect my Arduino Uno board with SeeedStudio Can Bus Shield to my 2006 325i BMW. After compiling and uploading the example program by SeeedStudio, the serial monitor returns "Can Bus Shield Init ok!"

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

    // demo: CAN-BUS Shield, receive data with check mode
    // send data coming to fast, such as less than 10ms, you can use this way
    // loovee, 2014-6-13

    #include <SPI.h>
    #include "mcp_can.h"

    // the cs pin of the version after v1.1 is default to D9
    // v0.9b and v1.0 is default D10
    const int SPI_CS_PIN = 9;

    MCP_CAN CAN(SPI_CS_PIN); // Set CS pin

    void setup() {
      Serial.begin(115200);
    START_INIT:
      if(CAN_OK == CAN.begin(CAN_500KBPS)) {
      // init can bus : baudrate = 500k
        Serial.println("CAN BUS Shield init ok!");
      } else {
        Serial.println("CAN BUS Shield init fail");
        Serial.println("Init CAN BUS Shield again");
        delay(100);
        goto START_INIT;
      }
    }

    void loop(){
      unsigned char len = 0;
      unsigned char buf[8];
      if(CAN_MSGAVAIL == CAN.checkReceive()) {
        // check if data coming
        CAN.readMsgBuf(&len, buf);
        // read data,  len: data length, buf: data buf
        unsigned char canId = CAN.getCanId();
        Serial.println("-----------------------------");
        Serial.println("get data from ID: ");
        Serial.println(canId);
        for(int i = 0; i<len; i++) {
          // print the data
          Serial.print(buf[i]);
          Serial.print("\t");
        }
        Serial.println();
      }
    }

So I get the initialize statement returned but I'm not receiving any data. It seems like the `if(CAN_MSGAVAIL == CAN.checkReceive())` statement isn't executed. I found my vehicle's Can high and Can low wires and inserted them into my Can Bus Shield. So I'm not sure if it's a code problem or if the wires aren't transmitting the data to the shield. Any help would be great.

body:
It may be a dumb question, but are you sure your car CAN bus is 500kbps?
Have a look at this:
[pdfLink](http://share.qclt.com/bmw资料/Bus & Power/BUS _en.pdf)
Maybe try different speeds? 100kbps maybe?

Also, look at the schematics of your shield? Is the bus termination resistor soldered on the board?


body:
Make sure to cut the P1 trace (see the link below) and also to connect GND from the OBD-2 to the shield/Arduino. There are two ground pins on the OBD-2 port, Signal and Chassis Ground. I went with Signal GND, but allegedly they are linked anyways.

This [guide][1] helped me a lot.

  [1]: http://matthewcmcmillan.blogspot.cz/2013/10/arduino-sending-data-over-can-bus.html


message:
PYM-1 PIR sensor current concerns

I am busy toying with some PIR sensors to detect movement etc for a nightlight for my kids. One of the sensors I ordered is the PYM-1 PIR sensor.

The data sheet states the following:

 - Operating Voltage: 4,5~5V.
 - Standby current: 65 micro-amps (65uA)
 - Operating Current: 40mA (40 milli-amps)

The limit for current on the arduino pins is 40mA. According to documentation at the arduino site 40mA is the upper limit per pin and the site clearly states: Absolute Maximum Ratings - the point where damage will start to happen I would rather avoid sinking the current directly on the Arduino.

So my question is will sinking 40mA on a pin cause damage? I have not been visited by the blue smoke genie yet and would rather avoid it at this point.

I suspect it might be safer to run this via a transistor and external power than directly on the arduino?

body:
When I look at the PYM-1 seen here:

http://www.ebay.com/itm/Infrared-PIR-Human-Sensor-NEW-Arrival-Pyroelectric-DIY-Kit-PYM-1-for-Arduino-/271677900953

I don't see any need for an external microprocessor such as an Arduino.  It seems that one just applies 5V as input and it switches on/off up to 300W of power.  Where would one use an Arduino GPIO?