message:
Arduino UNO doesn't produce expected square waveform

I want to produce quick square waveform for testing purposes. If I will use this code:

    void setup()
    {
     pinMode(2, OUTPUT);
    }

    void loop()
    {
     bitSet(PORTD, 2);
     bitClear(PORTD, 2);
    }

I will get expected pulses but I also will get these 6.25 us dips in waveform roughly every 1 ms.

I use latest Arduino 1.6.9 environment.

Whole loop cycle take 1 us which mean 16 instructions (62.5 ns per instruction). So I will get 125 ns high and rest of the time low signal.

Any idea what I'm doing wrong?

Same results if I use asm sbi and sci instead of macros bitSet/bitClear.

Thank you!

[![Oscilloscope waveform - 62.5 us detail][1]][1]

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

/*

So after yours advices and little bit further searching I came up with solution to produce clean square waveform. It make 2.66 Mhz and it's probably fastest what you can get:

    void setup()
    {
     pinMode(2, OUTPUT);
     noInterrupts();
    }

    void loop()
    {
     while(true)
     {
     bitSet(PORTD, 2);
     bitClear(PORTD, 2);
     }
    }

body:
As I explained in my comment, the reason for this glitch is the Timer 0
overflow interrupt kicking in every 1024 µs. This interrupt is used
by the Arduino core library for timekeeping. It is the basis of
`millis()`, `micros()` and `delay()`. The interrupt is [enabled by the
`init()` function in
wiring.c](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c#L279).
There are several approaches to avoid that:

## Avoid the Arduino core initialization

This may be overkill, but since it seems you are already familiar with
directly accessing the IO ports of the ATmega chip, it may well suit
you. You can use the Arduino IDE without the Arduino core initialization
simply by defining your own `main()`:

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

    #include <util/delay.h>

    int main(void)
    {
        DDRD |= _BV(PD2);        // PD2 as output
        for (;;) {
            PORTD |= _BV(PD2);   // PD2 high
            PORTD &= ~_BV(PD2);  // PD2 low
            _delay_us(0.625);    // 10 CPU cycles, loop time = 16 cycles
        }
    }

Notice the extra delay: without it, the loop would complete in 6 CPU
cycles (2 per port access, 2 more to loop back). Not doing the Arduino
core initialization means you have no timekeeping and no `analogRead()`
or `analogWrite()`. Other Arduino functions should work normally but
some, like `Serial.begin()` will bring their own interrupts.

## Disable interrupts

As suggested by Majenko, this may be the simplest way to have a steady
waveform:

    void setup()
    {
        pinMode(2, OUTPUT);
        noInterrupts();
    }

    void loop()
    {
        PORTD |= _BV(PD2);   // PD2 high
        PORTD &= ~_BV(PD2);  // PD2 low
    }

Without interrupts, you have no timekeeping, no serial communications
and, obviously, no `attachInterrupt()`. Most other Arduino functions
should work.

## Use a hardware timer

This allows you to generate the signal without relying on the CPU. You
can keep interrupts enabled and do other work in the program while the
waveform goes undisturbed. The simplest way to generate such a waveform
is with `analogWrite()`. The resulting frequency is quite low though,
like 0.5 to 1 kHz. If you want 1 MHz, you will have to
configure the timer the hard way. For example:

    void setup()
    {
        DDRD |= _BV(PD3);     // OC2B = PD3 as output
        OCR2A = 15;           // period = 16 clock cycles
        OCR2B = 1;            // high during 2 clock cycles
        TCCR2A = _BV(COM2B1)  // non-inverting PWM
               | _BV(WGM20)   // fast PWM, TOP = OCR2A
               | _BV(WGM21);  // ditto
        TCCR2B = _BV(WGM22)   // ditto
               | _BV(CS20);   // clock at f_CPU
    }

    void loop() { }

The output is on pin PD3 = digital 3. This configuration will disable
`analogWrite()` on pins 3 (PD3) and 11 (PB3).


sender: user

sender: assistant

body:
> I want to produce quick square waveform for testing purposes.
>
> Whole loop cycle take 1 us which mean 16 instructions (62.5 ns per instruction). So I will get 125 ns high and rest of the time low signal.
> Any idea what I'm doing wrong?

You are assuming that what goes on outside loop() and the call to loop() takes no time at all.

This is what the Arduino core [main()][1] looks like.

    int main(void)
    {
     init();

     initVariant();

    #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();

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

     return 0;
    }

There is both the call to loop(), if-branch, and for-branch. This all adds up. On top of this there are a number of Interrupt Service Routines (ISR) such as for the Timer which is used for the micros() and millis() count. These will interleave periodically (as you have observed).

Now the question is how to fix this and I think @Edgar Bonet has done an excellent job with that.

Cheers!

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/main.cpp#L33


body:
If you just want a rough square wave to test and you don't care about the frequency then try this:

    void setup()
    {
       pinMode(2, OUTPUT);
    }

    void loop()
    {
       digitalWrite(2, true);
       delay(2);
       digitalWrite(2, false);
       delay(2);
    }


message:
Arduino project - will this fit together?

I'm about to order parts for my project and I'd like to avoid some rookie mistake I might've missed. I'll be using Arduino chip and a wifi module to host a very simple webpage and a battery to make this all portable. I've decided to use Arduino Mini Pro 8MHz because of 3.3V input voltage, same as ESP8266, also FT232RL to program the board and TPS73601 for my battery. This is where I have some doubts, the battery I've picked is Li-Ion from my old Samsung Galaxy S AFAIK when charged it supplies ~4.2V and nearly discharged ~2.7V so the regulator should work (?). Is using Li-Ion in any way different from regular AA or just +/- because I see 3 pins on the back of it? Except for charging of course I'll be using the phone for that. Thanks in advance for any suggestions.

body:
From what you've provided everything seems to be compatible.

Concerning the battery, a quick look at the Arduino website shows:

> Input Voltage 3.35 -12 V (3.3V model)

Meaning the regulator will work as long as the battery provides voltage above 3.35 but since your battery's voltage drops as it gets depleted you might not get the battery life you'd expect :/. In other words: it'll work initially  until the voltage drops below 3.35V and then you would have to recharge it.

> Is using Li-Ion in any way different from regular AA

Yes and No.
No : both provide a stable DC source and both can be used in similar applications.

Yes: Li-Ion batteries can be recharged and have a longer life-span, and most importantly, Li-Ion batteries don't have a sharp voltage drop as they get depleted, unlike regular AA batteries. Which is a bonus for this project ( i guess :p )

>  I see 3 pins on the back of it

There are only 2 pins that actually provide the power from the battery while the third is usually used to monitor temperature or battery life remaining.So you can use this battery by only connecting the power providing pins (usually indicated by + and - ) and safely ignore the third.

Gd Luck!


message:
Join Serial Data Seperated by Newlines?

I have two Arduinos connected through Bluetooth. One sends a string of data similar to `506:507:1\r\n`. The data can vary similar to `0:1000:0\r\n`. I already have functions to break that string down into three variables. I send it from one Arduino over Bluetooth and the second Arduino receives it through `Serial`. The only problem is that the second Arduino receives this:

    5
    0
    6
    :
    5
    0
    7
    :
    1
    "\n"
At the end it adds a space at the end (`"\n"`) How can I parse this data back into a string similar to `506:507:1\r\n` that can still vary in length?

body:
Simply reverse the steps you took on the sending side.

 - Create a `char` array of sufficient size as well as an index variable to keep track of your position within the array. An Arduino String may be more convenient, though they can cause **a lot** of problems.
 - In a loop, use `available()` to wait for incoming chars and add them to the array you've created, using your index variable.
 - Keep going in the loop, while checking for that unique character (\n, perhaps) that signals the end of a packet. Add this last byte to the array and then terminate the string with null or `\0`.

If you want to re-use the array for another packet, simply set the index variable to 0 and continue.


message:
No sketches will upload to Arduino Uno board; says "access denied"

I'm using an Arduino Uno board with an HP computer running Windows 10 and IDE version 1.6.8. Arduino was working fine for me until a few days ago, when (and I suspect this is the root of the problem) I accidentally tried to upload software with something connected to the RX and TX pins on the board. Now I continually get the error message below:

> avrdude: ser_open(): can't open device "\\.\COM2": Access is denied.

The only other thing that changed is I disconnected a bluetooth dongle (Kinivo BTD-400 Bluetooth 4.0 USB Adapter for Windows) without uninstalling any software, so I suspect that software may be searching for open COM ports and disrupting the Arduino upload.

I've tried everything I could find about troubleshooting online, including that "did I brick my arduino" post elsewhere on this forum, and nothing has worked or even changed the problem - please help! I believe I've narrowed down the problem to my computer scanning open COM ports, but I can't find any reliable way to make sure that doesn't happen.

Thanks

body: It sounds like Windows thinks that port is in use and isn't letting the ArduinoIDE access it. If it's the same port your dongle had been using, try plugging the dongle back in, then dismounting it before you remove it. Hopefully that will clear the port for other uses.


message:
serial communication dead slow after a while

I'm workin on a node for blender to control an arduino. I notice it goes really slow after a while so I isolated the problem.
It is good in maintaining 60 frames a second, then after around 40 seconds (pretty exact), it drops to a pretty exact 1 fps for some reason.

What could be going on?

    import serial
    import time

    ser = serial.Serial('COM3', 115200)

    c = 0

    while True:
        c+=1
        print("ok ", c)
        numIn = "100n"
        ser.write(numIn.encode('ascii'))
        time.sleep(1./60)

arduino code:

 // special thx to  Nick Gammon

    const unsigned int MAX_INPUT = 50;

    unsigned long delay_time = 300;
    unsigned long last_toggle_time = 0;
    int current_state = LOW;

    void setup () {
      Serial.begin (115200);
      pinMode(12, OUTPUT);

    }

    void process_data (const char * data) {
      Serial.println (data);
      delay_time = atoi(data);
    }

    void processIncomingByte (const byte inByte) {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;

      switch (inByte) {

        case 'n':   // end of text
          input_line [input_pos] = 0;  // terminating null byte
          process_data (input_line);
          input_pos = 0;
          break;

        case 'r':
          break;

        default:
          if (input_pos < (MAX_INPUT - 1))
            input_line [input_pos++] = inByte;
          break;

      }
    }

    void loop() {

      while (Serial.available () > 0) {
        processIncomingByte (Serial.read ());
      }

      unsigned long m  = millis();

      if (m > last_toggle_time + delay_time) {
          current_state = current_state == HIGH ? LOW : HIGH;
          digitalWrite(12, current_state);
          last_toggle_time = m;
      }

    }

body:
If you print from arduino to serial and you don't read it then the buffer gets full. Causing it to go in a second delay. So make sure you read as well when you send data over.

A short sleep is required between the sleep and the read for some reason. Else it hangs.

    import serial
    from time import sleep

    ser = serial.Serial('COM3', 115200)
    sleep(1)

    c = 0

    while True:
        c+=1
        print("ok ", c)
        numIn = "100"
        ser.write((numIn + '\r\n').encode())
        sleep(1./120)

        inp = ser.readline()
        print(inp.decode("utf-8"))
        sleep(1./120)


message:
I²C only works when I short-circuit my Arduino

I'm trying to connect an Arduino Nano with a Raspberry Pi 3 via I²C.

This is the small test-program I found and used for I²C.

    #include <Arduino.h>
    #include <Wire.h>

    void setup() {
      Wire.begin(4);                // join i2c bus with address #8
      Wire.onReceive(receiveEvent); // register event
      Serial.begin(9600);           // start serial for output
    }

    void loop() {
      delay(100);
    }

    // function that executes whenever data is received from master
    // this function is registered as an event, see setup()
    void receiveEvent(int howMany) {
      while (1 < Wire.available()) { // loop through all but the last
        char c = Wire.read(); // receive byte as a character
        Serial.print(c);         // print the character
      }
      int x = Wire.read();    // receive byte as an integer
      Serial.println(x);         // print the integer
    }

After compiling and uploading, I ssh-ed into my Pi and executed `sudo i2cdetect -y 1` which prints an empty I²C table.

Here are images of how I connected the two devices, as far as I know the connection itself is okay. I also tested the cables with a multimeter.

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

Now the strange thing is, when I short-circuit my Arduino for a brief moment between GND and VIN I²C works, but Serial via USB with my PC stops working. Also the chip gets very hot and stays hot even though it isn't short-circuited anymore.

Any ideas what I'm doing wrong? I don't think the Arduinos are broken, since I tested it with 2 different ones. (while testing I accidentally short-circuited one and it worked)

EDIT: I tested I²C between the two Arduinos and it works flawlessly, but still doesn't want to work with my Pi. :(

  [1]: https://i.stack.imgur.com/xOVF6.jpg
  [2]: https://i.stack.imgur.com/KY21z.jpg
  [3]: https://i.stack.imgur.com/lorWc.jpg

body: There is not enough information in your question to know for sure, but remember that the rpi is three volt and the arduino is five volt. Given the heat you are seeing you have something miswired.


body:
> Any ideas what I'm doing wrong?

Apart from *deliberately shorting +5V to ground*? Sheesh!

---

Get, or make, a level-shifter. You can't pump 5V from the Nano to the Pi and expect things to work. Example schematic:

[![Level converter][1]][1]

In this example the low voltage (3.3V) side is marked LV, and the high voltage (5V) side is marked HV.

---

> You can use a level shifter with I²C but you don't need one. The Pi has pullup to 3.3V. Provided there are no other pullup it works. I routinely do this.

The important phrase there is "Provided there are no other pullup".

`Wire.begin()` enables the pull-ups. So make sure that *on the Nano side* you disable them again:

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

      Wire.begin (4);
      // disable internal pullups for twi.
      digitalWrite(SDA, LOW);
      digitalWrite(SCL, LOW);

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


message:
How to load Atmega328p 8mhz board using board manager

I need to load the Atmega328p 8kHz board definition using the board manager and can not find a way.  Any help will be appreciated.

body:
**Assuming that you have a 3.3V Atmega328P and are using an external 8MHz occilator:**

In the Arduino IDE click on `Tools`.
Scroll down until you see an option starting with the word `Board:`
Select the option called `Arduino Pro or Pro Mini`

Click the `Tools` menu once again.
This time select the option starting with `Processor:`
Select the `Atmega328P (3.3V, 8MHz)`
Done!

Alternatively you can edit the `boards.txt` file located somewhere similar to `C:\Program Files (x86)\Arduino\hardware\arduino\avr`
Fuse bits can be calculated using one of these online tools:

- [http://www.engbedded.com/fusecalc/][1]
- [http://eleccelerator.com/fusecalc/][2]

  [1]: http://www.engbedded.com/fusecalc/
  [2]: http://eleccelerator.com/fusecalc/


message:
radio wave generation using arduino

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

    const byte ANTENNA = 9;

    void setup()
      {
      // set up Timer 1
      TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
      TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
      OCR1A =  9;       // compare A register value to 10 (zero relative)
      }  // end of setup

    void loop()
      {
      pinMode (ANTENNA, OUTPUT);
      delay (500);
      pinMode (ANTENNA, INPUT);
      delay (300);
      }  // end of loop

It is just toggling the mode of the pin, so how it is related to radio wave generation?

body:
This looks incredibly like the post on my page: [Turn your Arduino into an AM radio transmitter!](http://www.gammon.com.au/forum/?id=11508)

As the page mentions:

> The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 KHz, since one toggle turns the output on, and second toggle turns it off.

These are the important lines:

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

      // set up Timer 1
      TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
      TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
      OCR1A =  9;       // compare A register value to 10 (zero relative)

Timer 1 is set up to run at 800 kHz. That is a radio frequency. The toggling code just turns the output on or off as a simple form of "keying".


message:
Did I fry a Sainsmart 1602LCD (not shield, just LCD), HD44780 compatible

Each new circuit I build, I seem to make every possible mistake, including inverting 5V and ground.
I did that precise mistake on this 2x16 Sainsmart LCD. The backlight definitely works, but is the only thing I seem to be able to make work. Do you believe I fried the screen, or do they maybe have a diode to protect from erroneous cabling, and my mistake is another one?

EDIT :

I found this somewhere, on a board that might be the one driving this LCD screen or not :

Operating Voltage VDD -0.3 to +7.0 V
Driver Supply Voltage VLCD VDD - 10 to VDD + 0.3

So I mistakenly put 5V in VLCD, and 0V in VDD, which makes VLCD 5V and not 0.3V above VDD, would you suppose I fried it?

Thanks for your input :)

body:
For me, it's extremely hard to tell if you did or did not fry a device.
Even if you have the device right in front of you, it's often hard to tell.

You've got two options:

**Attempt to diagnose it**

First you should try to run example code and follow the "instructions". I believe this product is relatively well documented (/libraried?) and shouldn't be all too hard to set up.

If this isn't working, it's likely the device is dead (given the situation). You could go on and fiddle around with it for hours, which might not be worth the effort.

**Buy a new one**

This will cost you some money. But if you get the new one working, you can test the same code on your old one.

**Tips**

 1. First connect the wires, check the wiring and AFTER THAT connect the power. (Especially take care on GND/VCC wiring.)
 2. Use black wires for GND/ground and red wires for VCC/5V.(It'll be easier to manage/spot)
 3. Check the devices datasheets (which pins, what maximal voltage)
 4. Try to use female connectors as power-output. (They don't short everything they touch)
 5. Try to use irreversible connectors.
 6. Don't have loose leads dangling around.
 7. Put a casing/backplate on your Arduino (and/or avoid placing it on metal)
 8. Keep your desk clean, bits of solder, wire, leads or screws may cause shorts between pins.


message:
"missing filename" compilation Error

I've recently got back to my Uno. I tried compiling my program and got the following error:

    Arduino: 1.6.6 (Windows 8.1), Board: "Arduino/Genuino Uno"

    avr-g++: error: missing filename after '-o'

    exit status 1
    Error compiling.

This happens on any of the programs I've tried to compile/upload.
I've searched around on Google but I have gotten no definite answers and how to fix this or what has caused this? Does anyone have an idea on what I could do?

body:
I had same problem. You should download Arduino IDE 1.6.8

https://www.arduino.cc/en/Main/Software


message:
Random numbers being printed back after entering data

I am currently working with an Arduino Micro / Linduino and making a program based on a lot of switch statements to execute certain functions that will be passed to a microprocessor (`LT2974`) on a board serially. For the most part, all of the functions I have work, except there is one that I am trying to determine if it is my program that is causing issues, or the Linear Tech libraries that are provided. Upon research, I did discover something strange in my code that I cannot explain.

Here is a quick snippet of my code:

    unsigned long serialdata;
    int inbyte;

    long getSerial()
    {
      serialdata = 0;
      while (inbyte != '/')
      {
        inbyte = Serial.read();
        if (inbyte > 0 && inbyte != '/')
        {
          serialdata = serialdata * 10 + inbyte - '0';
          Serial.print(serialdata);
          Serial.print("test \n");
        }
      }
      inbyte = 0;
      return serialdata;
    }

    void loop()
    {
      getSerial();
      // Switch statement represents Slot choices
      switch (serialdata)
      {

        case 1:
          {
            commands(Slot1);
            break;
          }
        case 2:
          {
            commands(Slot2);
            break;
          }
        case 3:
          {
            commands(Slot3);
            break;
          }
        case 4:
          {
            commands(Slot4);
            break;
          }
      }
    }

I have left out the following switch statements that are found in the commands function as they are not where the issue lies.

For some reason, when I pass data through to the Arduino, and then go to reprint it out with my `Serial.print` command in `getSerial()`, there is an additional number printing, and I believe the issue to lie here.

So, for example, if I type `"/1/"` (the slashes were used to pass multiple variables as shown in the function, but I'm only passing one for now), the Arduino reponds with:

    1test
    4294967268test

here is `"/2/"`

    2test
    4294967258test

and here is passing multiple variables with `"/2/9/"`

    2test
    9test
    4294967258test

All of the values I just showed you do not correspond to any of my switch statements implemented, and so no actual data is being returned besides the print command from `getSerial()`. So can anyone explain what is going on here?

EDIT: I added the data types of `serialdata` and `inbyte` to the top of the post.

body:
The problem is that you are blindly reading serial data without first looking to see if there is actually any serial data available to read.

If there is no data there `Serial.read()` will return -1.  Since you have only provided a snippet of your program I can't say what data type `inbyte` is, but my guess is it's some form of unsigned 32-bit value, since -1 mapped into an unsigned 32-bit value is 4294967295.

You need to be checking the presence of data, and only reading when you should read, and also looking for the end of your data sequence (add some terminating character, like a line feed) to know when to stop looking for and reading characters.


message:
Which tft works on both Arduino Uno and Raspberry pi

Ideally I'd like a 2.8 inch and it to be touch screen.
But most of all I'd rather it work on both boards without much hassle.

body:
adafruit has a resistive touch screen which is 2.8" and works on most boards. Its 30 dollars and works well. It has instructions and all and libraries which you can use. Plug it into a breadboard, connect the jumpers and you're all set.

https://www.adafruit.com/product/1770

on the other hand, Elegoo has made a very similar product, which can also be used on most boards if you plug it into a breadboard, but it is specially designed for the UNO. You can plug it straight into the UNO board, without the need of breadboards. This comes with a instructional DVD and is only 12 dollars on Amazon. It is also a resistive screen and basically the same product.

https://www.amazon.com/gp/product/B01EUVJYME/ref=oh_aui_detailpage_o04_s01?ie=UTF8&psc=1

Good luck!


body:
Well any display can work on both of the boards if you can adjust the voltage levels right there is a display which was made for old Nokia phones and it is called nokia-5110-3310 and  is dirt cheap display and it can be used with both Arduino or raspberry pi or any other board which support the protocol here is a link for quick reference.

[Adafruit link to the library ][1]

  [1]: https://learn.adafruit.com/nokia-5110-3310-lcd-python-library/overview


message:
Why does this code show me a lot of space?

I want to make a 4hz reading of GSR and temperature, in the following format for every second:

    697,20.8744
    696,20.86521
    695,20.8653
    699,20.8777

The print, in python, would be print(GSR+","+Temp)
The tries in C are giving problem, here's my actual code:

    #include <OneWire.h>

    const int GSR=A0;
    int threshold=0;
    int sensorValue;
    unsigned long startTime = 0;
    #define MEASURE_PERIOD 250
    OneWire  ds(3);

    void setup(){
      long sum=0;
      Serial.begin(115200);

      for(int i=0;i<500;i++)
      {
      sensorValue=analogRead(GSR);
      sum += sensorValue;
      delay(5);
      }
      threshold = sum/500;
      }

    void loop()
    {
      byte i;
      byte present = 0;
      byte type_s;
      byte data[12];
      byte addr[8];
      float celsius;
        if((millis() - startTime) >= MEASURE_PERIOD)
        {
            startTime += MEASURE_PERIOD;
            // Do your job, such as
            sensorValue=analogRead(GSR);
            Serial.print(sensorValue);
            Serial.print(",");
            if ( !ds.search(addr)) {
        ds.reset_search();
        return;
      }

      if (OneWire::crc8(addr, 7) != addr[7]) {
          return;
      }
      // the first ROM byte indicates which chip

      ds.reset();
      ds.select(addr);
      ds.write(0x44, 1);        // start conversion, with parasite power on at the end

       // maybe 750ms is enough, maybe not
      // we might do a ds.depower() here, but the reset will take care of it.

      present = ds.reset();
      ds.select(addr);
      ds.write(0xBE);         // Read Scratchpad

      for ( i = 0; i < 9; i++) {           // we need 9 bytes
        data[i] = ds.read();
      }

      // Convert the data to actual temperature
      // because the result is a 16 bit signed integer, it should
      // be stored to an "int16_t" type, which is always 16 bits
      // even when compiled on a 32 bit processor.
      int16_t raw = (data[1] << 8) | data[0];
      if (type_s) {
        raw = raw << 3; // 9 bit resolution default
        if (data[7] == 0x10) {
          // "count remain" gives full 12 bit resolution
          raw = (raw & 0xFFF0) + 12 - data[6];
        }
      } else {
        byte cfg = (data[4] & 0x60);
        // at lower res, the low bits are undefined, so let's zero them
        if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
        else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
        else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
        //// default is 12 bit resolution, 750 ms conversion time
      }
      celsius = (float)raw / 16.0;
      Serial.print(celsius);

        }
        Serial.println("\n");

    }

How can I reach the upper format?

body:
From the point of view of what you print, your loop boils down to:

    if (millis() - startTime >= MEASURE_PERIOD) {
        startTime += MEASURE_PERIOD;
        sensorValue = ...;
        celcius = ...;
        Serial.print(sensorValue);
        Serial.print(",");
        Serial.print(celsius);
    }
    Serial.println("\n");

You are printing _two_ newlines on every loop iteration. One is written
as `"\n"`, the other is the “ln” of `Serial.println` (“println” means
“print some stuff followed by a new line character sequence”). Instead,
you probably want to print a _single_ newline, and only when there is
actual data being printed:

    if (millis() - startTime >= MEASURE_PERIOD) {
        startTime += MEASURE_PERIOD;
        sensorValue = ...;
        celcius = ...;
        Serial.print(sensorValue);
        Serial.print(",");
        Serial.println(celsius);  // notice the ln in println
    }

But since you are doing nothing else in `loop()`, you could simplify a
bit and avoid having everything inside a big `if` statement:

    if (millis() - startTime < MEASURE_PERIOD)
        return;

    startTime += MEASURE_PERIOD;
    sensorValue = ...;
    celcius = ...;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.println(celsius);

**Edit**: Here is a simple test demonstrating this logic. In both the
second and the third case, it generates an output in the requested
format.

    const uint32_t MEASURE_PERIOD = 250;

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

    void loop()
    {
        static uint32_t startTime;
    #ifdef SECOND_CASE
        if (millis() - startTime >= MEASURE_PERIOD) {
            startTime += MEASURE_PERIOD;
            int sensorValue = random(695, 699);
            float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
            Serial.print(sensorValue);
            Serial.print(",");
            Serial.println(celsius, 3);  // notice the ln in println
        }
    #else  // third case
        if (millis() - startTime < MEASURE_PERIOD)
            return;

        startTime += MEASURE_PERIOD;
        int sensorValue = random(695, 699);
        float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
        Serial.print(sensorValue);
        Serial.print(",");
        Serial.println(celsius, 3);  // notice the ln in println
    #endif
    }


message:
What does serial monitor send with 'Both NL & CR'

There is something I don't understand about serial monitor.

As far as I know the `Newline` option is `\n`.

The `Carriage return` option is `\r\n`.

But does that make the `Both NL & CR` option `\n\r\n`?

body:
Newline is `\n`

Carriage Return is `\r`

Both NL & CR is `\r\n`


body:
"Both" means 1 Carriage Return and 1 Newline (formerly known as "Line Feed"). Our present day "standards" are descended from mechanical teletypes that used those separate codes for the two separate mechanical functions: Returning the print carriage to the left side of the page, and scrolling the paper up one line.

The DOS/Windows world adopted the teletype standard (both) as is.

The unix world dropped the carriage return as unnecessary, letting a single character stand for the end of a line, and more modern hardware (or its software drivers) could figure out what to do for the particular device.

The Apple world chose Carriage Return for its standard back in the mists of time, dropping it in later years for a selectable end-of-line sequence where appropriate, but more usually using the unix standard once it's OSes became hosted on unix.


message:
Arduino Mega2560, Ethernet Shield & OV0706: "Camera not found"

I want to make a picture with the OV0706 that saves the picture to the SD card. I'm using the Arduino Mega2560, Ethernet Shield (with SD slot) and the OV0706 (this one: http://www.aliexpress.com/item/NEW-RS232-TTL-JPEG-Digital-Serial-Camera-Module-SCB-1-with-video-out-Support-VIMICRO-VC0706/1975852463.html). I tried the tutorial for this camera from Adafruit, but I'm still getting the error 'No camera found?'.

Thought it had something to do with assigning the pins, but if I connect the RX from the OV0706 with A15 on the Mega (see picture), it still gives the same error.
<!-- language-all: lang-cpp -->

    // On Mega: camera TX connected to pin 69 (A15), camera RX to pin 3:
    SoftwareSerial cameraconnection = SoftwareSerial(69, 3);

The code (important part):

    // This is a basic snapshot sketch using the VC0706 library.
    // On start, the Arduino will find the camera and SD card and
    // then snap a photo, saving it to the SD card.
    // Public domain.

    // If using an Arduino Mega (1280, 2560 or ADK) in conjunction
    // with an SD card shield designed for conventional Arduinos
    // (Uno, etc.), it's necessary to edit the library file:
    //   libraries/SD/utility/Sd2Card.h
    // Look for this line:
    //   #define MEGA_SOFT_SPI 0
    // change to:
    //   #define MEGA_SOFT_SPI 1
    // This is NOT required if using an SD card breakout interfaced
    // directly to the SPI bus of the Mega (pins 50-53), or if using
    // a non-Mega, Uno-style board.

    #include <Adafruit_VC0706.h>
    #include <SPI.h>
    #include <SD.h>

    // comment out this line if using Arduino V23 or earlier
    #include <SoftwareSerial.h>

    // uncomment this line if using Arduino V23 or earlier
    // #include <NewSoftSerial.h>

    // SD card chip select line varies among boards/shields:
    // Adafruit SD shields and modules: pin 10
    // Arduino Ethernet shield: pin 4
    // Sparkfun SD shield: pin 8
    // Arduino Mega w/hardware SPI: pin 53
    // Teensy 2.0: pin 0
    // Teensy++ 2.0: pin 20
    #define chipSelect 4

    // Pins for camera connection are configurable.
    // With the Arduino Uno, etc., most pins can be used, except for
    // those already in use for the SD card (10 through 13 plus
    // chipSelect, if other than pin 10).
    // With the Arduino Mega, the choices are a bit more involved:
    // 1) You can still use SoftwareSerial and connect the camera to
    //    a variety of pins...BUT the selection is limited.  The TX
    //    pin from the camera (RX on the Arduino, and the first
    //    argument to SoftwareSerial()) MUST be one of: 62, 63, 64,
    //    65, 66, 67, 68, or 69.  If MEGA_SOFT_SPI is set (and using
    //    a conventional Arduino SD shield), pins 50, 51, 52 and 53
    //    are also available.  The RX pin from the camera (TX on
    //    Arduino, second argument to SoftwareSerial()) can be any
    //    pin, again excepting those used by the SD card.
    // 2) You can use any of the additional three hardware UARTs on
    //    the Mega board (labeled as RX1/TX1, RX2/TX2, RX3,TX3),
    //    but must specifically use the two pins defined by that
    //    UART; they are not configurable.  In this case, pass the
    //    desired Serial object (rather than a SoftwareSerial
    //    object) to the VC0706 constructor.

    // Using SoftwareSerial (Arduino 1.0+) or NewSoftSerial (Arduino 0023 & prior):
    #if ARDUINO >= 100
    // On Uno: camera TX connected to pin 2, camera RX to pin 3:
    //SoftwareSerial cameraconnection = SoftwareSerial(2, 3);
    // On Mega: camera TX connected to pin 69 (A15), camera RX to pin 3:
    SoftwareSerial cameraconnection = SoftwareSerial(69, 3);
    #else
    NewSoftSerial cameraconnection = NewSoftSerial(2, 3);
    #endif

    Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection);

    // Using hardware serial on Mega: camera TX conn. to RX1,
    // camera RX to TX1, no SoftwareSerial object is required:
    //Adafruit_VC0706 cam = Adafruit_VC0706(&Serial1);

    void setup() {

      // When using hardware SPI, the SS pin MUST be set to an
      // output (even if not connected or used).  If left as a
      // floating input w/SPI on, this can cause lockuppage.
    #if !defined(SOFTWARE_SPI)
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
    #else
      if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
    #endif
    #endif

      Serial.begin(9600);
      Serial.println("VC0706 Camera snapshot test");

      // see if the card is present and can be initialized:
      if (!SD.begin(chipSelect)) {
        Serial.println("Card failed, or not present");
        // don't do anything more:
        return;
      }

      // Try to locate the camera
      if (cam.begin()) {
        Serial.println("Camera Found:");
      } else {
        Serial.println("No camera found?");
        return;
      }

Thanks in advance.

(Pictures: http://prntscr.com/apdvi9 )

body:
Sinceat least my camera needs up to 2secs to initialize,I thing the

    if (cam.begin()) {
    Serial.println("Camera Found:");
    } else {
    Serial.println("No camera found?");

returns immedeatly what it thinks No camera found

try it with

        unsigned long timer = millis();
        Serial.println("Camera initializing:");
        while (!cam.begin()) {
        Serial.print(".");
        if (millis()-timer>3000) {
          Serial.println("No camera found?");
          break;
          }
        }


message:
Using Arduino and XBee at the same time

I have 2 Arduino Unos, 2 XBees and 2 Wireless Proto Shields. The first setup has a humidity/temperature sensor (SHT21P) and it writes data to serial and it works (I've tested it).

Now, the other Arduino with shield and XBee is plugged in my PC to get data from the sensor. So here's the problem: as far as I understand, I can't use XBee and Arduino at the same time, because USB and Arduino both use TX/RX pins to communicate to PC/XBee. I've tested both of the XBees when they are powered with DC jack and they both work. So can anyone confirm that it's true that they're not made for being used by PC and Arduino at the same time? If so, how can I get the data to my computer?

body: If I understand correctly your goal is to receive data on your computer from an arduino connected with xbee? You could use a USB > Xbee board similar to Sparkfun's Xbee USB explorer board. I am not familiar with the shield that you are using, but some xbee shields allow you to select the pins that the xbee is connected to. It sounds like yours is defaulting to Pin 0 and Pin 1, hardware serial on the Uno. If you can switch it to Pin 2 and Pin 3 (or any two digital pins) you could use software serial with the xbee, leaving hardware serial free for your USB connection.


body:
Okay, I guess I figured it all out. So right now I have the following setup:

1 Arduino Board with Wireless Proto Shield (switch in Micro position) and XBee hooked up via DC jack pin, sends data to serial with `Serial.print(variable)` where `variable` is a predefined char array.

1 Arduino with Wireless Proto Shield (switch in Micro position) and XBee is hooked to the PC via USB and with `Serial.read()` I'm able to read data via the Serial Monitor. No configuration required whatsoever, the only thing you need to do this is to declare `Serial.begin(9600)` to both boards.

So it's true that I can't use Arduino and XBee at the same time, but this still works for me to solve the problem I had.


message:
Serial Data Formatting not Correct?

I am writing two Arduino Uno programs. One is a remote with a joystick and the other has five LED's indicating which direction the joystick is pointing. They are Bluetooth, so everything is sent and received through `Serial`. I am sending three variables by joining them into one string, separated by colons. Then I separate them back into three variables on the other arduino The joystick, Bluetooth, and LED's part of the programs work, I'm having trouble receiving the data and separating it. I have included both programs below. As it is now, it doesn't work. In the slave code, you can change the `int xPosition = getValue(input, ':', 0).toInt();` to `int xPosition = getValue(input2, ':', 0).toInt();`( also change `yPosition` and `buttonState`) and everything works. What is the difference between that string and what I'm receiving?

#Slave code:
    #include <SoftwareSerial.h>
    #define RxD 7
    #define TxD 6
    SoftwareSerial BlueToothSerial(RxD,TxD);
    char flag=1;
    String input;
    int xPosition;
    int yPosition;
    int buttonState;
    char outstring[30];
    char *input2 = "510:609:1\r\n";

    void sendBlueToothCommand(char *Command)
    {
      BlueToothSerial.print(Command);
      Serial.print(Command);
      delay(100);
      while(BlueToothSerial.available())
      {
         Serial.print(char(BlueToothSerial.read()));
      }
    }

    String getValue(String data, char separator, int index)
    {
     int found = 0;
      int strIndex[] = {0, -1  };
      int maxIndex = data.length()-1;
      for(int i=0; i<=maxIndex && found<=index; i++){
      if(data.charAt(i)==separator || i==maxIndex){
      found++;
      strIndex[0] = strIndex[1]+1;
      strIndex[1] = (i == maxIndex) ? i+1 : i;
      }
     }
      return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
    }

    void setup()
    {
       pinMode(12, OUTPUT);
       pinMode(11, OUTPUT);
       pinMode(10, OUTPUT);
       pinMode(9, OUTPUT);
       pinMode(8, OUTPUT);
       Serial.begin(38400);
       BlueToothSerial.begin(38400);
       delay(500);
       Serial.println("Starting...");
    }

    void loop()
    {
        if(BlueToothSerial.available())
        {
          input = char(BlueToothSerial.read());
          int xPosition = getValue(input, ':', 0).toInt();
          int yPosition = getValue(input, ':', 1).toInt();
          int buttonState = getValue(input, ':', 2).toInt();
          Serial.println("xPosition");
          Serial.println(xPosition);
          Serial.println("yPosition");
          Serial.println(yPosition);
          Serial.println("buttonState");
          Serial.println(buttonState);
          if ((xPosition == 507)&&(yPosition == 506)){
            clear();
            digitalWrite(8, HIGH);
          } else if ((xPosition == 507)&&(yPosition == 0)){
            clear();
            digitalWrite(12, HIGH);
          } else if ((xPosition == 507)&&(yPosition == 1023)){
            clear();
            digitalWrite(10, HIGH);
          } else if ((xPosition == 1023)&&(yPosition == 507)){
            clear();
            digitalWrite(11, HIGH);
          } else if ((xPosition == 0)&&(yPosition == 1023)){
            clear();
            digitalWrite(9, HIGH);
          }
        }
    }

    void clear() {
      digitalWrite(12, LOW);
      digitalWrite(11, LOW);
      digitalWrite(10, LOW);
      digitalWrite(9, LOW);
      digitalWrite(8, LOW);
    }
#Master code:
    #include <SoftwareSerial.h>
    #define RxD 7
    #define TxD 6
    SoftwareSerial BlueToothSerial(RxD,TxD);
    int xPin = A1;
    int yPin = A0;
    int buttonPin = 2;
    char outstring[30];
    int xPosition = 0;
    int yPosition = 0;
    int buttonState = 0;

    void sendBlueToothCommand(char *Command)
    {
      BlueToothSerial.print(Command);
      Serial.print(Command);
      delay(100);
      while(BlueToothSerial.available())
      {
         Serial.print(char(BlueToothSerial.read()));
      }
    }

    void setup()
    {
       Serial.begin(38400);
       BlueToothSerial.begin(38400);
       delay(500);
       pinMode(xPin, INPUT);
       pinMode(yPin, INPUT);
       pinMode(buttonPin, INPUT_PULLUP);
       BlueToothSerial.println("Hello");
    }

    void loop()
    {
      joy();
      sprintf(outstring, "%d:%d:%d\r\n", xPosition, yPosition, buttonState);
      BlueToothSerial.println(outstring);
      Serial.println(outstring);
    }

    void joy() {
      xPosition = analogRead(xPin);
      yPosition = analogRead(yPin);
      buttonState = digitalRead(buttonPin);
    }

body:
In the slave's `loop()`, when you say

    input = char(BlueToothSerial.read());

I'd expect just the first character of the serial stream to be read and stored.  Without further investigation, I don't know just what a `String` class does when you assign a character to it, but I doubt that any of the following code ever has more than one character at a time to work on.  This will keep your `getValue()` calls from working like you want.

Instead of using `String` objects and your `getValue()` code, consider using code like the following to handle the serial input.  The data format that this code expects is `nnnxnnnynnnb`, where each `nnn` is a series of digits, and x, y, b are literal characters.

This code shortens two of the overly-verbose parts of your code by:
• Use of an array and subscripting to replace the long list of `if` statements that sort out the combinations of low/medium/high x and y values.
• Use of `Streaming.h` (which you can install by unzipping Streaming5.zip from arduiniana.org into your sketchbook/libraries directory) to clean up long lists of `Serial.println()` statements, without increasing code size.

    #include <Streaming.h>
    int numVal = 0;

    void doAction() {
      byte pins[] = { 9,0,0, 12,8,10, 0,11,0 };
      byte xy = 3*(x/500)+y/500;
      byte pin = pins[xy];
      if (pin) {
        clear();
        digitalWrite(pin, HIGH);
      }
      Serial << "xPosition =  " << xPosition << endl;
      Serial << "yPosition =  " << yPosition << endl;
      Serial << "buttonState = " << buttonState << endl;
      numVal = 0;
    }

    void loop() {
      while (BlueToothSerial.available()) {
        byte c = BlueToothSerial.read();
        if ('0' <= c && '9' >= c) {
            numVal = 10*numVal + c - '0';
        } else {
          switch (c) {
          case 'x':  xPosition = numVal;   break;
          case 'y':  yPosition = numVal;   break;
          case 'b':  buttonState = numVal; doAction(); break;
          }
          numVal = 0;
        }
      }
    }


body:
The problem is you are only reading one character and trying to split that single character into other smaller units. It just isn't going to happen.

Instead you need to append each character to the end of a string until you receive the end-of-line characters (`\r\n`). Then you can split that entire string into parts.

Alternatively you can read numbers until you hit a `:` or a `\r\n` and build up the numbers directly without having to store anything.

My preferred method is the first, but I know Nick Gammon prefers the second, so I shall leave it to him to describe his favourite Finite State Machine for you.

To store all the data in a string I use a C string, not one of Arduino's dodgy String objects.

    char input[15];
    int ipos = 0;

Then you read the data:

    if (BlueToothSerial.available()) {
        char c = BlueToothSerial.read();
        if (c == '\r') continue; // Skip the carriage return
        if (c == '\n') { // We have the line ending
            // Split the data on :
            char *xtxt = strtok(input, ":");
            char *ytxt = strtok(NULL, ":");
            char *btxt = strtok(NULL, ":");
            // Convert the text to integers
            if (xtxt) xPosition = atoi(xtxt);
            if (ytxt) yPosition = atoi(ytxt);
            if (btxt) buttonState = atoi(btxt);
            ipos = 0; // Reset the string to the start
        } else {
            // If there is still room in the array
            if (ipos < 14) {
                // Add the incoming character
                input[ipos++] = c;
                // and terminate the string.
                input[ipos] = 0;
            }
        }
    }


message:
Beat 1 LED light is always on - should turn off

<!-- language: c -->

    /**************************************/
    const int lowestPin = 1;//the lowest one attach to
    const int speaker = 13;
    int ts = 4;//how many beats you want
    int count = 1;
    const int keyPin = 11;
    const int keyPinR = 10;
    int buttonState = LOW;
    int buttonState2 = LOW;
    int bpm = 120;
    int rthm = 1;
    /**************************************/
    void setup()
    {
      Serial.begin(9600);
       for(int thisPin = 1;thisPin <= ts;thisPin++)
       {
     pinMode(thisPin,OUTPUT); //initialize thisPin as an output
     pinMode(8, INPUT);

     pinMode(keyPin, INPUT);
     pinMode(keyPinR, INPUT);
     digitalWrite(keyPin, HIGH);
     digitalWrite(keyPinR, HIGH);
     }

    }

    /****************************************/
    void loop()
    {
     buttonState = digitalRead(keyPin);
     buttonState2 = digitalRead(keyPinR);
     if(buttonState==LOW){
     ts++;
      if(ts==6)
       {
        ts = 2;
       }
      }
     if(buttonState2==LOW){
      rthm++;
        Serial.println(rthm);
      if(rthm==5)
      rthm = 1;

      }
      for(int thisPin = 1;thisPin <= ts;thisPin++)
      {

      for(int r = 1; r<=rthm; r++){
       bpm = pulseIn(6, HIGH);
        digitalWrite(thisPin,HIGH);

        pinMode(13,OUTPUT);

        if(count == 1&&r==1)
        tone(13,1500,40);
        else if(r==1)
        tone(13,1000,40);
        else
        tone(13,500,40);
        delay((bpm-52)/rthm);

        digitalWrite(thisPin,LOW);
        pinMode(13,INPUT);

       }
        count++;
        if(count >ts)
        count = 1;
        }

       }

This is a metronome project. Each LED represents a beat. However, The LED for beat 1 is always on. It should turn off when it's on a different beat other than one. Is there anything wrong with the code?

body:
You are using PIN1 as an output pin and you are writing data to the Serial interface.  The serial interface uses pin 1 and 0.
Change lowestPin to 2 and ts to 5 and it will work.


message:
Project 2: Arduino controlled spaceship interface

The circuit diagram attached shows that the switch is open. Yet, the LED connected to pin 3 of the arduino board lights up.

[![Arudino spaceship interface circuit diagram][1]][1]

I don't understand this - the circuit is open, so why should pin 3 light up?

I discussed this with one of my friends - he said that each pin on the board receives voltage after the battery is connected. If this is true, then that would answer my question.

This is my code:

    int switchState = 0;
    //configures the digital pins
    void setup() {
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(2, INPUT);
    }

    //Checks the voltageo of the digital input and chooses the pin for voltage ( pin 2 )
    void loop() {
      switchState = digitalRead(2);

      if (switchState == LOW) {
        //Button is not pressed

        digitalWrite(3, HIGH); //Green LED
        digitalWrite(4, LOW); //Red LED
        digitalWrite(5, LOW); //red LED
      }

      else { //the button is pressed
        digitalWrite(3, LOW);
        digitalWrite(4, LOW);
        digitalWrite(5, HIGH);

        delay(250); //wait for a quarter second
        //toggle the LEDs
        digitalWrite(4, HIGH);
        digitalWrite(5, LOW);
        delay(250); //wait for a quarter second
      }
    } //go back to the beginning of the loop

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

body:
So everyone else knows where this is from [enter image description here][2].

-------------

*EDIT*

I have edited the image you gave to attempt to answer your question on 'wiring' :

![wiring][2]

![current][3]

The first image shows simply and crudely how the parts are basically connected or there relationship.

The second one shows how the current flows on the circuit, there is a key.

What you need to do is take the information from the link you give in the comment and apply logic to it, like if you used a logic probe and stuck it one end of the switch, the right side in that image, it would be `high`, if though you do so on the left it would be `low`. Hence no current flows in that circuit but there is current flow in the circuit looking at it.

------------

What you have not examined is the code related to your project or the description of the project.

Looking at the code:

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

    // Create a global variable to hold the
    // state of the switch. This variable is persistent
    // throughout the program. Whenever you refer to
    // switchState, you’re talking about the number it holds
    int switchstate = 0;

    void setup() {
      // declare the LED pins as outputs
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);

      // declare the switch pin as an input
      pinMode(2, INPUT);
    }

    void loop() {

      // read the value of the switch
      // digitalRead() checks to see if there is voltage
      // on the pin or not
      switchstate = digitalRead(2);

      // if the button is not pressed
      // turn on the green LED and off the red LEDs
      if (switchstate == LOW) {
        digitalWrite(3, HIGH); // turn the green LED on pin 3 on
        digitalWrite(4, LOW);  // turn the red LED on pin 4 off
        digitalWrite(5, LOW);  // turn the red LED on pin 5 off
      }
      // this else is part of the above if() statement.
      // if the switch is not LOW (the button is pressed)
      // turn off the green LED and blink alternatively the red LEDs
      else {
        digitalWrite(3, LOW);  // turn the green LED on pin 3 off
        digitalWrite(4, LOW);  // turn the red LED on pin 4 off
        digitalWrite(5, HIGH); // turn the red LED on pin 5 on
        // wait for a quarter second before changing the light
        delay(250);
        digitalWrite(4, HIGH); // turn the red LED on pin 4 on
        digitalWrite(5, LOW);  // turn the red LED on pin 5 off
        // wait for a quarter second before changing the light
        delay(250);
      }
    }

From this we see that the default state of this code in the first `if()` statement is to turn on PIN3 and leave the rest off when the button is not pressed.

From Arduino:

>! A green LED will be ON, until you press a button. When the Arduino
>! gets a signal from the button, the green light will turn off and 2
>! other lights will start blinking.

  [1]: https://www.arduino.cc/en/ArduinoStarterKit/Prj02
  [2]: https://i.stack.imgur.com/FyQtP.jpg
  [3]: https://i.stack.imgur.com/kNRw2.jpg


body:
Where is all this confusion coming from?

      if (switchState == LOW) {
        //Button is not pressed

        digitalWrite(3, HIGH); //Green LED

Your code says, if the switch is **not** pressed, light LED on pin 3.

> I don't understand this - the circuit is open, so why should pin 3 light up?

Because that is what the code tells it to do.

> Does that mean that there is some internal wiring between ground and pin 3 that supplies current to the green LED?

Get the idea out of your head that this is some wiring issue. Your device is doing exactly what you are telling it to do.

When you `digitalWrite` HIGH to some pin, the processor activates the output driver MOSFET that attempts to drive the pin to +5V. Therefore current flows through the resistor to the LED which lights up.


message:
NEO 6M GPS speed

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

I am doing a project using a NEO 6M GPS with my Arduino LilyPad. I programmed it already, and it's working well except of the speed. I get stuck on fixing this. I wonder why the value is never getting zero although I am not moving to my place.

I need any suggestions/help that would make the speed working accurately.

Thanks.

Here is the code I used:

     #include <SoftwareSerial.h>
     #include <TinyGPS.h>

    SoftwareSerial mySerial(4, 3); // RX, TX
    TinyGPS gps;

    void gpsdump(TinyGPS &gps);
    void printFloat(double f, int digits = 2);

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
      delay(1000);
      Serial.print("Sizeof(gpsobject) = ");
      Serial.println(sizeof(TinyGPS));
      Serial.println();
    }

    void loop() {
      bool newdata = false;
      unsigned long start = millis();
      // Every 5 seconds we print an update
      while (millis() - start < 5000) {
        if (mySerial.available()) {
          char c = mySerial.read();
          if (gps.encode(c)) {
            newdata = true;
          }
        }
      }
      if (newdata) {
        Serial.println("Acquired Data");
        Serial.println("-------------");
        gpsdump(gps);
        Serial.println("-------------");
        Serial.println();
      }
    }

    void gpsdump(TinyGPS &gps) {
      long lat, lon;
      float flat, flon;
      unsigned long age, date, time, chars;
      int year;
      byte month, day, hour, minute, second, hundredths;
      unsigned short sentences, failed;
      gps.get_position(&lat, &lon, &age);
      Serial.print("Lat/Long(10^-5 deg): ");
      Serial.print(lat);
      Serial.print(", ");
      Serial.print(lon);
      Serial.print(" Fix age: ");
      Serial.print(age);
      Serial.println("ms.");
      // On Arduino, GPS characters may be lost during lengthy Serial.print()
      // On Teensy, Serial prints to USB, which has large output buffering and
      // runs very fast, so it's not necessary to worry about missing 4800 baud GPS characters.
      gps.f_get_position(&flat, &flon, &age);
      Serial.print("Lat/Long(float): ");
      printFloat(flat, 5);
      Serial.print(", ");
      printFloat(flon, 5);
      Serial.print(" Fix age: ");
      Serial.print(age);
      Serial.println("ms.");
      gps.get_datetime(&date, &time, &age);
      Serial.print("Date(ddmmyy): ");
      Serial.print(date);
      Serial.print(" Time(hhmmsscc): ");
      Serial.print(time);
      Serial.print(" Fix age: ");
      Serial.print(age);
      Serial.println("ms.");
      Serial.print("Alt(cm): ");
      Serial.print(gps.altitude());
      Serial.print(" Course(10^-2 deg): ");
      Serial.print(gps.course());
      Serial.print(" Speed(10^-2 knots): ");
      Serial.println(gps.speed());
      Serial.print("Alt(float): ");
      printFloat(gps.f_altitude());
      Serial.print(" Course(float): ");
      printFloat(gps.f_course());
      Serial.println();
      Serial.print("Speed(knots): ");
      printFloat(gps.f_speed_knots());
      Serial.print(" (mph): ");
      printFloat(gps.f_speed_mph());
      Serial.print(" (mps): ");
      printFloat(gps.f_speed_mps());
      Serial.print(" (kmph): ");
      printFloat(gps.f_speed_kmph());
      Serial.println();
      gps.stats(&chars, &sentences, &failed);
      Serial.print("Stats: characters: ");
      Serial.print(chars);
      Serial.print(" sentences: ");
      Serial.print(sentences);
      Serial.print(" failed checksum: ");
      Serial.println(failed);
    }

    void printFloat(double number, int digits) {
      // Handle negative numbers
      if (number < 0.0) {
        Serial.print('-');
        number = -number;
      }
      // Round correctly so that print(1.999, 2) prints as "2.00"
      double rounding = 0.5;
      for (uint8_t i=0; i<digits; ++i)
        rounding /= 10.0;
      number += rounding;
      // Extract the integer part of the number and print it
      unsigned long int_part = (unsigned long)number;
      double remainder = number - (double)int_part;
      Serial.print(int_part);
      // Print the decimal point, but only if there are digits beyond
      if (digits > 0)
        Serial.print(".");
      // Extract digits from the remainder one at a time
      while (digits-- > 0) {
        remainder *= 10.0;
        int toPrint = int(remainder);
        Serial.print(toPrint);
        remainder -= toPrint;
      }
    }

NOTE:  The altitude and longitude were already working. It's the speed that I want to fix. I want to see it as "ZERO SPEED" when at a steady state. How can I fix this? Please help me. Thanks!

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

body: Usually, this should be solved by just going outside to get the first fix point. If you still don't manage it, try the U-center software to make sure your GPS is properly working.


body:
The speed value is correct, like TisteAndi said.  Your GPS location "wanders" around the same way.  You can simply ignore small speed values.

One problem you may not be aware of yet: the printing isn't really coordinated with the GPS updates.  Sometimes that doesn't matter, but if you want your speed to update every second, you'll need to synchronize the two.  And as noted in the code, you can actually lose GPS data if you print too much.

I wrote a GPS library, called [NeoGPS](https://github.com/SlashDevin/NeoGPS), to fix some of these problems.  They are described in the [Troubleshooting](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Troubleshooting.md) section of the online documentation.

Also, `SoftwareSerial` is very inefficient.  I maintain a more-efficient alternative, [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial).  As you add more features to your GPS program, the efficiency will become important.

Here is your program, modified to use NeoGPS and NeoSWSerial, and it uses TisteAndi's suggestion to set the speed to zero:

    #include <Arduino.h>
    #include "NMEAGPS.h"
    #include <NeoSWSerial.h>

    NeoSWSerial mySerial(4, 3); // RX, TX//

    NMEAGPS     gps;
    gps_fix     fix;
    uint8_t     GPSupdates = 0;

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);

      delay(1000);

      Serial.print("Sizeof(gps) = "); Serial.println(sizeof(gps));
      Serial.println();
    }

    void loop() // run over and over
    {
      while (gps.available( mySerial )) {
        fix = gps.read();

        if (fix.valid.speed && (fix.speed_mkn() < 1000)) {
          // Too slow, zero out the speed
          fix.spd.whole = 0;
          fix.spd.frac  = 0;
        }

        GPSupdates++;
      }

      // Print once every 5 seconds
      if (GPSupdates >= 5) {
        Serial.println("Acquired Data");
        Serial.println("-------------");
        gpsdump();
        Serial.println("-------------");
        Serial.println();

        GPSupdates = 0;
      }

    }

    void gpsdump()
    {
      Serial.print("Lat/Long(10^-7 deg): ");
      if (fix.valid.location) {
        Serial.print(fix.lat);
        Serial.print(", ");
        Serial.print(fix.lon);
      }
      Serial.println();

      // GPS characters may be lost during lengthy Serial.print()
      //   See the NeoGPS Troubleshooting section.

      Serial.print("Lat/Long(float): ");
      if (fix.valid.location) {
        Serial.print(fix.latitude(), 5);
        Serial.print(", ");
        Serial.print(fix.longitude(), 5);
      }
      Serial.println();

      Serial.print("Date/Time: ");
      if (fix.valid.date | fix.valid.time)
        Serial << fix.dateTime;
      Serial.println();

      //*
      Serial.print("Date: ");
      if (fix.valid.date) {
        Serial.print(fix.dateTime.month);
        Serial.print("/");
        Serial.print(fix.dateTime.date);
        Serial.print("/");
        Serial.print(fix.dateTime.year);
      }

      if (fix.valid.date | fix.valid.time) {
        Serial.print("  Time: ");
        Serial.print(fix.dateTime.hours);
        Serial.print(":");
        Serial.print(fix.dateTime.minutes);
        Serial.print(":");
        Serial.print(fix.dateTime.seconds);
        Serial.print(".");
        Serial.print(fix.dateTime_cs);
      }
      Serial.println();
      //*/

      Serial.print("Alt(cm): ");
      if (fix.valid.altitude)
        Serial.print(fix.altitude_cm());

      Serial.print(" Course(10^-2 deg): ");
      if (fix.valid.heading)
        Serial.print(fix.heading_cd());

      Serial.print(" Speed(10^-3 knots): ");
      if (fix.valid.speed)
        Serial.print(fix.speed_mkn());
      Serial.println();

      Serial.print("Alt(float): ");
      if (fix.valid.altitude)
        Serial.print(fix.altitude());

      Serial.print(" Course(float): ");
      if (fix.valid.heading)
        Serial.print(fix.heading());
      Serial.println();

      Serial.print("Speed(knots): ");
      if (fix.valid.speed)
        Serial.print(fix.speed());
      Serial.print(" (mph): ");
      if (fix.valid.speed)
        Serial.print(fix.speed_mph());
      Serial.print(" (mps): ");
      if (fix.valid.speed)
        Serial.print(fix.speed_kph()*3600.0/1000.0);
      Serial.print(" (kmph): ");
      if (fix.valid.speed)
        Serial.print(fix.speed_kph());
      Serial.println();

      Serial.print("Stats: characters: ");
      Serial.print(gps.statistics.chars);
      Serial.print(" sentences: ");
      Serial.print(gps.statistics.ok);
      Serial.print(" failed checksum: ");
      Serial.println(gps.statistics.crc_errors);
    }

(Notice the increased accuracy of the integer lat/lon!  And you don't need `printFloat`.)

If you'd like to try it, be sure to follow the NeoGPS [Installation](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Installing.md) instructions.  NeoSWSerial is installed like most Arduino libraries.


message:
How to use a digital RGB LED Strip?

I know this is probably a little bit basic but I need SERIOUS help with using my new led strip. You can see here the type of strip I have, and the packet.

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

It's difficult because it looks slightly different to all the other ones I've seen in tutorials so I don't really know where to start now...All I've done is cut off the ends of the wires already on there and replace them with the regular pins that I can use on the Arduino and breadboards too. Where do I have to go from here? Are there any code libraries I need to use?

  [1]: https://i.stack.imgur.com/DwCYX.jpg
  [2]: https://i.stack.imgur.com/8LQdD.jpg
  [3]: https://i.stack.imgur.com/ksGON.jpg

body:
As far as I understand the DAT (Green wire) is a digital data wire. Try the following:
1. VCC to +5V pin
2. GND to GND pin
3. DAT to 2 Digital pin.

Then try to change the state of the 2 digital pin from high to low and see if anything happens... That's what I would start out with.


body: I had the same issue, in every example you see wiring diagrams with 3 wires, and my ledstrip had 5 wires, but it seems the two red wires (5v) are connected and the two white wires (gnd) are connected to eachother, so basicly you have 3 wires like in every wiring diagrams  what's out there


message:
What is the necessity of “Prototyping Shield” for an arduino UNO R3?

I just want to learn arduino and make some small projects.But in beginner starter kit there's a part named Prototyping Shield .Is it necessary or will it help me?

body:
The prototyping shield can be used to build your own circuits up in a more permanent form which can be plugged direct into the Arduino.

You can think of it as a blank canvass on which you can paint your own shield design.


message:
What are some "must-have" sensors or shields for an Arduino robot or motor?

I am starting to learn Arduino and wanna make some projects.which components will  I have to buy?please help me.

body:
It largely depends on your interests but since you've mentioned robotics, a motor shield, motor power supply, and one or a couple of hobby servos or DC motors will get you started on learning about controlling mechanical motion. You may be able salvage a DC motor from something else, like the vibrator motor from a dead cell phone.

If you want to start inexpensively, a few LEDs and a ~200 Ohm resistor for each one, and a couple of light or temperature sensors will give you plenty to play with. It's amazing how much real-world data you can collect and infer from a couple of well placed temperature sensors.

LM34 and LM35 are inexpensive and easy to use analog thermo-sensors that read directly in 0.01 Volts / degree (Fahrenheit and Celsius respectively), so only minimal arithmetic conversion is required (because along the way, you'll learn about Analog to Digital conversion, too).

Get some experience with those simple parts, and the coding to make them useful, and you'll have a much better idea of what you want to do next and what you'll need to acquire to do it.


message:
SDA/SCL pins Arduino Uno

I am trying to figure if SDA and SCL pins from Arduino Uno is a TTL or a CMOS technology. I am not able to find this info anywhere but regarding it is a I2C protocol it does make sense to be a TTL technology. Can someone kindly confirm this info, please?

body:
It is CMOS in that the IO pins of the MCU use MOSFETs not BJTs.

However I2C is slightly different in that it is open-drain not push-pull, so it's not really either TTL or CMOS since it doesn't conform to either logic level standard (since there is no "high" voltage, only what is pulled up by the external resistor). That said, since the ATMega is normally CMOS when in input or push-pull mode the logic levels of the I2C should conform to CMOS not TTL in order for the Arduino to read them properly.

It's closer to RTL than TTL or CMOS.


body:
Your question makes no sense. I²C uses open-drain/open-collector drivers which can even be discrete transistors or FETs although the inputs correspond to CMOS/TTL. These can be mixed - the Arduino uses MOS technology.

Of more significance is the supply voltage and the high/low trigger points (and of course the value of the mandatory pullup resistors which determine speed and/or range).

It is possible to use mixed 3.3V/5V levels. I use a Pi (3.3V) to communicate to Arduino (5V) which works (provided pullup is to 3.3V) although technically the Arduino input high levels are marginal.


message:
arduino quadcopter freezing while reading MPU6050/RC Receiver

I am trying to build an Arduino Flight controller. I have an MPU6050 (Gyroscope/Accelerometer) on board that is helping me configure my stabilization software. I also have my ESC's, and receiver plugged in to my Arduino. At some point during the code running, receiving and processing data from the Gyroscope and Receiver, the Arduino Uno freezes and I am not sure what is causing this problem. Any advice on how to fix this is greatly appreciated.

I am also getting FIFO overflows.

    #include <Servo.h>
    #include <Wire.h>
    Servo esc1;
    Servo esc2;
    Servo esc3;
    Servo esc4;
    byte last_channel_1, last_channel_2, last_channel_3, last_channel_4, last_channel_5;
    int receiver_input_channel_1, receiver_input_channel_2, receiver_input_channel_3;
    int receiver_input_channel_4, receiver_input_channel_5;
    unsigned long timer_1, timer_2, timer_3, timer_4, timer_5;
    int reciever1, reciever2, reciever3, reciever4, reciever5;
    int pastreciever1, pastreciever2, pastreciever3, pastreciever4, pastreciever5;
    bool keycode;
    int avg1, avg2, avg3, avg4;
    int i;
    const int avglen = 8;
    int reciever1avg[avglen], reciever2avg[avglen], reciever3avg[avglen], reciever4avg[avglen];
    int landingspeed = 1140;
    int requestedspeed = 1400;
    int autothrottle;
    int motor1change, motor2change, motor3change, motor4change;
    int yawchange, rollchange, nickchange;
    int wait;
    int set;
    unsigned long interval=5000; // the time we need to wait
    unsigned long previousMillis=0; // millis() returns an unsigned long.
    unsigned long timer = 0;

    //#define printdata

    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif
    MPU6050 mpu;
    #define OUTPUT_READABLE_YAWPITCHROLL
    #define LED_PIN 13
    bool blinkState = false;
    bool dmpReady = false;
    uint8_t mpuIntStatus;
    uint8_t devStatus;
    uint16_t packetSize;
    uint16_t fifoCount;
    uint8_t fifoBuffer[64];
    Quaternion q;
    VectorInt16 aa;
    VectorInt16 aaReal;
    VectorInt16 aaWorld;
    VectorFloat gravity;
    float euler[3];
    float ypr[3];
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };
    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }

    float initialGyroX;
    float initialGyroY;
    float initialGyroZ;
    const int autopilotkey = 1150;
    int deg_x;
    int deg_y;
    int deg_z;
    int requiredspeed;

    void setup()
    {
      //Arduino (Atmega) pins default to inputs, so they don't need to be explicitly declared as inputs
      PCICR |=  (1 << PCIE0);    // set PCIE0 to enable PCMSK0 scan
      PCMSK0 |= (1 << PCINT0);  // set PCINT0 (digital input 8) to trigger an interrupt on state change
      PCMSK0 |= (1 << PCINT1);  // set PCINT1 (digital input 9)to trigger an interrupt on state change
      PCMSK0 |= (1 << PCINT2);  // set PCINT2 (digital input 10)to trigger an interrupt on state change
      PCMSK0 |= (1 << PCINT3);  // set PCINT3 (digital input 11)to trigger an interrupt on state change
      PCMSK0 |= (1 << PCINT4);  // set PCINT4 (digital input 12)

      pastreciever1 = 1058;
      pastreciever2 = 1058;
      pastreciever3 = 1058;
      pastreciever4 = 1058;
      wait=0;
      set=0;
      keycode = false;

       esc1.writeMicroseconds(1000);
       esc2.writeMicroseconds(1000);
       esc3.writeMicroseconds(1000);
       esc4.writeMicroseconds(1000);

       esc1.attach(9);
       esc2.attach(6);
       esc3.attach(5);
       esc4.attach(3);

      #ifdef printdata
      Serial.begin(115200);
      #endif

        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 24;
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif
        mpu.initialize();

        #ifdef printdata
        Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
        #endif
        devStatus = mpu.dmpInitialize();
        mpu.setXGyroOffset(220);
        mpu.setYGyroOffset(76);
        mpu.setZGyroOffset(-85);
        mpu.setXAccelOffset(-2580);
        mpu.setYAccelOffset(2567);
        mpu.setZAccelOffset(1920);
        //Serial.println("The timer has begun.");
       if (devStatus == 0)
       {
        #ifdef printdata
            Serial.println(F("Enabling DMP..."));
            #endif
            mpu.setDMPEnabled(true);
            //Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(0, dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();
            #ifdef printdata
            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            #endif
            dmpReady = true;
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {
            // ERROR!
            // 1 = initial memory load failed
            // 2 = DMP configuration updates failed
            // (if it's going to break, usually the code will be 1)
            #ifdef printdata
            Serial.print(F("DMP Initialization failed (code "));
            #endif
            //Serial.print(devStatus);
            //Serial.println(F(")"));
        }
    }

    /*void ascend()
    {
      Serial.println("Ascending.");
      for (autothrottle = landingspeed; autothrottle<requestedspeed; autothrottle++)
      {
        esc1.writeMicroseconds(autothrottle);
        esc1.writeMicroseconds(autothrottle);
        esc1.writeMicroseconds(autothrottle);
        esc1.writeMicroseconds(autothrottle);
        delay(100);
        //gyro auto-level code??
        if ((avg3 != autothrottle)&&(avg3 < autothrottle));
        { }
        if ((avg3==requestedspeed)||(avg3>requestedspeed)||(avg1>1532)||(avg1<1472))
        {
          break; //go back to reciever input
        }
      }
    }

    void descend()
    {
      Serial.println ("Descending.");
      for (autothrottle = avg3; autothrottle>landingspeed; autothrottle--)
      {
        esc1.writeMicroseconds(autothrottle);
        esc1.writeMicroseconds(autothrottle);
        esc1.writeMicroseconds(autothrottle);
        esc1.writeMicroseconds(autothrottle);
        delay(100);
        //Gyro autolevel code??
        do
        { } while ((avg3 != autothrottle)||(avg3>autothrottle));
        if ((avg3 == autothrottle)||(avg3<autothrottle)||(avg1>1532)||(avg1<1472))
        {
          break; //go back to reciever input
        }
      }
    }*/

    void loop()
    {
       print_signals();
       motor1change=0;
       motor2change=0;
       motor3change=0;
       motor4change=0;

       if (wait==0)
       {
        delay(20000);
        //XBee.write the weather
       }
       wait=1;
       if (set==6)
       {
        initialGyroX = (ypr[1] * 180/M_PI)-0.34;//X
        initialGyroY = (ypr[2] * 180/M_PI)-0.5;//Y
        initialGyroZ = ypr[0] * 180/M_PI;//Z
        #ifdef printdata
        Serial.print ("STORED:");
        Serial.print("\t");
        Serial.print (initialGyroX);
        Serial.print("\t");
        Serial.print (initialGyroY);
        Serial.print("\t");
        Serial.println (initialGyroZ);
        #endif
        }

        //Automatic Take-off
        /*if ((set>=6)&&(average3<1300)&&(average4<1300)&&(average2<1300)&&(average1>1700))
        {
          Serial.println("Ascending..");
          ascend();
        }*/

       //Nick (Go forward/backward)------------------------------------------
       if(avg2 > 1532)
       {
        nickchange = (avg2 - 1532)/2;
        motor1change=motor1change+nickchange;
        motor2change=motor2change-nickchange;
        motor3change=motor3change-nickchange;
        motor4change=motor4change+nickchange;
       }
       if (avg2 < 1494)
       {
        nickchange = (1494-avg2)/2;
        motor1change=motor1change-nickchange;
        motor2change=motor2change+nickchange;
        motor3change=motor3change+nickchange;
        motor4change=motor4change-nickchange;
       }
       //Yaw-------------------------------------------------------------------
       if (avg1 > 1510)
       {
        yawchange = (avg1 - 1510)/2;
        motor1change=motor1change+yawchange;
        motor2change=motor2change-yawchange;
        motor3change=motor3change+yawchange;
        motor4change=motor4change-yawchange;
       }
       if (avg1 < 1470)
       {
        yawchange = (1470 - avg1)/2;
        motor1change=motor1change-yawchange;
        motor2change=motor2change+yawchange;
        motor3change=motor3change-yawchange;
        motor4change=motor4change+yawchange;
       }
       //Roll------------------------------------------------------------------
       if (avg4 > 1532)
       {
        rollchange = (avg4 - 1532)/2;
        motor1change=motor1change+rollchange;
        motor2change=motor2change+rollchange;
        motor3change=motor3change-rollchange;
        motor4change=motor4change-rollchange;
       }
       if (avg4 < 1472)
       {
        rollchange = (1472 - avg4)/2;
        motor1change=motor1change-rollchange;
        motor2change=motor2change-rollchange;
        motor3change=motor3change+rollchange;
        motor4change=motor4change+rollchange;
       }

        if (!dmpReady) return;
        while (!mpuInterrupt && fifoCount < packetSize) {
           }
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();
        fifoCount = mpu.getFIFOCount();
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            mpu.resetFIFO();
            #ifdef printdata
            Serial.println(F("FIFO overflow!"));
            #endif
        } else if (mpuIntStatus & 0x02) {
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
            mpu.getFIFOBytes(fifoBuffer, packetSize);
            fifoCount -= packetSize;
                //Print Data
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                /*Serial.print("XYZ:\t");
                Serial.print(ypr[1] * 180/M_PI);
                Serial.print("\t");
                Serial.print(ypr[2] * 180/M_PI);
                Serial.print("\t");
                Serial.println(ypr[0] * 180/M_PI);*/
            //#endif

    //Stabilization----------------------------------------------------------------------------
    if ((keycode==true)&&(avg3>autopilotkey))
    {
       //X Axis----------------------------------------------------------
      if ((ypr[1]* 180/M_PI)>(initialGyroX + 2))
      {
        deg_x = initialGyroX - (ypr[1] * 180/M_PI);
        requiredspeed = (-4.5*deg_x);
        #ifdef printdata
        Serial.print ("GyroX++: ");
        #endif
        //Serial.println(requiredspeed);
        motor1change=motor1change+requiredspeed;
        motor2change=motor2change+requiredspeed;
        motor3change=motor3change-requiredspeed;
        motor4change=motor4change-requiredspeed;
      }
      if ((ypr[1]* 180/M_PI)<(initialGyroX - 2))
      {
        deg_x = initialGyroX - (ypr[1] * 180/M_PI);
        requiredspeed = (4.5*deg_x);
        #ifdef printdata
        Serial.print("GyroX--: ");
        #endif
        //Serial.println (requiredspeed);
        motor1change=motor1change-requiredspeed;
        motor2change=motor2change-requiredspeed;
        motor3change=motor3change+requiredspeed;
        motor4change=motor4change+requiredspeed;
      }
      //Y Axis------------------------------------------------------------
      if ((ypr[2] * 180/M_PI)>(initialGyroY + 2))
      {
        deg_y = initialGyroY - (ypr[2] * 180/M_PI);
        requiredspeed = (-4.5*deg_y);
        #ifdef printdata
        Serial.print ("GyroY++: ");
        #endif
        //Serial.println (requiredspeed);
        motor1change=motor1change+requiredspeed;
        motor2change=motor2change-requiredspeed;
        motor3change=motor3change-requiredspeed;
        motor4change=motor4change+requiredspeed;
      }
       if ((ypr[2] * 180/M_PI)<(initialGyroY - 2))
      {
        deg_y = initialGyroY - (ypr[2] * 180/M_PI);
        requiredspeed = (4.5*deg_y);
        #ifdef printdata
        Serial.print ("GyroY--: ");
        #endif
        //Serial.println (requiredspeed);
        motor1change=motor1change-requiredspeed;
        motor2change=motor2change+requiredspeed;
        motor3change=motor3change+requiredspeed;
        motor4change=motor4change-requiredspeed;
      }
      //Z Axis--------------------------------------------------------------
      if ((ypr[0]* 180/M_PI)>(initialGyroZ + 4))//decrease
      {
        deg_z = initialGyroZ - (ypr[0] * 180/M_PI);
        requiredspeed = (-1*deg_z);
        #ifdef printdata
        Serial.print ("GyroZ++: ");
        #endif
        //Serial.println (requiredspeed);
        motor1change=motor1change-requiredspeed;
        motor2change=motor2change+requiredspeed;
        motor3change=motor3change-requiredspeed;
        motor4change=motor4change+requiredspeed;
      }
      if ((ypr[0]* 180/M_PI)<(initialGyroZ - 4))//increase
      {
        deg_z = initialGyroZ - (ypr[0] * 180/M_PI);
        requiredspeed = (1*deg_z);
        #ifdef printdata
        Serial.print ("GyroZ--: ");
        #endif
        //Serial.println (requiredspeed);
        motor1change=motor1change+requiredspeed;
        motor2change=motor2change-requiredspeed;
        motor3change=motor3change+requiredspeed;
        motor4change=motor4change-requiredspeed;
      }
     }
    }
      motor1change=constrain(motor1change, -100, 100);
      motor2change=constrain(motor2change, -100, 100);
      motor3change=constrain(motor3change, -100, 100);
      motor4change=constrain(motor4change, -100, 100);
      #ifdef printdata
       //Elevation------------------------------------------------------------
       Serial.print ("Motor Changes (1-4): ");
       Serial.print (motor1change);
       Serial.print (" ");
       Serial.print (motor2change);
       Serial.print (" ");
       Serial.print (motor3change);
       Serial.print (" ");
       Serial.println (motor4change);
      #endif
       if (avg3>1150)
       {
       esc1.writeMicroseconds((avg3+7)+motor1change);
       esc2.writeMicroseconds((avg3+7)+motor2change);
       esc3.writeMicroseconds(avg3+motor3change);
       esc4.writeMicroseconds(avg3+motor4change);
       }
    }

    //This routine is called every time input 8, 9, 10 or 11 changed state
    ISR(PCINT0_vect){
      //Channel 1=========================================
      if(last_channel_1 == 0 && PINB & B00000001 ){         //Input 8 changed from 0 to 1
        last_channel_1 = 1;                                 //Remember current input state
        timer_1 = micros();                                 //Set timer_1 to micros()
      }
      else if(last_channel_1 == 1 && !(PINB & B00000001)){  //Input 8 changed from 1 to 0
        last_channel_1 = 0;                                 //Remember current input state
        receiver_input_channel_1 = micros() - timer_1;      //Channel 1 is micros() - timer_1
      }
      //Channel 2=========================================
      if(last_channel_2 == 0 && PINB & B00000100 ){         //Input 10 changed from 0 to 1
        last_channel_2 = 1;                                 //Remember current input state
        timer_2 = micros();                                 //Set timer_3 to micros()
      }
      else if(last_channel_2 == 1 && !(PINB & B00000100)){  //Input 10 changed from 1 to 0
        last_channel_2 = 0;                                 //Remember current input state
        receiver_input_channel_2 = micros() - timer_2;      //Channel 3 is micros() - timer_3
      }
     //Channel 3=========================================
      if(last_channel_3 == 0 && PINB & B00001000 ){         //Input 11 changed from 0 to 1
        last_channel_3 = 1;                                 //Remember current input state
        timer_3 = micros();                                 //Set timer_4 to micros()
      }
      else if(last_channel_3 == 1 && !(PINB & B00001000)){  //Input 11 changed from 1 to 0
        last_channel_3 = 0;                                 //Remember current input state
        receiver_input_channel_3 = micros() - timer_3;      //Channel 4 is micros() - timer_4
      }
      //Channel 4=========================================
      if(last_channel_4 == 0 && PINB & B00010000 ){         //Input 12 changed from 0 to 1
        last_channel_4 = 1;                                 //Remember current input state
        timer_4 = micros();                                 //Set timer_5 to micros()
      }
      else if(last_channel_4 == 1 && !(PINB & B00010000)){  //Input 12 changed from 1 to 0
        last_channel_4 = 0;                                 //Remember current input state
        receiver_input_channel_4 = micros() - timer_4;      //Channel 5 is micros() - timer_5
      }
    }

    //Subroutine for displaying the receiver signals
    void print_signals()
    {
      //Constrain
      reciever1 = constrain(receiver_input_channel_1, 1000, 2100);
      reciever2 = constrain(receiver_input_channel_2, 1000, 2100);
      reciever3 = constrain(receiver_input_channel_3, 1000, 2100);
      reciever4 = constrain(receiver_input_channel_4, 1000, 2100);
      reciever5 = constrain(receiver_input_channel_5, 1000, 2100);

      set=set+1;

      //AVG 1-4-----------------------------------------------------
      for (i=0; i<avglen-1; i++)
      {
        reciever1avg[i]=reciever1avg[i+1];
      }
      reciever1avg[avglen-1]=reciever1;
      avg1=0;
      for (i=0; i<avglen; i++)
      {
        avg1+= reciever1avg[i];
      } avg1/=avglen;

      for (i=0; i<avglen-1; i++)
      {
        reciever2avg[i]=reciever2avg[i+1];
      }
      reciever2avg[avglen-1]=reciever2;
      avg2=0;
      for (i=0; i<avglen; i++)
      {
        avg2+= reciever2avg[i];
      } avg2/=avglen;

      for (i=0; i<avglen-1; i++)
      {
        reciever3avg[i]=reciever3avg[i+1];
      }
      reciever3avg[avglen-1]=reciever3;
      avg3=0;
      for (i=0; i<avglen; i++)
      {
        avg3+= reciever3avg[i];
      } avg3/=avglen;

      for (i=0; i<avglen-1; i++)
      {
        reciever4avg[i]=reciever4avg[i+1];
      }
      reciever4avg[avglen-1]=reciever4;
      avg4=0;
      for (i=0; i<avglen; i++)
      {
        avg4+= reciever4avg[i];
      } avg4/=avglen;

      //Activate Autopilot
      if ((avg1==pastreciever1)&&(avg2==pastreciever2)
        &&(avg3==pastreciever3)&&(avg4==pastreciever4)&&(avg3>autopilotkey))
      {
        keycode=true;

      } else {keycode=false;}

      pastreciever1 = avg1;
      pastreciever2 = avg2;
      pastreciever3 = avg3;
      pastreciever4 = avg4;

body:
This can happen in I2C sometimes. Basically the controller asks the sensors for data but there may be a bit error in the address. If so the sensor thinks you are talking to another chip, meanwhile your I2C master code waits for a reply, forever.

To fix this problem I would recommend the use of a watchdog timer. You can find the many examples online of how to set this up.


message:
How can I use my old cellphones camera on my arduino robot?

The pins are so small I dont know which pin needs to go to the which pin socket and if t's compatible or not. I have the selfie camera of Xperia Z phone and a Arduino Uno r3.

body:
> How can i use my old cellphones camera on my arduino robot?

No! Even if you got all the details on the camera there are too many limitations with the Arduino for any serious application. You will need more memory and processing power.


body:
Camera modules usually talk a protocol called CSI-2 or CSI-3. That's the Camera Serial Interface protocol.

It transfers very large amounts of data very fast. More data than a little Arduino can cope with.  For instance, a current typical mobile phone camera is measured in multiples of megapixels. Each pixel takes 3 bytes to represent at 24-bit, so say you have a 2 megapixel camera that would be in excess of 6 megabytes of data per image.  To put that into perspective the Arduino Uno has 2kB of RAM.

So no there is no way you will be able to directly interface a mobile phone camera to any of the microcontroller based Arduinos. That's not to say that something might not be able to be hacked on to one of the new-fangled things they try and pass off as Arduinos these days but are actually some strange SoC made by Intel. You're very much on your own with those though...

There are camera modules available aimed at the Arduino, but they are not directly readable by the Arduino due to lack of memory. They do, though, generally have a UART interface for controlling the camera, and then a separate streaming interface (often with a FIFO buffer to access the data slowly) for grabbing a snapped picture. The Arduino can't really do much with that data other than save it to an SD card or pass it on to a computer through USB, so they're pretty pointless really.


message:
What is the necessity of "Prototyping Shield" for an arduino UNO R3?

I just want to learn Arduino and make some  small projects. But in  the beginner starter kit there's  a part named Prototyping Shield. Is it necessary or will it help me?

body:
A prototyping shield allows you to create your own circuit that can sit neatly on top of an Arduino.  Its main advantage is the pins/holes to connect to the Arduino, as these aren't evenly spaced so they are difficult to replicate with strip-board.
Do you need one? I doubt it very much, stick to the bread board and leave the soldering iron alone until you know what you are doing.


body:
You can make a slightly neater project with a prototyping shield. You can use much shorter jumper wires are sufficient to connect to the Arduino pins than if the proto was on your bench beside the Uno. That makes the project much more easily portable without knocking wires out of place. And if the project is one you want to make permanent, you've already laid it out for a shield and you're pretty near ready to start soldering parts and wires to the board.

The shield is certainly not needed for prototyping. I don't own any; I keep a handful of solderless breadboards around for the purpose. But if I were planning to build a permanent Arduino shield, that's where I'd start.