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:
Getting values from multiple thermistors - one value glitches all over the place

I have a circuit with preferably long wires that get data from thermistors. The Arduino sends this data (formatted in JSON) to a web server where it can be collected by another program.
Some of these values appear correct, while others do not.
[
{
    "dht11": {
        "temperature": 73.4,
        "humidity": 41,
        "heat-index": 77.15
    },
    "thermistors": {
        "therm1": {
            "temp": 71.21,
            "resistance": 12727.27
        },
        "therm2": {
            "temp": 76.22,
            "resistance": 12045.51
        },
        "therm3": {
            "temp": nan,
            "resistance": -19393.41
        }
    }
}
]

code:
#define THERMISTORPIN A0
#define THERMISTORNOMINAL 10000
#define TEMPERATURENOMINAL 25
#define NUMSAMPLES 25
#define BCOEFFICIENT 4050
#define SERIESRESISTOR 10000
#define THERMISTORPIN2 A5
#define THERMISTORPIN3 A3
#define DHTPIN 2
#define PHOTORESISTOR 3
#define DHTTYPE DHT11
int samples[NUMSAMPLES];
int samples_two[NUMSAMPLES];
int samples_three[NUMSAMPLES];
int stuckintime;
#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
byte mac[] = {
  0x00, 0x00, 0x00, 0x00, 0x00, 0xEE
};
IPAddress ip(192, 168, 1, 3);
EthernetServer server(80);
DHT dht(DHTPIN, DHTTYPE);
void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  dht.begin();
  analogReference(EXTERNAL);
}

void loop() {
  uint8_t i;
          float average;
          float average_two;
          float average_three;
          float stuckintime;
          for (i = 0; i < NUMSAMPLES; i++) {
            samples[i] = analogRead(THERMISTORPIN);
            samples_two[i] = analogRead(THERMISTORPIN2);
            samples_three[i] = analogRead(THERMISTORPIN3);
            delay(10);
          }
          for (i = 0; i < NUMSAMPLES; i++) {
            average += samples[i];
            average_two += samples_two[i];
            average_three += samples_three[i];
          }
          average /= NUMSAMPLES;
          average = 1023 / average - 1;
          average = SERIESRESISTOR / average;
          float tempreading;
          tempreading = average / 10975;
          tempreading = log(tempreading);
          tempreading /= BCOEFFICIENT;
          tempreading += 1.0 / (TEMPERATURENOMINAL + 273.15);
          tempreading = 1.0 / tempreading;
          tempreading -= 273.15;
          tempreading = tempreading * 9 / 5 + 32;
          average_two /= NUMSAMPLES;
          average_two = 1023 / average_two - 1;
          average_two = SERIESRESISTOR / average_two;
          average_two = average_two;
          float tempreadtwo;
          tempreadtwo = average_two / 11811;
          tempreadtwo = log(tempreadtwo);
          tempreadtwo /= BCOEFFICIENT;
          tempreadtwo += 1.0 / (TEMPERATURENOMINAL + 273.15);
          tempreadtwo = 1.0 / tempreadtwo;
          tempreadtwo -= 273.15;
          tempreadtwo = tempreadtwo * 9 / 5 + 32;
          average_three /= NUMSAMPLES;
          average_three = 1023 / average_three - 1;
          average_three = SERIESRESISTOR / average_three;
          float tempreadthree;
          tempreadthree = average_three / THERMISTORNOMINAL;
          tempreadthree = log(tempreadthree);
          tempreadthree /= BCOEFFICIENT;
          tempreadthree += 1.0 / (TEMPERATURENOMINAL + 273.15);
          tempreadthree = 1.0 / tempreadthree;
          tempreadthree -= 273.15;
          tempreadthree = tempreadthree * 9 / 5 + 32;
          float h = dht.readHumidity();
          float t = dht.readTemperature();
          float f = dht.readTemperature(true);
          float hif = dht.computeHeatIndex(f, h);
  EthernetClient client = server.available();
  if (client) {
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json");
          client.println("Connection: close");
          client.println("Refresh: 0");
          client.println("");
          client.println("[");
          client.println("   {");
          client.println("    \"dht11\": {");
          client.print("          \"temperature\": ");  client.print(f);        client.println(",");
          client.print("          \"humidity\": ");         client.print(h);        client.println(",");
          client.print("          \"heat-index\": ");   client.print(hif);  client.println("");
          client.println("     },");
          client.println("    \"thermistors\": {");
          client.println("        \"under-bed\": {");
          client.print("             \"temp\": ");          client.print(tempreading);      client.println(",");
          client.print("             \"resistance\": ");    client.print(average);  client.println("");
          client.println("       },");
          client.println("        \"side-bed\": {");
          client.print("             \"temp\": ");          client.print(tempreadtwo);      client.println(",");
          client.print("             \"resistance\": ");    client.print(average_two);  client.println("");
          client.println("       },");
          client.println("        \"top-bed\": {");
          client.print("             \"temp\": ");          client.print(tempreadthree);        client.println(",");
          client.print("             \"resistance\": ");    client.print(average_three);    client.println("");
          client.println("       }");
          client.println("     }");
          client.println("   }");
          client.println("]");
          break;
        }
        if (c == '\n') {
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          currentLineIsBlank = false;
        }
      }
    }
    delay(1);
    client.stop();
  }
}

I have no idea what is causing this to happen - pushing RESET doesn't fix it at all, reconnecting wires does not fix it, any help?
(Please tell me what else to include if you need it.)

Your code would help somewhat...

@Majenko - added (ignore any redundancy in the code, i should really clean it up but i'm trying to fix it before i do that)

I suggest you write a function to do the maths. Having multiple lines of redundant code hinders investigations.

@NickGammon I found another piece of code that used different maths, but put it in a function - https://gist.github.com/viktorahlstrom/af1ebe275d54df104bdc

Looks a lot simpler. :)

Here's a major problem:
void loop() {

  uint8_t i;
          float average;
          float average_two;
          float average_three;
          float stuckintime;
          for (i = 0; i < NUMSAMPLES; i++) {
            samples[i] = analogRead(THERMISTORPIN);
            samples_two[i] = analogRead(THERMISTORPIN2);
            samples_three[i] = analogRead(THERMISTORPIN3);
            delay(10);
          }
          for (i = 0; i < NUMSAMPLES; i++) {
            average += samples[i];
            average_two += samples_two[i];
            average_three += samples_three[i];
          }

The variables average, average_two, and average_three have undefined values. Thus it isn't surprising that when you add something to them, they are still undefined.
Local variables must be initialized (eg. to zero in your case).
Also, you have two variables named stuckintime - I would do something about that.

source: Stack Exchange

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

sort: votes


text:
Reducing read time for reading DS18B20 temp sensors
I have a number of temperature sensors connected up to an Arduino - I've split it into 3 sections, with each section having a 2-4 sensors on it (due to distances).   This works, but the code I'm using would seem to me to be very inefficient - particularly with respect of how long it takes to read all the sensors.
I've got 3 code blocks one after each other (which are modified from some code online) which look as below - save, of-course, for the name of the 1wire class.
// Dallas 1 Wire (Main Area):

 //  ds.reset_search();
 //  delay(250);
  while (ds.search(addr))
  {
    for( i = 0; i < 8; i++) {
      Serial.print(addr[i], HEX);
    }

    if (OneWire::crc8(addr, 7) != addr[7]) {
        Serial.println("CRC is not valid!");
        return;
    }

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

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

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

    for ( i = 0; i < 9; i++) {           // we need 9 bytes
      data[i] = ds.read();
    }
    raw = (data[1] << 8) | data[0];
    if (type_s) {
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10) {
        // "count remain" gives full 12 bit resolution
        raw = (raw & 0xFFF0) + 12 - data[6];
      }
    } else {
      byte cfg = (data[4] & 0x60);
      // at lower res, the low bits are undefined, so let's zero them
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      //// default is 12 bit resolution, 750 ms conversion time
    }
    celsius = (float)raw / 16.0;
    Serial.print(":");
    Serial.print(celsius);
    Serial.print(",");
  }

I note that there is a 1000ms delay after each sensor is read, and I'm wondering if I can reduce this to a single 750ms delay for all the sensors.  My initial attempts to do this did not meet with success - but I confess that I can't quite get my head around the ds.reset, ds.select etc - and my initial attempts to do this have all failed.
Is it possible to remove this delay after reading each sensor ?

Which library do you use? This one seems to do 'bulk' reading by default.

Reducing the bit resolution will reduce the time required, however some libraries get the resulting conversion entirely wrong, and need to be repaired if you do this.

After nearly a year and a number of experiments later, I've learned a little bit more about using these devices:
Issuing the sensors a Skip ROM command followed by Convert T command starts all devices converting temperature at once (pg.11 of the datasheet). Then you need only wait one delay period of {750,375,188,94}ms for a {12,11,10,9}-bit conversion, respectively, before you can start reading back the temperatures.
If the devices are being powered parasitically, the bus will need a strong pullup during the conversion; the 4.7KOhm pullup is not sufficient (pg.5 of the datasheet).
An arduino pin can source 40mA and I've found that a second pin directly bypassing the 4.7K pullup without the suggested transistor, will source enough current for at least 3 sensors (as many as I've tried so far) and I assume the technique could be extended to more pins. The strong pullup must be switched on within 10uSec after the Convert T command and kept on for the duration of the conversion. The 10uSec spec pretty much means you have to do this in the library.
I keep an abbreviated DS18B20 library around in which I assume the sensors on the bus are related, so it sets all of their resolutions at once and starts their conversions at once, and assumes that the bus is parasite-powered, which mine are, so it switches a specified pin as a strong pullup. I give up some flexibility that the full DSTemperature library would allow but it satisfies my temperature measuring requirements (so far) and simplifies my application code by black-boxing the above techniques.

Doing a search every time is quite inefficient. The search function is for if you don't know the device address - and it takes a while to do. In your case, presumably the addresses will never change. Find the addresses and hard-code them into your code. Or if that isn't practical, store them in EEPROM. And if even that isn't practical find the addresses once in setup.

Next, you need a delay while you take the temperature readings. Why not parallel those up? In a loop, tell all the devices to take a reading. Then wait one second. Then read them all (in another loop). That way the one-second delay is shared between all your sensors.
However from the page Gerben linked:

And it is NOT possible to run DS1820 sensors on a simple pull-up resistor. During the "Conversion" phase, it needs more power. And there are Application Note discussing this in length.

That suggest that if you are using parasitic power, my suggestion won't work too well (having multiple devices taking readings would make it worse).

I found this code on my disk from a couple of years ago. There don't seem to be any delays between reading sensors. There is a delay at the end of the main loop, mainly to stop spamming the serial monitor.
Notice the comment:

Call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus

See if that works for you.
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Streaming.h>

// Data wire is plugged into port 10 on the Arduino
const byte ONE_WIRE_BUS = 10;
const byte TEMPERATURE_PRECISION = 10;
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// arrays to hold device addresses
DeviceAddress myThermometer [10];
int deviceCount;

void setup(void)
{

  // start serial port
  Serial.begin (115200);
  Serial << "Dallas Temperature IC Control Library Demo" << endl;

  // Start up the library
  sensors.begin();

  // locate devices on the bus
  Serial << "Locating devices..." << endl;
  deviceCount = sensors.getDeviceCount();

  Serial << "Found " << deviceCount << " devices." << endl;

  // report parasite power requirements
  Serial << "Parasite power is: " << (sensors.isParasitePowerMode() ? "ON" : "OFF") << endl;

  // method 1: by index

  for (int i = 0; i < deviceCount; i++)
  {
    if (sensors.getAddress(myThermometer [i], i))
    {
      Serial << "Device " << i << " Address: ";
      printAddress(myThermometer [i]);
      Serial << endl;
      sensors.setResolution(myThermometer [i], TEMPERATURE_PRECISION);
    }
    else
      Serial << "Unable to find address for Device " << i << endl;
  }  // end of for loop

}

// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

void loop(void)
{

  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  sensors.requestTemperatures();

  // now get all temperatures
  for (int i = 0; i < deviceCount; i++)
  {
    float tempC = sensors.getTempC(myThermometer [i]);
    if (tempC > -80)
    {
      Serial << "Device " << i << " Temperature: " << tempC << endl;
    }
    else
      Serial << "Unable to find temperature for Device " << i << endl;
  }  // end of for loop

  delay (1000);
}

Thank you for your answer.  I'm not using parasitic power, but my attempts at doing the readings in parallel failed-  possibly because my C skills are not great and partially because I am having difficulty understanding how the code works - or maybe it just can't be done.   Scanning the sensors on startup may be worthwhile doing at this point, but I deliberately scanned them in each loop so I could "hot plug" changes.

Look in the datasheet for using a "strong pullup" to supply extra current to to parasitically powered sensors. In my devices, I use an extra output port connected so as to bypass the pullup resistor (weak pullup), as a strong pullup. The datasheet shows an output port switching a transistor acting as the strong pullup. In practice, I've found that the port by itself sources enough current for 3 (the max I've tested) DS18b20 devices.

See amended post with another example.

In case the "Temperature Conversion Time (tCONV)" of each resolution is not fast enough ([MAX] 9-bit: 93.75ms; 10-bit: 187.5ms; 11-bit resolution: 375ms; 12-bit: 750ms), you can use more sensors.
For example, to get a half time (for 9-bit): 47ms:

You can use two sensors at the same measurement point, (they can operate in parallel , as long as the software can operate with each one of them) when reading one, the software starts converting the other.

Each one has its normal conversion time, but when doing the readings in an interleaved way, a shorter reading time can be obtained.
For 8 sensors, a time below 11.75ms can be achieved (for 9-bit).

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:
Arduino ,How I can see the value (0 or 5) on my screen, where I connected my sensors output to analog input A0,A1.. pins
I am working in my project and I want to see the output of my sensors as (0 or 5).
The maximum read was 770 and the minimum read was 0. So, how can I see the  value (0 or 5) on my screen, where I connected my sensors output to analog input A0, A1 pins.
I did the following code, but it didn't work:
void setup(){
Serial.begin(9600);
}
void loop()
{
if (analogRead(0)<385)
      Serial.print("0");
 else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(1)<385)
      Serial.print("0");
   else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(2)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(3)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(4)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

if (analogRead(5)<385)
      Serial.print("0");
  else
      Serial.print("5");
      Serial.print('  ');

delay(1500);
}

Note: I have 5 light sensors in my circuit.

Try this code - it should help you see what is going on more clearly:
const int threshold = 385;

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

void loop()
{
  int reading = analogRead(0);
  Serial.print("Analog 0 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  reading = analogRead(1);
  Serial.print("Analog 1 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  reading = analogRead(2);
  Serial.print("Analog 2 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  reading = analogRead(3);
  Serial.print("Analog 3 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  reading = analogRead(4);
  Serial.print("Analog 4 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  reading = analogRead(5);
  Serial.print("Analog 5 reads ");
  Serial.print(reading);
  Serial.print(" - this maps to ");
  if (reading < threshold){
    Serial.println("0");
  } else {
    Serial.println("5");
  }

  Serial.println();

  delay(1500);
}

thanx mr stefandz its working .

Excellent - please mark the question as answered in that case.

but if you can see this code for the same Purpose:
int a0=23;
int a1=24;
int a2=25;
int a3=26;
int a4=27;
void setup(){
Serial.begin(9600);
pinMode(a0,INPUT);
pinMode(a1,INPUT);
pinMode(a2,INPUT);
pinMode(a3,INPUT);
pinMode(a4,INPUT);
}
void loop()
{
Serial.println(a0);
Serial.println(' , ');
Serial.println(a1);
Serial.println('  ');
Serial.println(a2);
Serial.println('  ');
Serial.println(a3);
Serial.println('  ');
Serial.println(a4);
Serial.println('  ');
delay(1500);
}

I have no idea what you are trying to achieve there, but I can tell you that without an analogRead or digitalRead statement in there, you're not going to be reading anything other than the values of the variables you set at the top. If you have a new question, please ask it separately.

You can use DigitaRead command instead of analogread. It will give result in only 1 or 0. Hopefully this will help you.

This will use the microprocessor's internal logic thresholds, not the programmable threshold the original poster requested.

I don't think that's what he requested. He approached like that in his coding. Why should i do all this coding when arduino has its own solution.

From his original question: "the maximum read was 770 and the minimum read was 0". He clearly doesn't have 0 - 5V inputs, and hence his approach is more robust and less prone to error.

Your code has multiple issues.
if (analogRead(1)<385)
      Serial.print("0");
   else
      Serial.print("5");
      Serial.print('  ');

Note that Serial.print('  '); is not at all the same as Serial.print("  ");

Also, by the indentation it looks like you should be using braces. Amended code:
if (analogRead(1)<385)
      Serial.print("0");
   else
      {
      Serial.print("5");
      Serial.print("  ");
      }

Without the braces only the first statement after the else is conditionally executed.
If I am wrong about that, you should indent differently, eg.
if (analogRead(1)<385)
      Serial.print("0");
   else
      Serial.print("5");
Serial.print("  ");


text:
Why does the standard Arduino IDE not include the CH341G USB Drivers?
Can anyone explain why the standard Arduino IDE 1.6 distribution does not include support for the popular CH341G USB/serial drivers?
I am using these USB/serial chips in several teaching projects for CoderDojo and it is somewhat difficult to have each student download the drivers and reboot their PCs for each class. It seems like both Mac and PC users would benefit from having these drivers loaded directly into the standard Arduino IDE.
Is there possibly some security concern? I know that the latest Mac requires that the drivers are digitally signed. In fact for many modern Macs to use the drivers we have to disable the digital signature checks.
Here is the link to the official drivers.
Here is a good article on how to download the drivers.
BTW, the command to disable the digital signature check on the mac we need to do the following:
In the Mac "Terminal" application enter:
sudo nvram boot-args="kext-dev-mode=1"

Then we must reboot the mac. Then when we want to re-enable the checks change the 1 to 0:
sudo nvram boot-args="kext-dev-mode=0"

If we don't do this command, the Arduino App will not show the serial ports. Do to this go to Tools -> Port Menu within the Arduino application.
/dev/tty.SerialPort
/dev/cu.SerialPort

I should mention that the CH340G are also used in many "Arduino Nano" clones from China. Perhaps that is why the drivers are not included?
Tags: Driver CH340 Setup Installation

Because no Genuino uses them.

A question about why the Arduino company does not ship certain drivers would be best addressed to them. We would have no way of knowing why they made that decision.

This is simply because the CH340G is not supported officially. The Arduino IDE is meant primarily for genuine Arduinos.
What you could do is repackage the Arduino zip file with the required library and create a basic script file to install the drivers with just a couple of clicks.
Or you could shift to another board that uses the ATMEGA32u4 as this might not require anything special. Have a look here. I don't have tested this board so you will need to check the quality and whether it works with your projects.

I should mention that the CH340G are also used in many "Arduino Nano" clones from China.

I believe that the Arduino company already has concerns about the number of unofficial clones (many pretending to be genuine) and have lost a considerable amount of revenue to those knock-off products.
I imagine they are not going to make things worse for themselves by including drivers for unofficial boards, so that the job of the clone-makers is even easier.

Remember that Arduino driver is for the USB/Serial chip, not the Arduino Nano devices that included it.  I am not sure it is fair to discriminate against a USB/Serial chip manufacturer just because their chip is preferred by some products.

That is a unique and bizarre interpretation of the word "discriminate". By that definition, Arduino "discriminates" against sound card creators by not including any sound card drivers with their IDE.


text:
Arduino in Eclipse IDE: How to add SPI library (core library already added)?
I want to use eclipse for arduino programming, so I followed the guides to set up a static project for the arduino core library. Then I added the library file (.a) and the .h and .cpp files to my new project in the settings.
So far, so good.
But now I am trying to add the SPI library to my project without success (I only have the .h and .cpp files, no .a)!
My sample code
#include <Arduino.h>
#include <SPI.h>

int main(void) {
    init();
    pinMode(13, OUTPUT);
    for (;;) {
        digitalWrite(13,1);
        SPI.setBitOrder(0);
    }
}

The pinMode and digitalWrite parts work, but with the SPI method I get an error:
05:33:26 **** Build of configuration Debug for project ArduinoTestProject ****
make all
Building file: ../main.cpp
Invoking: AVR C++ Compiler
avr-g++ -I/home/fabio/Workspace/arduinoLIB/SPI -I/home/fabio/Workspace/arduinoCORE -Wall -g2 -gstabs -Os -ffunction-sections -fdata-sections -fno-exceptions -mmcu=atmega328p -DF_CPU=16000000UL -MMD -MP -MF"main.d" -MT"main.d" -c -o "main.o" "../main.cpp"
Finished building: ../main.cpp

Building target: ArduinoTestProject.elf
Invoking: AVR C++ Linker
avr-gcc -s -Os -o"ArduinoTestProject.elf"  ./main.o   -l"arduinoUNO" -l"m" -lm -Wl,-Map,ArduinoTestProject.map,--cref -mrelax -Wl,--gc-sections -L/home/fabio/Workspace/arduinoCORE/lib -mmcu=atmega328p; avr-nm -C -n "ArduinoTestProject.elf" >ArduinoTestProject.symbol
./main.o: In function `main':
../main.cpp:38: undefined reference to `SPIClass::setBitOrder(unsigned char)'
collect2: error: ld returned 1 exit status
avr-nm: 'ArduinoTestProject.elf': No such file
make: *** [ArduinoTestProject.elf] Error 1

05:33:26 Build Finished (took 72ms)

Does anyone see the problem?

Did you tell it to build and link against the .cpp file?

i did not intentionally... I just set configuration values.
How do you tell it to?

Upon makefile and console output analysis I have noticed, that I actually didn't include the library file to be compiled, so the linker doesn't find the object files and exits!

Does that mean the issue is solved?

Not really... But I'm not working in it right now. Should I remove the question or leave it open if I find some time again to work on it?

As far as I understand you are using eclipse CDT directly. (I mean you are not using an "arduino eclipse plugin" that does the stuff below for you)
The first thing to understand is that a arduino library is not treated as a library when compiling a arduino sketch.
In other words in the Arduino IDE, a arduino library is compiled like standard source code just like your .ino files.
As such there is no SPI.a file created during the compilation process.
In CDT you can have both options (with or  without .a file) but the Arduino IDE way is the easiest, by far.
So lets first assume you want to compile the "Arduino way" aka without SPI.a.
What you need to do is simply drag and drop the files in your project. If you want to drop in a subfolder (like libraries/SPI) you will need to add those folders to your include path.
That is all there is to it.
If you want to treat the library as a real library (saying you want a SPI.a) the best thing I can think of is to create a new library project for each sketch-project . Drag and drop the SPI code in that project (like above) and make your project dependent on the library project. There are probably some include path issues but the .a file should be found and included in the build
Note that the second approach makes that you will need a SPI project for each and every (arduino) board you have. If you want to use project defines it is even more difficult.
I would strongly advise to start your arduino eclipse development with my arduino eclipse plugin because it is simply easier. Later you can evolve to the full freedom of CDT.
If you want to drag and drop folders instead of the .h and .cpp files you will have to add exclusion rules to your include path. This because otherwise all the examples of the library will be in your project making you have multiple setup and loop functions.

You assume correctly: I was using only CDT with avr-eclipse. Weird that i have never heard of this eclipse plugin before...? Anyway you answered my question: it is not easy to create static libraries (.a) to link directly to the main code. This was my intention, as I didn't want to drag and drop files into each single project.

Thanks for accepting my answer. I don't know why you haven't heard of my plugin. It has been around for quite some time. I guess I'm bad at marketing ;-)


text:
How to measure the state of charge of a battery in arduino
This questions has been formulated several times with not clear answer, and I wonder if there is one.
it is well stablished from several sources that measuring the voltage of a battery alone is not good indicator of the State of Charge (SOC) of the battery because voltage does not decline proportional to the soc.
Another solution (http://fritzing.org/projects/battery-charge-level/) suggest measuring the voltage (with analogread) between two resistors connected to the gnd and vcc of the circuit (I presume this constantly draw power) and then choose what is the critical voltage of the circuit.
However, my question is how to measure the SOC of a battery using units of 0 to 100% in arduino?

Are you asking about how to make up a circuit with two resistors, or how to convert the analogRead result into a number from 0 to 100%, or something else?

What type of battery/charger? I'm using a Li-Ion (4.2V to 2.75V). By measuring the voltage I can determine the percentage of power left. I actually make it 0 to 100 from around 3.2V, as I don't want people to drain the battery completely (Li-ion rechargable).

I noted that the state of charge of a batery in many graphs I found is shown as percentage values from 0 to 100%. My question is how are those percentage calculated for any given battery? My  guess is that if the batery has let's say 2700 mAh, how much of that is left at any given time, but I am not certain.

The datasheet of the battery gives you a discharge curve. You can e.g. create a lookup table that converts the battery voltage to a percentage of charge remaining based on this graph. As for the voltage divider; choosing large value resistors will make the current lost negligible. Adding a small capacitor could be used to stabilize the voltage if very high resistance values are used. If the battery is connected directly to the AVR chip, you can use the internal bandgap voltage to measure the battery voltage.

THe answer here and here
My answer to the 1st question contains links to "Battery University" which tells what can be achieved and what effort is required.

To do it correctly, you need a coulomb counter. Something like this.
Even that is not fully sufficient, as the charge that can be obtained from a battery depends on various factors, such as temperature and ageing.
More recent batteries have somewhat flat discharge curve, when it comes to voltage, till they run flat, then the voltage drops significantly.
Which means that you would need a very accurate voltage meter.
However the starting point is that you must be able to count how much charge is going in and out.


text:
Timer 2 interrupt with ATmega328p and make measurement in ISR

I am working in my project and i want to use Timer2 interrupt every 100ms to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.
I read in some article that using delay instruction is not as good as using timers'Interruptions so, I tried this code put it didn't work properly :
void setup(){

cli();

  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2  = 0;
  OCR2A = 99;
  TCCR2A |= (1 << WGM21);
  TCCR2B |= (1 << CS21);
  TIMSK2 |= (1 << OCIE2A);
sei();

Serial.begin(9600);
}
void loop()
{
Serial.print(digitalRead(1));
Serial.print(' ');
Serial.print(digitalRead(2));
Serial.print(' ');
Serial.print(digitalRead(3));
Serial.print(' ');
Serial.print(digitalRead(4));
Serial.print(' ');
Serial.print(digitalRead(5));
Serial.println(' ');

}

Where is your ISR?

in fact I dont know where i put the ISR interupt service routine where i have to put measurement instruction .

Enabling the interrupt without writing a ISR is pointless.

i know that but where  in the code i put the ISR?I think i have to put it in the loop

i want to use Timer2 interrupt every 100ms to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5. - your code does not reflect those intentions.

yes i mean i want to see in my screen new measurement every 100ms ,
I don't want to use delay instruction.

I am sorry mr nick put i know more in 8051 cause we use assembly but in arduino it's hard.

Before trying to use an ISR, why not start with simple things?

ISR(TIMER2_COMPA_vect){ ..code here.. }. However with your current setting the ISR gets called once every 0.5ms.

Well let's start from the start ...

Analog readings

to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.

Serial.print(digitalRead(1));

That is not reading analog pin A1, it is reading digital pin 1. If you want to read A1 you need:
Serial.print(analogRead(1));

Check the time
By far the simplest thing would be to simply check the time and take a reading when 100 ms is up.
Example:
void setup()
{
  Serial.begin(115200);
}  // end of setup

unsigned long lastReading;
const unsigned long INTERVAL = 100;  // ms

void loop()
{

  // is time up?
  if (millis () - lastReading >= INTERVAL)
    {
    lastReading = millis ();  // when we took this reading
    Serial.print(analogRead(1));
    Serial.print(" ");
    Serial.print(analogRead(2));
    Serial.print(" ");
    Serial.print(analogRead(3));
    Serial.print(" ");
    Serial.print(analogRead(4));
    Serial.print(" ");
    Serial.print(analogRead(5));
    Serial.println();
    }  // end of if time up

  // do other things here

}  // end of loop

I increased the baud rate to 115200. Why use 9600 when you are trying to print 5 x 4 characters every 100 ms?

Using timers
If you really want to use timers (and I don't see what they achieve here) I have a page about timers that describes using them, and interrupts, in some depth.
The very least you would need is a timer 2 "compare A" interrupt like this:
ISR (TIMER2_COMPA_vect)
  {
  // Timer 2 has reached its comparison value
  }


text:
Connect multiple modules to arduino micro
I have an Arduino Micro and I want to connect an LCD and Bluetooth module to it. The problem I face is that there are not enough power pins for them both.
I understand that I probably need some external power supply for them, but I have no idea how to do this properly.

Just split the wire going from the vcc pin.

You can design/build/deploy a power supply that provides to each board (arduino included) the voltage it needs (but it's advisable to have modules working at the same voltage level) and that should be sufficient.
As long as you have a shared Vcc-to-GND reference, it's enough.
To verify that the power supply you choose is ok, do the following:

check that the modules are compatible with its voltage (ex: all at 5V)
check that the combined power consumption of each module (you get that from the datasheet) is lower than the total power output of the power supply.

Additional checks:

check that the maximum voltage ripple provided by the power supply is lower than what the modules can tolerate
check that the peak current the power supply can provide is larger than the combined peak current of all the other devices.


text:
HC-06 module versus 1sheeld
Why would someone buy a 1sheeld?
Why not connect an Arduino to their smartphone using HC-06 bluetooth module and find an appropriate Android app, like for example RoboRemo. What is the advantage of using a 1sheeld?

What is "1sheeld" when it's at home?

Why would you buy a car when you can cobble something together from some old pram wheels, a lawnmower engine, some old scaffolding, gaffer tape and chewing gum?
Because buying a car is considerably easier and more reliable.  Plus your "friends" don't laugh at you when they see you trying to drive it to work.
Yes, you could cobble something together that might work using random components and other bits of software, but the work involved would be considerably more than plugging in a shield and downloading an app that is guaranteed to work perfectly with that shield.

Giving an equally biased answer as @Majenko, from the other side:
Because they're lazy, they don't know anything about electronics, and they don't want to. And they have more money than they know what to do with.
I am horrified at people shelling out for an "Arduino Temperature Sensor", "Arduino Shift Register", or "Arduino LED", each of which is a generic component soldered on to a board, with pins, at a 1000% markup
I also question the claim that "cobbled together" items are more reliable, or are less likely to have people laugh at you - if you want it to look nice, put it in a nice box (this applies both to "pre-made" items, and to cobbled together).
You will also learn a lot more from making it yourself; you will learn how things work, and you have a better idea and have the opportunity to fix when things go wrong. Your projects will also be a lot smaller.
If you want something that "just works", go buy an ipad. Then, when it doesn't work, throw it in the rubbish and buy a new one. And if you want it to do something it doesn't do, tough luck.

1000% ? The cost of spinning a board, pcba, and all the headaches that manufacturing brings far exceeds the cost of any single component. I would be surprised if people make much money even on  the simple shields. The value in a product like this is 1. Existing API so you don't have to start designing a framework from day 1 just to test an idea 2. Validated Design so you know the components all work together (multiple options for everything under the sun). Even professionals will purchase dev-boards for a huge markup to have some grounding with a device before moving to custom designs.

1,000% markup means the sell price is 11 times the cost price. For example: http://www.jaycar.co.nz/p/XC4230 (NZ$22) is http://www.aliexpress.com/item/New-DS18B20-Temperature-Measurement-Sensor-Module-High-Quality/1887290646.html (US$1.29) with Arduino branding.


text:
Help choosing a servo motor
I am struggling to choose servo motor for my project. There are two servos on ebay. Th First one is named Only "Towerpro micro 9g servo" and the second one that is cheaper is named as a "Towerpro 9g Digital servo".
The Links are:
Servo1: http://www.ebay.in/itm/TowerPro-SG90-9g-Mini-Servo-9-gram-Servo-RC-Robotics-/201386256243?hash=item2ee38e6773
Servo2: http://www.ebay.in/itm/251928442829?aff_source=Sok-Goog
My Problem is that I am confused with the name "Digital Servo". Its cheaper but I a afraid that will it work as normal.
Please help me.
Are both the same product, but with a different name?

Servos are digital by definition.  All you have there is two sellers that are selling the same product, but they are describing them slightly differently.  They are both SG90 servos. They are both digital (they require a digital PWM signal to control them, hence they are digital).
However, here's a little hint: Add the postage costs on to the cost of the servo - you'll see there's not that much difference in price - only 3 rupees between them.  That's about ¢5 or 3p.

On ebay I've seen stepper motors erroneously labelled as servos and real servos labelled as digital servos, to differentiate from the misnamed stepper ones. Usually the price is a good indicator of which is which, but comparing with similar products is the safest bet.


text:
Is it correct to use pulseIn() in ISRs?
Since it is not right to use millis() in an ISR to calculate duration of the input, Is it correct to use pulseIn()?

Why can't you use millis inside and ISR? I don't see why not.

Using millis() inside an ISR is fine. Waiting for its return value to change is not.

@Gerben@Edgar see comments on Nick's answer.

Can you accept my (or someone's) answer please so that this question is not bumped to the top as unanswered every month? Thanks! The page for attachInterrupt has been corrected.

It is quite OK to use millis() or micros() inside an ISR. In fact that is an excellent time to do it, because you are recording the time of the event shortly after it happened. Make sure the variable you are saving it to is unsigned long and volatile. Eg.
volatile unsigned long whenItHappened;
volatile bool eventHappened;

void myISR ()
  {
  whenItHappened = millis ();
  eventHappened = true;
  }

Now in your main loop you can test the eventHappened flag, so you will know if this event has happened, and whenItHappened is when.
It is not a good idea to use pulseIn() because that can wait quite a long time for a pulse. The default timeout for pulseIn is 1 second, which is far too long to wait inside an ISR.
If you want to time something (eg. how long it takes a ball to cross a sensor) use the interrupt twice, once to find the first event, and again to find the second.

Example
Example code which times how long a ball passes a sensor:
const byte LED = 12;
const byte photoTransistor = 2;

unsigned long startTime;
volatile unsigned long elapsedTime;
volatile boolean done;

void ballPasses ()
{
  // if low, ball is in front of light
  if (digitalRead (photoTransistor) == LOW)
    {
    startTime = micros ();
    }
  else
    {
    elapsedTime = micros () - startTime;
    done = true;
    }

  digitalWrite (LED, !digitalRead (LED));
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ("Timer sketch started.");
  pinMode (LED, OUTPUT);
  attachInterrupt (0, ballPasses, CHANGE);
}

void loop ()
  {
  if (!done)
    return;

  Serial.print ("Time taken = ");
  Serial.print (elapsedTime);
  Serial.println (" uS");
  done = false;
  }

That code used micros() for a more accurate timing.

Reference

Interrupts

But the doc page (https://www.arduino.cc/en/Reference/attachInterrupt) says its incorrect : "as delay() and millis() both rely on interrupts, they will not work while an ISR is running."

It also says (higher up the page): Inside the attached function, delay() won't work and the value returned by millis() will not increment. That is my point. millis() won't increment but it will return an accurate figure. I'll raise a bug report about the "will not work" phrase further down the page.

See: https://github.com/arduino/Arduino/issues/3700

You shouldn't really use anything much in interrupts.  Using anything that runs for a period of time is usually bad since no other interrupts can happen at the same time.
It is more normal to use the interrupt to set a flag that is then checked within your main loop to determine what should be done.


text:
Help with LCD's menu and seeing values continuously
I want to see the voltage data using void volt();, when I go to the "Item2SubItem3" within void menuChanged. Now I can only see the data at that time: how can I refresh the value every second?
void setup()
{
    // setup()...
}

void loop()
{
    //loop()...
}

// DC Voltometer
float vPow = 4.7;
float r1 = 100000;
float r2 = 10000;

void volt()
{
    lcd.clear();
    float v = (analogRead(0) * vPow) / 1024.0;
    float v2 = v / (r2 / (r1 + r2));
    lcd.setCursor(0, 0);
    lcd.print("DC VOLTOMETER");
    lcd.setCursor(0, 1);
    lcd.print(v2);
    delay(1000);
}

void menuChanged(MenuChangeEvent changed)
{
    MenuItem newMenuItem = changed.to; // get the destination menu
    lcd.setCursor(0, 1);            // set start position for lcd
                                 // printing to the second row

    if (newMenuItem.getName() == menu.getRoot())
    {
        lcd.print("Main Menu       ");
    }
    else if (newMenuItem.getName() == "Item1")
    {
        lcd.print("Item1           ");
    }
    else if (newMenuItem.getName() == "Item1SubItem1")
    {
        lcd.print("Item1SubItem1");
    }
    else if (newMenuItem.getName() == "Item1SubItem2")
    {
        lcd.print("Item1SubItem2   ");
    }
    else if (newMenuItem.getName() == "Item2")
    {
        lcd.print("Item2           ");
    }
    else if (newMenuItem.getName() == "Item2SubItem1")
    {
        lcd.print("Item2SubItem1   ");
    }
    else if (newMenuItem.getName() == "Item2SubItem2")
    {
        lcd.print("Item2SubItem2   ");
    }
    else if (newMenuItem.getName() == "Item2SubItem3")
    {
        lcd.print("Item2SubItem3   ");
        delay(2000);
        volt();
    }
    else if (newMenuItem.getName() == "Item3")
    {
        lcd.print("Item3           ");
    }
    else if (newMenuItem.getName() == "Item4")
    {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Item4           ");
    }
}

I think it would be easier to answer your question if you try to break down your problem to a smaller piece of code.

menuChangeEvent is only called if the menu is changed. I.e. you moved inside the menu. I don't this the MenuBackend framework supports what you want it to do.

how can i use a menu in order to monitoring sensors?

As Gerben implied in a comment, menuChangeEvent is called only when the menu selection changes.  Thus, your voltmeter readout will print only whenever you change the menu selection to Item2SubItem3.  The code shown below illustrates how to modify your loop() so that it checks the menu selection once per second.  Each second the main loop will do whatever function is currently selected, such as displaying a current voltmeter reading.  Note, you can make the menu decoding shorter and less tedious as shown in the answer, and can put variable declarations near where they are used instead of in random places.
void setup() {
}  // setup()...

// DC voltmeter reading
void volt () {
  const float vPow = 4.7, r1 = 100000, r2 = 10000;
  lcd.clear();
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = v / (r2 / (r1 + r2));
  lcd.setCursor (0,0);
  lcd.print("DC Voltmeter");
  lcd.setCursor (0,1);
  lcd.print (v2);
  // Don't delay(1000) since loop() takes care of delay.
}

long int second = 0;
uint8_t itemcode = 0; // Will be number nm for Item n, Subitem m
int passnumber = 0;
void menuChanged(MenuChangeEvent changed) {
  MenuItem menuitem = changed.to; //get the destination menu
  String itemname = menuitem.getName();
  lcd.clear();        // Make printing spaces at line ends unnecessary
  lcd.setCursor(0,1);         //set lcd printing position = second row
  if(newMenuItem.getName() == menu.getRoot()){
    lcd.print("Main Menu");
    itemcode = 0;
  } else {
    lcd.print(itemname);
    itemcode = 10*(itemname[4] & 7);
    if (itemname.length() > 5)
      itemcode += itemname[itemname.length()-1] & 7;
  }
  passnumber = 0; // Actions can test passnumber if they like
  second = 0; // Cause actions to take place now
}

void loop() {
  long int now = millis()/1000; // Get elapsed-seconds
  if (now == second) return;    // Only do stuff once per second
  // Update to current second and do chosen menu item
  second = now;
  switch (itemcode) {
  case  0: break;
  case 10: break;
  case 11: break; // Fill in with code for different cases
  case 12: break;
  case 20: break;
  case 21: break;
  case 22: break;
  case 23:    // Item 2, subitem 3, read voltmeter
    volt();
    break;
  case 30: break;
  case 40: break;
  }
  // You can test passnumber to control for cases that only go once
  ++passnumber;
} // end of loop()

Edit: I moved the declaration of second and added second = 0 within menuChanged() to decrease latency between a menu item being selected and its action taking place.  Without second being zeroed in menuChanged(), up to a second could pass between an item's selection and its action; latency would average 0.5 seconds, which is undesirable in a user interface.


text:
Help Connecting Arduino Uno To Computer
I am A Newbie to Arduino
I have a Windows 7 PC. Last Time I bought an Arduino Uno Clone but after working for a day, it stopped detecting on the port. So I bought a new Clone Of different brand. Now I Want in which sequence should I install its drivers, Coonect it, Unzip Arduino IDE...Reboot??
I dont want a problem this time. Another question is Should I first connect the clone and then Install its drivers Or first install drivers and then plug the board? When Is the reboot required?
Product Link : https://m.ebay.in/itm?itemId=121708881208
Please Explain...
Thanks In Advance

Tip: Don't buy an "Arduino" from someone that can't even spell "Cable".

In $US, they are selling it for $7.64. This is indeed cheap. In english, there is a phrase; You get what you pay for. This means in this context, you are paying for low quality. If you can, try to but the real thing.

I have shorted my bords a few time and they always came back to "life" after a minute. Maybe you should be more concern about the voltage you supply to the board. Even if it can take up to 12 volt I never use more then 9 volt on the board. And if you run motors on them its always good to supply them with an external power source and use something like a H bridge to power your devices. I made mistakes and my board are still in mint conditions.

I would like to start by pointing out that you are using a clone. The arduino IDE by default does support clones. Just install your port drivers that's far enough.
The reason your board got spoilt the last time definitely was not cause you did not install the drivers in the right order. It could be due to many reasons, few listed below:

Poor PCB quality
Humidity
Cheap USB to UART converter.
Short circuit in your connection

So what I recommend is the either the use of genuine arduino boards if you can afford.
Note: Most likely its only the USB to UART (CH340G) that has been destroyed, you could buy a hot air station and replace the IC, it is a much cheaper solution.

The clone Uno probably cost $5. A hot air station would be more likely to be 10 to 20 times that much, plus you would need the replacement chip and considerable skill to change it over.

@NickGammon You do have a point, the only reason I recommended him to replace the IC was since he was getting into electronics he might as well learn to replace an IC. While we are here, have you had any experience with clones as to why the USB to UART chip tends to get fried easily?

No, I don't know that. Possibly they are manufactured "on the cheap" and have lower tolerances. It might save a hundredth of a cent to omit, for example, protection diodes. It seems to work, people buy it, and you can always blame "user error".

I bought an Arduino Uno Clone - strictly speaking it should be a "Xxxx brand: (Arduino-compatible)". There is only one Arduino Uno, and that is the official one made by Arduino. According to the Arduino FAQ "Arduino" is a trademark of Arduino LLC and should not be used for unofficial variants.. If you mentioned the brand in your question, it might help other people's buying decisions in the future.

I just checked the link and the item is not available anymore. That way it is impossible to say which driver you should install.
I agree with the answers and comments so far, get the real board. I've heard of people who fried their USB ports because of Arduino clones and their terrible/absent circuit protection.
If you can't afford the original board, what will you do if it damages your computer?


text:
Integrating an analog signal using Arduino Due
I have an 2 analog signal, and I want to calculate the difference between 2 signals (A0 and A1), then integrate an analog, but it doesn't work (I just started studying Arduino).
Please could you show me how to deal with this problem?
Thanks a lot
float analogInPin = A0;
float analogInPin1 = A1;
float analogOutPin = DAC1;
float FeqIn, FeqIn1, FeqIn2, FeqIn3, FeqOut, w, Triarea, Recarea, area, n, y, t;

void setup() {
  Serial.begin(9600); // use the serial port
}

void loop() {
  FeqIn1 = analogRead(analogInPin);
  FeqIn2 = analogRead(analogInPin1);
  FeqIn3 = FeqIn1 - FeqIn2
  // integration
  area(1) = 0;
  y(1) = 0;
  for (n = 1; n = t; t++) {
    Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));
    Recarea(n+1) = t(2)*(FeqIn3(n));
    area(n+1) = (Triarea(n+1) + Recarea(n+1)) + area(n);
  }
}

The error message is:
Arduino: 1.6.5 (Windows 8.1), Board: "Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

_02.ino:3: error: 'DAC1' was not declared in this scope
_02.ino.ino: In function 'void loop()':
_02.ino:20: error: expected ';' before 'area'
_02.ino:21: error: 'y' cannot be used as a function
_02.ino:24: error: 'Triarea' cannot be used as a function
_02.ino:24: error: 't' cannot be used as a function
_02.ino:24: error: 'FeqIn3' cannot be used as a function
_02.ino:24: error: 'FeqIn3' cannot be used as a function
_02.ino:25: error: 'Recarea' cannot be used as a function
_02.ino:25: error: 't' cannot be used as a function
_02.ino:25: error: 'FeqIn3' cannot be used as a function
_02.ino:26: error: 'area' cannot be used as a function
_02.ino:26: error: 'Triarea' cannot be used as a function
_02.ino:26: error: 'Recarea' cannot be used as a function
_02.ino:26: error: 'area' cannot be used as a function
'DAC1' was not declared in this scope

Please copy and paste your actual code into your question (edit the question to do this) - not a screen shot of it. Then we are in a position to test it ourselves, or to amend it and post the amended code.

You tagged this question with arduino-uno and arduino-due. Which one is it? They are not the same thing.

Now please post the error messages which I can just see a tiny bit of in the screen shot. area(1) = 0; - what is that supposed to be doing?

I think your main problem here is a fundamental lack of understanding about C++.  There's numerous basic errors in your code.  Let's take a look at them:
FeqIn3 = FeqIn1 - FeqIn2

All C++ statements must be terminated by a ; otherwise it doesn't know where one statement finishes and the next one begins.
area(1) = 0;
(and many others)

You have declared a bunch of float variables in the global scope.  You are then trying to use those float variables as functions, and on top of that you are then trying to assign a value to the return value of that function.  That makes absolutely no logical sense whatsoever.
I think you meant to be using arrays of float values.  Arrays are denoted by [ and ] not ( and ).  Further, they have to be defined as arrays, including the size of the array, not a single value.  Also in C++ arrays are zero based (i.e., they start at index 0 not index 1).
For example, area could be defined as:
float area[1024]; // 1024 floating point values in an array
// ...
area[0] = 0;

Next:
Recarea(n+1) = t(2)*(FeqIn3(n));

I don't even know what to make of this bit...  If I assume you should replace (...) with [...] for indices to arrays, it still makes no sense.  You're calculating a single value (FreqIn3 = FreqIn1 - FreqIn2) then using that as an array (FreqIn3[n]) which makes absolutely no sense to me at all.  Then you're using another value t which you are incrementing (incorrectly, more on that later), which again you are then trying to use as an array (t[2]).  Which is it - arrays or single values? And how do you increment an entire array?
Now the incrementing:
for (n = 1; n = t; t++)

n starts at the value 1.  While n is assigned the value t, increment t.  Now, does that sound logical?  And what is t? when that loop starts?  It has no defined value, so it could be anything at all.  And when does the loop end?  Well, since you're using float values for your counters (which is idiotic at best) you won't ever get any integer wraparound, so t will never equal 0 and consequently the result of assigning t to n will never be 0, so the loop will never end.
I think you need to go back to absolute basics and learn a bit more about syntax of C++, arrays, functions, loops, etc, before embarking on something complex like signal integration.

float FeqIn, FeqIn1, FeqIn2, FeqIn3, FeqOut, w, Triarea, Recarea, area, n, y, t;

...

      Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));

I honestly don't know what you are doing here.
Triarea is a float, right? A single variable of type float.
What is this?
      Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));

Triarea(n+1) looks like you are calling a function called Triarea with the argument n+1.
That doesn't make any sense because it isn't a function.

Maybe you mean to treat it as an array?
  Triarea[n+1] = (0.5*t[2])*(FeqIn3[n+1] - FeqIn3[n]);

But you have not declared those variables as arrays.
It is pure guesswork what is going on in your mind.
However your syntax certainly explains the error messages, for example:
_02.ino:24: error: 'Triarea' cannot be used as a function

If I may suggest, read a tutorial on basic C++ programming.

As previous answers have pointed out, your understanding of C syntax has shortcomings, and you should study C further.  Besides those syntax issues, you may need to revise some of your concepts of how to program.
Firstly, the references you looked at regarding integration may have shown forms like Tₓ₊₁ = (δ/2)·(Vₓ₊₁ – Vₓ) for “triangle area” and Rₓ₊₁ = δ·Vₓ for “rectangle area” [where I've written δ in place of your t(2)].  In spite of the use of subscripts in these formulas, the array concepts mentioned in other answers are not relevant here.  Instead of saving voltage data in arrays, just save and work with two voltage values:  the current differential voltage reading and the previous differential voltage reading.  Letting Vᵣ and Vₓ stand for previous and new voltage differences, use Vᵣ where Vₓ is called for, and Vₓ where Vₓ₊₁ is called for.  At the end of each step, set Vᵣ = Vₓ.
Secondly, making separate computations of “triangle area” and “rectangle area” is verbose, unnecessary, and less accurate than a properly combined computation.  Note that Tₓ₊₁ + Rₓ₊₁, as used in computing areaₓ₊₁, is equal to  (δ/2)·(Vₓ₊₁ – Vₓ) + δ·Vₓ = (δ/2)·Vₓ₊₁ – (δ/2)·Vₓ + δ·Vₓ = (δ/2)·Vₓ₊₁ + (δ/2)·Vₓ = δ·(Vₓ₊₁ + Vₓ)/2.  Thus, instead of those three lines of code using two temporary variables and lots of indices, use code like the following for the integral:
area += deltaT*(Volt_r + Volt_s)/2;
Volt_r = Volt_s;

(In the above, Volt_s corresponds to your FeqIn3 value.)
Thirdly, your attempted for loop needs to be replaced by an actual for loop; and in addition, deltaT, a time-step delta, needs to be computed.  (Your t(2) needs to represent a change in time, not an absolute time, to represent the time-width of the rectangle and triangle you are adding to the total.)  To get a deltaT, read millis() after the analogRead lines.  For example, you could say:
Volt_s = analogRead(analogInPin) - analogRead(analogInPin1);
t_s = millis();
deltaT = t_s - t_r;
area += deltaT*(Volt_r + Volt_s)/2;
t_r = t_s;
Volt_r = Volt_s;

Fourthly, using two analogReads to get a differential voltage has two problems:  first, any common-mode voltage wastes bits of ADC resolution, so contributes to error; second, the two reads occur at different times so their voltages are not comparable.  Instead, you could use an external op-amp to subtract voltages, or could use the Due's differential-front-end ADC mode, per Section 43.6.8, Differential Inputs, on page 1326 in the ARM Cortex M3 Processor manual, plus possibly a gain of 1, 2, or 4 (per Section 43.6.9).  Also see: Analog performance ... of Due's 12 bit ADC (including how to speed up analogReads on the Cortex), Differential Sensing with Arduino, Setting ADC compare mode in a differential input, and Due pinout diagram.


text:
Arduino Uno vs Arduino Micro timers → pins
Where do I find the pins relative to timers of each individual Arduino microcontroller?
As I like Arduino's I already have various samples of them. The one I mostly use is the Uno and Micro for now... I'm planning to also get a Mega and others. Most simple things work on all devices, but if you start with complex code to fasten up things, every device is a little different.
A problem I could not solve for days now is the relation between pins and timers.
I cannot find any information about the Arduino Micro. I also don't know exactly what the proper keywords are that I need to find the relation between timers and pins.
Example:
A PWM driver multiplexing
As I for now just got some stuff from my local dealer I have no access to shift registers, PWM drivers and other proper integrated circuits.
So I used the Arduino as a PWM driver for 8 RGB or 24 (3*8) white LEDs.
The code works on Arduino Uno. But as the Arduino Micro has no Timer2, TCCR2B, I cannot use the same code on the Arduino Micro.
Even if I understand the code (I wrote a lot in other languages...), some of the Atmel chip specific parameters are not clear.
This function sets the prescaler of the timer:
void setPwmFrequency(int pin, int divisor){

  byte mode;
  if(pin==5||pin==6||pin==9||pin==10){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 64:mode=0x03;break;
      case 256:mode=0x04;break;
      case 1024:mode=0x05;break;
      default:return;
    }
    if(pin==5||pin==6){
      TCCR0B=TCCR0B&0b11111000|mode;
    } else{
      TCCR1B=TCCR1B&0b11111000|mode;
    }
  }else if(pin==3||pin==11){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 32:mode=0x03;break;
      case 64:mode=0x04;break;
      case 128:mode=0x05;break;
      case 256:mode=0x06;break;
      case 1024:mode=0x7;break;
      default:return;
    }
    TCCR2B=TCCR2B&0b11111000|mode;
  }
}

First of all, I probably don't even need this function as soon I know what frequency I want, and so I probably need only two lines to set my three (RGB) pins.
//Arduino Uno timer setup for pin 9, 10, and 11
TCCR1B=TCCR1B&0b11111000|0x01; // Pin 9,10
TCCR2B=TCCR2B&0b11111000|0x01; // Pin 11

Correct, I need to set TCCR1B only one time?
What does the 0b11111000 refer to?

In the setup function there is also this line:
TIMSK2 = 1<<TOIE2;

What does this do?

While the above three questions are not so important until it works, I need to understand how I can convert those timers to work with Arduino Micro, but also later with other Arduino boards.

On Arduino Micro
There is no timer 2
Do pin 9, 10, and 12 have the same timer?
??????=??????&0b11111000|0x01;

Also if I understand correctly the Arduino Micro has:

A higher PWM range 1024 vs 255 (UNO)??
A much higher frequency available in on Timer4 only for pin 13

So is there somewhere a table describing the differences between all Arduino timers?
Full working (on Arduino Uno) code.
unsigned char Prescaler=0;
unsigned char CurrentLED=0;
unsigned char LEDValues[8][3];
unsigned char ports[8]={
  0b00000100,
  0b00001000,
  0b00010000,
  0b00100000,
  0b01000000,
  0b10000000,
  0b00000001,
  0b00010000
};//PINS 2,3,4,5,6,7,8,12

#define PrescalerOverflowValue 4

ISR(TIMER2_OVF_vect){
  if(Prescaler<PrescalerOverflowValue){
    Prescaler++;
  }else {
    Prescaler=0;
    Multiplex();
  }
}

void Multiplex(void){
  PORTD&=0b00000011;
  PORTB&=0b11101110;
  analogWrite(9,255-LEDValues[CurrentLED][0]);
  analogWrite(10,255-LEDValues[CurrentLED][1]);
  analogWrite(11,255-LEDValues[CurrentLED][2]);
  CurrentLED<6?(PORTD|=ports[CurrentLED]):(PORTB|=ports[CurrentLED]);
  CurrentLED++;
  if(CurrentLED>7)CurrentLED=0;
}
void setPwmFrequency(int pin, int divisor){
  byte mode;
  if(pin==5||pin==6||pin==9||pin==10){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 64:mode=0x03;break;
      case 256:mode=0x04;break;
      case 1024:mode=0x05;break;
      default:return;
    }
    if(pin==5||pin==6){
      TCCR0B=TCCR0B&0b11111000|mode;
    }else{
      TCCR1B=TCCR1B&0b11111000|mode;
    }
  }else if(pin==3||pin==11){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 32:mode=0x03;break;
      case 64:mode=0x04;break;
      case 128:mode=0x05;break;
      case 256:mode=0x06;break;
      case 1024:mode=0x7;break;
      default:return;
    }
    TCCR2B=TCCR2B&0b11111000|mode;
  }
}

void setup(void){

  pinMode(2,OUTPUT);//1
  pinMode(3,OUTPUT);//2
  pinMode(4,OUTPUT);//3
  pinMode(5,OUTPUT);//4
  pinMode(6,OUTPUT);//5
  pinMode(7,OUTPUT);//6
  pinMode(8,OUTPUT);//7
  pinMode(12,OUTPUT);//8
  pinMode(9,OUTPUT);//red
  pinMode(10,OUTPUT);//green
  pinMode(11,OUTPUT);//blue
  setPwmFrequency(9,8);
  setPwmFrequency(10,8);
  setPwmFrequency(11,8);
  TIMSK2=1<<TOIE2;
}

void loop(void){
  for(int i=0;i<8;i++){
    //LEDValues[i][0]; // Red
    //LEDValues[i][1]; // Green
    //LEDValues[i][2]; // Blue
  }
}

I cannot find any information about the arduino micro. I also don't know exactly what the proper keywords are that i need to find the relation between timers and pins.

Go to the products page for the Micro on the Arduino web site. You will find that the processor is the ATmega32U4.
Download the datasheet for the ATmega32U4 - it's on that page.
Download the reference schematic for the Micro - also on that page.

Now we know the processor, the datasheet tells you about the timers, and the schematic tells you which ATmega32U4 pins are connected to which pins on the Micro board.

But as the Arduino Micro has no Timer2 TCCR2B i cannot use the same code on the Arduino micro.

True. But it has Timer 1, Timer 3 and Timer 4. You just need to adjust the registers a bit.

Correct, I need to set TCCR1B only one time?

Yes you can do that. Personally I normally stop the timer and then set the parameters in case setting them when it is running has a different effect. eg
TCCR1A = 0;  // stop timer 1
TCCR1B = 0;
TCCR1C = 0;

   TCCR1B=TCCR1B&0b11111000|0x01; //pin 9,10

What do the 0b1111000 refer to?

In this case the first part TCCR1B & 0b11111000 clears the low-order 3 bits (the rest are ANDed in with 1 so they stay the same as before).
Then it sets the lower-order bit. In this particular case you are setting up a prescaler of 1 times the clock rate.

   TIMSK2=1<<TOIE2;

what does this ?

TIMSK2 is a timer register.

By shifting 1 left "TOIE2" bits it sets that bit (ie., TOIE2 in TIMSK2).
In other words, it enables the overflow interrupt for Timer 2.

On Arduino Micro
  There is no timer 2
  Pin 9,10,12 have the same timer ?

Look at the reference schematic. Yes it looks like it.

As you can see from that pin 30 (on the chip) is labelled OC4B which means it is the "output compare timer 4: B output". That pin has the net name "IO10*" which I presume means it is connected to board pin 10 (pin 30 on the chip).

Also if I understand correctly the Arduino micro has:

a higher PWM range 1024 vs 255 (UNO)??
a much higher frequency available in on timer4 only for pin 13

No, the Uno has Timer 1 which is 16 bits (up to 65536). The Micro has Timer 4 which is 10 bits and therefore can count up to 1024.
Anyway, the frequency is a function of the clock speed. On either chip, by using a prescaler of 1, and counting up to 1, you can get an 8 MHz frequency (one up, one down from 16 MHz).
The higher number of bits in the timer, the finer the resolution - that is you can adjust the frequency in finer steps, and you can adjust the PWM duty cycle in finer steps.
However with Timer 4 on the Micro you can, apparently, clock it with 6 times the clock rate (96 MHz) which is used for the USB part of the chip. Setting appropriate bits (I haven't done this personally) you could get that higher frequency.
You can apparently get 96 MHz, 64 MHz or 48 MHz clock frequencies on Timer 4 (as well as the normal ones).

Added in response to comments

Pin 12 on the chip has 2 timers, OC0A & OC1C??

Yes, from the datasheet:

The Output Compare unit 1C and Output Compare unit 2 shares the PB7 port pin for output. The outputs of the Output Compare units (OC1C and OC0A) overrides the normal PORTB7 Register when one of them is enabled (i.e., when COMnx1:0 is not equal to zero). When both OC1C and OC0A are enabled at the same time, the modulator is automatically enabled.

What timer do i need to use for let's say pin 9,10,12 on arduino micro?

Looks like Timer 4.

in arduino ide i can only write analogWrite(255)

That is changing the PWM duty cycle for the timers configured in their default way.
Have a look in wiring.c:
// timers 1 and 2 are used for phase-correct hardware pwm
// this is better for motors as it ensures an even waveform
// note, however, that fast pwm mode can achieve a frequency of up
// 8 MHz (with a 16 MHz clock) at 50% duty cycle

analogWrite changes the duty cycle, not the frequency.

You can apparently get 96 MHz... so at the end arduino micro can go faster on timer 4

I'm not sure what you mean by "go faster" here.

but I actually did not solve the problem. I hope you give me a hint to how to make it work.

It isn't clear really what you want to happen.

What devices are you driving?
Why do you need high frequencies?
What is the underlying problem?

Reference

Timers and counters - mainly about the Atmega328P, however a lot of it applies to the other chips as well.

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

You can check pins_arduino.h file as well.
// ATMEL ATMEGA32U4 / ARDUINO LEONARDO
//
// D0               PD2                 RXD1/INT2
// D1               PD3                 TXD1/INT3
// D2               PD1     SDA         SDA/INT1
// D3#              PD0     PWM8/SCL    OC0B/SCL/INT0
// D4       A6      PD4                 ADC8
// D5#              PC6     ???         OC3A/#OC4A
// D6#      A7      PD7     FastPWM     #OC4D/ADC10
// D7               PE6                 INT6/AIN0
//
// D8       A8      PB4                 ADC11/PCINT4
// D9#      A9      PB5     PWM16       OC1A/#OC4B/ADC12/PCINT5
// D10#     A10     PB6     PWM16       OC1B/0c4B/ADC13/PCINT6
// D11#             PB7     PWM8/16     0C0A/OC1C/#RTS/PCINT7
// D12      A11     PD6                 T1/#OC4D/ADC9
// D13#             PC7     PWM10       CLK0/OC4A
//
// A0       D18     PF7                 ADC7
// A1       D19     PF6                 ADC6
// A2       D20     PF5                 ADC5
// A3       D21     PF4                 ADC4
// A4       D22     PF1                 ADC1
// A5       D23     PF0                 ADC0
//
// New pins D14..D17 to map SPI port to digital pins
//
// MISO     D14     PB3                 MISO,PCINT3
// SCK      D15     PB1                 SCK,PCINT1
// MOSI     D16     PB2                 MOSI,PCINT2
// SS       D17     PB0                 RXLED,SS/PCINT0
//
// TXLED    D30     PD5                 XCK1
// RXLED    D17     PB0
// HWB              PE2                 HWB

There is an array inside the same file with name  digital_pin_to_timer_PGM that list the timers also.
const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    TIMER0B,        /* 3 */
    NOT_ON_TIMER,
    TIMER4A,        /* 5 */
    TIMER4D,        /* 6 */
    NOT_ON_TIMER,

    NOT_ON_TIMER,
    TIMER1A,        /* 9 */
    TIMER1B,        /* 10 */
    TIMER0A,        /* 11 */

    NOT_ON_TIMER,
    TIMER4A,        /* 13 */

    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,

    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
};


text:
Using L239D with a joystick
Im making a small, controllable toy car. Im using the L239D motor controller to drive 2 6V DC motors, which I intend to control with a joystick. Using the L239D state table (shown below), I can make the car move forward, backward, left and right.
Thats all good, but I want the car to do all the bits in between those movements (drifting slightly left/right etc depending on joystick location). So far I have two separate functions that look at the x-axis and y-axis value from the joystick, scale them and apply a pwm signal. This works fine when only one function is on but ofcourse, they overwrite each other.
My idea then was to create a variable that takes the displacement of the joystick in both axis and divides them, this will be the duty cycle. I then have a delay at the end of each loop which is sized by this duty cycle. The only problem is that the motor stutters a lot and it dosent work very well at all.
I was wondering if anyone has a better idea for getting full motor control with the joy stick rather than the simple block movements (full right, full left, full forward, full backward). Thanks!

Please look at the chip on the driver board and verify the number on it.  The usual L239 is a diode, while the usual L293 is a driver (with 4 half-H-bridges, making 2 H-bridges).  If the chip is indeed L293 instead of L239, please edit your question and fix the number all thru.

Ah sorry, Im pretty sure out of the two people could guess what I'm on about anyway just through common sense

Did you look at the chip and figure out the number?  Please fix the question if the question is wrong.

The problem here is that you lack the concept of speed with your motors.
It's not enough to turn the motors on or off in the right direction, you have to control the speed of them.
Your left/right control is fine as it is (without the delay in your loop), which is controlled by the inputs being either on or off to define the flow of current through the motor.  Now all you need to do is control the speed of the motors while they are in those states.
Fortunately there is another pair of inputs to the driver chip that you have completely overlooked: ENABLE1 and ENABLE2.  These can accept a PWM signal and define the ratio of on-to-off for the motor on that channel.
So you can connect a PWM signal to each of those inputs (all the other inputs are just straight digital ON/OFF signals), and setting the duty cycle of those PWM signals defines the speed of the motor (0 = stop, 255 = full speed).
Now all you need to do is interpret the joystick properly, for instance:

Between centre and half-left: Left = Stop, Right = Forward, Enable Right = percentage of half the joystick range
Between half-left and full-left: Left = Reverse, Right = Forward, Enable Right = 100%, Enable Left = percentage of half the remaining joystick range

And of course reversed for right turns.
You could incorporate into that the forward/backward position of the joystick to add an overall forward or backward speed to the motors so you have full 2D motion.
It may be better to visualise the joystick in Polar space instead of simple Cartesian space.  Convert the X/Y coordinates of the joystick's position into an angle and distance from the centre point.  The distance defines the overall speed, and the angle defines how that speed is split between the left and right motors (enable pins), and the direction of those motors (input pins).

Brilliant. You knew exactly where I went wrong. I decided to create a series of if statements with flags that dictated which pins to set digitally. I then created a value that was the maximum displacement of both axis (0 to 255, whichever axis is bigger) and applied that value as a PWM signal to the enable lines. Works perfectly!


text:
Sending joystick data via bluetooth
Joysticks usually have two outputs, one for the x-axis and one for the y-axis. Most of the bluetooth modules I have found only have one tx line.. Is there a way to set them up to use one bluetooth module to connect to arduino?
Im thinking of buying another but I'm wondering if anyone has a better idea than this, or if what I'm thinking is even possible.
Thanks!

What joystick? What bluetooth module?

Unless you have a very special joystick and a very special bluetooth module you can't just connect a joystick to the TX pin of a bluetooth module.
Instead you have to have the joystick (I am assuming a 2D analog joystick) to a pair of analog inputs on (for instance) an Ardiuno, which then samples the analog values.  It is then up to you to decide what you do with that sampled data - in your case you want to send it out via serial to the bluetooth module (I assume something like a HC-05 or HC-06).  What that data is, and how you interpret it, is up to you.
You could send the data as plain text, such as:
512,512
512,512
384,512
229,512
83,512
83,938
82,1012

Each line specifies a pair of analog values and is terminated by a line-feed.  The receiving end then needs to read each line, split it on the ,, and interpret the two values as X/Y readings.
That's quite inefficient, though, and there are better "binary" methods that use less bytes to send the readings, but that is more advanced.

So your joystick is sending bt signals?
If you can't find an appropiate data sheet to that i advise you link it with your pc, start hterm and analyse what exactly is sent.(requires to link the bt devices)
If your joystick is not able to out bt signals I'm not sure what you are trying to do there and need more info
PS: I already did the following: control a robot with your smartphone via bt
control a robot with an old ps2 joystick via cable


text:
What minimum equipment is needed to program the Freematics Vehicle Data Logger?
I was looking for a GPS/OBD2 data logger that logs data to an SD card and eventually arrived at the Arduino powered Freematics Vehicle Data Logger. It's great that it's programmable, but I have no experience with Arduino.
Reading the documentation, it says that I program the device either by USBasp or Arduino as ISP. The USBasp is a dongle programmer, but I don't know what is meant by Arduino as ISP.
My goal is to use this device to log data. I don't plan to extensive write programs for it. What is the minimum equipment that I need to have in order to be able to write a bit of code and flash it to the device?

"Arduino as ISP" refers to using an Arduino board in place of a USBasp.  It involves loading a specific sketch onto the Arduino then using the SPI port (and a few other pins) as the programming interface to the target.
It is most often used to program blank chips for use in breadboards by people who don't have a USBasp.  Great for moving your project from the Arduino board to a breadboard without having to buy a hardware programmer.


text:
Fast Python to arduino communications
I've been communicating with a teensy arduino over USB using pySerial--which has been simple, but slow. With simple write commands from Python and a corresponding read command on the teensy, I can only achieve 200kHz transfer rates. I'm hoping to get over 1MHz at least, but I don't see a path towards that rate.
Are Ethernet shields capable of augmenting for rates over the MHz range? How can I get faster data transfer rates between my computer and arduino? I'm mainly interested in one-way communications (computer directs teensy).

You can't communicate faster than the MCU can respond.

@ignacio what is the MCU?

With simple write commands from Python and a corresponding read command on the teensy, I can only achieve 200kHz transfer rates. - is this serial comms we are talking about? What are you planning to do with the Teensy that it needs to be told to do something at 1 MHz?

I'm configuring hundreds of analog nodes over SPI buses.

@nick_name the MCU is the microcontroller unit. The brain. That black square-shaped plastic thing on the Teensy with all the little legs. On the Teensy 3.1 it's the MK20DX256, part of the Freescale K20 series, if you need to know. It can run at up to 96MHz (on the Teensy), so receiving data at speeds in MHz+ won't be a problem.

The fastest means of communicating with the Arduino is SPI. Ethernet shields use that (as do SD cards). It's quite fast, but it has limits. The fastest the SPI clock can go is the CPU (MCU) clock rate divided by 2 (per bit), that is one byte every 16 CPU clock cycles. There is also an overhead of a couple of clock cycles between bytes, so you can reckon on 888,888 bytes absolute maximum (ie. about 868 kHz) on an Arduino running at 16 MHz.
However that's just throwing the data away. It needs to be stored somewhere, compared to something, acted upon. That all takes clock cycles.
That is for the 16 MHz Arduinos. The Teensy 3.1 apparently runs at 72 MHz which is somewhat faster. I haven't timed SPI on that, presumably you can get a faster transmission rate, but I suspect that the ARM processors also take more instructions to do the same thing, so the 72 MHz might not be quite as fast as it looks.
Then you have the issue of how fast you can get data in and out of the Ethernet card, and how fast you can do whatever-it-is you want to do with it, in the processor.

Thank you for the detailed response! Right, so an Ethernet shield using an SPI interface is going to be best then. I'm curious--does the Ethernet transmission protocol that would link the computer and arduino support these rates, or would I be bottlenecked there?

I can't really answer that. It would depend on the Ethernet card, the library driving the card, quite possibly what your router can handle, and what the PC Ethernet card can handle. Plus, of course, the speed of communication between the Arduino and the Ethernet card, and how much time you spend doing something with the data once you get it.

First of all, khz and mhz are not data transfer rates. They are frequencies - "something per second" - did you mean kilobits/second or kilobytes/second (both, confusingly, abbreviated to kbps by various people).
If you have not already done so, you can specify a bitrate for your communications - serial.begin takes a parameter which specifies the speed - most example seem to use 9600 bits/second, you can crank this all the way up to 115,200 bits/second - 12 times the speed. I don't know if this will work with a Teensy, and/or USB. You will probably at least need to specify this in your terminal program and/or pySerial.
I wonder what you are doing that requires 1Mbyte/second communication with an Arduino, and if you can do that a little smarter?
At that rate, the 64kbytes of memory can be filled up in 1/16th of a second.
You can get a faster "information transfer" by increasing the information density - for example, the English word "True" takes up 4 characters = 32 bits , but a logical true value only takes up 1 bit.
If you are processing the data on the Arduino, at 1mbyte/second, you have 72 instructions to do something with that byte before the next one is there - not much time.
You could increase the data rate by pushing the data in in parallel, using multiple pins - e.g. 32 bits in parallel, one on each of 32 pins, one data point per cycle. There would be no practical way to assimilate data at that speed.
If you are sending this from a PC, perhaps some of the data could be processed on the PC before sending?
Another option would be to divide the work over multiple Teensies, with the PC combining the work - e.g. if you have temperature sensors that output 4 byte values, you want to read 250 of them at a rate of 1000 samples per second (= total of 1mbyte/second), then you might be able to run 25 Teensies, each sampling 10 sensors, and each pushing data at 40kbytes/second, rather than one running at 1mbyte/second.
Quite frankly, these are all fairly contrived examples - most sensors can't be read that quickly; even an Arduino's analog read is limited to 10,000 reads per second - if you do nothing else. This produces 100 kbits/second, or 20kbytes per second (each 10-bit read is returned as two bytes, with the remaining 6 bits being 0).