text:
SIM 900 stop after 1'5 hours; what's wrong?
I have a Gboard module (from Itead) configured to recieve data from Xbee sensors, and log data to a server DB on inet (via GPRS). This module is programmed with Arduino IDE.
I turn on the module (without any xbee sending, to check that the GPRS is working). The module works fine; The GPRS part sends some "control" packages to the DB to inet as expected. The problem appears after 1'5 hours because module is still on but the GPRS doesn't seem to be working (doesn't send any more packages to inet).
Excuse me for my messy code, I´m newbie! (a lot of copy/pastes from others!). Thank you in advance for your tipps and recomendations!.
Note: I use a power supply 12v and 2Amp.
Code:
#include <elapsedMillis.h>///para controles
#include <SoftwareSerial.h>
#include <Streaming.h> ///para xbee
#include <XBee.h>      ///para xbee
int xbeeRecibido;
char urlArreglo[100];
uint8_t slCmd[] = {'S', 'L'};
uint8_t dbCmd[] = {'D', 'B'};
char adr_part[8];
char rssiValor_part[8];
String adr = "";
String rssiValor = "";
AtCommandRequest atRequest = AtCommandRequest();
AtCommandResponse atResponse = AtCommandResponse();
elapsedMillis timeElapsed = 0;
unsigned long interval = 180000 ;////en milisegundos  cada 3 min.
String direccionRed;
int bateria;
String valorRssi;
int actividadPir;
String datosHttp; ///concatenacion de datos para enviar por HTTP
int8_t answer;
char data[512];
int data_size;
char aux_str[100];
char aux;
int x = 0;
XBee xbee = XBee();                //XBee object
Rx16Response rx = Rx16Response();
SoftwareSerial mySerial(2, 3); // RX, TX (ahora puesto en TX, RX)
int b01;
int b02;
int b03;
int b04; //source network adress 64Bit
int b05; //source network adress 64Bit
int b06; //source network adress 64Bit
int b07; //source network adress 64Bit
int b08; //source network adress 64Bit
int b09; //source network adress 64Bit
int b10; //source network adress 64Bit
int b11; //source network adress 64Bit
int b12; //source network adress 16Bit
int b13; //source network adress 16Bit
int b14;
int b15; //pir digital
int b16; //bateria
int b17; //checksum
char response[100];
unsigned long previous;

void setup() {
  pinMode(6, OUTPUT);///para encender SIM900 ...en pin6 HIGH de arduino GBOARD
  digitalWrite(6, HIGH);///para encender SIM900 ...en pin6 HIGH de arduino GBOARD
  mySerial.begin(9600);
  Serial.begin(9600);
  ///////GPRS////////
  power_on();
  delay(3000);
  sendATcommand("AT+ipr=9600", "OK", 2000);///////MIO PARA BAUDERATE A 9600 (por defecto 0=auto..¿se apaga?)
  // sets the PIN code
  sendATcommand("AT+CPIN=****", "OK", 2000);
  delay(3000);
  while (sendATcommand2("AT+CREG?", "+CREG: 0,1", "+CREG: 0,5", 2000) == 0);
  sendATcommand("AT+SAPBR=3,1,\"Contype\",\"GPRS\"", "OK", 2000);
  sendATcommand("AT+SAPBR=3,1,\"APN\",\"gprs.lebaramobile.es\"", "OK", 2000);
  sendATcommand("AT+SAPBR=3,1,\"USER\",\"\"", "OK", 2000);
  sendATcommand("AT+SAPBR=3,1,\"PWD\",\"\"", "OK", 2000);
  while (sendATcommand("AT+SAPBR=1,1", "OK", 20000) == 0)
  {
    delay(5000);
  }
  ////FIN GPRS////
  ////PRIMER AUTOCONTROL!
  lanzarHttpAutoControl();
  delay(15000);
}

void loop() {
  // PARA AUTOCONTROL!
  if (timeElapsed > interval)
  {
    lanzarHttpAutoControl();
    timeElapsed = 0;             // reset the counter to 0 so the counting starts over...
  }
  if (Serial.available() == 18) { //make sure the frame is all there
    if (Serial.read() == 0x7E) {
      b01 = Serial.read();
      b02 = Serial.read();
      b03 = Serial.read();
      b04 = Serial.read(); //source network adress 64Bit
      b05 = Serial.read(); //source network adress 64Bit
      b06 = Serial.read(); //source network adress 64Bit
      b07 = Serial.read(); //source network adress 64Bit
      b08 = Serial.read(); //source network adress 64Bit
      b09 = Serial.read(); //source network adress 64Bit
      b10 = Serial.read(); //source network adress 64Bit
      b11 = Serial.read(); //source network adress 64Bit
      b12 = Serial.read(); //source network adress 16Bit
      b13 = Serial.read(); //source network adress 16Bit
      b14 = Serial.read();
      b15 = Serial.read(); //pir digital
      b16 = Serial.read(); //bateria
      b17 = Serial.read();  //checksum
      direccionRed =  String(b04, HEX);
      direccionRed +=  String(b05, HEX);
      direccionRed +=  String(b06, HEX);
      direccionRed +=  String(b07, HEX);
      direccionRed +=  String(b08, HEX);
      direccionRed +=  String(b09, HEX);
      direccionRed +=  String(b10, HEX);
      direccionRed +=  String(b11, HEX);
      actividadPir = b15;
      bateria = int(b16);
      xbeeRecibido = 1;
    } //fin if 0x7E
  }///fin recorrer bytes
  Serial.flush();
  Serial.end();
  Serial.begin(9600);///paro el serial para evitar solapaciones, y hacer esperar a los sensores (al no recibir resp. del gateway)
  if (xbeeRecibido == 1) {///si se ha recibido info de xbee sensor
    colectorDatos();
    xbeeRecibido = 0;
  }
}//fin loop

///FUNCION PARA RSSI XBEE///
void rss() {  ///PARA RSSI
  /* returns received signal strength value for the last RF data packet */
  union {
    byte B;
    char C;
  } atCmd[3];
  AtCommandRequest atCmdReq;
  AtCommandResponse atResp;
  byte respLen, *resp, dBm;
  strcpy(&atCmd[0].C, "DB");
  atCmdReq = AtCommandRequest(&atCmd[0].B);
  atResp = AtCommandResponse();
  xbee.send(atCmdReq);
  if (xbee.readPacket(5000)) {
    if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
      xbee.getResponse().getAtCommandResponse(atResp);
      if (atResp.isOk()) {
        respLen = atResp.getValueLength();
        if (respLen == 1) {
          resp = atResp.getValue();
          dBm = resp[0];
          valorRssi = (String)dBm;

        }
        else {
        }
      }
      else {

      }
    }
    else {
    }
  }
  else {
  }
}///fin rss()

void power_on() {
  uint8_t answer = 0;
  // checks if the module is started
  answer = sendATcommand("AT", "OK", 2000);
  if (answer == 0)
  {
    // waits for an answer from the module
    while (answer == 0) {
      // Send AT every two seconds and wait for the answer
      answer = sendATcommand("AT", "OK", 2000);
    }
  }
}

int8_t sendATcommand(char* ATcommand, char* expected_answer1, unsigned int timeout) {
  uint8_t x = 0,  answer = 0;
  memset(response, 0, sizeof(response));///a cero el array ///15-08-2015
  memset(response, '\0', 100);    // Initialize the string
  delay(100);
  while ( mySerial.available() > 0) mySerial.read();   // Clean the input buffer
  mySerial.println(ATcommand);    // Send the AT command
  x = 0;
  previous = millis();
  do {
    if (mySerial.available() != 0) {
      response[x] = mySerial.read();
      x++;
      if (strstr(response, expected_answer1) != NULL)
      {
        answer = 1;
      }
    }
  }
  while ((answer == 0) && ((millis() - previous) < timeout));
  return answer;
}

int8_t sendATcommand2(char* ATcommand, char* expected_answer1,
                      char* expected_answer2, unsigned int timeout) {
  uint8_t x = 0,  answer = 0;
  memset(response, 0, sizeof(response));///a cero el array ///15-08-2015
  memset(response, '\0', 100);    // Initialize the string
  delay(100);
  while ( mySerial.available() > 0) mySerial.read();   // Clean the input buffer
  mySerial.println(ATcommand);    // Send the AT command
  x = 0;
  previous = millis();
  do {
    if (mySerial.available() != 0) {
      response[x] = mySerial.read();
      x++;
      // check if the desired answer 1 is in the response of the module
      if (strstr(response, expected_answer1) != NULL)
      {
        answer = 1;
      }
      // check if the desired answer 2 is in the response of the module
      if (strstr(response, expected_answer2) != NULL)
      {
        answer = 2;
      }
    }
    // Waits for the asnwer with time out
  } while ((answer == 0) && ((millis() - previous) < timeout));
  return answer;
}

void colectorDatos() {
  rss(); ////recupero rssi que se pone en variable valorRssi
  datosHttp = direccionRed + ";"; ///cualquier valor del array, todos deverian tener mismo valor (direccion64bits)
  datosHttp += bateria;
  datosHttp += ";";
  datosHttp += valorRssi;
  datosHttp += ";";
  datosHttp += actividadPir; //pir
  envio(datosHttp); ///envio por gprs
}///fin colectorDatos

void lanzarHttpAutoControl() {
  adr = "";
  // set command to SL to get low part of MAC address
  atRequest.setCommand(slCmd);
  while (!sendAtCommand()) {};
  for (int i = 0; i < atResponse.getValueLength(); i++) {
    mySerial.print(atResponse.getValue()[i], HEX);
    sprintf(adr_part, "%lX", (unsigned long)(atResponse.getValue()[i]));
    if (atResponse.getValue()[i] <= 0xF)
      adr += 0;
    adr += adr_part;
  }
  envio(adr); ///envio por gprs
}

///envio GPRS...recibe String con datos (o control o sensor)
void envio(String entrada) {
  Serial.end();///paro el serial para evitar solapaciones, y hacer esperar a los sensores (al no recibir resp. del gateway)
  memset(urlArreglo, 0, sizeof(urlArreglo));///a cero el array
  answer = sendATcommand("AT+HTTPINIT", "OK", 10000);
  if (answer == 1)
  {
    // Sets CID parameter
    answer = sendATcommand("AT+HTTPPARA=\"CID\",1", "OK", 5000);
    if (answer == 1)
    {
      //char urlArreglo[100];
      sprintf(urlArreglo,  "AT+HTTPPARA=\"URL\",\"www.pestmonitors.com/dream/prueba_gsm_get.php?datos=%s\"", entrada.c_str());
      answer = sendATcommand(urlArreglo, "OK", 5000);
      delay(5000);
      if (answer == 1)
      {
        answer = sendATcommand("AT+HTTPACTION=0", "+HTTPACTION:0,200", 10000);
      }
      else
      {
      }
      sendATcommand("AT+HTTPTERM", "OK", 5000);
      delay(5000);
    }
  }
  Serial.begin(9600);///paro el serial para evitar solapaciones, y hacer esperar a los sensores (al no recibir resp. del gateway)
}

// used here to sens AT command to the Xbee to get information such as the MAC address
int sendAtCommand() {
  xbee.send(atRequest);
  if (xbee.readPacket(5000)) {
    if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
      xbee.getResponse().getAtCommandResponse(atResponse);
      if (atResponse.isOk()) {
        if (atResponse.getValueLength() > 0) {
          mySerial.println(atResponse.getValueLength(), DEC);
          for (int i = 0; i < atResponse.getValueLength(); i++) {
            mySerial.print(atResponse.getValue()[i], HEX);
          }
        }
        return 1;
      }
      else {
      }
    } else {
      mySerial.print(xbee.getResponse().getApiId(), HEX);
    }
  } else {
    if (xbee.getResponse().isError()) {
    }
    else {
    }
  }
  return 0;
}

When it's not working anymore, is it still attached to the network? Does it always stop at 1h30? Or does it differ? Might be something that the connection will be automatically dropped if it's longer as 1h30? You should ocassionally check your connection and handle the errors?

Thanks for comment FuaZe! I don`t know if still attached because I don't write any debug LED or something (I'm very noob newbie, jejej). Yes, is just 1h30 (1 or 2 min up or down). Now I´m trying a possible solution: Reseting all sketch (with "asm volatile" command) and reseting hardware SIM900 (gboard have a especific PIN for reset SIM900 by software(7)), on at 1 hour... I don't know  if that is a good solution...sorry for my english! Thanks man!


text:
AT command XBee from atmega to disable DIO5 (associated led)
I community! I need put ATcommand to my XBee from my atmega using a "xbee library" and a function that I have found in internet. I think the ATComand is "ATD50" to change the DIO5 to value "0" (disabled). My intention is to turn off a led connected into DIO5 (digital input/output 5 (associated led)) after X second/minutes of turning on the device (so that it doesn't turn one again after initial check).
This is a part of my code:
#include <XBee.h>
XBee xbee = XBee();
uint8_t atdCmd[] = {'A','T','D','5','0'}; //<---command to put DIO5 to "0" (disabled)
AtCommandRequest atRequest = AtCommandRequest();
AtCommandResponse atResponse = AtCommandResponse();
void setup()
{
delay(30000);
atRequest.setCommand(atdCmd);
xbee.send(atRequest);
}
void loop()
{}

...but it doesn't work!
Thanks guys!

Thanks for aswer david! The API mode is set on mode 2 but doesn't work

In case .setCommand() needs a null-terminated string, try adding , \0 after '0' or use uint8_t *atdCmd = (uint8_t *)"ATD50"; to declare it, or char *atdCmd = "ATD50"; if the API allows.

Thank you Jwpat7, I try your recomendations, but it doesn't work, other tipps? ...maybe my command is wrong?

finally I solved the problem with this code:
uint8_t atdCmd[]={'D','5'};
uint8_t value[]={4};///pongo DIO5 a output LOW
uint8_t length=1;
AtCommandRequest atRequest = AtCommandRequest(atdCmd, value, length);
xbee.send(atRequest);

The problem was that I tried to put command with 5 caracters,... and only accepts 2 caracters for "AT command"

source: Stack Exchange

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

sort: votes


text:
Employing C++ code for Arduino
I have Googled quite a lot regarding using a C++ program for uploading to Arduino and related, however I am confused now. Right, my problem is this:
I have written a C++ program which imports RGB data of a 24 bit bitmap (which was generated using Matlab) and now I would like to use this array (3 arrays - R,G,B) for an Arduino sketch to be used for a LED matrix project that I am working on. I am not exactly a programmer and hence had to resort to this path -- MATLAB to c++ and then Arduino, although this could be entirely done in C++ too (importing a bitmap and extracting pixel info). So, my C++ code spits out the 3 arrays and I am not sure how to get those into an Arduino sketch.
I read a lot about this and I understood this - As the Arduino "language" is C and C++ therefore it is possible to program an Arduino in C++/c. I need a maker file and a compiler. However my question is that isn't there a more non-programmer friendly way to get this done, some software or an IDE which supports Arduino programming in C++? I cannot understand much of this method, hence trying to bypass this.
If anybody's got any better method, I would be really glad if you could share it. I am also looking to use the Arduino package for MATLAB to send the array directly from there using serial communication. But I just wanted to make sure I at least tried this path.
Would really appreciate if somebody could offer some help. I am quite stuck here.
Can share any other info if required.
Thanks a lot!

EDIT 1:
To clarify as Nick Gammon pointed out in the comments below. In brief steps, this is what I have done till now:

Got a 24 bit bitmap (some random image)
Extracted the RGB data for each pixel using Matlab
Have 3 arrays of (for eg.) 122X300 dimensions whose every element has values between 0-255 (8 bit) and for R,G and B colors
Want to get these 3 arrays for use in Arduino sketch for further working
Stuck here - how to do that .....
So I did this - I imported that the RGB data into 3 separate text files and made a c++ program to read those arrays assuming that I should be able to then somehow use this program in Arduino sketch.
Now I am not sure what to do....my goal would be to have these 3 arrays (CRGB arrays, FastLED) in my arduino sketch which I can control and then upload to my Due.
On googling I found that to use c++ for arduino , you need the avr compiler and make file, which I want to avoid. Tried other IDEs too, Eclipse, PlatformIO too .. ummmm ... not that successful to be honest.
as per Paul's ans- Matlab to Arduino method I have to try.
Hope I have clarified my process till now :)

EDIT 2:

C++ code for reading the above array (thought I could use the output in Arduino)
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <sstream>
#include <stdlib.h>

const int HEIGHT = 4;

const int WIDTH = 5;

using namespace std;

int main(){

  int array_req [HEIGHT][WIDTH];

string userinputprompt, filename;

userinputprompt = "COLORDATA FILENAME: ";

cout<<userinputprompt<<endl;

getline(cin,filename);

ifstream inputfile;

inputfile.open(filename.c_str());

 for (int i = 0; i < HEIGHT; ++i)
{
  std::string tmpString;
  std::getline(inputfile, tmpString);

 std::stringstream ss(tmpString);

 for(int j=0;j < WIDTH; ++j)
  {
    ss >> array_req[i][j];
  }
 }

    for(int p=0; p<HEIGHT; p++)
    {
      for(int q=0; q<WIDTH; q++)
    {
        cout<<array_req[p][q]<<" ";
    }
    cout<<"\n";
}

inputfile.close();
getchar();
return 0;

}

Comments are not for extended discussion; this conversation has been moved to chat.

@NickGammon dont have 20 rep for chat. Would have to wait. Sorry.

You have 23 rep now. :)

Although down voted twice by people who apparently are uninformed, many of the C++ problems you are describing as it pertains to your coding environment can be overcome by using Visual Studio free edition with Visual Micro add-in fro Arduino. It makes using C++ a snap for Arduino.

You've got quite an interesting project.
Programming an Arduino (C++)
Arduino is C++ (or atleast a subset).
The Arduino IDE uses the GNU AVR-GCC compiler. And it takes care of all "make" files and stuff. You shouldn't really bother too much. Just paste the code right in, and fix whatever is broken ;)
Also, the Arduino IDE is basically click&install, click&compile/upload, I'm not sure why you're even trying all the other options.

For the sake of clarity/simplicity I'll give you an example of sending a single R/G/B pixel to the Arduino.
Matlab
You should set up your Matlab code something like this.
I'm not a "Matlab guru" nor do I know whatever code you have.
You should open a COM port and write to it.
s = serial('COM1','BAUD',115200);
fopen(s);
Pixel pix = getPixelFromBMP("image.bmp",0);
fprintf(s,'%s',pix.r.to_String()+pix.g.to_String()+pix.b.to_String());
fclose(s);

Arduino
In the Arduino IDE (withouth worrying about makefiles and toolchains).
You do the reverse of what you've done in your Matlab code.
Read the serial input and write it to the LED strip.
I'm quite sure this code won't compile, and there are a lot of fancier ways to read the serial buffer:
#include <ledstrip.h>

LedStrip ledStrip;

int incomingByteR = 0;   // for incoming serial data
int incomingByteG = 0;   // for incoming serial data
int incomingByteB = 0;   // for incoming serial data

void setup() {
        Serial.begin(115200);     // opens serial port, sets data rate to 115200 bps
        ledStrip.begin(1,RGB);    // initializes the ledstrip (RGB).
}

void loop() {
        // send data only when you receive data:
        if (Serial.available() > 3) {
                // read the incoming byte:
                incomingByteR = Serial.read();
                incomingByteG = Serial.read();
                incomingByteB = Serial.read();
                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByteR, DEC);
                Serial.println(incomingByteG, DEC);
                Serial.println(incomingByteB, DEC);
                ledStrip.pixel[0].r = incomingByteR;
                ledStrip.pixel[0].g = incomingByteG;
                ledStrip.pixel[0].b = incomingByteB;
                ledStrip.show();
        }
}

C++
So, you don't really need C++ (other than to program the Arduino). You could interchange Matlab for C++ or Arduino for pure AVR C++, but I wouldn't recommend it.

wow! your answer did clear some of my doubt. Thanks! I just realised when I was trying to use a cpp code for arduino in Codeblocks that I have to eventually go the hard way - Avr compliler,make files etc. etc...installed WinAVR and got lost again. I guess Matlab should save me. Let me try with it, your code and concept and will update here maybe tom. Hope that's fine :)

Everything is fine. You can consider accepting this as an answer. If you run in other problems, you could create a new question.
But I indeed find your project interesting.

Hmmm...Right mate. I will accept it..no issues. I thought creating another similar question would be frowned upon ;) I will look into it and get back on this later. need some time. Thanks!

@fattypanda I'm not such a frowner ;)
But it's very likely you'll run into a problem that's completely different. If you then update/change the question, the inital problem might get lost.
If you'd like to discuss the project or minor questions related to it. I'd be happy to answer them in chat (http://chat.stackexchange.com/rooms/38302/matlab-bmp-to-arduino-rgb-matrix)

@fattypanda it seems you do not have enough reputation to talk in chat, though I'm sure it would be helpfull (I've worked with BMP an APA102 LED strips). You could try to edit an answer/question (if that gets accepted you get +2 rep), by asking another interesting question or by answering a question.

lol yes. .pretty nice to see though you worked with APA102.  Let me see how to get around this (+2 rep min)

You can make some minor edits to my question, if it gets accepted you'll get +2 I believe.

Re: "Arduino is C++." Isn't it more like a subset of C++? Do you have any sources for this claim?

@PeterMortensen I've edited my answer. But for all practical purposes, it's the same. (Especially in this question/context). It's compiled with the AVR GNU GCC toolchain and thus "as close to C++ you can get in an AVR microcontroller".

@PeterMortensen it's by that beyond the scope of the question. http://www.idogendel.com/en/archives/19#comment-2809 and http://arduino.stackexchange.com/questions/816/c-vs-the-arduino-language

Here's a sample program you could use as reference, just replace the values in the array and adjust VALUES_NUMBER accordingly.
Disclaimer: I didn't try to compile/run it, but it should give you an idea of how to use the values you already have.
// These are Arduino Pins that support "analog" output.
const unsigned short ANALOG_RED_PIN = 3;
const unsigned short ANALOG_GREEN_PIN = 5;
const unsigned short ANALOG_BLUE_PIN = 6;

const unsigned int VALUES_NUMBER = 12;

const unsigned short REDS[VALUES_NUMBER] = {
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
  0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B
};

const unsigned short GREENS[VALUES_NUMBER] = {
  0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05
};

const unsigned short BLUES[VALUES_NUMBER] = {
  0x09, 0x0A, 0x0B, 0x03, 0x04, 0x05,
  0x00, 0x01, 0x02, 0x06, 0x07, 0x08
};

void setup() {
  pinMode(analogRed, OUTPUT);
  pinMode(analogGreen, OUTPUT);
  pinMode(analogBlue, OUTPUT);
}

void loop() {
  unsigned int counter;
  for (counter = 0; counter < VALUES_NUMBER; counter++) {
    analogWrite(ANALOG_RED_PIN, REDS[counter]);
    analogWrite(ANALOG_GREEN_PIN, GREENS[counter]);
    analogWrite(ANALOG_BLUE_PIN, BLUES[counter]);
    delay(1000); //sleep 1 second
  }
}

.thanks for the reply. Your code is a very simplified version. However, its my mistake, apologies..i didnt mention..I am implementing this project using APA102 led strips which has a data and a clock pin. So, as far as my knowledge goes, control of strip using individual analog pins is not possible. Also, the second part of the code where the data is passed on to the leds, I am done with that part. Its the first part where I am stuck. Acquiring of data in 3 different arrays. Rest is done using the fantastic FastLED lib. :)

As the arduino "language" is C and C++ therefore it is possible to program an Arduino in C++/c. I need a maker file and a compiler. However my question is that isn't there a more non-programmer friendly way to get this done, some software or an IDE which supports Arduino programming in C++?

Yes, it's called the Arduino IDE. You plug your board into the USB port, write your program, or use an existing example, and then hit the Upload button.

lol...I guess you misconstrued my question :P I meant that I wanted to be more flexible with the Arduino IDE by incorporating c++ environment. I was sort of handicapped (most probably because I am a non-programmer). Couldn't relate the output of a c++ program (or for that matter Matlab) directly into Arduino sketch. I have been using Arduino IDE for the last couple of months :)

I'm not sure where this is heading. In the Arduino IDE you are programming in C++. You don't need to install or change anything to use it - or to "incorporate the C++ environment". It's just there.

Nick Gammon is right. Recently I started programming Arduino in Eclipse though. See here if interested: https://arduino.stackexchange.com/questions/40/what-are-the-other-ides-for-arduino/75491#75491. Also, this is very relevant: https://arduino.stackexchange.com/questions/816/c-vs-the-arduino-language/50839#50839. Lastly, Nick Gammon is an Arduino master. His website is filled with sooo much incredibly useful and detailed information. He is one of the foremost experts in the world when it comes to the ATmega328 microcontroller and Arduino.

Use the Visual Studio free community edition (or the paid versions if you already have them) with the Visual Micro extension for Arduino. Makes life a lot easier since you have indicated your desire to write in C++, and you get true debugging and intellisense as well, which you DO NOT get with the aforementioned IDE's.

Could you please tell me how this is relevant to this question?

Your first line,
I have Googled quite a lot regarding using a C++ program for uploading to Arduino and related, however I am confused now. Right, my problem is this:....and that is what I answered

There is nothing about needing debugging in the original question. If you wanted to say that one can use VS CE then edit the answer appropriately.

@Avamander....is my answer now more suitable for you.

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

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


text:
Build arduino with windows command line
Can someone explain, step by step, along with all software I must use for using Windows command prompt to build an Arduino sketch (.ino file )?
I've followed these steps but I can't.

See the examples at the end of the link that Federico gave eg example only:
Compile and upload a sketch to an Arduino Nano, with an Atmega168 CPU, connected on port /dev/ttyACM0:
arduino --board arduino:avr:nano:cpu=atmega168 --port /dev/ttyACM0 --upload /path/to/sketch/sketch.ino

You said "I can't": can you clarify what you tried, what you expected andwhat you got?

The command line interface of the Arduino IDE is described in this document
https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc
For example, this command will compile and upload the Blink example to my Arduino Leonardo
./arduino --upload --board arduino:avr:leonardo --port /dev/ttyACM0 --verbose examples/01.Basics/Blink/Blink.ino

Foot note: with IDE 1.6.0, there is an experimental version of the IDE for recent MacOSXs. It doesn't yet support the command line. If you need the command line on Mac, use the recommended version. This will be fixed with 1.6.1


text:
snprintf crashing my program
I have to admit that I can't really use this function.
I'm trying to format some json but it crashing all the time my arduino:
char response[300];
tmp = "123";
snprintf(response, 300, "[{Name:'Furnace',Value=%s,Alarm={MinValue=%s,MaxValue=%s}},{Name:'Room',Value=%s,Alarm={MinValue=%s,MaxValue=%s}}]", tmp);

How should I use this function properly?

That's not JSON.

char response[300];
tmp = "123";
snprintf(response, 300,
    "[{Name:'Furnace',Value=%s,Alarm={MinValue=%s,MaxValue=%s}},"
    "{Name:'Room',Value=%s,Alarm={MinValue=%s,MaxValue=%s}}]",
    tmp, tmp, tmp, tmp, tmp, tmp);

In other words, you should add, after the format string, as many extra
parameters as there are %s in the format string.
PS: This looks like JSON, but it is not really valid JSON.
The format below should give valid JSON:
"[{\"Name\":\"Furnace\",\"Value\":%s,"
"\"Alarm\":{\"MinValue\":%s,\"MaxValue\":%s}},"
"{\"Name\":\"Room\",\"Value\":%s,"
"\"Alarm\":{\"MinValue\":%s,\"MaxValue\":%s}}]",


text:
Possibilities and limitations for onboard data acquisition
I could define myself as a "nerdy cyclist", so while my interest in Arduino is steadily growing (have not bought or used yet), my first idea for a project would be:

Instrument a bicycle with some sensors (accelerometer, reed switch, etc) and an Arduino;
Ride long distances (that is, four hours or more, sometimes non-stop);
When at home, download some sort of "data file" (from SD card, I think);
Analyze results with Python/Matlab/whatever.

So my questions:

Is any model of Arduino suitable for this purpose?
What is the expected sample rate vs number of channels? 100Hz per channel would be excellent for my purposes, for example.
Can I keep incrementally saving to SD "forever" (that is, while battery and card space are available)?

First of all your idea project is feasible. And to answer to your questions:

There is no right Arduino for your project simply because theoretically every Arduino board can do the job. But as you said it has to be portable you might use Arduino nano/mini or even Uno if you have enough room or space.
The acquisition rate depends on the on the type of sensor you have. So if you have let's say one analog reading you can use the built in function in Arduino which is capable of making about 10000 readings at time. So if you have multiple outs you can easily for the calculation. There are also sensors which has a digital output in this case in order to read your value you communicate with Tue sensor board through Two wire interface or I2C communication interface, for this there is a library you can use. Usually the speed at which this communication work s very high, at 100kHz( if I'm not wrong).
3.Yes you can save data on the SD card until you don't exceed the memory or the battery doesn't die.

I have a suggestion for your project, as you're going to acquire some sort of data and then analyze it on your computer, do less calculations on your Arduino board and let the PC handle the hard work.
Useful links:

Reference to the two wire communication: http://arduino.cc/en/reference/wire
Reference to the SD card reading on Arduino: http://arduino.cc/en/Reference/SD

I would venture to say that any Arduino can be portable for an arbitrary definition of "portable".

You're right but I was thinking about the space that the board itself occupies. Obviously any Arduino board can be used to do the job as I wrote.

In a long distance bike, I think the Uno is still considered portable. Putting it ahead of the headtube (possibly even inside a basket) would be acceptable I think (at least experimentally).

I would accept the answer, but you could please post links to what you are talking about. For example, "there is a library for that" doesn't teach me much, you could make it a link to the library itself.

Another idea -
I believe if you are making electronics you must be using some smart phone?
If I am correct why don't u utilize your smart phone with Arduino?
1) Connect sensors to Arduino
2) Use Bluetooth or WiFi shield
3) Store data locally until memory available
4) Transfer to your phone or to web via phone network every hour or 5 hours.
This will make battery consumption less and also make device Compaq.
Regards,
Pathik SHAH


text:
Float arithmetic vs. int arithmetic - is there any power penalty?
It is widely known that float arithmetic takes longer (that is, eats more cycles) than fixed-point (or integer, or bitwise arithmetic), and that surely is something to consider for speed- and time-critical applications.
My question is: supposing I don't have any time-critical need (and I have enough program and RAM memory), should I be worried by any other disadvantage of using float?
Specifically, I wonder if the processor would be more power-hungry because of those extra CPU cycles.

UPDATE:   What will my application do meanwhile?
The only goal of the application is to turn lights on and off (lots of them) based on push-button input. I am using float to apply filtering to button inputs, in order to debounce the buttons simulating a RC filter + schmitt-trigger. So the loop in pseudo-code would be:

Read all inputs (digitalRead or direct port access);
Filter the readings and decide if a button action has been detected;
Set some control flags that determine which part of the cycle the lights are in;
Check for elapsed time to actually turn blinkers on and off.

So, since I plan to react to button input as realtime as possible, most time would be spent filtering (that is, performing floating point operations), since direct port access and flag-setting are supposed to be nearly instantaneous, right?

port access and flag-setting are supposed to be nearly instantaneous - yes direct port access would take place in about 2 clock cycles.

It depends on what your processor is doing while it has no real work to do:

If you put it to sleep, then yes, using floats will keep the CPU awake for a longer time and burn more energy.
If you are instead doing busy-waits (e.g. with delay()) it should make no difference, since the CPU is busy 100% of the time anyway.

Update: According to your update, it seems your program never
sleeps. Then I would expect no substantial difference in power
consumption between using floats or ints. As Majenko said, there can
theoretically be some small difference depending on the number of
transistor transitions involved in each instruction (and, I would add,
the capacitive loading of the involved transistors), but I do not expect
this to be very significant.
If you are really concerned about the consumption of your Arduino, I
would suggest you use it only for prototyping, then move your code to a
bare ATmega (or maybe even an ATtiny) chip. Also, add at least one call
to sleep_mode() inside your main loop. Each such call will put your
CPU to sleep until the next timer interrupt, which typically happens
every 1024 µs. There is a lot more to say about power savings, see
for example this excellent writeup by Nick
Gammon.
Edit: When trying to minimize power consumption, one of the very
first things to do is figure out how much work has to be done, and make
sure your program never does more work than required. In your case, this
means you have to know how often your main loop should execute, and
prevent it from running more often than needed. For example:
#include <avr/sleep.h>

const unsigned long loop_period = 5;  // run the loop every 5 ms.

void loop() {

    /* Sleep while waiting for the next time slot. */
    static unsigned long last_time;
    while (millis() - last_time < loop_period)
        sleep_mode();
    last_time += loop_period;

    /* Actual work goes here... */
}

If the actual loop work takes significantly less time than the loop
period, your CPU will sleep most of the time, leading to significant
power savings. Then you can start digging into more advanced
power-saving techniques like those mentioned in the article linked
above.

See my update, I described the workflow of my mainloop, thanks! :D

@heltonbiker: I updated my answer to address your updated question.

Perfect! Your answer not only addresses my initial questions, but also shows an array of additional considerations, all of them very relevant and well explained. Thank you very much!

The only goal of the application is to turn lights on and off (lots of them) based on push-button input. I am using float to apply filtering to button inputs, in order to debounce the buttons simulating a RC filter + schmitt-trigger.

Using floats is way overkill here. To debounce all you need to do is note when the switch changed state, and ignore further state changes during a certain interval, say 10 ms. It is even quite feasible to sleep during that debounce period. One of the watchdog timer intervals is 16 ms which would be about right for that.
In any case, an application that turns lights on is hardly going to be one where you are worried about how much power floating point operations take. I would be 1000 times more worried about how much power the lights use.

Thanks for your answer! I know debouncing is usually something quite trivial, but depending on the electrical nature of your contact, there can be some interesting problems. For a discussion on that - and on why one would want to use smoothing - see the link on my update. Also, the lights and the Arduino board will be possibly running on different power sources - say, hub dynamo for the lights, small battery for the board. But I'll consider all of your tips!

Yes, more power will (theoretically) be consumed.  That is, compared to doing nothing.
Float operations will require more mathematical operations to perform compared with integer or fixed point.  That will mean more gates are being activated and deactivated etc, compared to doing nothing.
Would that increase in power be noticeable?  Probably not.  It'll be so tiny as to be negligible.  As Edgar Bonet has mentioned, if you are making use of sleep modes then the extra time taken to perform the float operations will impact the ratio of running to sleep time, but if all you are doing is a set of mathematical operations a few times a second and using the millis() or delay() functions to control the timing then the difference will be so minimal you'll never notice it.
The effect is more noticeable on a PC when you perform very complex operations (like 3D rendering) and the CPU gets hotter and the fan speeds up.  In this situation the CPU is entering an idle state (like sleep, but less so) when it's not needing to perform any tasks which reduces both power consumption and heat dissipation.  When performing heavy tasks it has less time to be idle and so generates more heat. The more complex the operations the more transistors need to switch and so the more heat is dissipated.
Unfortunately the power dissipation per op-code is not documented, but it should be possible to write some assembly code to execute a single instruction in a tight loop (start with NOP) and measure the current, then change that instruction for a different one and compare the current.  Using NOP as a baseline you should then be able to calculate the increase in current for each op-code.  Of course, the actual data the op-codes are operating on will also have a bearing on the power consumption.
But that would be pretty pointless unless you are budgeting for every single femtowatt of power.

See my update. I don't have timing on the loop itself, so it is free to run as fast as possible. Only the flag-setting logic is based on elapsed time, since the system is supposed to blink leds on a bicycle (yeah, I know...) with traffic-signaling purposes.

If you are interested in power saving, I think it would be more important to check that the standard Arduino library doesn't turn on HW blocks that you do not need.
From an engineering perspective, though, the filter you are pursuing seems a bit overkill, if you only worry about bounces. Waiting for a reasonable amount of time after the first transition should be sufficient and would keep the code simpler to write, test and debug.
The mechanical switch is already a dampened system with its own intrinsic time constant.


text:
RGB and Potentiometer

How do I start this program???
int x=0;
int P1=A5;
int P2=A4;
int P3=A3;
int R1=3;
int G1=5;
int B1=6;
int R2=9;
int G2=10;
int B2=11;
int sValue1;
int sValue2;
int sValue3;
int oValue1;
int oValue2;
int oValue3;
int timer(1000);

void setup() {
 pinMode(P1,INPUT);
 pinMode(P2,INPUT);
 pinMode(P3,INPUT);
 pinMode(R1,OUTPUT);
 pinMode(G1,OUTPUT);
 pinMode(B1,OUTPUT);
 pinMode(R2,OUTPUT);
 pinMode(G2,OUTPUT);
 pinMode(B2,OUTPUT);

}

void loop() {

sValue1=analogRead(P1);
sValue2=analogRead(P2);
sValue3=analogRead(P3);

oValue1=map(sValue1,0,1023,0,255);
oValue2=map(sValue2,0,1023,0,255);
oValue3=map(sValue3,0,1023,0,255);

if ((sValue1=0)&&(sValue2=0)&&(sValue3=0));
{
  setColor1(0,255,255);
  delay(timer);
  setColor2(255,0,0);
}
}

void setColor1(int red1, int green1, int blue1){
  {
    analogWrite(R1,red1);
    analogWrite(G1,green1);
    analogWrite(B1,blue1);
  }
}

void setColor2(int red2, int green2, int blue2){
  {
    analogWrite(R2,red2);
    analogWrite(G2,green2);
    analogWrite(B2,blue2);

  }
}

Also i get Error compiling from this program I started and I don't know what's wrong.

Welcome to SO. You should edit your question, select the entire block of code, and click the "format as code" button. (it looks like opening and closing curly braces, {}.) Unformatted code is really hard to read. (and never post more than a short code fragment in a comment since those don't line breaks.)

What do you mean "how do I start this program?" Do you mean how do you install and run it on an Arduino?

Now it has an error compiling for board. How do i fix this?

@DuncanC I think so. The question could be "How to run this sketch from a source code", screenshot is irrelevant.

@D3DSEC What compiling error do you get? BTW: Your if line is wrong. Replace = by ==. Also remove the ; at the end of the line.

int B1=6;
 ^

exit status 1
Error compiling for board Arduino/Genuino Uno.

I don't know what's wrong with my int B1=6;

Dude, you need to improve your question. State your problem more clearly, and then identify which specific lines are giving you trouble, and the exact, complete error message(s) you are getting.

I think int timer(1000); should be int timer = 1000;. sValue1=0 should be sValue1==0, or to actually match the assignment's <=50%; sValue1<=127.

I'd also like to point out that using potentiometers to collect 0 or 1 values and then drive an RGB LED is absurd. The pots should be used as voltage dividers to feed into analog inputs, and then the Arduino should be set to feed PWM signals to the different color channels of the RGB LED proportional to the inputs to the pots.

Arduino has created binary numbers: B1, B101, B00111, and so on.
It is documented in the reference page "Integer Constants".
The "B1" is defined in "binary.h".
They should not have done that. Not a single C++ software engineer thinks that it was a good addition. The C++ language is perfectly fine for creating binary values: 0b1, 0b101, 0b00111, and so on.
It is not your fault, you can blame Arduino. Because of this, you should never create variables with the name: B1, B101, B00111, and so on.

This sounds like the source of the error on that one line `int B1=6; Good callout. (Voted)

Install Arduino IDE
New sketch
Paste code
Connect the Arduino board to your PC
Upload sketch

Also i get Error compiling from this program

Obviously B1 is already defined as something, like your A5, A4 and A3 are.
You will very likely have the same issue with B2.

See Jot's answer. It sounds like B1 is the problem because apparently the Arduino library has some binary constants. like B1, B101, etc.

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


text:
Boost an audio signal for analog read - Envelope Detector
I'm working on my first Arduino project and I have a sensitivity issue.
I'm building a module to listen to an audio signal and to start the power source of my speaker with a relay. Everything seems to work fine, but if I drop the volume of my sound, the analog pin doesn't record values (at maximum volume, it peaks at around 50, which is not a lot).
I thought about getting a capacitor but I'm really not sure on what I should get and how the wiring should be done.

An analog input on an Arduino can only tolerate voltages from 0 to 5VDC.  It can't tolerate negative voltages.  Audio signals are AC signals.  Their voltage changes rapidly from positive to negative.  The negative voltages involved could damage your Arduino.  It isn't safe to connect an audio source directly like this.

Hooo, thanks for that, I knew I'd learn something but not that I could have fryed my Arduino ;) Do you have any suggestions on what I could do and that is secure? I suppose that a diode bridge could fix that problem since I really don't care about the content of the signal?

If you only want to detect whether the signal existed or not, you can use a low-pass filter (basically through a diode and  resistor to charge a capacitor) to give you a near-DC output, and bring it down to appropriate level, say 2.5v, and just read it through analogRead().

What you're looking for is called a peak detector, or probably better in your case - an envelope detector. Pass this through an op-amp with adjustable gain to let you tune your sensitivity. R3 - your potentiometer will let you adjust the sensitivity.Your gain will be
.
Set Vdd to 5V and common ground with your Arduino.
It's unlikely your audio source is generating too much voltage given you're saying its not registering - but in the unlikely event you're above 5V put a reverse biased Zener diode in parallel with your capacitor to clamp voltage to 5V

simulate this circuit – Schematic created using CircuitLab
Hit simulate to see what playing with values does!

Sorry, it took sometime, everything was closed here... I just got my hand on all parts required. The problem that I now have is that the TL081 always give me the same reading on the arduino, even when I remove the jack from my board, I remove everything from my Vin but I kept having reading from the analogue IN. Have any idea on waht can cause that?

it sounds like what you are wanting to do is to detect a minimum threshold of sound so that your speaker power source can be turned on when an audio signal is playing.
You need to amplify your signal while also avoiding voltages that exceed the maximum input specification and also don't go negative. One way to accomplish this is with an operational amplifier (op-amp) circuit. A specific type will accomplish all three requirements. An op-amp that is powered by a single-sided supply, for example +5V and ground, will prevent negative voltages and limit the maximum voltage exceeding what the Arduino can take.
For your application, you don't really care about making a high-quality audio amplifier. You care about not distorting the signal (music) that you are monitoring and detecting a threshold level. Op-amps are good because they have high impedance inputs (they don't draw much (or any) current from your music signal) and they work with few external components.
A classic text for learning about electronics is Horowitz and Hill. Alternatively, you can find references for circuit designs on-line with appropriate searches. For any op-amp that you buy, you can get a datasheet that tells you how to use it. The following reference goes into detail (maybe too much) about single supply op-amps.
Circuits (and search terms) that you might find useful are op-amp follower, single supply, bias, and capacitive coupling. You'll need to purchase components. A good supplier is DigiKey. DigiKey has an on-line catalog that allows you to do a parametric search to identify the components that you need. You'll need a breadboard, resistors, capacitors, and the op-amp in a dual-inline package (DIP).
One search filters the list of possibilities from tens of thousands to a reasonable number. The LM833 Datasheet here is a reasonable choice.
Test equipment, like a single generator and oscilloscope can be very helpful when building amplifiers. You might be able to digitize your amplified signal with your Arduino if you don't have access to test equipment.


text:
Why does an LED sometimes flash when increasing brightness?
This is admittedly a cross-post from LED fade malfunction (random flash)  but I can't get an answer on the Arduino forum.
I was mucking around with some very basic code and I noticed that when repeatedly holding an LED at 0 brightness for 1 second and then fading in to full brightness, a small flash would occasionally happen at the beginning of each fade (seemingly random).
int led = 11;
int brightness = 0;

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

void loop()
{
  if(brightness >= 256) //checks if brightness has passed 255, resets to 0
  {
    analogWrite(led, 255);
    brightness = 0;
  }
  analogWrite(led, brightness);
  if(brightness == 0)
    {
      delay(1000); //LED off for 1 second
    }

  brightness+=1; //increment brightness
  delay(20);
}

So, the thing that has me completely perplexed is that I can use a different piece of code (below) and the flash goes away!
int i = 0;
int led = 11;

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

void loop()
{
analogWrite(led, i);
delay(6);
if(i%256 == 0)
{
  i = 0 ;
  delay(1000);
}
i++;
}

Has anyone got any clue as to why this would happen? Both programs have basically the same code, except for that i is reset to 0 in the first program whereas in the second, i keeps incrementing past 255 so that analogWrite 'overflows.' I think it must be a firmware, (or maybe a software?) problem.
There is a video on youtube of it happening here, Arduino - fading LED problem.

Try removing analogWrite(led, 255); as it's quite useless, given that two lines below it, it is set back to 0. Can't see anything really wrong with the code (other that a bit of a weird order).

In your second code, change delay(6) to delay(20) - does the flash appear? You've got the second code rolling round three times faster than the first code (ignoring the 1-second delay, of course), so the random flash is probably undetectable. As for why there's a flash at all... no idea.

@Gerben That is true... :) Will do

@CharlieHanson I have tried increasing the delay and it doesn't have any effect. I can still detect the flash with the 6 second delay. I have now got a good answer/explanation as to why it happens on the Arduino forum.

Oops, I meant 6 millisecond delay.

According to the links you provide from the arduino.cc forum the question is more or less answered. If not that important, just avoid analogWrite(led,0) and make it analogWrite(led,1)
if you still want that analogWrite(led,0), I've tested your code with the advice and it seems to work OK when changing the register manually:
#include "wiring_private.h"

int led = 11;
int brightness = 0;

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

void loop()
{
  if (brightness >= 256) //checks if brightness has passed 255, resets to 0
  {
    brightness = 0;
    sbi(TCCR2A, COM2A1);
    OCR2A = 0; // set pwm duty
  }

  analogWrite(led, brightness);
  if (brightness == 0)
  {
    delay(1000); //LED off for 1 second
  }

  brightness += 1; //increment brightness
  delay(20);
}

Edit: to explain what those "strange codes" are
I'm not very expert in this field to explain how exactly this works but basically sbi is function defined in a macro by Atmel (?), it stands for "set bit in" and is used to change registers of ATmega chips. So basically what I did was change register defined by the macro TCCR2A (why? because it is the register that controls PWM in pin 11) and pass the bitmask COM2A1 (this is a mode of compare defined in datasheet) and OCR2A is a register used to store the compare value that defines duty cycle. Imagine a counter that every time it receives a tick from a signal clock it compares the value of the counter with the value stored in OCR2A and it sets the pin high or low if that value as been passed or not (more or less like this, depending on the mode stored on TCCR2A).
But in fact I've not done some black magic. I just looked into the code of analogWrite() and that is the way they use to set a value of PWM in pin 11:
void analogWrite(uint8_t pin, int val)
{
    // We need to make sure the PWM output is enabled for those pins
    // that support it, as we turn it off when digitally reading or
    // writing with them.  Also, make sure the pin is in output mode
    // for consistenty with Wiring, which doesn't require a pinMode
    // call for the analog output pins.
    pinMode(pin, OUTPUT);
    if (val == 0)
    {
        digitalWrite(pin, LOW);
    }
    else if (val == 255)
    {
        digitalWrite(pin, HIGH);
    }
    else
    {
        switch(digitalPinToTimer(pin))
        {

...

          #if defined(TCCR2A) && defined(COM2A1)
            case TIMER2A:
                // connect pwm to pin on timer 2, channel A
                sbi(TCCR2A, COM2A1);
                OCR2A = val; // set pwm duty
                break;
          #endif
...

}

So basically I just used that info to set the register to zero, as suggested from the arduino.cc forum link that you have.
If you want to know more about PWM in Arduino, this site has a lot of info and explains a lot of the modes of registers also.

Thanks @Personagem, I will test it, but could you please explain the use of sbi, TCCR2A, COM2A1, and OCR2A. Also, considering that wiring_private.h is of the included header files in the Arduino directory, is it necessary to include it?

Also, how do you learn how to use these libraries in the first place??

@Adrian I've edit to explain a bit of those codes and arduino IDE complains if I do not made that include. I'm not really an expert but if you want to dig in, the datasheet of atmega is your friend. This should be used in kinda of advanced way. What arduino.cc team did ( and that is the real beauty that change a bit everyone's world) was create simple functions that don't need typical user to dig into datasheets and some registers settings. They kinda made simple what could be hard for not so experienced people. However if you really need you can look at all code in github of arduino

Thanks a lot for the help, explanation and for the link. I can basically see how to do it now. I think you can also find all of the code in \hardware\arduino\avr\cores\arduino.

Wouldn't analogWrite(led,1) accomplice a similar effect to sbi(TCCR2A, COM2A1);OCR2A = 0;? I.e, setting the duty cycle to a very low value, just before setting the output to LOW. That would make it a lot more readable.

yes it does, I've suggested that in first sentence. But in case he really wanted for any reason or just curiosity this should be the way. In fact the problem relies on how analogWrite function handles values of 0 and 255 without changing the registers


text:
Why is resolution 20?
I am using an amazing code to send/read infrared pulses without any external library. The code is fine and I took about 1 hour to fully understand it. The only thing I didnt understand is the variable RESOLUTION. I believe it should be 0 not 20. I think it should be as low as possible.
You can see the code at:
https://learn.adafruit.com/ir-sensor/using-an-ir-sensor
or below:
/* Raw IR decoder sketch!
This sketch/program uses the Arduino and a PNA4602 to
decode IR received. This can be used to make a IR receiver
(by looking for a particular code)
or transmitter (by pulsing an IR LED at ~38KHz for the
durations detected
Code is public domain, check out www.ladyada.net and adafruit.com
for more tutorials!
*/

// We need to use the 'raw' pin reading methods
// because timing is very important here and the digitalRead()
// procedure is slower!
//uint8_t IRpin = 2;
// Digital pin #2 is the same as Pin D2 see
// http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
#define IRpin_PIN PIND
#define IRpin 2
// for MEGA use these!
//#define IRpin_PIN PINE
//#define IRpin 4

// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000

// what our timing resolution should be, larger is better
// as its more 'precise' - but too large and you wont get
// accurate timing
#define RESOLUTION 20

// we will store up to 100 pulse pairs (this is -a lot-)
uint16_t pulses[100][2]; // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
  Serial.begin(9600);
  Serial.println("Ready to decode IR!");
}

void loop(void) {
  uint16_t highpulse, lowpulse; // temporary storage timing
  highpulse = lowpulse = 0; // start out with no pulse length

// while (digitalRead(IRpin)) { // this is too slow!
    while (IRpin_PIN & (1 << IRpin)) {
     // pin is still HIGH

     // count off another few microseconds
     highpulse++;
     delayMicroseconds(RESOLUTION);

     // If the pulse is too long, we 'timed out' - either nothing
     // was received or the code is finished, so print what
     // we've grabbed so far, and then reset
     if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  // we didn't time out so lets stash the reading
  pulses[currentpulse][0] = highpulse;

  // same as above
  while (! (IRpin_PIN & _BV(IRpin))) {
     // pin is still LOW
     lowpulse++;
     delayMicroseconds(RESOLUTION);
     if ((lowpulse >= MAXPULSE) && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  pulses[currentpulse][1] = lowpulse;

  // we read one high-low pulse successfully, continue!
  currentpulse++;
}

void printpulses(void) {
  Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
  for (uint8_t i = 0; i < currentpulse; i++) {
    Serial.print(pulses
* RESOLUTION, DEC);

    Serial.print(" usec, ");
    Serial.print(pulses[1] * RESOLUTION, DEC);
    Serial.println(" usec");
  }

  // print it in a 'array' format
  Serial.println("int IRsignal[] = {");
  Serial.println("// ON, OFF (in 10's of microseconds)");
  for (uint8_t i = 0; i < currentpulse-1; i++) {
    Serial.print("\t"); // tab
    Serial.print(pulses[1] * RESOLUTION / 10, DEC);
    Serial.print(", ");
    Serial.print(pulses[i+1][0] * RESOLUTION / 10, DEC);
    Serial.println(",");
  }
  Serial.print("\t"); // tab
  Serial.print(pulses[currentpulse-1][1] * RESOLUTION / 10, DEC);
  Serial.print(", 0};");
}

Most IR remotes send pulses that are at least 400 micro seconds long. E.g. on a NEC IR remote you get pulses that are 560 or 2240 microseconds long (depending on whether it's sending a 1 or a 0).
So with a RESOLUTION of 20 you get at least 20 'pulse counts' for a 0 and 80 for a 1. Because remotes aren't that precise in you'll get somewhere between e.g. 18 and 22 or 78 and 82. Those values are different enough to easily detect whether a 0 or 1 was send.
Changing this RESOLUTION to e.g. 2 will give you 200 or 800 pulsecounts. You'll get a more precise timings from a still imprecise source. But this better precision is useless.
PS setting it to 0 could break the code, as the highpulse and lowpulse are only 16 bit integers so they will overflow after 65536, which will happen pretty fast.
Hope that helps somewhat. Just let me know is anything is still unclear.

Thank you so much! But I still didnt understand one thing you said: I agree that 20 of resolution would allow me to get 20 'pulse counts' of 400 microseconds. But the problem is that in the code the delay is 20 microseconds ->> delayMicroseconds(RESOLUTION); <<--. With a delay of 20 microseconds I could not even get a complete pulse according to your explanation cause a 0 pulse would request 400 microseconds. What am I understanding wrong?

This 'RESOLUTION' is a kind of misleading name. It is limiting the number of measurements per second. With a value of 20, you'd end up with 20 measurements per 400uS. (Note the the IR receiver doesn't return the 38kHz signal, just a LOW or HIGH, depending on whether it's detecting a 38kHz light-source). Hope that helps, otherwise let me know.

you are amazing. Now I can understand it. I read your answer 6 times and finally I (think) I understand it. The only thing wasnt clear (to me) is your 3rd paragraph's answer. A smaller resolution would definately provide more precise pulsecounts (or pulse lenght) so why should it be 1 or 2 instead of 20? I understand that 0 could overflow the highpulse variable and maybe 1 too, but what about 2 or 3? Why 20? If a pulse lenght is 100us then a 20 value for resolution would generate 20% of error that could break my goal when I try to send back the signal.

If your goal it to replay the IR pulses, a lower value might indeed be a good idea. But if you just want to decode the signal, the ir "protocols" have such a huge difference in 0 or 0 signals, that even very inaccurate data is good enough to decode.

Hi Gerben, yes I read about the most used protocols of infrared like NED but still RESOLUTION looks a little weird in that code. Do you have any idea a better value than 20? Maybe 3? Could you please clear what you wanted to say with " have such a huge difference in 0 or 0 signals, that even very inaccurate data is good enough to decode."?

Oops. Should have been 0 or 1. E.g. in NEC a 1 takes 4 times as long as a 0. Pretty hard to misread that. By the way, it is NEC, not NIC or NED.

Thank you for correcting me, it's NEC! :) Finally I understood it!


text:
How does an analog input pin work?
I have a potentiometer of 10k and I connected it this way:
5v -> potentiometer -> analog input pin of Arduino
When I turn the potentiometer I change the resistance of the circuit but in the Arduino documentation they say that an analog pin in INPUT mode will have 1 megaohm resistance. So, for example, if I turn the potentiometer to the middle it will generate 5k of resistance + 1 megaohm of the analog pin it will result in a tiny, very tiny current. If I use U = R x I across the potentiometer it will be:
U = 5000 x 0.0000001
U ~ 0 across the potentiometer. So U will be 5 V at the analog input because there was no drop of voltage in the circuit. If turn the potentiometer all way up to 10k resistance the voltage in the analog input will also be 5 V because the voltage drop across the potentiometer is still really small.
I know that an analog pin in INPUT mode will read 0 V as 0 and 5 V as 1023. But as I showed you it should always read 5 V even when I turn the potentiometer all way up because the voltage is not being changed. I know I am wrong cause when I log the input pin it shows different values as I turn the potentiometer. So how does this work?

Potentiometers have 3 pins. One for 5v, one for ground, and one that outputs the voltage in between (depending on the orientation of the knob).

The potentiometer and the internal resistance form a voltage divider. The voltage created by this voltage divider is essentially indistinguishable from 5V regardless of what the pot is set to because the internal resistance is so high.
What you want to do is to create an external voltage divider that will cause the voltage to vary full scale between 5V and 0V. You do so by connecting one end of the pot to 5V and the other end to 0V, and drawing the voltage from the wiper.

Hi Ignacio! Thank you for helping me but I still didnt understad how a 10M ohm resistor inside the input pin helps it to read the voltage. What am I missing?

It doesn't. The ADC reads the voltage. The 10Mohm resistance means that the ADC will draw very little current when taking a measurement, but that a comparable external resistance will distort the results.

This is incorrect.  A potentiometer is by defintion a three terminal device.  It forms its own voltage divider.  The input impedance of the ADC, if substantially higher, has minimal loading effect.  Your answer would be correct if the poster had a simple two terminal variable resistor rather than a potentiometer.

@ChrisStratton: The asker never describes connecting the second terminal, only the first and the wiper.

If that were the case, then the question would be erroneous and as they would not be using a poteniometer.  Their results suggest that either  they have wired a potentiometer, or the input impedance is lower than imagined.

Or that they completely botched the circuit analysis.

I am using the 5v wire and the middle wire of my pot. I must be very dumb cause I still dont understand how an analog pin works. Please take a look at this formula (wikipedia) http://upload.wikimedia.org/math/4/4/b/44b8b16db945a778e558f2c5ffd70157.png . If Z2 is 10M ohm and Z1 a small resistor then Vout will be always the same value as Vin, it will never be 2, 3... it will always be the same as Vin independentrly of what my potentiometer effective resistance.


text:
Cannot give battery through USB cable
I just make a simple circuit with uno and breadboard ,that connected 4 LED and 4 IR sensor. The arduino program is simple that makes the light on or off with the determination of IR sensors .
However my computer cannot find the USB COM when it connects the 5v and GND.
Hence, I plug out the 5v and GND that connect to the breadboard .The computer can recognize COM 4 then . I successfully upload the program after this .
Now , when I connect the computer and UNO to give battery to UNO , no battery passed (because the computer cannot detect the USB COM) .The lights of IR sensor aren't on .How to tackle the problem?
It failed to  give battery with external battery too unless I plug out the 5v and GND
This is my simple program:
int irPin1 = 2;
int ledPin1 = 13;
int irPin2 = 3;
int ledPin2 = 11;
int irPin3 = 4;
int ledPin3 = 9;
int irPin4 = 5;
int ledPin4 = 7;
int serialSpeed = 9600;

void setup() {
  // put your setup code here, to run once:
  pinMode(irPin1,INPUT);
  pinMode(irPin2,INPUT);
  pinMode(irPin3,INPUT);
  pinMode(irPin4,INPUT);
  pinMode(ledPin1,OUTPUT);
  pinMode(ledPin2,OUTPUT);
  pinMode(ledPin3,OUTPUT);
  pinMode(ledPin4,OUTPUT);
  Serial.begin(serialSpeed);
}

void loop() {
  // put your main code here, to run repeatedly:
  int reading1 = digitalRead(irPin1);
  int reading2 = digitalRead(irPin2);
  int reading3 = digitalRead(irPin3);
  int reading4 = digitalRead(irPin4);
  digitalWrite(ledPin1,reading1);
  digitalWrite(ledPin2,reading2);
  digitalWrite(ledPin3,reading3);
  digitalWrite(ledPin4,reading4);
  String output = "{\"1\":" + (String)reading1 + ",\"2\":" + (String)reading2 + ",\"3\":" + (String)reading3 + ",\"4\":" + (String)reading4 + "}";
//  String output = "{\"" + (String)reading1 + "\",\"" + (String)reading2 + "\",\"" + (String)reading3 + "\",\"" + (String)reading4 + "\"}";
  Serial.println(output);
  delay(100);
}

My Arduino circuit:
UNO 5v to breadboard 5v
UNO GND to breadboard GND
1st set: IR :5v GND
from breadboard , pin from UNO
2nd set: IR :5v GND from breadboard ,
pin from UNO
3rd set: IR :5v GND from breadboard , pin from UNO
4th
set: IR :5v GND from breadboard , pin from UNO

Can you upload an actual picture of your breadboard? Think you have short.

@Zunzullaalagaty see update ! My Arduino circuit:
UNO 5v to breadboard 5v UNO GND to breadboard GND
1st set: IR :5v GND from breadboard , pin from UNO
2nd set: IR :5v GND from breadboard , pin from UNO
3rd set: IR :5v GND from breadboard , pin from UNO
4th set: IR :5v GND from breadboard , pin from UNO

on a first glance it seems fine actually. What I see from your picture is that your arduino doesnt light up. If you press the reset button, does any led light up? If not, try disconnecting sensors and leds until it starts to light up when pressing the reset button

@Zunzullaalagaty The power is fine after I plug one of the IR out  .What just happened? what is short circuit actually

It's a circuit where the current can pass without any consumer. It seems like you have that IR sensors plugged in wrong? Or maybe made a mistake in the code about the Input and Output for the IR sensor.

What voltage does your battery have? If you feed into Vin and got a short, the voltage regulator or the diode might be blown due to the high current. This would block the battery power to get in anymore. Please be carefull with building the circuit. A short can destroy the Arduino, but also the USB port of your PC, if connected to it.


text:
Aduino Due Can messages
I am trying to read/send CanBus messages using a Arduino Due.
As of now I have used https://github.com/collin80/due_can library to setup my Can Bus interface.
I am using Vector Software CanAylzer to see what CAN message are being received.
This is where I have my issue.
Although the CanAylzer software is being able to detect Can Messages on the line it gives be a Bit error on bit position 119. All the fields of relevance for me ID,Data etc seem to be reported fine.
Here is a snapshot of the CanAylzer Error Frame. Below is my Arduino code . Any help would be awesome.

Here is the ino code:
// Arduino Due - CAN Sample 1
// Brief CAN example for Arduino Due
// Test the transmission from CAN0 Mailbox 0 to CAN1 Mailbox 0

#include <Arduino.h>
#include "variant.h"
#include "due_can.h"

#define TEST1_CAN_TRANSFER_ID    0x18FF0017 //random 29 bits
#define TEST1_CAN0_TX_PRIO       1
#define CAN_MSG_DUMMY_DATA       0xABC

// CAN frame max data length
#define MAX_CAN_FRAME_DATA_LEN   8

// Message variable to be send
uint32_t CAN_MSG_1 = 0;

void setup()
{

   // start serial port at 115200 bps:

   Serial.begin(115200);
   Serial.println("Program Started");

}

void loop(){

   CAN_FRAME frame1, frame2;
   // say what you got:
   Serial.print("Sent Value: ");
   Serial.println(CAN_MSG_1, DEC);

   // Initialize CAN0 and CAN1, baudrate is 250kb/s
   CAN.init(CAN_BPS_250K);
   CAN2.init(CAN_BPS_250K);

   //Initialize the definitions for the frames we'll be sending.
   //This can be done here because the frame never changes
   frame1.id = TEST1_CAN_TRANSFER_ID;
   frame1.length = MAX_CAN_FRAME_DATA_LEN;
   //Priority
   frame1.priority = 0;
   frame1.rtr = 1;
   //Below we set the 8 data bytes in 32 bit (4 byte) chunks
   //Bytes can be set individually with frame1.data.bytes[which] = something
   frame1.data.low = 0xAFAFAFAF;
   frame1.data.high = CAN_MSG_DUMMY_DATA;
   //We are using extended frames so mark that here. Otherwise it will just use
   //the first 11 bits of the ID set
   frame1.extended = 1;

   CAN.sendFrame(frame1);
   while (1) {
   }
}

Update
Ok so here are the printed(via serial port) values of various registers. I don't think it is a problem with the values in the registers. I have cross referenced these with the SAM3X/A (on the due) Micro-controller manual (chapter 41, pertaining to the CAN). The only one I am fishy about is the baudrate one.
Serial Port Initialized
******START OF LOOP ******
No of Sent frames: 1
<><><><><><><><><>><><><><>
CAN_SR:( Status Register)
Bits 3 | 2 | 1 | 0
     0 | 0 | 0 | 0

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 0

Bits 11 | 10 | 9 | 8
      0 | 0  | 0 | 0

Bits 15 | 14 | 13 | 12
     0  | 0  | 0  | 0

Bits 19 | 18 | 17 | 16
     0  | 1  | 1  | 0

Bits 23 | 22 | 21 | 20
     1  | 0  | 1  | 0

Bits 27 | 26 | 25 | 24
     0  | 1  | 0  | 0

Bits 31 | 30 | 29 | 28
     0  | 1  | 0  | 0

<><><><><><><><><>><><><><>
#####END OF LOOP ######

Serial Port Initialized
******START OF LOOP ******
No of Sent frames: 1
<><><><><><><><><>><><><><>
CAN_MR: (Mode Register)
Bits 3 | 2 | 1 | 0
     0 | 0 | 0 | 1

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 0

Bits 26 | 25 | 24
     0  | 0  | 0
<><><><><><><><><>><><><><>
#####END OF LOOP ######

******START OF LOOP ******
No of Sent frames: 4
<><><><><><><><><>><><><><>
CAN_MID7: (Message ID Register Mailbox 7)
Bits 3 | 2 | 1 | 0
     0 | 1 | 1 | 1

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 1

Bits 11 | 10 | 9 | 8
     0  | 0  | 0 | 0

Bits 15 | 14 | 13 | 12
     0  | 0  | 0  | 0

Bits 19 | 18 | 17 | 16
     1  | 1  | 1  | 1

Bits 23 | 22 | 21 | 20
     1  | 1  | 1  | 1

Bits 27 | 26 | 25 | 24
     1  | 0  | 0  | 0

Bits 31 | 30 | 29 | 28
     0  | 0  | 1  | 1

Serial Port Initialized
******START OF LOOP ******
No of Sent frames: 1
<><><><><><><><><>><><><><>
CAN_ECR: (Error Count Register)
Bits 3 | 2 | 1 | 0
     0 | 0 | 0 | 0

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 0

Bits 11 | 10 | 9 | 8
     0  | 0  | 0 | 0

Bits 15 | 14 | 13 | 12
     0  | 0  | 0  | 0

Bits 19 | 18 | 17 | 16
     0  | 0  | 0  | 0

Bits 23 | 22 | 21 | 20
     1  | 0  | 0  | 0

Bits 27 | 26 | 25 | 24
     0  | 0  | 0  | 0

Bits 31 | 30 | 29 | 28
     0  | 0  | 0  | 0

<><><><><><><><><>><><><><>
#####END OF LOOP ######

Lastly and most importantly in my opinion:
Serial Port Initialized
******START OF LOOP ******
No of Sent frames: 1
<><><><><><><><><>><><><><>
CAN_MSR7: (CAN Message Status Register Mailbox 7)
Bits 3 | 2 | 1 | 0
     0 | 0 | 0 | 0

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 0

Bits 11 | 10 | 9 | 8
      0 | 0  | 0 | 0

Bits 15 | 14 | 13 | 12
     0  | 0  | 0  | 0

Bits 19 | 18 | 17 | 16
     1  | 0  | 0  | 0

Bits 23 | 22 | 21 | 20
     0  | 0  | 0  | 0

Bits 27 | 26 | 25 | 24
     0  | 0  | 0  | 0

Bits 31 | 30 | 29 | 28
     0  | 0  | 0  | 0

<><><><><><><><><>><><><><>
#####END OF LOOP ######

and the Baud rate register
******START OF LOOP ******
No of Sent frames: 1
<><><><><><><><><>><><><><>
CAN_BR:
Bits 3 | 2 | 1 | 0
     0 | 0 | 0 | 1

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 1

Bits 11 | 10 | 9 | 8
     0 |  0  | 1 |  0

Bits 15 | 14 | 13 | 12
     0  | 0  | 1  | 0

Bits 19 | 18 | 17 | 16
     1  | 0  | 0  | 1

Bits 23 | 22 | 21 | 20
     0  | 0  | 1  | 0

Bits 27 | 26 | 25 | 24
     0  | 0  | 0  | 0

Bits 28
     0
<><><><><><><><><>><><><><>
#####END OF LOOP ######

You can find what all the register bits details on Atmel's website or leave some way for me to email the documentation to you.
Any Help would be much appreciated!
Update 2:
I have attached 2 different Oscilloscope readings and deconstructed the entire binary representation of the Can message manually. Furthermore I calculated the associated CRC's of the two different messages, and then compared them to the ones the hardware created and found them(hardware ones) to be incorrect. I have provided a link to Google Drive where the results from the Oscilloscope can be found.
PS: the messages I used had in one 7 A's(hex, i.e 28bits) for the ID and 16 A's for the Data field.
The second one had 7 C's for the Id and 16 C's for the Data field.
Both are 2.0B can extended frames.

Looks like a CRC error. But the CRC calculation is done by hardware, so neither your fault nor the library's. Do you see a chance of monitoring the CAN line? If I'm not completely wrong, CRC for this frame should be 0x5F88

@mic the CANalyzer(pictured above) does that for me. I know its a problem with the CRC but why? And how do I fix it?

Good question! :-) That Vector stuff is not perfect, but the tools (and especially the prices) are made for professional use. The only thing I can imagine at the moment is a slightly different baudrate and/or an improper tq setting in your CANalyzer. What happens if you play a little bit with the sampling point? And again: Do you have a chance to look directly at the CAN line (e.g. using a scope)? It would be interesting to know what the Arduino really transmits.

@mic how do I check the tq settings? I have checked all the registers on the hardware level as well they seem to have the correct information.

@mic also have you used vector software before?

I'm quite familiar with Vector. In Canalyzer, "Configuration" - "Hardware configuration", you will see your CAN channel, and in "Setup" you can adjust the sampling. Play a little bit with the settings and see what happens.

yeah *I did that but the issue was the prescalers dont match up for the baudrate. If I put a prescaler of 4 in my arduino side code it gives me a sync error if i try to put a higher scaler then there is no equivalent in CanAylzer

Of course the baudrates have to match EXACTLY. 250kb/s is a common baudrate for a mid speed CAN network. I'm pretty sure CANalyzer as well as the Arduino offers at least one parameter set for this baudrate. What is your master clock on Arduino?

its the SystemCoreClock defined in the system_sam3xa.h (due's MC) header

Sorry, but this discussion doesn't really show progress. Maybe it's a good idea to post all your Arduino register settings as well as your CANalyzer timing parameters.

@mic updated stuff

@mic you were initially right. I used an oscilloscope to track the signal and found out the CRC doesn't match up to what it should be. This I believe is throwing the bit error. Any advise on how to fix this ? All other fields are correct. Also the frequency and therefore the baudrate are correct. I calculated that from the scope measurements.

This is strange, as you have no influence on CRC calculation. But what I've noticed when analyzing your register settings: In CAN_SR, the "Warn" flag is set. This should not happen after only one transfer. Also the "AERR" is set. This may be ok, if CANalyzer has detected a bit error and thus doesn't send an acknowledge. Can you post the scope screenshot for the complete message?

@mic please See the Section Update 2.

@mic the WARN Flag is set correctly. Firstly because I am sending a message in a loop multiple time not only once. Secondly as per CAN protocol a failed transmission attempt will be followed by multiple re-transmission attempts up to 255 times. At which point the CAN Bus will be disabled. Reference pg 1219 SAM3X/A manual.


text:
How to access the member of union in loop?
Trying to get the address of receiving XBee's data in the loop in API mode with escape.
Sent data can be received properly. However, in order to identify XBee, I need the address in the loop. In other words I need those address1 to 7 which is in union XbEE_FRAME. How to get the address in main loop. Following is the code. Appreciate your help.
#include <SoftwareSerial.h>

struct SENSOR_DATA{
   char rpm;   // worked
  //float rpm;
  //float strain;
  //unsigned long sampling_interval;
};

boolean xbee_rx(struct SENSOR_DATA *ret) {
  union LEN_FRAME{
    byte len_array[2];
    word len;
  }lenlen;
  static int len_i = -1;

  union XbEE_FRAME{
    byte buf[25]; // 30
    struct {
      byte frame_type;
      byte frame_id;
      byte address1;
      byte address2;
      byte address3;
      byte address4;
      byte address5;
      byte address6;
      byte address7;
      byte reserved1;
      byte reserved2;
      byte recieve_options;
      struct SENSOR_DATA sensor_data;
      byte checksum;
    } frame;
  } xbee;
  static int buf_i = -1;
  static bool escape = false;
  static byte sum;

  while (Serial.available() > 0) {
    byte b = Serial.read();

    //Serial.print(b, HEX);

     //b = Serial.read();
    if (
      b != 0x7e &&
      buf_i == -1 &&
      len_i == -1
      ) {
      continue;
    } else if (b == 0x7e){
      buf_i = 0;
      lenlen.len = 0;
      len_i = 0;
      sum = 0;
      escape = false;
      continue;
    } else if (b == 0x7d){
      //Serial.print("es: ");
      //Serial.println(b,HEX);
      escape = true;
      continue;
    }

    if (escape){
      b = b ^ 0x20;
      escape = false;
    }

    if (len_i < 2){
      lenlen.len_array[1 - len_i] = b;
      len_i++;
    } else {
      xbee.buf[buf_i++] = b;
      sum += b;
    }
    if (
      len_i == 2 &&
      buf_i >= sizeof(xbee.buf)
      ){
      len_i = -1;
      buf_i = -1;
      // frame recieved !!
      if (sum == 0xff){ // check sum!
        *ret = xbee.frame.sensor_data;
        return true;
      }
    }
  }
  return false;
}

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

void loop() {
  //mySerial.println("work");
  // put your main code here, to run repeatedly:
 struct SENSOR_DATA data;
  if (xbee_rx(&data)){
    //Serial.print(data.rpm);

     // if(b == 0x40 )  //&& b == 0xd5 && b == 0xaa && b == 0xac
  }
}

Function xbee_rx() only returns the contents of struct SENSOR_DATA which doesn't include those addresses. You could instead 1) return the contents of the entire struct {...} frame which does contain them (making sure loop() 's buffer is large enough; or 2) instead of returning all of that data at all, make the union {...} xbee static so it persists after xbee_rx() exits, and return a pointer to sensor_data, with which loop() can access any member of it, such as p->address1.
Update:
The caller - rather than the called-function - allocates the memory buffer and the called-function uses that memory instead of its own, effectively passing the data to the caller. Here's your code, slightly re-written, with my initialed comments. I have not tried to run it but it does compile:
#include <SoftwareSerial.h>

struct SENSOR_DATA{
   char rpm;   // worked
  //float rpm;
  //float strain;
  //unsigned long sampling_interval;
};

//-jr-: Here we define what an XbEE_FRAME is and make it a data-type
// but we don't allocate any storage. This is just information to the
// compiler:
typedef union {
    byte buf[25]; // 30
    struct {
      byte frame_type;
      byte frame_id;
      byte address1;
      byte address2;
      byte address3;
      byte address4;
      byte address5;
      byte address6;
      byte address7;
      byte reserved1;
      byte reserved2;
      byte recieve_options;
      struct SENSOR_DATA sensor_data;
      byte checksum;
    } frame;
} XbEE_FRAME;

//-jr-: This function expects a pointer to memory (i.e., its address)
// allocated for data of type 'XbEE_FRAME' - the union from your
// original code. Note that we don't allocate any memory for it here;
// the caller is expected to do that, and this function will use what
// the caller allocated.
boolean xbee_rx(XbEE_FRAME *pXbF) {
  union LEN_FRAME{
    byte len_array[2];
    word len;
  }lenlen;
  static int len_i = -1;

  static int buf_i = -1;
  static bool escape = false;
  static byte sum;

  while (Serial.available() > 0) {
    byte b = Serial.read();

    //Serial.print(b, HEX);

     //b = Serial.read();
    if (
      b != 0x7e &&
      buf_i == -1 &&
      len_i == -1
      ) {
      continue;
    } else if (b == 0x7e){
      buf_i = 0;
      lenlen.len = 0;
      len_i = 0;
      sum = 0;
      escape = false;
      continue;
    } else if (b == 0x7d){
      //Serial.print("es: ");
      //Serial.println(b,HEX);
      escape = true;
      continue;
    }

    if (escape){
      b = b ^ 0x20;
      escape = false;
    }

    if (len_i < 2){
      lenlen.len_array[1 - len_i] = b;
      len_i++;
    } else {
       //-jr-: Note how we changed our reference from 'xbee.buf...' to
       // 'pXbF->buf...'! The '.' style addressing is used to refer to
       // memory we can name directly, as when you allocated that union
       // here. But now we  have to refer to it by the  pointer we received -
       // its address. The '->' symbol is how you address members of a
       // union or struct through a pointer:
      pXbF->buf[buf_i++] = b;
      sum += b;
    }
    if (
      len_i == 2 &&
      buf_i >= sizeof(pXbF->buf)
      ){
      len_i = -1;
      buf_i = -1;
      // frame recieved !!
      if (sum == 0xff){ // check sum!
    //-jr-: Notice that here we don't try to return any data;
    // we don't have to. Since We did everything in memory the
    // caller owns, the caller already has the data!
        return true;
      }
    }
  }
  return false;
}

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

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

   //-jr-: Define the entire XbEE_FRAME here and pass its address to
   // your function. The function will use _this_ local storage
   // (instead of its own) to buffer the data, so it will already
   // be here when your function returns:
   XbEE_FRAME data;     //-jr- Define the entire union here
   if (xbee_rx(&data)){    //-jr-  and pass its address to the function
      //-jr-: You can address a member such as address3 as:
      //      data.frame.address3
    //Serial.print(data.rpm);

     // if(b == 0x40 )  //&& b == 0xd5 && b == 0xaa && b == 0xac

  }
}

Update:

How to get the SENSOR_DATA sensor_data?

Use: data.frame.sensor_data.rpm (lower case).

SENSOR_DATA only describes the kind of contents in a struct, not any actual data in memory.
sensor_data is one instance of such a struct.

To go a bit further, suppose frame{} contained more than one SENSOR_DATA in it, maybe named sensor_data_a, sensor_data_b, ..., etc. Now to get the data from, say, sensor_data_a it should be clear that you need to refer to the particular instance you're interested in.

JRobert, I am trying method No.1 that you have suggested, though still I cant get. Could you please write the code?

Ok, got the address. But now can not get the SENSOR_DATA sensor_data. How to get the SENSOR_DATA sensor_data?

I tried to get with Serial.print(data.frame.SENSOR_DATA.rpm); but didn't work.

I don't think you can.
The structures are defined within a function so the loop() won't have access to them.
Further the parameter returned from the function xbee_rx() is of type SENSOR_DATA which is a sibling in the frame structure to the data you want to read.


text:
Need help to send serial data from arduino to XBee and to another XBee wirelessly?
I try to send serial data RPM to XBee series1 and then from XBee to another XBee wirelessly in API with Escapes Mode. I think I have to send the data Frame.But not very sure.
Any help?
Following is the code to read RPM and send to XBee?
#include <XBee.h>
#include <SoftwareSerial.h>
/* Serial communication with Xbee.
On Arduino pin 9 is Rx connect to Xbee Tx,
pin 8 is Txconnect to Xbee Rx*/
SoftwareSerial xbeeSerial(9, 8); // RX, TX

XBee xbee = XBee();

int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val,time;
float rps;
float read_rpm;

uint8_t start_data[] = { 0x7E, 0x00, 0x50, 0x01, 0x01, 0xff, 0xff,0x00, 0x05, 0x00,0x01,0x03, 0x84, 0x00 };

void setup()
{
  Serial.begin(9600);
  pinMode(pin, INPUT);
  Serial.println("I am ready to send some RPM!");
  xbeeSerial.begin(9600);
  time = millis();
}

void loop()
{

void loop()// run over and over
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

/* Sending float to Xbee
Float is 4 byte size*/
serialFloatPrint(rpm);

int floatToInt = (int)rpm;

/* To send INT to XBEE
Int is 2 byte size*/
xbeeSerial.write(highByte(floatToInt));
xbeeSerial.write(lowByte(floatToInt));

  Serial.write(0x03);

  delay(2000);
}

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;

  //xbeeSerial.print("f:");
  xbeeSerial.print(b[0]);
  xbeeSerial.print(b[1]);
  xbeeSerial.print(b[2]);
  xbeeSerial.print(b[3]);
  /* DEBUG */
  Serial.println();
  Serial.print(b[0],BIN);
  Serial.print(b[1], BIN);
  Serial.print(b[2], BIN);
  Serial.println(b[3], BIN);
  //*/
}
}

As @TMa showed, download this library and first test the communication without any RPM calculation. When you will be sure you get good messages on another arduino, then add rpm and etc... In Xbee-Arduino library there are examples

Please use the code tag.

@werner, where is the code tag?

couldn't find the example what I want. I tried the following. Though can't recevive any serial data.

I got stucked with this. Any help?

Dear zalt, it is hard to read code in comments. Please edit your question and add the code there

Sorry. I did it.

Your code is unreadable.  Please learn how to use the code tag. http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks

I did. Is there any solution?

Any hint? What is the solution?

You are using it as in non-API mode when data are passed to Xbee wireless transparently. To use Xbee in API mode use e.g. Xbee-Arduino library.


text:
Is parity check hardware only or can I read it? ( Arduino Mega )
Maybe a simple question, but I can't seem to find it.
Parity check is simple error detection.
But is in done in hardware on the arduino and is the data discarded before i can read it from software?
The reason I ask this quote from Thomas

1  Command bit, set on the first character of each datagram. Reflected in the parity bit of most UARTs. Not compatible with NMEA0183 but well suited for the multiprocessor communications mode of 8051-family microcontrollers (bit SM2 in SCON set).

From http://www.thomasknauf.de/rap/seatalk1.htm#Dat which might have confused me. So I guess this is not an option ... after the feedback from users.
So i need to read the 9 bit and since the hardware support it. The Arduino team won't implement it, since it has a bigger overhead and it's really not used anymore ... I agree ... but the SeaTalk bus uses it ... so I'm stuck here.
But after more seaching I found this GitHub repo: https://github.com/rob42/FreeboardPLC_v1_2 which have made changes to the HardwareSerial.h and HardwareSerial.cpp but only for version 1.5.7
Think I will go for this version unless someone have done the mods to 1.6.x ... have searched the web. Later I will try to see if I can get it to work with 1.6.x ... but since this is all new. I'm taking small steps.

@wouter Thank ... I read more and got a bit more knowledge about the subject.

@stefan I have cleared up the question and also the part why I was looking into the Parity part ... which I guess is not the right way to go.

This came up a while back on the Arduino Forum - talking about Asynchronous SeaTalk.
I made a modified version of HardwareSerial which can be downloaded from http://gammon.com.au/Arduino/HardwareSerial9bit.zip
Changes are:

The internal buffers have been changed from 8-bit characters to 16-bit characters (to hold the 9th bit). Thus the buffers double in size.
There is a new argument to the Serial.begin() function, which is a boolean, whether or not you want 9-bit mode. It defaults to false.
There is a new function Serial.write9bit (). This takes an unsigned int argument, letting you supply a character with the 9th bit set. I didn't want to change the existing write function because it is used in the Print class.
The read function, which already returns an int, now will return the 9th bit where required.

Example code:
void setup ()
{
 Serial.begin (115200);  // debugging prints
 Serial1.begin (115200, true);  // 9 bit mode
 Serial2.begin (115200, true);  // 9 bit mode
 Serial.println ("--- starting ---");
}  // end of setup

int i;

void loop ()
{

 Serial1.write9bit (i++);  // send another byte

 // display incoming on Serial2
 if (Serial2.available ())
   Serial.println ((int) Serial2.read (), HEX);

 // check if we have sent all possible characters
 if (i >= 0x200)
   {
   delay (100);
   while (Serial2.available ())
     Serial.println ((int) Serial2.read (), HEX);
   delay (5000);
   i = 0;
   }  // end of sent 512 bytes
}  // end of loop

As Ignacio Vazquez-Abrams said, the hardware supports this 9-bit mode natively, it just takes a bit of fiddling around to make it work.
Because of the way that hardware serial is integrated into the IDE it is, unfortunately, necessary to find your existing files:

HardwareSerial.cpp
HardwareSerial.h

... and replace them with the ones in the download.

Note that this is for version 1.0.1 of the IDE. No guarantees are given that this will work with other versions. This was written a while back, I'm not sure what changes have been made to HardwareSerial in the meantime.
The actual changes are here: http://gammon.com.au/Arduino/hardwareSerial_diffs.txt
You could use those to guide your implementation on more recent versions, if the file download does not work "as is".

AVR devices with a hardware USART have a real 9-bit mode; there is no need to "fake" it.
But to answer your question, it is done in hardware; the appropriate USART Parity Error bit is set and while the datasheet is vague about it, it is implied that the data is stored in the receive buffer.

Thanks. That cleared up some of my confusion and also added more. Have updated the question with more information about my original issue since the parity check is not the way to go.


text:
Analogue input 0 staying at 0 when sensing light with Arduino and a photocell
I am doing a circuit for capturing light intensities.
I followed the tutorial provided by Adil Moujahid
Yet, when I plug the jumper wires on 5V the circuit stops working and when I plug on 3.3V the analog in A0 sent back only a series of zero...
What did I missed? I acknowledge that I tried to be the most economical on the jumper wires...
The sketches, program and circuit given by Adil Mouhajid

My attempt

While the code is not relevant to your issue here, in the future please place your code text into the question directly, instead of as a screenshot.

What did I missed? I acknowledge that I tried to be the most economical on the jumper wires. - that's what you missed. The bottom two lines are connected horizontally (all the way along) - thus you just shorted everything together.

The two strips on either side of the bread board, color red and blue (typically) are power rails, and each strip is all connected. Your circuit connections that are on that strip are shorted together and will not work. I suggest following his layout exactly to begin with, and once you've learned the basics of breadboard connections, you can start doing your own layouts.