text:
Sim900 data logging through Sparkfun
I've been trying to upload data to data. Sparkfun's servers using HTTP commands, but I've hit errors every time I try.
This is my code:

#include <String.h>

void setup()
{
  Serial1.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);    // the GPRS baud rate
  delay(500);
}

void loop()
{
  if (Serial.available())
    switch(Serial.read())
   {
     case 'h':
       SubmitHttpRequest();
       break;
       case 'j':
       http();
       break;
        }
  if (Serial1.available())
    Serial.write(Serial1.read());
}

///SubmitHttpRequest()
///this function is submit a http request
///attention:the time of delay is very important, it must be set enough
void SubmitHttpRequest()
{
  Serial1.println("AT+CSQ");
  delay(100);

  ShowSerialData();// this code is to show the data from gprs shield, in order to easily see the process of how the gprs shield submit a http request, and the following is for this purpose too.

  Serial1.println("AT+CGATT?");
  delay(100);

  ShowSerialData();

  Serial1.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR, the connection type is using gprs
  delay(1000);

  ShowSerialData();

  Serial1.println("AT+SAPBR=3,1,\"APN\",\"airtelgprs.com\"");//setting the APN, the second need you fill in your local apn server
  delay(4000);

  ShowSerialData();

 // Serial1.println("AT+SAPBR=1,1");//setting the SAPBR, for detail you can refer to the AT command mamual
  //delay(2000);

  ShowSerialData();

  Serial1.println("AT+HTTPINIT"); //init the HTTP request

  delay(4000);
  ShowSerialData();

  Serial1.println("AT+HTTPPARA=\"URL\",\"http://data.sparkfun.com/input/[public key]?private_key=[private key]&gas=24\"");// setting the httppara, the second parameter is the website you want to access
  delay(10);

  ShowSerialData();
  Serial1.print(" HTTP/1.1\r\n");
  delay(500);
  ShowSerialData();

  delay(1000);
  ShowSerialData();

  Serial1.println("AT+HTTPACTION=1");//submit the request
  delay(10000);//the delay is very important, the delay time is base on the return from the website, if the return datas are very large, the time required longer.

  ShowSerialData();

  Serial1.println("AT+HTTPREAD");// read the data from the website you access
  delay(300);

  ShowSerialData();

  Serial1.println("");
  delay(100);
}
void http()
{
  Serial1.println("AT+CGATT?");
  delay(300);
  ShowSerialData();
Serial1.println("AT+SAPBR=3,1,\"APN\",\"airtelgprs.com\"");//setting the APN, the second need you fill in your local apn server
  delay(1000);
  ShowSerialData();

 Serial1.println("AT+CIFSR");//get local IP adress
  delay(2000);
  ShowSerialData();

  Serial1.println("AT+CIPSPRT=0");
  delay(3000);
  ShowSerialData();

  Serial1.println("AT+CIPSTART=\"TCP\",\"http://data.sparkfun.com\",\"80\"");//start up the connection

  delay(2000);
  ShowSerialData();
  Serial.println();
  Serial1.println("AT+CIPSEND");//begin send data to remote server
  delay(4500);
  ShowSerialData();

  Serial1.print("PUT /input/[public key]?private_key=[private key]&gas=4");
  delay(10);
  ShowSerialData();

  Serial1.print(" HTTP/1.1\r\n");
  delay(500);
  ShowSerialData();

  Serial1.println("Host: http://data.sparkfun.com\r\n");
  delay(500);
  ShowSerialData();

  Serial1.print("Connection: keep-alive");  //working
  Serial1.print("\r\n");
  Serial1.print("\r\n");
  Serial1.println();
  delay(500);
  ShowSerialData();

Serial1.println((char)26);
  Serial1.write(0x1A);
  delay(500);//waitting for reply, important! the time is base on the condition of internet
  Serial1.println();
  ShowSerialData();

  Serial1.println("AT+CIPCLOSE");//close the connection
  delay(100);
  ShowSerialData();

  Serial1.println("AT+CIPSHUT=0");
  delay(100);
  ShowSerialData();

}

void ShowSerialData()
{
  while(Serial1.available()!=0)
    Serial.write(Serial1.read());
}

For the first function (httprequest) I don't get a response on the server, even though the at commands all work. The second function(http) At At+CIPSEND, I get this:
ERROR

STATE: IP STATUS

CONNECT FAIL

And I've changed the URL but no luck. I still get the same response.
I'm using an Arduino Mega and a GSM SIM900

Post the results of all the AT commands for one iteration of loop(). Is this an example provided by Sparkfun? Did you deliberately omit the public and private keys in you sketch? How are you powering the SIM900?

Heya. The remaining AT commands all returned OK. nothing else.The SIM is powered with 12v and 3A. The example was pieced together from these: http://forum.arduino.cc/index.php?topic=116867.0   http://www.seeedstudio.com/wiki/GPRS_Shield_V1.0

Use an interactive sketch instead and enter commands and HTTP requests with the serial monitor. It is possible that one of the delays wasnt long enough. I also asked if you intentionally omitted the private and public keys in your request.

Hm, alright, thanks. And Yea, I did. I use the public and private keys when I run it.

This is what i mean by an interactive sketch: http://arduino.stackexchange.com/questions/19041/read-a-string-from-serial-to-debug-the-at-commands-sent-to-my-gps-shield/19050#19050. Try the code in the answer.


text:
Error with libraries after setting up Code::blocks to work as an arduino IDE
I followed this guide: http://arduinodev.com/guide-to-arduino-development-environment-codeblocks/
Everything seemed to work until I compiled the example code:
#include <Arduino.h>

/*
  Turns on an LED on for one second, then off for one second, repeatedly.

  This example code is in the public domain.
*/

void setup()
{
    // initialize the digital pin as an output.
    // Pin 13 has an LED connected on most Arduino boards:
    pinMode(13, OUTPUT);
}

void loop()
{
    digitalWrite(13, HIGH);   // set the LED on
    delay(1000);              // wait for a second
    digitalWrite(13, LOW);    // set the LED off
    delay(1000);              // wait for a second
}

and it gave me this errors:
||=== Build: Simulator - Debug in test (compiler: GNU GCC Compiler) ===|
/home/meneses/.codeblocks/ardusim/include/util/delay.h|90|warning: #warning "Compiler optimizations disabled; functions from <util/delay.h> won't work as designed" [-Wcpp]|
/usr/include/x86_64-linux-gnu/sys/types.h|197|error: conflicting declaration ‘typedef long int int64_t’|
/home/meneses/.codeblocks/ardusim/arduino/cores/stdint.h|33|error: ‘int64_t’ has a previous declaration as ‘typedef long long int int64_t’|
/usr/include/unistd.h|267|error: conflicting declaration ‘typedef __intptr_t intptr_t’|
/home/meneses/.codeblocks/ardusim/arduino/cores/stdint.h|66|error: ‘intptr_t’ has a previous declaration as ‘typedef int intptr_t’|

If I click on those errors I go to this following libraries:
first error - type.h, on line 197:
__intN_t (64, __DI__);

second error: stdint.h, on line 33:
typedef long long  int64_t;

third error: unistd.h, on line 267:
typedef __intptr_t intptr_t;

forth error: stdint.h, on line 66:
typedef int intptr_t;

And there's also the warning, on the delay.h library, line 90:
# warning "Compiler optimizations disabled; functions from <util/delay.h> won't work as designed"

How can I fix this?
Thank you!
edit: I've also found this error if instead of running the simulation debugger I run arduino UNO for example:
library features.h, line 374, error:
fatal error: sys/cdef.h: No such file or directory

But none of the other errors above..
The line is: #  include <sys/cdefs.h>
Edit2: solved the previous error by running this command:
sudo apt-get install libc6-dev-i386
but now I'm running into 'uint_farptr_t' was not declared in this scope, I'll try to solve them.
edit3: fixed the previous item by going into code::block's settings -> compiler -> selected compiler -> GNU GCC compiler for AVR -> Search directories -> Compiler -> remove /usr/include
I don't know the consequences of this, but it fixed that error.
Now I'm getting 5 errors of this type:
/home/meneses/.codeblocks/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp|91|error: attempt to use poisoned "SIG_USART0_RECV"|

edit4: I feel like cryinggg
edit5: I'm now willing to install other IDE, all I want is to be able to run simulations.
I'm using Linux Mint 17.3.

Why are you compiling 64bit stuff for an 8 bit Arduino?  That seems really weird to me, is it possible you are picking up a header file or define from you Linux machine?  Can you run the IDE on a virtual machine running Windows?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


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

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

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

authors: Алексей Валл

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Beat 1 LED light is always on - should turn off
/**************************************/
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?

Can you clarify which pins you are talking about? You have lots of pin names and some numbers scattered throughout the code. What pin is always on? Pin number.

You code is very difficult to read, probably because of the pasting, but why do you set pins as inputs and then write to them.  Also why do you set pins mode 4 times?

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.


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

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

Impossible to say without seeing your code. Why does anything happen in code that you can't see? Please edit your question and include it.

What I can tell you from the diagram is that pin 2 is grounded when the switch is open and at 5V when it's closed.  That wouldn't mean anything for pin 3 unless the chip alters 3 depending on 2.

he said that each pin on the board receives voltage after the battery is connected - not unless the code tells it to.

To elaborate on Nick Gammon's comment, at power on, all the Arduino pins, except power lines, are tri-stated, i.e. in a high-impedance state. This means they will not source nor sink any significant current. Then the Arduino starts executing whatever program was last uploaded into it. If an LED lights up, it does so under the program's command.

@NickGammon: Here's the code:

http://forum.codecall.net/blog/1824/entry-1957-arduino-project-02/

@NickGammon - thanks for your replies. See my comment below:
I understand the code well. But my question is more to do with the circuit diagram (see http://c03.apogee.net/contentplayer/?coursetype=foe&utilityid=gulfpower&id=4702) - based on this link, no current flows through the open circuit and the bulb doesn't light up.
The code tells Uno "if the switch isn't connected", light up green led that is connected to pin 3. Does that mean that there is some internal wiring between ground and pin 3 that supplies current to the green LED?

@EdgarBonet  - see comment to Nick Gammon.

@CandiedOrange - see comment to Nick Gammon.

You don't need to copy and paste the same comment 3 times. That's just clutter. Four times if you count virtually the same comment on the answer below. I've edited the duplicate comments out.

“there is some internal wiring between ground and pin 3”. There is an internal electrically controlled switch (we call that a transistor) between each pin and GND, and another one between the pin and +5V. The latter is the one that lights up the LED.

@EdgarBonet - thank you, Mr Bonet (& RSM and CandiedOrange as well) for you insights.

So everyone else knows where this is from enter image description here.

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

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

Thanks @RSM - I understand the code well. But my question is more to do with the circuit diagram (see http://c03.apogee.net/contentplayer/?coursetype=foe&utilityid=gulfpower&id=4702) - based on this link, no current flows through the open circuit and the bulb doesn't light up.
The code tells Uno "if the switch isn't connected", light up green led that is connected to pin 3. Does that mean that there is some internal wiring between ground and pin 3 that supplies current to the green LED?

@user755939 Yes, that internal wiring is called the chip.  You don't see it in the diagram. The code is controlling the behavior of that internal wiring but if the chip wasn't getting pulled high on the 5V pin and grounded on the GND pin it wouldn't be able to do a blessed thing with any of the other pins no matter what your code says.

@user755939 Is your problem that the diagram doesn't show any power source?  That's supposed to be assumed.  It doesn't come from the chip.  It's simply not shown as anything other than 5V and GND.

@user755939    I am going to be honest, I don't think you have grasped the basics of electronics and to your credit you are attempting to apply general electrical knowledge to embedded design and electronics. What you need to do is understand the basic construction of a microcontroller, this will help you understand the interaction between it and the code and external components.

@user755939    please examine the updated answer attempting to simplify the basic of the circuit

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.


text:
NEO 6M GPS speed

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!

Code and schematic?

@TisteAndii please see the code I inserted above. Thank you for your reply. :)

What speed do you get when you've been stationary for a minute?

Sometimes, I get 1.01, 0.89, 0.06, 0.3 but I never get zero even when stationary state. That's impossible to get that values even when you are not moving on your place, so I concluded that there is something wrong on it.

Not necessarily. These modules arent perfect nor is the GPS technique they use to determine your speed. There will always be some tiny offset. So if you write code based on this, you will have to account for this offset in the code. E.g. if (gps.speed <= 1) moving = False. You will have to run tests and determine the maximum value you can get from the module, when you arent moving and use that to determine motion or the lack of it.

Just to see if you get better results, you could also try powering the module using the Arduino 5V pin through an LM1117 regulator since the 3.3V pin can only supply 50mA max and the NEO 6M may exceed that (max current is 67mA)

@TisteAndii I'll update you once I have the LM1117.

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, to fix some of these problems.  They are described in the Troubleshooting section of the online documentation.
Also, SoftwareSerial is very inefficient.  I maintain a more-efficient alternative, 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 instructions.  NeoSWSerial is installed like most Arduino libraries.

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.

have you find installer of the u-center for mac? I kept searching for it but I can't even find one.


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

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?

My bet would be that these are WS2812B LED strips. They should be compatible with Adafruit Neopixels.

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.

Interesting result, about 3 of the lights came on, and were all different colors, then I adjusted the wires and they went off, and still are off...

Worst case scenario- the board did not have resistors and you just burned them down. Do you have schematic of your led strip?

No I don't think so, I could find some but who knows if it would be the right one. Would a close up photo do?

I added one anyway, there is a tiny piece in the centre wire or the strip right next to the LED, is that a resistor?

If by that you mean the element that has letter C near it, it should be capacitor because C stands for capacitance. But it also could be resistor because they look pretty much the same. Try to find a schematic, it's pretty hard to help when I don't even know what's on the board.

@L2PA these LED strips have "constant current" drivers built in. My bet would be them being these https://www.adafruit.com/datasheets/WS2812B.pdf or https://www.adafruit.com/images/product-files/1138/SK6812%20LED%20datasheet%20.pdf

@L2PA Plus, they are "Digital LED strips" so changing the state of digital pin 2 isn't going to do a lot, unless you time it exactly right. I also wouldn't recommend driving an analog LED strip directly from Arduino..

Ok, I think I found them on aliexpress, they look exactly the same as mine so I'll try look for the schematics now, heres the link if you want to take a look, not sure if theres anything useful...http://www.aliexpress.com/item/1M-WS2812B-Full-Color-LED-strip-light-Built-in-WS2811-30-LED-30-pixels-Raspberry-Pi/32601142057.html?spm=2114.01010208.3.112.jf2vIu&ws_ab_test=searchweb201556_6,searchweb201602_3_10017_10005_10006_10034_10021_507_10022_508_10020_9912_10018_10019,searchweb201603_7&btsid=c6194586-8b45-4a24-ac33-795408b73bc3

Right, I found it, @Paul you were right, it was these: https://www.adafruit.com/datasheets/WS2812B.pdf

You're somewhat in luck, Adafruit has an "Neopixel uberguide" which is an extensive document on how to use these type of strips. They also have a library which should make programming easier.

@Paul Is this it? https://learn.adafruit.com/downloads/pdf/adafruit-neopixel-uberguide.pdf

All working now, thanks @paul for that uberguide!

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

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


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

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.


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

Depends on the task of your robot :)
But in general: motors, wheels/chassis, motor shield, battery pack (and charger), bluetooth or other wireless communication, Arduino (nano?), LED's and probably soldering stuff, there you have the basics.

This seems interesting: http://litbimg1.rightinthebox.com/images/384x384/201412/lwxxyp1418874401020.jpg Try searching Arduino Robot Kit, you could even order the items seperatly off e-bay (to check if that's cheaper).

Make sure to pick a motor shield with an FET bridge on it - the L293/L298 and compatible bipolar bridges have horrible losses.

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.


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

This is another X-Y question. In your comments below you start to reveal the real issue. How about amending the question to describe the real problem?

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.

Many thanks for the help. I am struggling in establishing an I2c communication between arduino and pic32mx, and it seems I have a prob here.  As you said arduino is RTL and pic is a CMOS technology. Arduino is at 5V and PIC at 3.3V and I am facing many issues in order to release the bus line. Probably this is the reason why. Do you have a clue?

PIC is CMOS like the Arduino, just a different voltage. More strictly, it's LVCMOS - CMOS at 3.3V. CMOS itself is 5V normally. How are you dealing with the PIC32MX side of things?

I already started this conversation in this chatroom a few days ago http://chat.stackexchange.com/rooms/37934/discussion-between-tisteandii-and-scuba
let me know if there's any problem in entering the room.

connect both SDA and SCL via a pullup resistor (about 4.7k-10k) to 3.3V

This app-note describes one way to mix voltages on a I2C bus simply: http://www.nxp.com/documents/application_note/AN10441.pdf

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.


text:
Problem with my Arduino project
I am making a smart bin which automatically sense (with the help of IR sensor ) and dispose the trash by moving with help of DC geared motor 12V 60 RPM and it also detects for obstacles with the help of ultrasonic sensor which is placed at the front of the bin. Once the bin is empty the motor has to spin in the reverse direction. My questions is that there is something wrong in my code and am not able to solve it.
The issue that I am having is that when I run the code the bin was perfectly working as checking whether the bin is empty or not at the start and check for obstacles. If both are clear it will start move and whenever it detects any obstacles, the bin will stop the motor and checks again if any obstacles present, else it will start move and dispose the trash from the bin. The problem is when I code to reverse the motor direction to bring back the bin to original state the relay in relay board making a trrrrr sound.
Project technical specifications:

Arduino Uno
60 RPM 12V DC geared motor
4 channel relay board with 2 relay active for two motors
Ultrasonic sensor
Infrared module
Plunger to open the door placed inside

My sketch:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins

LiquidCrystal lcd(10, 11, 5, 4, 3, 2);
int motor_fwd = 7;
int motor_rev = 8;
int plung_rly = 6;
int irsensor = 9;
const int trigPin = 13;
const int echoPin = 12;
int mtr_time = 10;
int mtr_time_rev = 1;

void setup()
{
    digitalWrite(motor_fwd, LOW);
    digitalWrite(motor_rev, LOW);
    digitalWrite(plung_rly, LOW);
    digitalWrite(irsensor, LOW);

    // initialize the relay1 pin as an output;
    pinMode(motor_fwd, OUTPUT); // initialize the relay2 pin as an output;
    pinMode(motor_rev, OUTPUT); // pinMode(irsensor, INPUT);
    pinMode(plung_rly, OUTPUT);
}

void loop()
{
    irsen_chk_low();
    delay(500);
    irsen_chk_high();
    delay(500);
}

void irsen_chk_low()
{
    if (digitalRead(irsensor) == LOW) {
        lcd.begin(16, 2);   // Print a message to the LCD.
        lcd.print("bin Empty");
        delay(500);
        digitalWrite(motor_fwd, LOW);
        if (mtr_time_rev >= 1) {
            mtr_time_rev = mtr_time_rev - 1;
            {
                digitalWrite(motor_rev, HIGH);
                delay(5000);
                digitalWrite(motor_rev, LOW);
                delay(5000);
                int mtr_time = 10;
            }
        }
    }
}

void irsen_chk_high()
{
    if (digitalRead(irsensor) == HIGH) {
        lcd.begin(16, 2);   // Print a message to the LCD;
        lcd.print("Bin is full");
        obs_detection();
        delay(500);
        digitalWrite(motor_fwd, HIGH);
    }
}

void obs_detection()
{
    long duration, inches;
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    pinMode(echoPin, INPUT);
    duration = pulseIn(echoPin, HIGH);
    inches = microsecondsToInches(duration);
    cm = microsecondsToCentimeters(duration);
    lcd.begin(16, 2);
    lcd.print(inches);
    delay(100);
    if (inches <= 10) {
        digitalWrite(motor_fwd, LOW);
        delay(200);
    } else {
        if (mtr_time >= 1) {
            mtr_time = mtr_time - 1;
            digitalWrite(motor_fwd, HIGH);
            delay(200);
        } else {
            int mtr_time = 10;
        }
    }
}

long microsecondsToInches(long microseconds)
{
    return microseconds / 74 / 2;
}

You'll need to tell us more than "something is wrong with my code" - what specifically doesn't work the way you expected it to? What have you tried yourself? How is your project connected to your Arduino? It would also be very helpful if you would format your code by highlighting it and clicking the "{}" code-formatting symbol. It's pretty hard to read right now.

yes i am new to stack exchange am doing it...

when i run the code the bin was perfectly working as checking whethere bin is empty or not at the start and check for obstacles, if both are clear it will start move and whenever it detects any obstacles, bin will stop the motor and checks again if any obstacles present , else it will start move and dispose the trash from the bin . the problem is when    i code to reverse the motor direction to bring back the bin to original state the relay in relay board making a trrrrr sound ..

Hint: Check statement "int mtr_time = 10 ;" in blocks. How does that work according to C/C++?

okay if i remove that code, does the motor start spin in reverse direction ??

I've reformatted your code to make it more readable. Two notes: 1. mtr_time_rev = mtr_time_rev - 1; can be shortened to mtr_time_rev--; and 2. Why are the following lines put into a block?

Firstly, if you added some comments to the code to explain what each part is doing, it would be easier to figure out what is happening. Secondly, as @MikaelPatel and ott state, why are there odd blocks of code nested in braces { and }? Again as Mikael states, you need to check the logic of your code, w.r.t. to these blocks. Thirdly, does the motor start spin in reverse direction?... dunno, you tell us :-)

guys thanks for your suggestions, i have added for loop for reversing the motor upto a value :)

I love the trrrr description! I'd love to see it in action (about the point opf failure). Certainly not a requirement, but a short video may get that over any translation barrier :)

Please, post your own solution as an answer and accept it to close this question


text:
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;

What does the Arduino IDE say about memory usage when building the sketch?

Sketch uses 18,698 bytes (57%) of program storage space. Maximum is 32,256 bytes.
Global variables use 597 bytes (29%) of dynamic memory, leaving 1,451 bytes for local variables. Maximum is 2,048 bytes.

Hint: Can "do { } while ((avg3 != autothrottle)||(avg3>autothrottle));" lock up?

I commented those two voids out, and it is still freezing. I believe it is some sort of track overflow.

I am receiving data from both the MPU6050 and my Hobby-king RC Receiver simultaneously  .

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.


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

If you need a camera, chances are that an "arduino" is the wrong tool for your job, or at least that part of it.   Consider a more serious "computer" for high levels tasks, and potentially an Arduino-type device as a motion control delegate if that can't handle such things itself.

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.

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.


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

The official starter kit has no "Prototyping Shield" (but a breaboard).

In general, there's no need for a prototyping shield; a simple breadboard and wires will do. The only advantage is (from my viewpoint) that it is easier to bring along with you on holiday if you want to perform some experiments... That's the only way I use it.

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.

Also this would have been better in the Arduino StackExchange forum, pop on over some time.

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.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to design and debug a custom I2C master-slave system?
How to proceed, when in need of a custom I2C master-slave system?
What are the design criteria to apply?
What are the debugging tools one can use to troubleshoot problems?

This is a reference question. I have deleted a couple of comments that made this less obvious. (The question is answered by the asker).

This tutorial I gave at the Embedded Linux Conference tries to answer the questions, providing links to more detailed description of the topics addressed and using the practical example of driving a 4WD drone, where an Arduino Mini Pro acts as slave and controls the 4 independent wheels.
The original document can be found here.
Note: This answer is currently work in progress, as I adapt the highlights from the link.

Typical Applications of the I2C bus

Interfacing with relatively slow peripherals. Ex: sensors, mechanical actuators.
Controlling “fast” peripherals, that use other channels for exchanging data. Ex: codecs.
In a PC, the Operating System usually interacts over I2C with:

temperature and battery voltage meters;
fan speed controllers;
audio codecs.

In case multiple bus controllers are available, peripherals are grouped by speed, so that fast ones are not penalized by slower ones.

A quick introduction to the I2C bus - key features

Serial bus.
Only 2 lines: Serial CLock and Serial DAta (plus ground).
4 speeds: 100kHz, 400kHz, 1MHz, 3.2MHz.
Typically, 1 master device and 1 or more slaves.
Communications are always initiated by a master device.
Multiple masters can co-exist on the same bus (multi-master).
Open-Drain: both SDA and SCL need pull-up resistors.
“Clock Stretching”

The master controls SCL, but a slave can hold it down (because open drain), if it needs to adjust the speed.
The master must check for this scenario.
A slave can get stuck and jam the bus: need for reset lines from the master to the slave.

Typically 7-bit addressing, but also 10 bit is supported.
Logical protocol: actual voltage levels are not specified and depend on individual implementations. Ex: 1.8V / 3.3V / 5.0V

Reference URLs:

http://www.i2c-bus.org
http://www.robot-electronics.co.uk/i2c-tutorial

Example of Bus Configuration

Characteristics of the Protocol (simplified)

2 message types: read and write
Start / Stop bit - represented as “[“ and “]” in the rest of the answer
Address: 7 or 10 bits
R/W bit: R = 1 / W = 0 Used to discriminate the type of message sent.
Data on the bus: (Address << 1 | R/W)
Registers as information handlers, within the selected device.

Example of Bus traffic

Custom Slaves
Why create a custom I2C slave?

Desired sensor/actuator unavailable with I2C interface.
Less unique addresses available than slaves needed.
Desired custom functionality on the slave:

Semi-autonomous reactions to stimuli.
Filtering/preprocessing input data.

Power optimization: custom “sensor hub” does the housekeeping while the main processor is idle.
Realtime response to inputs.
[your imagination here]

How to design a custom I2C slave?

Define requirements (see previous slide).
Choose microcontroller or microprocessor.
Choose Scheduler or Operating System (if any).
Define communication sub-protocol:

Define parameters and commands to be exchanged.
Organize them into “registers” and choose a free address.

Design of the I2C Master
Key design criteria:

Weight/Dimensions.
Required computational power and average latency.
PC-like device

Embedded device, typically headless.
Preferred programming language: interpreted vs compiled.

Availability of busses/gpios for driving the slave(s):

GPIOs only: bitbang the protocol
I2C: user-space application vs kernel driver.
No GPIOs/I2C interfaces available: USB to I2C adapter.

Debugging: Divide and Conquer
Take direct control of the bus with an ad-hoc device.
Examples:

Bus Pirate (useful also for other busses)
USB to I2C Master adapter, also based on the FTDI FT232R chip.
Custom device (could be a separate project).
Snoop the bus with a logic analyzer or a scope/advanced meter.
Examples:

sigrok/pulseview with compatible logic analyzer
2-channels standalone scope/meter
Use slave-specific In Circuit Debugger/In Circuit Emulator.
Example:
AVR Dragon for AVR chips (Arduino UNO, Nano, Mini, MiniPro)

BUS Pirate

Primarily for development purposes.
Can both sniff the bus and drive it.
Console interface over serial (ttyACM) port, including macros, or programmatic access for several programming languages.
Built-in pullup resistors and voltage sources (5V / 3.3V)
Supports many other protocols.
References: Wikipedia, main page

USB to I2C Adapter

Small footprint.
Suitable for permanent installations.
No need for special connections on the host: it can be used to interface with a typical PC.
Variant available that is also SPI-capable.
No console interface, only serial binary protocol.
Requires protocol wrapper.
Reference: protocol

sigrok and pulseview
sigrok(bakend component) logo

pulseview (visualizer) example

Example of low end logic Analyzer

De-facto standard for PC-driven measurements on linux (but available on other OSes too).
Support for vast range of logic analyzers, scopes and meters.
Various protocol decoders, including I2C.
Useful for visualizing the logical signals and debugging protocol errors.
Even very low end, inexpensive HW can provide a whole new dimension to debugging.
References: sigrok, pulseview, supported hardware

Example: steering a 4WD drone
Prototype built using 2 Arduino Mini Pro.

What does the slave do in the example?
The I2C slave:

Controls the amount of torque applied to each wheel.
Controls the direction each wheel spins.
Measures  the rotation speed of each wheel through an optical encoder (Odometer).
Exposes the parameters above to the I2C Master.

High level block diagram of the I2C Slave.

Selecting the Slave: Arduino Mini Pro

Enough pins/functions to provide for each wheel:

1 PWM output with independent configuration of the duty-cycle.
1 GPIO for registering odometer input as IRQ.
2 GPIOs for selecting:

Forward
Reverse
Idle
Lock

I2C HW block for interrupt-driven i2c exchanges.
Dedicated pins for SPI-based programming.
Small footprint.
Low Cost.
The board layout of the clone represented in the picture is optimized for mounting on a DIL socket.

Slave-specific ICD: AVR Dragon

Supports various programming modes, included SPI programming, through AVRDude.
Doesn’t interfere with normal AVR operations, so it can be left plugged into the system.
After enabling debugWire interface, it allows configuring HW/SW breakpoints, by a dedicated backend for gdb/ddd.

Selecting the OS: ChibiOS

RTOS: preemption, tasks, semaphores, dynamic system tic, etc.
Small footprint: link only used code/data.
Distinction between RTOS and BSP through HAL.
GPLv3 for non-commercial use.
Actively developed, but already mature.
Supports 8bit AVR.

However it had limited BSP support for AVR, lack of:
 - interrupts driver for AVR GPIOs (added).
 - I2C support for AVR slave mode (custom).
Which had to be developed separately as part of the Drone SW for the AVR.

Defining the Communication Parameters
For each wheel:

Duty Cycle of the PWM signal used to drive it - 1 byte.
0xFF = max torque / 0x00 = no torque.
Direction of rotation - 1 byte.

0x00 = idle
0x01 = reverse
0x02 = forward
0x03 = locked

Average period in between slots of the optical encoder - 2 bytes.

Writing anything resets the measurement.

Parameter Index - 1 nibble:

0 = Duty Cycle
1 = Direction
2 = Average Period

Wheel indexes - 1 nibble:

0 = Left Rear
1 = Right Rear
2 = Right Front
3 = Left Front
4 = All

Sub Protocol: Defining the Registers
Register format:   0xαβ
 - α = Parameter Index
 - β = Wheel Index
Address (chosen arbitrarily): 0x10
Bus Pirate format:
 - [ = start bit
 - ] = end bit
 - r = read byte
 - address times 2 (left shift 1), for R/W bit

Example - in Bus Pirate Format
[   i2c_addr   reg_addr=(parm,wheel)   reg_value  ]
[0x20 0x20 0x02]  Left Rear Forward
[0x20 0x21 0x01]  Right Rear Backward
[0x20 0x22 0x01]  Right Front Backward
[0x20 0x23 0x02]  Left Front Forward
[0x20 0x14 0xFF]  Wheels set to max torque

The car spins clockwise.


text:
Is Gsm antenna effect on microcontroller working?
in my embedded system I used patch antenna and Atmega 328 microcontroller,but somehow it causes the abrupt function of a microcontroller or reset. how can it be solved?

It's a common problem with GSM. A GSM can have a sudden current spike. The supply might not be able to deliver this and thus one or more devices will reset (power down and up). (http://www.tek.com/sites/tek.com/files/media/document/resources/2032%20Power%20Supply%20WP.pdf)

There are 3 possible causes that I can think of (it's difficult to say more without further details):

SW bug: this is hard to confirm without actually finding the bug, but it might cause a lock-up and trigger a watchdog reset (do you have a watchdog running?) or a pointer error cause a jump to some memory location along the boot path (not so likely, I suspect)
Too tight power envelope: when your system tries to transmit, it draws more power than the power supply/battery can provide. This cause a temporary voltage drop, to the point that the system kinda power cycles. You can try to use a power supply with higher maximum current.
Electromagnetic interference: somehow the transmission interferes with the AVR. You can try to direct the antenna further away from the AVR and to increase the distance in between.

But you should really add more information to your question.


text:
I am trying to connect the PS3 controller with the Arduino Uno using a USB Host Shield. Getting stuck at 'PS3 Bluetooth Library Started'
I did the research for similar issues and found that I had to enable debug. I did the following attempts:
Changes to settings.h - enabled debugging by change from 0 to 1
Getting the following compiling error:
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp: In member function 'void USBH_MIDI::parseConfigDescr(byte, byte)':
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp:298:63: error: 'PrintEndpointDescriptor' was not declared in this scope
                                 PrintEndpointDescriptor(epDesc);
                                                               ^
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp: At global scope:
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp:421:80: error: no 'void USBH_MIDI::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR*)' member function declared in class 'USBH_MIDI'
 void USBH_MIDI::PrintEndpointDescriptor( const USB_ENDPOINT_DESCRIPTOR* ep_ptr )
                                                                                ^
exit status 1
Error compiling for board Arduino/Genuino Uno.

At the risk of stating the bleeding obvious you need to define "PrintEndpointDescriptor()".  I'm sorry but I can't give you a definitive answer to your problem, only generic steps that should solve it.
This almost certainly means you have either missed a include file out or there is a pre-processor flag that is disabling or maybe not enabling that bit of code.
Search through the files in the library and see if there are any pre-processor flags that affect compilation and if so this function.  Have a search on Google for the filename and function name, see that others say.
Another possible solution is look for a readme in the library, or comments in the files that say you need another library including first.  In fact if you are including multiple libraries try changing the order of inclusion.
One last cause could be that the function is within a namespace.  This means you either need to fully qualify the function call (namespace::class::function), or use the horrible using command.


text:
Is Arduino reliable for serious tasks, such as medical machines?
I'm just getting started with Arduino, and it has a LOT of uses, however, I would like to know how reliable is it? Can it be used for medical purposes (Measure vital signs, or to help surgeons perform surgeries), if it depends on the board, which one is the most accurate and reliable?
I know most robotic tasks will rely on the quality of the servo to interpret the Arduino commands, and sensors, and even the coding/logic, but we can replace/recode all of those things, but when it comes to the main board it gets more complicated

I'd suggest you do background reading specifically on medical device design, then try asking on Electrical Engineering Stack Exchange for more detail on best practices for medical robotics. An Arduino is unsuitable for this sort of work (except very simple concept/demo that will never be used in real surgery.)

You should NOT trust using an Arduino for life safety measures (medical purposes).
This discusses the reliability of an Arduino pretty well- https://electronics.stackexchange.com/questions/15535/reliability-of-the-arduino-platform-for-industrial-use

Althought you should NOT trust Arduino for medical devices, it's perfectly normal to use it to PROTOTYPE your idea and flush it out (without putting human lives in danger).

What kind of board should I use for such task then?

It depends what you want to achieve. Here is a description of the boards https://www.arduino.cc/en/Main/Boards

If you are asking what type of board to use in a medical device, you are not remotely qualified to engineer one.

@ChrisStratton because every good programmer/engineer started by being the best one, not by learning.

@Dodekeract - if you wish to learn by experiment, you must do so in a different field of applications than actual medical devices.  Anyone legitimately prepared to engineer a medical device is going to have a long list of requirements and procedures which every aspect of a design must meet - asking for advice from random internet posters does not remotely figure into it, and indicates that the asker is not qualified to design to this level of reliability requirement.


text:
Compiler doesn't like function code
I am getting this error from the Visual Studio compiler (I use the Visual Studio add-in Visual Micro for Arduino).

ModelRailroadCrossingSignalController.ino:In function 'void loop()
  ModelRailroadCrossingSignalController.ino:210:15: error: too few arguments to function 'Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer, const char*)
  :onSignalSound()
  ModelRailroadCrossingSignalController.ino:note  declared here
  :Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
  Error compiling project sources

Here is the function and loop (all the defines and instances left out for brevity, they aren't the issue
void loop() {
// put your main code here, to run repeatedly

signalEntrySensor = checkEntrySensor();
if (signalEntrySensor == true) {
    if (crossingSignalInOperation == false)
    {
        Adafruit_VS1053_FilePlayer mp = onSignalSound(musicPlayer,"Trainxng.mp3");  //all other functions are called in the sound routine?
        if (debugMode)
        {
            Serial.println("Sound byte called");
        }
        while (mp.playingMusic) {
            // file is now playing in the 'background' so now's a good time
            // to do something else
            offRoadPower();
            lowerSignalArms();
            onSignalSound();
            startSignalFlashers();
            crossingSignalInOperation = true;
        }
    }
}

Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
// Play the train crossing sound file
if (debugMode)
{
    Serial.println(F("Playing track - "));
    Serial.print(fileName);
}
//all sound files are on the micro sd card on the music player shield
if (!mp.startPlayingFile(fileName)) {
    Serial.println(F("Could not open file "));
    Serial.print(fileName);
    while (1);
}
return mp;  }

I'm a C# guy, not ever using C++ until now, but this code should certainly work, not sure why the function is not compiling.

Related: http://arduino.stackexchange.com/questions/23059/proper-way-to-run-functions-in-loop

The clue is in the error...

too few arguments to function 'Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer, const char*)

You have defined the function as this:
Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {

And yet you then try and call it like this:
onSignalSound();

Spot the mismatch?
I suspect you don't want to be calling that function there since it seems to be in a bit where the sound has already been started.

not sure how i missed that, I had it commented out earlier


text:
MQ135 Air Quality Sensor Signal Amplifier needed? Higher Quality Sensor?
I am trying to strengthen the signal from my MQ135 air quality sensor so it can detect aerosols from 3 feet away, as, currently as it stands the resolution is pathetic, it only blips from 0.21 to 0.58 when you practically insert the sensor into the nozzle of a bottle full of vinegar/rubbing alcohol.
It would be ideal if you could guide me as to what sort of signal amplifier to buy to strengthen the signal coming from this board?
Alternatively: Could I increase the sensitivity of this sensor?
I'd like to plot this to a graph at some point, so I will be working on an ASP.NET app that tells me if there are any aerosols in my room or not.

Here's the code:
/*
  Graph

 A simple example of communication from the Arduino board to the computer:
 the value of analog input 0 is sent out the serial port.  We call this "serial"
 communication because the connection appears to both the Arduino and the
 computer as a serial port, even though it may actually use
 a USB cable. Bytes are sent one after another (serially) from the Arduino
 to the computer.

 You can use the Arduino serial monitor to view the sent data, or it can
 be read by Processing, PD, Max/MSP, or any other program capable of reading
 data from a serial port.  The Processing code below graphs the data received
 so you can see the value of the analog input changing over time.

 The circuit:
 Any analog input sensor is attached to analog in pin 0.

 created 2006
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe and Scott Fitzgerald

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Graph
 */

void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
}

void loop() {
  // send the value of analog input 0:
  Serial.println(analogRead(A0));
  // wait a bit for the analog-to-digital converter
  // to stabilize after the last reading:
  delay(20);
}

/* Processing code for this example

 // Graphing sketch

// This program takes ASCII-encoded strings
// from the serial port at 9600 baud and graphs them. It expects values in the
// range 0 to 1023, followed by a newline, or newline and carriage return

// Created 20 Apr 2005
// Updated 24 Nov 2015
// by Tom Igoe
// This example code is in the public domain.

import processing.serial.*;

Serial myPort;        // The serial port
int xPos = 1;         // horizontal position of the graph
float inByte = 0;

void setup () {
  // set the window size:
  size(400, 300);

  // List all the available serial ports
  // if using Processing 2.1 or later, use Serial.printArray()
  println(Serial.list());

  // I know that the first port in the serial list on my mac
  // is always my  Arduino, so I open Serial.list()[0].
  // Open whatever port is the one you're using.
  myPort = new Serial(this, Serial.list()[0], 9600);

  // don't generate a serialEvent() unless you get a newline character:
  myPort.bufferUntil('\n');

  // set inital background:
  background(0);
}
void draw () {
  // draw the line:
  stroke(127, 34, 255);
  line(xPos, height, xPos, height - inByte);

  // at the edge of the screen, go back to the beginning:
  if (xPos >= width) {
    xPos = 0;
    background(0);
  } else {
    // increment the horizontal position:
    xPos++;
  }
}

void serialEvent (Serial myPort) {
  // get the ASCII string:
  String inString = myPort.readStringUntil('\n');

  if (inString != null) {
    // trim off any whitespace:
    inString = trim(inString);
    // convert to an int and map to the screen height:
    inByte = float(inString);
    println(inByte);
    inByte = map(inByte, 0, 1023, 0, height);
  }
}

*/

/* Max/MSP v5 patch for this example
 ----------begin_max5_patcher----------
1591.3oc0YszbaaCD9r7uBL5RalQUAO3CvdyS5zVenWZxs5NcfHgjPCIfJIT
RTxj+6AOHkoTDooroUs0AQPR73a+1cwtK3WtZxzEpOwqlB9YveAlL4KWMYh6
Q1GLo99ISKXeJMmU451zTUQAWpmNy+NM+SZ2y+sR1l02JuU9t0hJvFlNcMPy
dOuBv.U5Rgb0LPpRpYBooM3529latArTUVvzZdFPtsXAuDrrTU.f.sBffXxL
vGE50lIHkUVJXq3fRtdaoDvjYfbgjujaFJSCzq4.tLaN.bi1tJefWpqbO0uz
1IjIABoluxrJ1guxh2JfPO2B5zRNyBCLDFcqbwNvuv9fHCb8bvevyyEU2JKT
YhkBSWPAfq2TZ6YhqmuMUo0feUn+rYpY4YtY+cFw3lUJdCMYAapZqzwUHX8S
crjAd+SIOU6UBAwIygy.Q1+HAA1KH6EveWOFQlitUK92ehfal9kFhUxJ3tWc
sgpxadigWExbt1o7Ps5dk3yttivyg20W0VcSmg1G90qtx92rAZbH4ez.ruy1
nhmaDPidE07J+5n2sg6E6oKXxUSmc20o6E3SPRDbrkXnPGUYE.i5nCNB9TxQ
jG.G0kCTZtH88f07Rt0ZMMWUw8VvbKVAaTk6GyoraPdZff7rQTejBN54lgyv
HE0Ft7AvIvvgvIwO23jBdUkYOuSvIFSiNcjFhiSsUBwsUCh1AgfNSBAeNDBZ
DIDqY.f8.YjfjV1HAn9XDTxyNFYatVTkKx3kcK9GraZpI5jv7GOx+Z37Xh82
LSKHIDmDXaESoXRngIZQDKVkpxUkMCyXCQhcCK1z.G457gi3TzMz4RFD515F
G3bIQQwcP3SOF0zlkGhiCBQ1kOHHFFlXaEBQIQnCwv9QF1LxPZ.A4jR5cyQs
vbvHMJsLll01We+rE2LazX6zYmCraRrsPFwKg1ANBZFY.IAihr8Ox.aH0oAL
hB8nQVw0FSJiZeunOykbT6t3r.NP8.iL+bnwNiXuVMNJH9H9YCm89CFXPBER
bz422p8.O4dg6kRxdyjDqRwMIHTbT3QFLskxJ8tbmQK4tm0XGeZWF7wKKtYY
aTAF.XPNFaaQBinQMJ4QLF0aNHF0JtYuHSxoUZfZY6.UU2ejJTb8lQw8Fo5k
Rv6e2PI+fOM71o2ecY1VgTYdCSxxUqLokuYq9jYJi6lxPgD2NIPePLB0mwbG
YA9Rgxdiu1k5xiLlSU6JVnx6wzg3sYHwTesB8Z5D7RiGZpXyvDNJY.DQX3.H
hvmcUN4bP1yCkhpTle2P37jtBsKrLWcMScEmltOPv22ZfAqQAdKr9HzATQwZ
q18PrUGt6Tst2XMCRUfGuhXs6ccn23YloomMqcTiC5iMGPsHsHRWhWFlaenV
XcqwgCQiGGJzptyS2ZMODBz6fGza0bzmXBj7+DA94bvpR01MffAlueO7HwcI
pWCwmzJdvi9ILgflLAFmyXB6O7ML0YbD26lenmcGxjVsZUN+A6pUK7AtTrPg
M+eRYG0qD9j4I7eEbco8Xh6WcO.or9XDC6UCiewbXHkh6xm5LiPEkzpJDRTu
mEB44Fgz4NCtJvX.SM1vo2SlTCZGAe7GZu6ahdRyzFOhYZ+mbVVSYptBw.K1
tboIkatIA7c1cTKD1u.honLYV04VkluHsXe0szv9pQCE9Ro3jaVB1o15pz2X
zYoBvO5KXCAe0LCYJybE8ZODf4fV8t9qW0zYxq.YJfTosj1bv0xc.SaC0+AV
9V9L.KKyV3SyTcRtmzi6rO.O16USvts4B5xe9EymDvebK0eMfW6+NIsNlE2m
eqRyJ0utRq13+RjmqYKN1e.4d61jjdsauXe3.2p6jgi9hsNIv97CoyJ01xzl
c3ZhUCtSHx3UZgjoEJYqNY+hYs5zZQVFW19L3JDYaTlMLqAAt1G2yXlnFg9a
53L1FJVcv.cOX0dh7mCVGCLce7GFcQwDdH5Ta3nyAS0pQbHxegr+tGIZORgM
RnMj5vGl1Fs16drnk7Tf1XOLgv1n0d2iEsCxR.eQsNOZ4FGF7whofgfI3kES
1kCeOX5L2rifbdu0A9ae2X.V33B1Z+.Bj1FrP5iFrCYCG5EUWSG.hhunHJd.
HJ5hhnng3h9HPj4lud02.1bxGw.
-----------end_max5_patcher-----------

 */

so to answer the question: it turns out there is a different sensor for every different detectable out there....what a nightmare!                             Ammonia - MQ137
Carbon Monoxide - MQ-7
Chlorine - MQ 7
ChlorineDioxide - MQ2
EthyleneOxide - MQ-2
Fluorine - MQ-3
Hydrazine
Hydrogen - MQ-8
HydrogenFlouride - MQ-8
Hydrogen Sulfide - MQ136
NitricOxide - MQ-7
NitrogenDioxide - MQ-4
Oxygen
Grove - Gas Sensor(O2)
SKU: 101020002
Ozone - mq-3
Phosgene mq-7
Phosphine mq-7
Silane - MQ-6
SulfurDioxide MQ-136

It will be more clear what you want answered if you address one topic per post.  What sensor to use; how to set sensitivity; how to plot data – those three issues can be addressed separately.  It wastes time to mash them up together.

What board is it precisely?  Googling "MQ135" shows a discrete part that needs a variable calibration resistance, and it must then be calibrated to your application.  Depending on the board, it might already have some conditioning/amplification.

Thanks Dave, it's just an arduino board, I've twisted the variable pot on it to get some fine tuned readings....i did not see any significant amplification...https://olimex.files.wordpress.com/2015/05/mq-1.jpg

int sensorValue;
int pin8 = 8;
void setup()
{
Serial.begin(9600);
pinMode(pin8, OUTPUT);
}
void loop()
{
sensorValue = analogRead(0); // read analog input pin 0
Serial.print(sensorValue, DEC); //prints the value read
Serial.println("ppm");
if (sensorValue > 500) {
//Activate digital output pin 8 - the LED will light up
digitalWrite(pin8, HIGH);
}
else
{
// Deactivate digital output pin 8 - the LED will not light up
digitalWrite(pin8, LOW);
}
delay(50);

}

"it turns out there is a different sensor for every different detectable out there" and some say: such sensors do indeed detect gas particles, but for cheap sensors you'll never know if they measure what's advertised.

int sensorValue;
int pin8 = 8;
void setup()
{
  Serial.begin(9600);
  pinMode(pin8, OUTPUT);

  }

  void loop()
  {
    sensorValue = analogRead(0); // read analog input pin 0
    Serial.print(sensorValue, DEC); //prints the value read
    Serial.println("ppm");
    if (sensorValue > 500) {
      //Activate digital output pin 8 - the LED will light up
      digitalWrite(pin8, HIGH);
    }
    else
    {
      // Deactivate digital output pin 8 - the LED will not light up
      digitalWrite(pin8, LOW);

    }
    delay(50);

}


text:
Start program on PC using Arduino
I want to create arduino sketch that start program on my computer (i.e., browser) when I push button on Arduino itself.
Is it possible to make it using Arduino uno? I already know how to make a serial connection between PC and Arduino and use Processing software, but as I know, Processing cannot interact with another programs.

Processing is just Java.  If Java can do it Processing can do it.
And Java can do it.
Just ask Google about the Java ProcessBuilder class.

You can also make the Arduino look like a keyboard/mouse to the PC and then reproduce some key combo that will perform the action you want.
See reference here.