text:
Arduino Remote controlled RGB LED strip, having issues with brightness/dimming
I have this sketch:
#include <TimerOne.h>
#include <IRremote.h>
#include <RGBMood.h>

int RECV_PIN = 2;  // IR-Receiver PIN
int led = 13;       // Satus-LED PIN
int modus;          // Modus for Interrupt-Querry
int ledr = 11;       // RGB LED red PIN
int ledg = 12;       // RGB LED green PIN
int ledb = 13;       // RGB LED blue PIN
int SerialBuffer = 0;

RGBMood m(ledr, ledg, ledb);

int timerwert = 20;   // Timer time for Interrupt in ms

String readString;

// Color arrays
int black[3]  = { 0, 0, 0 };
int white[3]  = { 100, 100, 100 };
int red[3]    = { 100, 0, 0 };
int green[3]  = { 0, 100, 0 };
int blue[3]   = { 0, 0, 100 };
int yellow[3] = { 40, 95, 0 };
int dimWhite[3] = { 30, 30, 30 };

int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
// etc.

// Set initial color
int redVal = black[0];
int grnVal = black[1];
int bluVal = black[2];

int wait = 10;      // 10ms internal crossFade delay; increase for slower fades
int hold = 0;       // Optional hold when a color is complete, before the next crossFade
int DEBUG = 1;      // DEBUG counter; if set to 1, will write values back via serial
int loopCount = 60; // How often should DEBUG report?
int repeat = 3;     // How many times should we loop before stopping? (0 for no stop)
int j = 0;          // Loop counter for repeat

// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;

#define ON                0xF4F37A66
#define OFF               0x1363ADB4
#define BRIGHTNESS_UP     0xE6721691
#define BRIGHTNESS_DOWN   0xE9721B48
#define FLASH             0xFFF00F
#define STROBE            0xFFE817
#define FADE              0x39ED1255
#define SMOOTH            0xFFC837

#define RED               0x9D561314
#define GREEN             0XCB8E93A5
#define BLUE              0xC88E8EEC
#define WHITE             0x16DBBEE3

#define ORANGE            0xFFB04F
#define YELLOW_DARK       0xFFA857
#define YELLOW_MEDIUM     0xFF9867
#define YELLOW_LIGHT      0xFF8877

#define GREEN_LIGHT       0XFF30CF
#define GREEN_BLUE1       0XFF28D7
#define GREEN_BLUE2       0XFF18E7
#define GREEN_BLUE3       0XFF08F7

#define BLUE_RED          0XFF708F
#define PURPLE_DARK       0XFF6897
#define PURPLE_LIGHT      0XFF58A7
#define PINK              0XFF48B7

IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  pinMode(ledr, OUTPUT); // Set RGB LED Pins as Output
  pinMode(ledg, OUTPUT); // Set RGB LED Pins as Output
  pinMode(ledb, OUTPUT); // Set RGB LED Pins as Output
  pinMode(led, OUTPUT); // set Status-LED as Output
  m.setMode(RGBMood::RANDOM_HUE_MODE);  // Automatic random fade.
  m.setHoldingTime(4000);  // Keep the same color for 4 seconds before fading again.
  m.setFadingSteps(150);   // Fade with 150 steps.
  m.setFadingSpeed(50);    // Each step last 50ms. A complete fade takes 50*150 = 7.5 seconds
  m.setHSB(random(359), 255, 255);

Serial.begin(9600);

  irrecv.enableIRIn(); // Start of IR-Recive

  Timer1.initialize(timerwert); // Initialisation of Timer-Interrupts
  Timer1.attachInterrupt(leseIR); // IR-Read from Interrupt
}

void leseIR(){
  if (irrecv.decode(&results)){
     irrecv.resume();  // Receive the next value
    switch (results.value)  {

      case FADE: // Modus Fade (DIY 4)
        modus = 1;
      break;

      case 0xFF906F: // Modus pcambi (DIY 5)
        modus = 2;
      break;

      case ON:  //Power
       modus = 0;
        crossFade(white);         // RGB LEDs Off
      break;
            case OFF:  //Power
       modus = 0;
        crossFade(black);         // RGB LEDs Off
      break;

      case BLUE:  //Blau 0,0,255
        modus = 0;
      crossFade(blue);
      break;

      case RED: //Rot
        modus = 0;
        crossFade(red);
      break;

      case GREEN://Grün
        modus = 0;
        crossFade(green);
      break;

      case WHITE: //Weiss
        modus = 0;
        crossFade(white);
      break;

      case BRIGHTNESS_UP: //DIMMING
        modus = 0;
        // fade in from min to max in increments of 5 points:
  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
    // sets the value (range from 0 to 255):
    analogWrite(ledg, fadeValue);

  }

      break;

       case BRIGHTNESS_DOWN: //orange
        modus = 0;
      for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
    // sets the value (range from 0 to 255):
    analogWrite(ledg, fadeValue);
      }

      break;

      case 0xFFAA55://Grün mitrtel
        modus = 0;

      break;

      case 0xFF926D: //blau mittel
        modus = 0;

      break;

      case 0xFF12ED: //rosa
        modus = 0;

      break;

     }             // Switch END

  }

}

void loop() {
if(modus==1){    // Querry pb Modus:1
m.tick();
}

      Serial.println(results.value, HEX);
      Serial.println(DEC);
      Serial.println(DEC);
      Serial.println(DEC);

  }

  int calculateStep(int prevValue, int endValue) {
  int step = endValue - prevValue; // What's the overall gap?
  if (step) {                      // If its non-zero,
    step = 1020/step;              //   divide by 1020
  }
  return step;
}

/* The next function is calculateVal. When the loop value, i,
*  reaches the step size appropriate for one of the
*  colors, it increases or decreases the value of that color by 1.
*  (R, G, and B are each calculated separately.)
*/

int calculateVal(int step, int val, int i) {

  if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
    if (step > 0) {              //   increment the value if step is positive...
      val += 1;
    }
    else if (step < 0) {         //   ...or decrement it if step is negative
      val -= 1;
    }
  }
  // Defensive driving: make sure val stays in the range 0-255
  if (val > 255) {
    val = 255;
  }
  else if (val < 0) {
    val = 0;
  }
  return val;
}

/* crossFade() converts the percentage colors to a
*  0-255 range, then loops 1020 times, checking to see if
*  the value needs to be updated each time, then writing
*  the color values to the correct pins.
*/

void crossFade(int color[3]) {
  // Convert to 0-255
  int R = (color[0] * 255) / 100;
  int G = (color[1] * 255) / 100;
  int B = (color[2] * 255) / 100;

  int stepR = calculateStep(prevR, R);
  int stepG = calculateStep(prevG, G);
  int stepB = calculateStep(prevB, B);

  for (int i = 0; i <= 1020; i++) {
    redVal = calculateVal(stepR, redVal, i);
    grnVal = calculateVal(stepG, grnVal, i);
    bluVal = calculateVal(stepB, bluVal, i);

    analogWrite(ledr, redVal);   // Write current values to LED pins
    analogWrite(ledg, grnVal);
    analogWrite(ledb, bluVal);

    delay(wait); // Pause for 'wait' milliseconds before resuming the loop

  }
  // Update current values for next loop
  prevR = redVal;
  prevG = grnVal;
  prevB = bluVal;
  delay(hold); // Pause for optional 'wait' milliseconds before resuming the loop
}

It's working like a charm, the fade operates smoothly using timer1, the colors appear correct on led, but I can't fix the brightness part. Can  someone provide sample code to do this?
If anyone else wants to use the code, I'm using an Arduino Mega 2560, please use the same PINs as mine since timers works only on 11,12,13 on this Arduino. (link with pin info regarding several Arduino boards)

RGB mood library
TimerOne library
IR Library

I'm using a small Xbox 360 IR control (no numbers keypad), some HEX codes are left intact from the original sketch found on internet.
original topic

Whats wrong with the brightness part?

i cannot set the brightness of the leds. Maybe i should use the expression "dim" instead of brightness to make it more clear. If i set the color RED, i cannot dim it up or down, same aplies for GREEN and BLUE.

No 'brightness' was clear, I just couldn't tell what wasn't working from your question. :P

You don't have a delay in the fade loop, this goes from 0 to 255 almost instantly:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
    // sets the value (range from 0 to 255):
    analogWrite(ledg, fadeValue);
}

But I'm not sure you want to fade from off to on in one go. If you want to just increment and decrement the brightness:
First notice that prevR, prevG, prevB hold the current led values. So we shall use them.
Change the switch case to:
case BRIGHTNESS_UP:
    modus = 0;
    int c[3];
    // decrease by 0.9*value but also take off 2 so we get to zero
    c[0] = (prevR-2) * 90 / 100;
    c[1] = (prevG-2) * 90 / 100;
    c[2] = (prevB-2) * 90 / 100;
    for( int j = 0; j < 3; j++ ) {
        if (c[j] < 0) c[j] = 0;
    }
    crossFade(c);
    break;

case BRIGHTNESS_DOWN:
    modus = 0;
    int c[3];
    // increase value by 1/0.9 but also add 2 so we get off zero
    c[0] = (prevR+2) * 100 / 90 + 2;
    c[1] = (prevG+2) * 100 / 90 + 2;
    c[2] = (prevB+2) * 100 / 90 + 2;
    for( int j = 0; j < 3; j++ ) {
        if (c[j] > 100) c[j] = 100;
    }
    crossFade(c);
    break;

I can't check this to see if it works see please test and see.
Edit
Different approach:
Global variable for brightness:
int brightness = 100;
int c[3];

Change this value each time:
case BRIGHTNESS_UP:
    modus = 0;
    brightness += 5;
    if (brightness > 255) brightness = 255;
    c[0] = prevR; c[1] = prevG; c[2] = prevB;
    crossFade(c);
    break;

case BRIGHTNESS_DOWN:
    modus = 0;
    brightness -= 5;
    if (brightness < 0) brightness = 0;
    c[0] = prevR; c[1] = prevG; c[2] = prevB;
    crossFade(c);
    break;

Then in crossFade we change the last few lines:
analogWrite(ledr, redVal * brightness / 255);   // Write current values to LED pins
analogWrite(ledg, grnVal * brightness / 255);
analogWrite(ledb, bluVal * brightness / 255);

Edit 2:
I think that what might be happening is that the color is reduced by brightness, then that reduced value is saved in prevR/G/B when actually it should just be the full brightness value. Try changing last bit of crossFade to :
prevR = color[0];
prevG = color[1];
prevB = color[2];

IDE reports that there is redeclaration of 'int c [3]

Try move int c[3] outside leseIR() and make it global. Delete all instances in the switch statement.

you might want to muck around with the ratios too, say use 80 instead of 90 and 5 instead of 2 etc. I tried to use a ratio because our eyes perceive brightness on a log scale, so a small change in low brightness is like a large change in high brightness.

i removed it, code compiled, but, when i press the brighntess up button the color fades to black (switches off) and when i press the brightness down then the color brights up to white after several button presses.

oops, i got BRIGHTNESS_UP and BRIGHTNESS_DOWN round the wrong way

see this question for some people's approach to getting brightness changes correct  http://electronics.stackexchange.com/questions/1983/correcting-for-non-linear-brightness-in-leds-when-using-pwm

The brightness might actually have to be made a separate variable and applied in crossFade

Hi, i've tried the edited approach, all colors dim to 0, with a single button press, no matter if press the up or down brightness. So, if i've chosen the GREEN color, it dims to 0, the same applies to all. Crossfade class do the following: When the selected color is RED and press the GREEN button, then RED dims down to 0 and GREEN dims up to 100. So my guess is that we must not use the Crossfade class to control brightness.

Hey could you make crossFade print out the colour and the R G B values and just check they look ok? e.g. Serial.println(colour[0],DEC); and so on.

RED button pressed results crossfade : 100,0,0 and color : 255,0,0 .  GREEN crossfade : 0,100,0 and color : 0,255,0 . BLUE crossfade : 0,0,100 and color : 0,0,255 . WHITE crossfade : 100,100,100 and color 255,255,255 . So everything seems ok.

Oh sorry, I meant for the brightness up / down with the code I posted. :)

I've moved the analogWrite part of the code inside the switch case BRIGHTNESS_UP & BRIGHTNESS_DOWN and it's working. I also removed the crossFade(c); line.
Here's the working code:
#include <TimerOne.h>
#include <IRremote.h>
#include <RGBMood.h>

int RECV_PIN = 2;  // IR-Receiver PIN
int led = 13;       // Satus-LED PIN
int modus;          // Modus for Interrupt-Querry
int ledr = 11;       // RGB LED red PIN
int ledg = 12;       // RGB LED green PIN
int ledb = 13;       // RGB LED blue PIN
int SerialBuffer = 0;
int c[3];

//RGB Pins Array
int CH[3] = {11, 12, 13};
int val[3] = {0, 0, 0}; // led brightness 0-255

RGBMood m(ledr, ledg, ledb);

int timerwert = 20;   // Timer time for Interrupt in ms

String readString;

// Color arrays
int black[3]  = { 0, 0, 0 };
int white[3]  = { 100, 100, 100 };
int red[3]    = { 100, 0, 0 };
int green[3]  = { 0, 100, 0 };
int blue[3]   = { 0, 0, 100 };
int yellow[3] = { 40, 95, 0 };
int dimWhite[3] = { 30, 30, 30 };

int brightness = 100;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
// etc.

// Set initial color
int redVal = black[0];
int grnVal = black[1];
int bluVal = black[2];

int wait = 10;      // 10ms internal crossFade delay; increase for slower fades
int hold = 0;       // Optional hold when a color is complete, before the next crossFade
int DEBUG = 1;      // DEBUG counter; if set to 1, will write values back via serial
int loopCount = 60; // How often should DEBUG report?
int repeat = 3;     // How many times should we loop before stopping? (0 for no stop)
int j = 0;          // Loop counter for repeat

// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;

#define ON                0xF4F37A66
#define OFF               0x1363ADB4
#define BRIGHTNESS_UP     0xE6721691
#define BRIGHTNESS_DOWN   0xE9721B48
#define FLASH             0xFFF00F
#define STROBE            0xFFE817
#define FADE              0x39ED1255
#define SMOOTH            0xFFC837

#define RED               0x9D561314
#define GREEN             0XCB8E93A5
#define BLUE              0xC88E8EEC
#define WHITE             0x16DBBEE3

#define ORANGE            0xFFB04F
#define YELLOW_DARK       0xFFA857
#define YELLOW_MEDIUM     0xFF9867
#define YELLOW_LIGHT      0xFF8877

#define GREEN_LIGHT       0XFF30CF
#define GREEN_BLUE1       0XFF28D7
#define GREEN_BLUE2       0XFF18E7
#define GREEN_BLUE3       0XFF08F7

#define BLUE_RED          0XFF708F
#define PURPLE_DARK       0XFF6897
#define PURPLE_LIGHT      0XFF58A7
#define PINK              0XFF48B7
#define MAX 255

IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  pinMode(ledr, OUTPUT); // Set RGB LED Pins as Output
  pinMode(ledg, OUTPUT); // Set RGB LED Pins as Output
  pinMode(ledb, OUTPUT); // Set RGB LED Pins as Output
  pinMode(led, OUTPUT); // set Status-LED as Output
 //initiate rgb pins output
    for (int i=0; i<3; i++)
  {
    pinMode(CH[i], OUTPUT);
  }

  m.setMode(RGBMood::RANDOM_HUE_MODE);  // Automatic random fade.
  m.setHoldingTime(4000);  // Keep the same color for 4 seconds before fading again.
  m.setFadingSteps(150);   // Fade with 150 steps.
  m.setFadingSpeed(50);    // Each step last 50ms. A complete fade takes 50*150 = 7.5 seconds
  m.setHSB(random(359), 255, 255);

Serial.begin(9600);

  irrecv.enableIRIn(); // Start of IR-Recive

  Timer1.initialize(timerwert); // Initialisation of Timer-Interrupts
  Timer1.attachInterrupt(leseIR); // IR-Read from Interrupt
}

void leseIR(){
  if (irrecv.decode(&results)){
     irrecv.resume();  // Receive the next value
    switch (results.value)  {

      case FADE: // Modus Fade (DIY 4)
        modus = 1;
      break;

      case 0xFF906F: // Modus pcambi (DIY 5)
        modus = 2;
      break;

      case ON:  //Power
       modus = 0;
        crossFade(white);         // RGB LEDs Off
      break;
            case OFF:  //Power
       modus = 0;
        crossFade(black);         // RGB LEDs Off
      break;

      case BLUE:  //Blau 0,0,255
        modus = 0;
      crossFade(blue);
      break;

      case RED: //Rot
        modus = 0;
        crossFade(red);
      break;

      case GREEN://Grün
        modus = 0;
        crossFade(green);
      break;

      case WHITE: //Weiss
        modus = 0;
        crossFade(white);
      break;

      case BRIGHTNESS_UP: //DIMMING UP
        modus = 0;
    brightness += 5;
    if (brightness > 255) brightness = 255;
    c[0] = prevR; c[1] = prevG; c[2] = prevB;
    analogWrite(ledr, redVal * brightness / 255);   // Write current values to LED pins
    analogWrite(ledg, grnVal * brightness / 255);
    analogWrite(ledb, bluVal * brightness / 255);

      break;

       case BRIGHTNESS_DOWN: //DIMMING DOWN
         modus = 0;
    brightness -= 5;
    if (brightness < 0) brightness = 0;
    c[0] = prevR; c[1] = prevG; c[2] = prevB;
    analogWrite(ledr, redVal * brightness / 255);   // Write current values to LED pins
    analogWrite(ledg, grnVal * brightness / 255);
    analogWrite(ledb, bluVal * brightness / 255);

      break;

      case 0xFFAA55://Grün mitrtel
        modus = 0;
      break;

      case 0xFF926D: //blau mittel
        modus = 0;

      break;

      case 0xFF12ED: //rosa
        modus = 0;

      break;

     }             // Switch END

  }
}

void loop() {
if(modus==1){    // Querry pb Modus:1
m.tick();
}
if(modus==2){    // Querry pb Modus:1

}
        Serial.println(prevR);
        Serial.println(prevG);
        Serial.println(prevB);
//      Serial.println(results.value, HEX);
//      Serial.println(DEC);
//      Serial.println(DEC);
//      Serial.println(DEC);
//      Serial.print("channel 1,2,3 values:");              // sends  brightness values to the serial monitor
    //  for(int i=0; i<3; i++){                             // every time the remote is pressed
    //  Serial.print(CH[i]);
//      Serial.print("   ");
    // }
  }

  int calculateStep(int prevValue, int endValue) {
  int step = endValue - prevValue; // What's the overall gap?
  if (step) {                      // If its non-zero,
    step = 1020/step;              //   divide by 1020
  }
  return step;
}

/* The next function is calculateVal. When the loop value, i,
*  reaches the step size appropriate for one of the
*  colors, it increases or decreases the value of that color by 1.
*  (R, G, and B are each calculated separately.)
*/

int calculateVal(int step, int val, int i) {

  if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
    if (step > 0) {              //   increment the value if step is positive...
      val += 1;
    }
    else if (step < 0) {         //   ...or decrement it if step is negative
      val -= 1;
    }
  }
  // Defensive driving: make sure val stays in the range 0-255
  if (val > 255) {
    val = 255;
  }
  else if (val < 0) {
    val = 0;
  }
  return val;
}

/* crossFade() converts the percentage colors to a
*  0-255 range, then loops 1020 times, checking to see if
*  the value needs to be updated each time, then writing
*  the color values to the correct pins.
*/

void crossFade(int color[3]) {
  // Convert to 0-255
  int R = (color[0] * 255) / 100;
  int G = (color[1] * 255) / 100;
  int B = (color[2] * 255) / 100;

  int stepR = calculateStep(prevR, R);
  int stepG = calculateStep(prevG, G);
  int stepB = calculateStep(prevB, B);

  for (int i = 0; i <= 1020; i++) {
    redVal = calculateVal(stepR, redVal, i);
    grnVal = calculateVal(stepG, grnVal, i);
    bluVal = calculateVal(stepB, bluVal, i);

    analogWrite(ledr, redVal);   // Write current values to LED pins
    analogWrite(ledg, grnVal);
    analogWrite(ledb, bluVal);

    delay(wait); // Pause for 'wait' milliseconds before resuming the loop

  }
  // Update current values for next loop
  prevR = redVal;
  prevG = grnVal;
  prevB = bluVal;
  delay(hold); // Pause for optional 'wait' milliseconds before resuming the loop
}

thanks geometrikal for your support! You believe it's possible to manipulate the dimming of the fade effect too? It's using the RGBMood class to create a HSB color mix.


text:
Arduino Nano and SIM300 module for http calls for location
I am new to Arduino and SIM300/900 world. But I see that there is a possibility of building a vehicle tracker (approximate locality since I will use GPRS network location) using just these 2 boards.
My question is, is my assumption correct ? Can I build a vehicle tracker using just Arduino Nano and SIM300 mobule ? Is there a board that has both of them on one board so that I dont have to buy them separately ? Cost is a major factor on the decision.

Not really.
Module can read the cell ID by below command. However, only phone company has the list of cell ID and their location. This information is only accurate to serving range of a cell, mostly in range of, 0.1 to 15km, from very dense city to country
Module can also read network ID and know, from public information, the country and network operator name.
Example taken from web:
AT+CREG?

This should give you a result like:
+CREG: 2,1,"1030","639E"

Working through the 4 returned values, the "2" reflects the
current "+CREG" setting (2 means "Enables unexpected network
registration and location information messages"), "1" indicates
that the phone is registered with the network, "1030" is the
Location Area Code (LAC) in hex (4144 decimal), and "639E" is the
CellID (CI) in hex (25502 decimal).

source: Stack Exchange

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

sort: votes


text:
Arduino GSM Module with network GPS
I have looked through the AT command set of Arduino GSM Shield boards. I dont find any AT command that provides network GPS. I wonder what I am missing. Why isn't it possible for GSM module to provide NetworkGPS (the one that is not really accurate) ?

A very simple answer could be that the firmware does not support it.

I believe the SIM900 has a command for it: http://www.puntoflotante.net/SIM900-Gsm-Location-AT-commands.pdf
But other manufacturers may have it aswell. (EDIT: the answers seem to differ and I must agree that it may not work depending on which carrier you use)

Simple answer is that it is function of cellular network (phone company) instead of the module.
More informative answer is, Position is calculated by network via

serving cell base station ID and location
when phone on standby, it monitors signal strength from multiple base stations and signal strength is roughly related to distance
when phone on transmitting, base station has one more piece of information. It calculates distance through time taken for signal to travel to multiple base stations (called 'time advance' in original GSM)

US E911 utilizes these to locate the phone.
Good technical paper with diagrams
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&cad=rja&uact=8&ved=0CEUQFjAF&url=https%3A%2F%2Fwww.fig.net%2Fpub%2Fcostarica_1%2Fpapers%2Fts08%2Fts08_01_schwieger_2407.pdf&ei=Ms3bU8-DItfr8AXT7oLQCg&usg=AFQjCNHImn4G34WC0Naw8IH6g1gfLzykuQ&bvm=bv.72197243,d.dGc
http://en.wikipedia.org/wiki/Positioning_%28telecommunications%29

I would agree that much of the functionality is in the carrier's network infrastructure, but that wouldn't explain why it's not available on a module that is almost certainly a network who's phone clients do receive this service.

The AT command set follows international technical standard, now 3GPP, was GSMMOU. The function you want is not there, according to the standard.  Individual network use what i describe above, also in the detailed tech paper I quote, for their own use, like E911 and other commercial LBS (locate based service). Some network make the info available on commercial terms. For example, one actual implementation is auto advertisement for long distance phone call (to call home) when user pass to a new country border.

You are right in that info is available as part of the overall structure, but, not via the module AT command.  If you like more detailed tech info. http://www.telecomsys.com/products/location-based-services/infrastructure-gsm/smlc.aspx  http://en.wikipedia.org/wiki/Location-based_service  http://en.wikipedia.org/wiki/GMLC

This is a very complicated situation.  In short, the module itself does not provide Assisted GPS without both the handset's help, and the help of the carrier.
Since the module is sold as an OEM or embeddable object, the manufacturer either hasn't included such functionality, or hasn't enabled it, or hasn't documented it.
Even if it were included, enabled, and documented, it has to work with the carrier, and each carrier provides different services for different modules.  Some locate solely based on triangulation using cell towers and the module's command channel.  Others depend on the module capturing a short sequence of RF from the GPS network, sending it to the carrier's AGPS server to be processed, which then reports back a very accurate position.
At any rate, this is not a standardized function for embedded cellular modules because cellular networks and carriers vary in how they've chosen to implement AGPS.
If you want to use AGPS in an embedded cellular module, you'll need to work with both the module manufacturer and the cellular carrier to enable that functionality.  It usually involves additional charges - renting an AGPS server, for instance.  These often involve a monthly fee in addition to a per-request fee.  Some companies set up their own AGPS servers to do the processing, but the cellular company still has to provide gross location information based on the tower signal reception.
Suffice to say, this is not something that is common or cheap enough for low volume projects.  Unless you're going to be working with thousands of these devices it's typically cheaper to integrate a standalone GPS chipset in your device.

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


text:
Using Arduino as USB Device?
I'm trying to get audio data from an ADC connected to an Arduino into a host PC.  I've done some digging and found LUFA, which I think Arduino uses under the hood. Is it possible to use the Arduino as a USB device, and if so, are there any examples?  Thanks!

For those Arduinos which use general purpose microcontrollers for their USB interface, yes, you can reprogram them.  But what data rate do you need to move?  An ATmega based Arduino tends to imply a moderate one, and if you don't need to put it directly into the PC's unmodified audio stack, you can probably just crank the serial channel to maximum baud rate and push your data that way, with a lot less work.  One where the USB comes direct from the sketch processor - either a Leonardo or one of the ARM-based boards - would probably be most capable.

Do you want to have it be a HID device or is serial to audio fine? It might be cheaper to buy something designed for this and prebuilt... anyway no, Arduino doesn't use LUFA. It uses a similar firmware for the serial connection.

I need it to appear as a USB Class Audio device so that it can interact with pre-existing OS drivers.

I'd assume this would require me to do some low-level stuff

Someone has done 10-bit 16 Ksps stereo with a Leonardo: http://forum.arduino.cc/index.php?topic=208140.0

I'm glad if it helps you, but as just a link it's sort of an answer of last resort in quality, and unfortunately there's not much more that can be said about it without downloading and studying that code to see what can be learned from it.

Thanks so much!  I've seen you comment on some of my other questions and you were a huge help!

LUFA is used for the USB to serial firmware on the separate USB-serial bridge AVR found on Uno and newer Megas. The firmware is compiled using a supplied makefile. Otherwise LUFA isn't used by Arduino.
But LUFA is probably the right choice if you want to make a USB audio device. It comes with examples of both input and output audio devices. But you will have to compile using the supplied makefile, unless you are really ninja. On a Linux distro it's easy - don't know about other OS'es.
The demo "Audio Input Device Demo" comes with LUFA and is ompatible with the atmega32u4 used on Leonardo. It can be set up to sample analog input and send it to the pc. From the documentation:

On start-up the system will automatically enumerate and function as a USB microphone. By default, the demo will produce a square wave test tone when the board button is pressed. If USE_TEST_TONE is not defined in the project makefile, incoming audio from the ADC channel 1 will be sampled and sent to the host computer instead.

I am confused on what your end purpose is.  do you want something that works or you want to make a project for self-learning purpose.
For ready-made products that you can buy, if you want the PC to be able to input and output sound, there are hundreds models of a) sound card plug into PC  b) external sound card link to PC via USB cable    They ranges from a few USD to 50 to 200 with huge range of performance in terms of sampling rate and number of bits (low noise).
Ardu build-in ADC is 10 to 12 bits. These card are 16 to 24 bits.
See
http://www.bestbuy.com/site/computer-cards-components/sound-cards/abcat0507003.c?id=abcat0507003
24 bits 116 dB SNR very low noise
http://us.creative.com/p/sound-blaster/sound-blaster-z
I used them as test instrument for commercial/university projects with success.
I saw on TV news that same setup (high bit card, at -110dB or lower noise level) used in the underwater signal search for MH370 down plane months ago.


text:
LED's won't light up when LCD/RNG hits 2 || 3 of a kind
I am a true beginner here. Trying to build a "slot machine" type game and am in the beginning stages. Found a RNG for LCD code and tweaked it a bit to get three digits to display randomly. Worked just fine. But what I'm trying to accomplish is getting a red LED to blink when none of the RN match, blue when 2 RN match, and green when 3 RN match. What is happening now, is that the LCD will no longer generate random numbers when I press my button UNless I hold the button in for a couple of seconds. As soon as the random numbers appear my green led flashes briefly then the red and blue blink opposite of each other (red on 1 sec, off 1 sec, blue on 1 sec, off 1 sec, repeat......green only briefly when random numbers change). So after hours and hours of searching goggle and trying to figure this out on my own I am turning the folks who know what they are doing :)Please tell me what I am doing wrong.... Any help would be greatly appreciated. So why did the RNG stop working with a single press of my button, and where is my code wrong that gets the correct lighting operation? Here is my code so far
#include <WProgram.h>
 #include<Arduino.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

/* pin laayout of the LCD with the arduino:
arduino pin = LCD pins
7=RS
8=E
9=D4
10=D5
11=D6
12=D7
RW=ground
*/

int inpin=2; //switchpin
int reading; // stocks switchpin

int inpin2=4; //switchpin
int reading2; //stocks switchpin

int inpin3=6; //switchpin
int reading3; //stocks switchpin

int ran; //stocks random number for dice roll 1
int ran2; //stocks random number for dice roll 2
int ran3; //stocks random number for dice roll 3

int outpin=LOW;
int LED1=0; // red LED

int outpin2=LOW;
int LED2=1; // Blue LED

int outpin3=LOW;
int LED3=3; // Green LED

void setup()

 {
 lcd.begin(16,2);
   pinMode(LED1,OUTPUT);
   pinMode(LED2,OUTPUT);
   pinMode(LED3,OUTPUT);
 }

  void loop()
  {

    //reading of switch

    reading=digitalRead(inpin);
    reading2=digitalRead(inpin2);
    reading3=digitalRead(inpin3);

    //random numbers generation

    ran3=random(6);
    ran2=random(6);
    ran=random(6);

    {
    if (reading != reading2 != reading3);
      digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(LED1, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second
  }

  {
    if (reading3 == reading2 || reading);
      digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(500);               // wait for a second
      digitalWrite(LED2, LOW);    // turn the LED off by making the voltage LOW
      delay(500);               // wait for a second
  }

  {
    if (reading==reading2==reading3)
      digitalWrite(LED3, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(250);               // wait for a second
      digitalWrite(LED3, LOW);    // turn the LED off by making the voltage LOW
      delay(250);               // wait for a second
  }

    // Set the screen for the PL1 and PL2 label on the top.

    lcd.setCursor(0,0);
    lcd.print("RL 1");

    lcd.setCursor(6,0);
    lcd.print("RL 2");

    lcd.setCursor(12,0);
    lcd.print("RL 3");

    //display of random number.

    if (reading==HIGH){
        lcd.setCursor(2,1);
        lcd.print(ran);
       delay(250);} // not really clean but used as a debouche founction. That way the µC can read only once the inpin within 250ms. i'll try to improve that.

   if(reading2==HIGH){ //same as the player , only the location of the result on the screen is different
       lcd.setCursor(6,0);
       lcd.print("RL 2");
       lcd.setCursor(8,1);
       lcd.print(ran2);
      delay(250);}

      if(reading3==HIGH){ //same as the player , only the location of the result on the screen is different
       lcd.setCursor(12,0);
       lcd.print("RL 3");
       lcd.setCursor(14,1);
       lcd.print(ran3);
      delay(250);}

And here is the original code I found: http://www.desiquintans.com/articles.php?page=randuino (which also shows how it is wired up).
Tweaked to get the 3 random numbers and not just the two that it was set to:
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

/* pin laayout of the LCD with the arduino:
arduino pin = LCD pins
7=RS
8=E
9=D4
10=D5
11=D6
12=D7
RW=ground
*/

int inpin=2; //switchpin
int reading; // stocks switchpin

int inpin2=4; //switchpin
int reading2; //stocks switchpin

int inpin3=6;
int reading3;

int ran; //stocks randoms for player 1
int ran2; //stocks random for player 2
int ran3;

void setup(){
  lcd.begin(16,2);
}

void loop(){

    //reading of switch

    reading=digitalRead(inpin);
    reading2=digitalRead(inpin2);
    reading3=digitalRead(inpin3);

    //random numbers generation

    ran3=random(6);
    ran2=random(6);
    ran=random(6);

    // Set the screen for the PL1 and PL2 label on the top.

    lcd.setCursor(0,0);
    lcd.print("RL 1");

    lcd.setCursor(6,0);
    lcd.print("RL 2");

    lcd.setCursor(12,0);
    lcd.print("RL 3");

    //display of random number.

    if (reading==HIGH){
      lcd.setCursor(2,1);
      lcd.print(ran);
      delay(250);} // not really clean but used as a debouche founction. That way the µC can read only once the inpin within 250ms. i'll try to improve that.

   if(reading2==HIGH){ //same as the player , only the location of the result on the screen is different
       lcd.setCursor(6,0);
       lcd.print("RL 2");
        lcd.setCursor(8,1);
        lcd.print(ran2);
      delay(250);}

      if(reading3==HIGH){ //same as the player , only the location of the result on the screen is different
       lcd.setCursor(12,0);
       lcd.print("RL 3");
        lcd.setCursor(14,1);
        lcd.print(ran3);
      delay(250);}
}

reading != reading2 != reading3 doesn't work. Use reading != reading2 && reading != reading3. I don't get what the buttons are supposed to do.

Thanks for replying Gerben :) will try that right away.. There is only one button and when it is pressed the random numbers are generated and displayed on the LCD, well at least that's what it did before I tried to add the lights. Thanks again

1 button? But you have 3 digitalReads?

Did you have the button when your code was working with the LCD? Do you have a pull down resistor or any way to handle debouncing the switch?

Yes.. one button and 3 digitalReads. I was under the impression that the digitalReads was the signal to the lcd from the arduino to generate 3 different random numbers when one button was pushed.

Thanks for commenting Doowybbob. Yes, I did have the button with the original code when the LCD was working. Here is a copy of that before I started trying to add all the LED's.

#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
/* pin laayout of the LCD with the arduino:
arduino pin = LCD pins
7=RS
8=E
9=D4
10=D5
11=D6
12=D7
RW=ground
*/
int inpin=2; //switchpin
int reading; // stocks switchpin
int inpin2=4; //switchpin
int reading2; //stocks switchpin
int inpin3=6;
int reading3;
int ran; //stocks randoms for player 1
int ran2; //stocks random for player 2
int ran3;
void setup(){
lcd.begin(16,2);
}
void loop()
{

reading=digitalRead(inpin);
reading2=digitalRead(inpin2);
reading3=digitalRead(inpin3);
ran3=random(6);
ran2=random(6);
ran=random(6);
lcd.setCursor(0,0);
lcd.print("RL 1");
lcd.setCursor(6,0);
lcd.print("RL 2");

lcd.setCursor(12,0);
lcd.print("RL 3");

//display of random number.

if (reading==HIGH){
  lcd.setCursor(2,1);
  lcd.print(ran);
  delay(250);}

if(reading2==HIGH){
lcd.setCursor(6,0);
lcd.print("RL 2");
lcd.setCursor(8,1);
lcd.print(ran2);
delay(250);}
  if(reading3==HIGH){
   lcd.setCursor(12,0);
   lcd.print("RL 3");
    lcd.setCursor(14,1);
    lcd.print(ran3);
  delay(250);}
  }

@SWTORguy Maybe edit your question to add the initial working code. It isn't readable in the comments. Also, what exactly are pins 2, 4, and 6 connected to. You do a digitalRead() on them but never set their pinMode()

Good idea Doowybbob. Did as suggested... Pins 2 4 and 6 are connected in series on the breadboard then jumped to the negative side of my button. Also that negative side of the button has a resistor to it and a jumper that goes to a5 on my uno.

http://www.desiquintans.com/articles.php?page=randuino  the code and "diagram"

So after a ton more research I figured out what I was doing wrong. For anyone who reads these answers, I found two web sites to be an enormous help. They are http://playground.arduino.cc/uploads/Main/arduino_notebook_v1-1.pdf  and  http://mikrohw.wz.cz/HakDuino/Arduino_Cookbook.pdf   Good luck to you and have fun with your project. Thank you Gerben & Doowybbob for responding and trying to get me to look in the right direction. Turns out that a lot of my code was correctly heading in the right direction. But in my if statements, I wasn't addressing all the possible states. So now the LEDs light up at the appropriate time and I also added a buzzer. Here is my final code...... Thanks and Cheers, SWTORguy
#define PIEZO 5 // pin 5 is capable of PWM (Pulse width modulation) output to drive tones
#include <WProgram.h>
#include<Arduino.h>
#include <LiquidCrystal.h>
  LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

/* pin laayout of the LCD with the arduino:
arduino pin = LCD pins
7=RS
8=E
9=D4
10=D5
11=D6
12=D7
RW=ground
*/

const int button = A5;  // changes 2 to an integer from a constant
int buttonState;
int prevButtonState;

int inpin=2; //switchpin (rolling of dice1)
int reading; // stocks switchpin

int inpin2=4; //switchpin (rolling of dice2)
int reading2; //stocks switchpin

int inpin3=6; //switchpin (rolling of dice3)
int reading3; //stocks switchpin

int ran; //stocks randoms for dice 1
int ran2; //stocks random for dice 2
int ran3; // stocks random for dice 3

int outpin=LOW;
int LED1=13; //red LED

int outpin2=LOW;
int LED2=1; //blue LED

int outpin3=LOW;
int LED3=3; //green LED

int outpin4=LOW;
int BUZ=5; //piezio Buzzer

int del = 500; //buzzers delay time for inbetween LED flashes

void setup(){
   lcd.begin(16,2);
   pinMode (PIEZO, OUTPUT); //pin mapping
   pinMode(LED1,OUTPUT); //pin mapping
   pinMode(LED2,OUTPUT); //pin mapping
   pinMode(LED3,OUTPUT); //pin mapping
   pinMode (button, INPUT); //pin mapping
   pinMode (reading, INPUT); //pin mapping
   pinMode (reading2, INPUT); //pin mapping
   pinMode (reading3, INPUT); //pin mapping
}

void loop(){
    buttonState = digitalRead (button);
    if (buttonState != prevButtonState && buttonState == HIGH) //pushing the button
    {
    //reading of switch
    reading=digitalRead(inpin);
    reading2=digitalRead(inpin2);
    reading3=digitalRead(inpin3);

    //random numbers generation
    ran3=random(1,7); // #'s 1 through 6
    ran2=random(1,7); // #'s 1 through 6
    ran=random(1,7); // #'s 1 through 6

    // Set the LCD screen for dice 1-3 label on the top.
    lcd.setCursor(0,0);
    lcd.print("die");

    lcd.setCursor(5,0);
    lcd.print("die2");

    lcd.setCursor(11,0);
    lcd.print("die3");

    //display of random number.
    if (reading==HIGH){
        lcd.setCursor(2,1);
        lcd.print(ran);
        delay(250); // not really clean but used as a debounce function.
    }

    if(reading2==HIGH){
       lcd.setCursor(5,0);
       lcd.print("die2");
       lcd.setCursor(8,1);
       lcd.print(ran2);
      delay(250);
    }

    if(reading3==HIGH){
       lcd.setCursor(11,0);
       lcd.print("die3");
       lcd.setCursor(14,1);
       lcd.print(ran3);
       delay(250);
    }

    /*the logic that tells which LED to blink and when to sound the buzzer
      dependent upon which state the random numbers dispayed are in*/
    if (ran == ran2 && ran2 == ran3) // random number state (3 of a kind)
    {
      for (int c=0; c <= 2; c++) // variable defining how many times the green LED will blink and buzzer sound
      {
          digitalWrite(PIEZO, LOW); // buzzer off
          delay(del); // wait for .5 second
          digitalWrite(LED3, HIGH);   // Green - turn the LED on (HIGH is the voltage level)
          delay(100);               // wait for a second
          digitalWrite(LED3, LOW);    // turn the LED off by making the voltage LOW
          delay(100);               // wait for a second
          analogWrite(PIEZO, 128); //Buzzer on
          delay(del); // wait for .5 second
      }
      digitalWrite(PIEZO, LOW); //buzzer off
    }else{
        if(ran == ran2 || ran2 == ran3 || ran == ran3) // random number state (2 of a kind)
        {
            for (int b=0; b <= 2; b++) // variable defining how many times the blue LED will blink and buzzer sound
            {
                digitalWrite(PIEZO, LOW); // buzzer off
                delay(del); // wait for .5 second
                digitalWrite(LED2, HIGH);  //Blue - turn the LED on (HIGH is the voltage level)
                delay(100);   // wait for a second
                digitalWrite(LED2, LOW);  // turn the LED off by making the voltage LOw
                delay(100);   // wait for a second
                analogWrite(PIEZO, 128); //Buzzer on
                delay(del); // wait for .5 second
            }
            digitalWrite(PIEZO, LOW); //buzzer off
        }else{
            for (int a=0; a <= 10; a++) // variable defining how many times the red LED will blink.
            {
                digitalWrite(LED1, HIGH);   // Red - turn the LED on (HIGH is the voltage level)
                delay(100);               // wait for a second
                digitalWrite(LED1, LOW);    // turn the LED off by making the voltage LOW
                delay(100);               // wait for a second
            }
        }
    }

  }
}

On behalf of the Stack exchange community, thank you for posting a follow-up message explaining the solution you found (voted.) That turns a newbie question into an asset that others can learn from. BTW, parts of your answer are missing code tags, making it harder to read. You might want to edit your answer and clean it up.


text:
Using an Adafruit Trellis to control a set of relays
I've been going through my program again and again, and I can't figure out what is causing it not to work as intended.  First, the story: I'm trying to use an Arduino to control a bunch of relays which are controlling sockets (8 of them). I want to use an Adafruit Trellis LED panel/switches to do this. Basically, when the button is pressed, the LED lights up and the relay gets tripped.  Pressing it again does the reverse.
I will provide my code for inspection.
#include <Wire.h>
#include "Adafruit_Trellis.h"

/***************************************************
This example shows reading buttons and setting/clearing buttons in a loop
"momentary" mode has the LED light up only when a button is pressed
"latching" mode lets you turn the LED on/off when pressed

Up to 8 matrices can be used but this example will show 4 or 1
****************************************************/

#define MOMENTARY 0
#define LATCHING 1
// set the mode here
#define MODE LATCHING

Adafruit_Trellis matrix0 = Adafruit_Trellis();

// uncomment the below to add 3 more matrices
/*
Adafruit_Trellis matrix1 = Adafruit_Trellis();
Adafruit_Trellis matrix2 = Adafruit_Trellis();
Adafruit_Trellis matrix3 = Adafruit_Trellis();
// you can add another 4, up to 8
*/

// Just one
Adafruit_TrellisSet trellis = Adafruit_TrellisSet(&matrix0);
// or use the below to select 4, up to 8 can be passed in
//Adafruit_TrellisSet trellis =  Adafruit_TrellisSet(&matrix0, &matrix1, &matrix2, &matrix3);

// set to however many you're working with here, up to 8
#define NUMTRELLIS 1

#define numKeys (NUMTRELLIS * 16)

// Connect Trellis Vin to 5V and Ground to ground.
// Connect the INT wire to pin #A2 (can change later!)
#define INTPIN A2
// relay pins
#define relay1 2
#define relay2 3
#define relay3 4
#define relay4 5
#define relay5 6
#define relay6 7
#define relay7 8
#define relay8 9
int i = 0;

// Connect I2C SDA pin to your Arduino SDA line
// Connect I2C SCL pin to your Arduino SCL line
// All Trellises share the SDA, SCL and INT pin!
// Even 8 tiles use only 3 wires max

void setup() {
    Serial.begin(115200);
    Serial.println("Trellis on");

    // INT pin requires a pullup
    pinMode(INTPIN, INPUT);
    //relay pins
    pinMode(relay1, OUTPUT);
    pinMode(relay2, OUTPUT);
    pinMode(relay3, OUTPUT);
    pinMode(relay4, OUTPUT);
    pinMode(relay5, OUTPUT);
    pinMode(relay6, OUTPUT);
    pinMode(relay7, OUTPUT);
    pinMode(relay8, OUTPUT);

    digitalWrite(INTPIN, HIGH);

    // begin() with the addresses of each panel in order
    // I find it easiest if the addresses are in order
    trellis.begin(0x70);  // only one
    // trellis.begin(0x70, 0x71, 0x72, 0x73);  // or four!

    // light up all the LEDs in order
    for (uint8_t i = 0; i < numKeys; i++) {
        trellis.setLED(i);
        trellis.writeDisplay();
        delay(50);
    }
    // then turn them off
    for (uint8_t i = 0; i < numKeys; i++) {
        trellis.clrLED(i);
        trellis.writeDisplay();
        delay(50);
    }
}

void toggleLight(int i){
    if (trellis.isLED(i))
        trellis.clrLED(i);
    else
        trellis.setLED(i);

}

void loop() {
    delay(30); // 30ms delay is required, dont remove me!
    //init relay states
    static int relay1state = 0;
    static int relay2state = 0;
    static int relay3state = 0;
    static int relay4state = 0;
    static int relay5state = 0;
    static int relay6state = 0;
    static int relay7state = 0;
    static int relay8state = 0;

    if (MODE == MOMENTARY) {
        // If a button was just pressed or released...
        if (trellis.readSwitches()) {
            // go through every button
            for (uint8_t i = 0; i < numKeys; i++) {
                // if it was pressed, turn it on
                if (trellis.justPressed(i)) {
                    Serial.print("v"); Serial.println(i);
                    trellis.setLED(i);
                }
                // if it was released, turn it off
                if (trellis.justReleased(i)) {
                    Serial.print("^"); Serial.println(i);
                    trellis.clrLED(i);
                }
            }
            // tell the trellis to set the LEDs we requested
            trellis.writeDisplay();
        }
    }

    if (MODE == LATCHING) {
        // If a button was just pressed or released...
        if (trellis.readSwitches()) {
            // go through every button
            for (i; i < numKeys; i++) {
                // if it was pressed...
                if (trellis.justPressed(i)) {

                    switch (i)
                    {
                    case '0':
                        relay1state ^= 1; // xor current value with 1 (causes value to toggle)
                        if (relay1state) {
                            delay(100);
                            digitalWrite(relay1, HIGH);
                            toggleLight(i);
                            Serial.println("Outlet 1 on");
                            break;
                        }
                        else {
                            delay(100);
                            digitalWrite(relay1, LOW);
                            toggleLight(i);
                            Serial.println("Outlet 1 off");
                            break;
                        }

                    case '1':
                        relay2state ^= 1; // xor current value with 1 (causes value to toggle)
                        if (relay2state) {
                            delay(100);
                            digitalWrite(relay2, HIGH);
                            toggleLight(i);
                            Serial.println("Outlet 2 on");
                            break;
                        }
                        else {
                            delay(100);
                            digitalWrite(relay2, LOW);
                            toggleLight(i);
                            Serial.println("Outlet 2 off");

                            break;
                        }
                        //...add case 3-8 & 9-15
                    }
                    trellis.writeDisplay();
                }
            }
        }

    }
}

Relay1 one doesn't work because it's commented out //digitalWrite(relay1, HIGH);. Could you also post the serial output you get?

I commented it out to test.  It should be on. I will correct it in the original post.
Output from serial monitor:
Opening port
Debug on
Port open

Specifically, i'm not seeing the LED's light when I press button 1. Nor am I getting any serial feedback that I included ( when it lights, it prints on the serial).

You should see "trellis on" in the console. Try adjusting the baud rate (bottom right).

Yup, that's showing.

Port open
Debug on
Debug on
Trellis on
0 on
Outlet 1 on

relay1state ^= 1 is just a hack. Just write relay1state = !relay1state. Compilers are smart enough to make these kinds of optimizations. Using XOR might even be slower. Though this will probably not fix your problem.

Stepping back from your code problems, why are you using relays? Do you mean electromechanical relays? Those draw a lot of current and you need to wire them with a protection diode so they don't destroy the control circuit when you disconnect the power and the inductive field on the relay coil collapses.
If you're switching AC power, mechanical relays are a reasonable way to go, but for DC like motors/LEDs, etc, it's usually better to use electronic switches of some kind (e.g. transistors).

I am using the relays to switch on electrical outlets. Mainly for centralized control of the lighting in our office/workspace. It has been done as safe as can be (i.e. fuses in place, proper grounding).I've done this already with a Spark Core controlling 4 relays. I can turn on the relay from the cell network and get my soldering iron preheated, as an example.

Gotcha. Like I said, for switching AC power, relays are a reasonable choice. Remember to put flyback protection diodes in parallel with your relay coils to prevent damage to your switching transistors.

There's an issue with your switch case statement. You switch on int i but your cases use chars like '1'. This is comparing the value of i to the integer value of the character 0 or 1 which are actually 48 and 49 respectively. Check out an ASCII table for more info on this.
Try removing the single quotes and just have something like this:
switch(i) {
    case 0:
        //case 0 stuff
        break;
    case 1:
        //case 1 stuff
        break;
}

This will compare the value of i to the number that you expect.
I suppose another way to fix this would be to add 48 to i every time you check it. I would change the case statements though.
UPDATE
You should be declaring the ready state variables outside of your loop() function and then initializing them in setup().
Something like this:
int ready1state;
void setup() {
    //setup stuff
    ready1state = 0;
}

void loop() {
    //loop stuff
    ready1state ^= 1;
    //use ready1state
}

That was a stupid mistake on my part.  Now I have the relay and the light turning on but doesn't respond when pressed again. (i.e. light stays on, relay stays in position)

No worries, we all make silly mistakes! As for the lastest problem, does the code enter the else block? Does it ever print out "Outlet 1 off" or "Outlet 2 off"?

No, it doesn't print when it is supposed to switch off. I would gather that the else block isn't being entered.

Oh, should have seen this earlier. You declare your ready states equal to 0 at the beginning of the loop() function. So every time the code loops, your ready states get set to 0 and then xor'ed with 1 which equals 1. So it will never enter the else statement. Declare them outside of a function (like where your defines are) and then set them equal to 1 in setup(). I'll post an update in my answer.

Made your suggested change. Still looks like it's not getting to the else part. Lights up and relay trips, but after the one press of the button, no other buttons or relays respond (nor does that same one turn off).

Hmm... Maybe add a serial print out of the value of relay state to see if it actually toggles. If that isn't the issue, you have to verify that the trellis functions that you are using are working as expected. The fact that no other buttons respond after the first one makes me wonder about the readSwicthes() function.

@Doowybbob relay1state is declared static, so that wasn't a problem.

It's actually a good point. This library has nil for documentation, just examples, and so I'm working with it by looking at the Python version of it (which does have some documentation in comments of the library). I'll look around and see if I'm misusing this function.  You guys have been a fantastic help!


text:
How to avoid odd naming rules for Arduino when writing a library?
I'm building a small library that will be used and production and released open source. I'm paying a lot of attention to the "best practices" to make sure this code is reliable and easy to use. I also would also like to make this easy to edit. I'm having an issue with the naming scheme of the whole project.
There are a few Arduino naming quirks. If I have a sketch called mylib:

...I can't create a tab called mylib.cpp. However, I can create a file called mylib.h...
...The folder and main sketch file must be the same name as the folder it is in
...The sketch name (and folder) cannot contain any spaces.

Well, why are you creating a sketch for a library? The Arduino IDE won't open a .cpp file unless there's a sketch in that folder (and you have to open the .ino/.pde file in that folder). I'm trying to get this to work with the Arduino IDE so, if users need to edit the library, then can just open the file and go to the correct tab. If they use an external editor, they won't be able to compile it to see if there are any errors.
I'd ideally just do this structure:
my_lib
   |- my_lib.ino
   |- mylib.cpp
   |- mylib.h

However, a user might see that the folder is called my_lib and try including the file my_lib.h.
I think this is a major oversight in the Arduino IDE, but I need to have this work with the Arduino IDE. If it was just me working on this code, I might consider making the library directly in a project directory, but that isn't ideal. Is there anything that I can do to bypass this/make it easy for users to edit? Is there any "standard"/"convention" that defines how to do this?

I'm currently trying to spin the thoughts going through my head into something not quite so negative (about the Arduino IDE), but... nothing doing.

@Ignacio after a few things like this, I couldn't agree more. I'm really confused why it does this...

Usually you would not expect a user to be editing library code.

Why not just have them edit the library in an external editor? If they want to compile, they just open the example you include with the library inside Arduino IDE and press verify. Alt-tab back and forth, I use that a lot.

@user2973 but how would you open the .cpp file in the first place to see if it compiles? You can't, and the command line isn't ideal (even if it supports compilation from non .ino files)

@Annonomus Penguin The Arduino IDE will automatically compile all .cpp files in a library folder when you include a header from that same library - regardless of the file name.

The IDE copies your files to a temporary location to compile them. In the process your main sketch gets some preprocessing (ie. adding function prototypes) and copied as a .cpp. Thus your mylib.ino cannot also have a mylib.cpp file in the project, because they would both end up being mylib.cpp once copied to this temporary location. BTW - to avoid this preprocessing stuff just leave the main sketch empty, and just put all your code into .cpp files. There are a few caveats: How to avoid the quirks of the IDE sketch file pre-preprocessing

That's is one very good reason to use UECIDE (http://uecide.org), who impose no such limitation and it's better in every way.

Yep, the Arduino IDE kinda sucks eventually. There is no best practise really, as Arduino *.ino files aren't proper c / c++ anyway. I would hope that people who know how to write C++ classes (as opposed to Arduino) would be able to do it outside the IDE.
My suggestion would be to make the *.ino file a test file. That is, it runs a set of functions to check that the library behaves as desired. It could also include example code, so people who use the library know how to include it in their programs.
All that being said, time to fly Penguin...  Ditch the Arduino IDE and go with embedXcode or some other third party IDE template :P

(I just wanted to put a pic of a penguin)

+1 for that penguin :) Anyway, I still need the compile with the Arduino IDE, so I don't know if a third party IDE would really work...

I forgot to add i'm in the same situation - writing code that others might have to maintain using the Arduino IDE. I never  thought to including an ino file in there, so thanks for the question.

...well thanks for the penguin! :) Anyway, there doesn't seem to be an ideal situation. I think I'm going to use the naming rule [in my answer] for my main GitHub code and then just rename and move the .ino` file to an "examples" folder when making a release... that way users can get the best of both worlds.

@AnonymousPenguin I know I'm late to the party (as usual) but there's a setting on the Arduino IDE called 'use external editor' that blocks you from editing in the IDE and lets you use an external program (e.g. notepad++) to edit your code, and then you just use the IDE for compiling and uploading. Also creating the .cpp in the directory it's supposed to be in works too if you reboot the IDE afterwards. (These are the sorts of terrible problems you get when you target a tool for programming circuits at non-programmers.)

For anyone curious what I did, I ended up doing a naming convention like this:
my_lib_v1_2
   |- my_lib_v1_2.ino
   |- mylib.cpp
   |- mylib.h

Then, the user could include mylib.h still, and people with the Arduino IDE could edit it.

The Arduino IDE's restriction of not allowing you to create a .cpp tab with the same name as the sketch has been removed since the 1.6.12 release.
In fact, older IDE versions would happily open and save sketches that contained, e.g., mylib.ino and mylib.cpp. You just needed to create the .cpp file outside of the Arduino IDE.
The reason for this restriction in previous IDE versions was that the file in the temporary build folder generated from the preprocessed sketch was named {build.project_name}.cpp, which would be overwritten by the other .cpp "tab" file of the same name. Of course that is not an issue for your desired usage of the Arduino IDE simply to edit library source files. Later, the Arduino developers changed to the much more sensible system of naming the preprocessed file {build.project_name}.ino.cpp. Thus the restriction was no longer necessary.


text:
Measure low current with variable voltage
I want to make a system that always have the same current (about 1ma) in a water with silver electrode. At start it will be purified water so conductivity will be really low.
But with time silver particle will be released in water, raising his conductivity so if I don't lower the voltage the current will raise too (meaning that bigger particle will be released which I don't want too).
So, is there any way I can measure low current and adapt voltage with the result (since deducting resistance wouldn't be hard).
I know about ASC712 but It seem that he can't be precise enough (steps of 13ma max) to my use.
I precise it's not that long I'm trying to get back in electronics with arduino so many school things have been forgotten.

What you want is called a constant current source. You can actually build a simple one using one transistor ; but a better one uses two transistors - as in the left example below - see this page for explanations.

Here the leds would be your load, R=680 Ohm would give you about 1mA - and you would need to increase the value of the 2k2 resistor to somewhere around 22k.
The problem is that, as John Williams noted, forcing 1mA through a high resistance requires high voltage : 1MOhm would need 1kV, 10MOhm needs 10kV etc. That's very dangerous voltages! and quite some power as well : 10kV at 1mA means 10W.
I think you need to define your needs first :

What is a tolerable error on the absolute value of current? (Would constant 1.1mA be OK?)
What is a tolerable error on the current variations? (Would current varying between 1.19mA and 1.21mA be OK?)
Do you absolutely need 1mA right from start? Or can you accept a lower current at start, growing with increased conductivity until 1mA is reached and then being held nicely constant?

If the above examples are fine, a current source as described above would do the job nicely for less than 1USD.
If you really need a constant current source right from the start, then be prepared to work with expensive and dangerous pieces of equipment.

I maybe not need 1mA from the start I think that's mostly for the end of the process but that's not very well documented anywhere :/. And I don't need to be precisely 1ma either, I even think that I can go to 10 or 50ma without issue but again there is no really exact value to refer out there

Alternatively, you can buy ready made unit. Random search from web give example like this has 3 models for, 1.5, 3 and 6kV 1mA constant current.  http://www.matsusada.com/high-voltage/sc/
Safety first if self make (do you need a unit for use or you want to do exercise trying to make it). May not be a easy project.
Your post stated 'purified water', resistance will be really high, in many mega ohm range, if it is really pure.
First measure resistance with multitester to get realistic ohm reading in pure and later stage when "with time silver particle will be released in water".
The hi and then lower ohm will get you voltage needed. to drive 1mA through multiple mega ohm need kilo volt and need special circuit and suitable experience for hi volt safety.

if you may describe more about your intended application, people may be more help in alternate idea/method. Like, it that hobby or 'real' use? Why you need to drive that much current into purified water? At 10 watts, 10KV, it will be quite a bit of hydrogen/ oxygen gas for REAL explosion risk. Today news, gas explosion kill 100, hurt 300, damaged kilo meters of road and car flied 30 foot and landed on rooftop.

Correction. 10 watts make a lot of gas at more typical low volt case. At high voltage (if purified in original post refers to distilled or RO water, at commercial/industrial/factory/lab quality level), 1 to 50mA, gas quantity is much less.


text:
External (pin change) interrupt and power consumption
I want to write a lipoly powered arduino device that can be launched from sleep mode by pressing a certain key that is connected to ground. Usually, when no in sleep mode I enable the internal pull-up resistor for a definite level. But when in sleep mode, I assume this would drain to much power and hence I want to avoid it. Is it sufficient to just wait for a pin-change interrupt on the same port pin without the internal or an additional external pull-up resistor?

The rule for micropower sleep mode is not that you can't have pulling resistors, it's that you can't have anything such as a switch holding a signal against it's pulling resistor, as that would put a voltage difference across the resistor and cause measurable current to flow.

You must not leave CMOS inputs floating. This will increase power consumption, and as a worst result may damage the device. Use an external pull-up if you feel that the internal pull-up passes too much current.

It doesn't matter what internal or external value you use for a pullup resistor unless something is creating a current path to ground.  Hopefully the button is not being held down while the device is trying to sleep, so that is a non-issue.  The other possible path would be leakage through the input structure itself, but if that is present you are going to have to put current through it if you want the input to be high, and there isn't going to be a drastic difference between the current necessary to be reliably high and the current which would be supplied holding the input even closer to Vdd.

Yes, was a thinking error about the pull-up resistor draining to much current. The push-down button of my rotary encoder usually is open, but for the two rotary channels I'll set the outputs to low - in case the rotary encoder has a connection to GND which would result in the pull-up resistor draining current. BTW, IIRC, the default port state is input by default. For unused port pins, should I always enable the pull-up resistors or make them to output? Or does the massive default code produced by Arduino already does it?

Tutorial from University of South Florida
https://www.youtube.com/watch?v=HiAbxSO_9nU
Internal pull-up resistor does not drain too much current. Only leakage in nA range. It is correct to use pull up, in your case, as this is what it is designed to do. As Ignacio Vazquez-Abrams, do not leave input pin open.
MCU are designed to do the precise action you mentioned, to wake up on pin change as in mass produced wrist watch and TV remote controller. On remote, MCU sleeps until key pressed. On watch, it wake on timer 1 second) and key change.


text:
YUN. How to reset the micro controller from linux?
As the title, I'd like to reset the Arduino sketch from the linux machine. Is it possible? how?
One solution could be to save the hex file inside the sd card and then upload it via the lua sketch but I think there is a smarter solution.

Use command reset-mcu: it's a linux script that resets the 32u4 via GPIO

According to the Yun schematic, GPIO18 of the SoC is connected to the MCU reset circuitry. Toggling it should allow you to reset the MCU.

I lightly understand what are you saying. Any ideas on how practically do it?

Depends on where you are when you want to reset it. C? Python? Shell?

python or shell.. c is only the last resource (I'm not good at C)

http://linino.org/doku.php?id=wiki:gpio


text:
H_Bridge with PWM gets too hot
I'd like to use an H-Bridge  AND send PWM signal.
I've used this schematics: http://itp.nyu.edu/physcomp/Labs/DCMotorControl
and use the PWM signal inside the enablePin. But the H_Bridge is getting very hot.
Am I wrong?
EDIT:
I'm using and H-Bridge but not for driving a motor, instead I'm driving a peltier cell (like this one: https://www.sparkfun.com/products/10080). What I'm trying to achieve is to have a fixed peltier cell and to have in the same side sometimes hot, sometimes cold. This behaviour is done by switching the positive and negative with the H-Bridge. To control how much cold and how much hot I'm using PWM.

Short answer: You're drawing too much current through the H-bridge.
Longer answer: The H-bridge is most efficient when fully on and that's when the chip gets rated for the maximum current. The rating also, probably, states that a heat sink is attached to the chip. Using PWM to slow down the motor decreases the current going through the bridge, but also incurs inefficiencies because the transistors / MOSFETs are partially on, and thus acting somewhat as resistors. This inefficiency manifests as heat.
So you have several options.
1. Choose a smaller motor.  This reduces the overall current needed.  Only feasible if this is a learning project.
2. Choose a beefier H-bridge.  This increases the ratings of the bridge to handle current for this motor.
3. Add a heat-sink to the existing bridge.  This will help dissipate the heat generated.
Generally I'd recommend both 2 and 3, but it depends on your ultimate goal of the project.

I'm not using a motor, see the edits.

Ok, but the same applies to the peltier device. You're drawing too much current through the chip.  Choose a different chip for the bridge and heat-sink it. Though that may seem odd for a project with heating / cooling features, but if your bridge overheats it will stop doing what you want.

This L298N board with heat sink is widely available, low cost, used in many successful project with 2 amperes capacity to support reasonably large motors.
Video, tutorial, code example in:
http://www.youtube.com/watch?v=qwNvYYqBy7I
http://www.icstation.com/product_info.php?products_id=2540#.U90l_kBbIlh
http://arduino-info.wikispaces.com/MotorDrivers
http://arduino-info.wikispaces.com/ArduinoShieldL298N

I'm not using a motor, see the edits.

Your peltier cell is 7A, well above L293 and L298. Choose one of these, says about 10A to 12A (with some spare for safety) http://www.pololu.com/category/11/brushed-dc-motor-drivers. Software is same, motor forward/backward become hot/cold. No issue of fast brake in your case. Some 2 pins units can be used. if doubt, ask tech support of the seller and they also have excellent document at web.

Temp control is relatively slow, depending on heat capacity of load. PWM can give you very accurate temperate control at range of 0.1 degree centigrade or better. If cost is concern, use on off control if no demand for too high accuracy, by solid state relay or mechanical relay (switching time slower, lower accuracy).

Are you using the L293NE or the SN754410?
My guess it the L293NE. With this one, if you set the enable to low, it will go into "Fast motor stop". What this does is short the two pins of the motor. This will make the motor turn into a dynamo, will all the current that is being generated going through the IC. This will make the IC hot.
This also means you motors are running very inefficiently.

I'm not using a motor, see the edits.

Try lowering the PWM frequency to something like 1hz.

According to data sheet from factory, L293 and L298 do not go into fast stop mode if you connect and program them as below.
They have two inputs to control direction and one ENABLE for PWM.
When PWM signal is zero, both transistors are high impedance according to page 2 of factory data in http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0CDUQFjAB&url=http%3A%2F%2Fwww.ti.com%2Flit%2Fds%2Fsymlink%2Fl293d.pdf&ei=0z7dU-G4OZPf8AX-loDQCA&usg=AFQjCNEHiZAPaBUP_j8kV3BBPstAKiFDyw&bvm=bv.72197243,d.dGc
Data sheet Page 6 of L298, PWM connects to enable. CD is 10 and 01 for direction. fast stop is CD 00 or 11
http://www.st.com/st-web-ui/static/active/en/resource/technical/document/datasheet/CD00000240.pdf
Hope it helps


text:
square root of large number
I've got 2 int16_t numbers, say 388 and 10288, which are sensor readings from an accelerometer. I want to estimate the angle of the device on that, but seemingly there are some type overflow issues:
My final goal is this:
theta =  atan(-ax/sqrt((float)ay*ay+az*az));

The problem occurs in the bracket: ay^2 and az^2 are the 2 power of the given numbers. I recalculated with matlab and for the above example I get a^2+b^2 = 388^2+10288^2 = 105993488 what I get from the arduino however is 152848.
To be short: I don't know much about fixed point math or thelike and I couldn't find a sufficient answer to this: How do I calculate the square root term?

You need 2 typecasts. So
atan(-ax/sqrt((float)ay*ay+(float)az*az));

Otherwise it will use int16_t for the right side of the addition and overflow.
Though for speed you might want to typecast them as long (int32_t), as floats calculations on the arduino are really slow. The sqrt function will covert this double into a float for you.

Ah, so dumb, thanks!     'theta =  atan(-ax /sqrt((uint32_t)ayay +(uint32_t)azaz)) *RAD_TO_DEG;'
works! uint, because its squares, which are allways positive^^. Could you however explain to me how sqrt and atan work, when getting an int as input as here? Do they cast automatically? If so, which casts do they do (can I make that obvious by casting myself?)?

sqrt is part of math.h, and it accept a double. A float, in arduino and most cases, is a double. Why it automatically typecasts, I don't know. I would rather expect a compile error, but I don't know C. PS in my question I said double, but meant to say long (fixed in edit).

Because sqrt() and atan() are declared (in math.h) to be functions of double returning double (e.g. double sqrt(double x);), the compiler knows to cast a non-double argument to double before calling the function. Yes, you not only can write the cast explicitly; it is good practice to do so, making clear to the reader that you intended / were aware of the cast.


text:
What is exactly MQ-2 sensor?
What does the MQ-2 sensor detect?
I know it detects concentrations of flammable gas. But does it detect smoke from fires too?
What about smoke from cigarettes, and other things?

Simple answer is no.
There are about 10 similar sensors, each detect specific kind of chemicals


text:
Read multiple char from USART
int i, j;
char data;
int flag=0;

void loop()
{
if(Serial.available() > 0){
    data  = Serial.read();
    flag=0;
  }

  if (data == 'd' && 'b') {
    digitalWrite(cONOF, HIGH);
  } else if (data == 't' && 'w') {
    digitalWrite(cONOF, LOW);
  }

  if (data == 'y' && 'w') {
    digitalWrite(start, HIGH);
    delay(2000);
    digitalWrite(start, LOW);
  }

  if (data == 'e' && 'r' && 'h' && 'i') {
    for (i=0;i<10;i++) {
      digitalWrite(horn, HIGH);
      delay(100);
      digitalWrite(horn, LOW);
      delay(100);
    }
    for (j=0;j<10;j++) {
      digitalWrite(horn, HIGH);
      delay(500);
      digitalWrite(horn, LOW);
      delay(500);
    }
    digitalWrite(horn, LOW);
  }

}

I want to read data from the USART where the messages have more than one character. I tried the code above but it doesn't work well. For example, I want to send the message 'db' to turn the output on, but just sending 'd' also turns it on, how do I fix this?

You need split the reading into two processes - storing the characters and checking if they are the right message.
To store the characters for example:
String message = "";

void loop()
{
while(Serial.available()) {
    char b = Serial.read();

    if (b == '\r') {
        processMessage();
        message = "";
    }
    else {
        message += b;
    }
}
}

The process might look like
void processMessage() {

    if (message == "fb") {
         foo();
    }
    else if (message == "bf") {
         bar();
    }
}

I just use the Messenger library usually. But note you have to change WProgram.h to Arduino.h in Messenger.cpp to get it to work.

ohh yaaa thx broder :) it works... perfect

Just be careful, in the code I posted if the string gets too big you could run out of memory. Might be wise to count the characters going in and stop adding em if it gets too long. Please accept my answer if its all good :P


text:
Delay function without using a timer
Is there a delay function available that does not use millis() which itself makes use of a timer? Does not need to be hyper-exact.

delayMicroseconds(1000);// maximum delay is 65535 uS

or
#include <util/delay.h>
_delay_ms(1);

delayMicroseconds() does not accept long int (32-bits) but only unsigned int (16-bits), hence the maximum you can pass it is 65535.


text:
125 kHz RFID reader with Arduino
Why is a toroidal inductor being used in the RFID reader described in DIY FSK RFID Reader?
I feel that a toroidal inductor wouldn't be very effective in grasping the changes in electromagnetic field changes.

The word "toroidal" may be misapplied in the instructions. They don't show a picture, but their description doesn't seem to include any toroidal core which would contain internal / exclude external flux in the manner you are thinking of.

Yes, Chris Stratton is right. A toroidal inductor keeps flux within the core, reduces the external flux to near zero and have near zero ability to grasp/convert external flux/magnetic field into electrical signal. Apparently, the word 'toroidal' was used in loose sense referring to a circularly shaped coil.
In an real-life commercial product, a 125 kHz coil typically has many turns on a very thin wire on an open-air core (no core).
An example profession factory made a 125 kHz RFID with a GitHub Arduino library and photos of an antenna coil:

125 kHz RFID module - UART
Seeed-Studio/RFID_Library
125Khz RFID module - UART (wiki)

Also, see Building RFID Card Reader using PIC Microcontroller.
Note, for higher frequency RFID, not shown in above examples, coils have fewer turns than for 125 kHz.

While this is supporting material, you have three answers here none of which answer the actual question which was asked.  At the very least you should be combining them.

So If they mean about circular Inductor for 'toroidal' ......why did they use 'former' word(empty scotch tape as former)....

One link inside the article leads to this, http://forums.parallax.com/showthread.php/105889-World-s-simplest-RFID-reader.  At middle page, the coil, same shape as the factory made example but bigger, is 'just visible' (red color wire) sitting under the white tag.  Big size antenna, in this photo, can work longer, may be 6 to 12 inches, instead of the typical 1 to 2 inch when coil is human palm size

authors: Сергей Говядовский


text:
Olimexino (32u4): power down
I want to power down my Olimexino as much as possible and only wakeup on a pin-change interrupt. I removed the 3.3V/5V jumper (so the processor does not get power) and 3µA were displayed, so the voltage regulator is really a low power variant. What I have done:
#include <avr/power.h>

power_all_disable();
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_cpu();

This resulted in still using 220µA. Now I disable the ADC, too:
ADCSRA = 0;

which reduces it to 100µA. I've tried to disable further ADC-stuff using
ACSR = 0;
ADMUX = 0;

and tried to disable (?) the Watchdog Timer using
WDTCSR = 1 << WDP3;

but without any further improvements. The datasheet for the 32u4 suggests to disable the Brown-Out-Detector, too, but I don't seem to be able to do that using code, but only by setting some fuses which is not possible directly using the Arduino IDE. Any further ideas?

Did you use the PRRx registers? Did you disable JTAG? Why can't you use ISP?

PRRx registers are set using power_all_disable(). JTAG? I don't use ISP, because that doesn't work with the Arduino IDE.

ISP works fine with the Arduino IDE. It just doesn't work with the USB connection. Besides, you wouldn't set the fuse through the IDE regardless.

The timing for setting the registers to disable the brown-out-detection is pretty strict. You'll have to set the registers right before sleep_cpu()

Gerben, what registers to set for the 32u4?


text:
Using both TMRpcm and VirtualWire libs with ATmega328, despite the conflict on TIMER1
I wanted to use both TMRpcm and VirtualWire with ATmega328 in an Arduino-like board I'm making, but both libraries use TIMER1. I wanted to use each lib for the following purposes:

TMRpcm: play a WAV sound from an SD Card;
VirtualWire: to receive commands from an RF remote control.

TMRpcm Advanced Features Wiki has a section on how to use TIMER2 instead, but I couldn't get it to work. They also say:

Notes:

This is usually not the best solution.

So, before I spend any more time on this, I would like to hear what you guys have to say.
So, my question is: is there a workaround to solve this conflict on the use of TIMER1, so I can use both libs in my project?
If not, what other alternatives do I have?
My circuits for reading the SD card and driving the speaker are similar to the schematic in this Instructable: Playing Wave file using Arduino. And I'm using one of those
433MHz Receiver modules for the RF part (standard, working circuit).
Both features, the RF receiver and SD card WAV playing, work correctly, when run separately (with separate sketches).

I ended up working around the issue by building a board with two ATmegas in it. One MCU handles the sound while the other handles the RF receiver, each using its own TIMER1, both communicating via I2C.
It's kind of a low tech dual core controller board. Not the most efficient solution, but it worked great for me.

You could edit the VirtualWire.cpp source to use Timer2 instead of Timer1. For VirtualWire 1.18 the relevant section starts on line 512 with #else // ARDUINO.
On line 515 change (uint16_t)-1 to (uint8_t)-1 since Timer2 is only 8 bit. Then change all the TCCR1A, TCCR1B, OCR1A, TIMSK1 and OCIE1A to their Timer2 equivalent (hint: swap the 1's for 2's). Line 533 should be the last. On line 778 you also need to make a change to use TIMER2_COMPA_vect for VW_TIMER_VECTOR.
I hope that it helps.

For good measure also change OCIE1A to OCIE2A, and WGM12 to WGM22, though they have the same value so it will work without.

Gave it a try but couldn't make VW work with TIMER2. Instead, I'll try Manchester encoding lib a go...

Got the Manchester libs working, but also got a lot more dropouts with it, so I couldn't even get to make it work with TMRpcm.

the virtual wire library has been obsoleted, and you should now use the RadioHead library. In this RadioHead Library, you can edit the RH_ASK.cpp file, and uncomment the #define RH_ASK_ARDUINO_USE_TIMER2 near the top.


text:
Shortest time interval that Arduino Uno R3 can read
I am doing a light speed determination experimsmt. Lightspeed is around 3*10^8 m/s. For this, I need to measure time interval between 2 light sensors in nanoseconds, Somewhere about 50ns. Is this possible using the Uno R3? I know the clock is 16MHz only but is the clock irrelevantto the topic? If it is not possible, Some tips would be helpful. Thank you.
Sorry for irrelevant tags. No suitable tags found.

You may be able to do much better with other parts having faster timer clocks; a lot of relatively easy to work with ARM chips may push this close to if not over 100 MHz.  The ATtiny 25/45/85 have possibility as well, but may need some calibration trickery as the PLL seems only to work with the imprecise internal oscillator.

At 16MHz, the quickest operation that the cpu can do (a one cycle operation) will take 62.5 nanoseconds (1/(16*10^6) seconds). That means the best resolution you could conceivably have is 62.5 ns chunks. It will take considerably longer than one clock to respond to an outside event though, so making an experiment will be really tough even then.
Maybe you could build an experiment like the Fizeau apparatus where the arduino measured pulses of light that make it back through the slit? Those would be measured in microseconds. The arduino could change the speed of the grooved wheel and maximize the returning pulse width, reading the rpm then gives you the speed of light.
I'll note that since the meter is defined by the speed of light, and the foot defined by the meter, You would not be measuring the speed of light in feet or meters per second; you would be measuring the length of a meter given how long a second is, or vice versa.

When I use h=1 metre and use a motor of 4000 rpm, theta will come in range of 10^-6. I wouldnt want this.

This would be done with a hardware timer, not the CPU.

The meter is defined by the speed of light in a vacuum. So you are actually measuring the refractive index of the air q-:


text:
What electronics should I study to create something like a fridge temperature monitor?
I would like to be able to design an Arduino circuit for a fridge monitor that would have a temperature sensor, a small speaker to emit a sound when the temperature changes past a threshold and an LCD screen showing the current temperature.
I have found a few examples online, but I would like to know why components like capacitors and transistors are used in their circuits so I'd be able to design similar circuits myself.
I found this list of electronics topics:

Basic Theory
Basic Passive Components
Passive Circuits
Discrete Active Components
Active Circuits
Integrated Circuits
Digital Logic
Analog
Signals
Outputs
Inputs
Digital Electronics

Some of these things, like digital logic seem unnecessary in such a project, but obviously some others are useful, but I don't know which. I'd like to know what it would be useful to study so I can understand the reasons for the circuit design of something like a fridge monitor.

You're going to need a large portion of that in order to do more than just banging rocks against other rocks and hoping you get a useful tool.

...or you can pick a goal you want to accomplish, and learn what you need to in order to enable it (while being open to discovering that you need to alter your goal in light of practicalities you learn about)

All of the above + embedded system design

I voted to reopen this. I removed the lamp since that's a whole other question :) Feel free to ask another question if you wish to do so.

And now we get to "It depends on what pieces you want to use.". You handle a thermocouple very differently from e.g. a TMP36. A coil speaker vs. a piezo buzzer. A bare segmented LCD vs. a HD44780U-compatible module.

Why don't you pick one of the circuits you found online, the one you find most interesting, study it a little, then post your specific questions here (or at EE.SE)? Pick a simple circuit that features only one of the components you described (temp sensor or speaker or LCD). Don't forget to post the link to the circuit and make sure there's a schematic for the EE folks to look at. That's how our site works best - to answer specific questions users have.

A fridge temperature monitor (or any system that talks to world using some data) will include a sensor (temperature sensor like LM35), a controller (to do calculations, arduino ofcourse) and an output (display, like LCD). The topics you should be aware of, are digital electronics, basic passive components (working of resistor, capacitor etc). And a little arduino programming and lots of logic.


text:
Using TMRpcm object, why is the SD Card failing to be found by arduino?
I am using this micro-sd card reader, and my wiring configuration is as follows (double and triple checked):
3.3v goes to 3.3v on the Arduino UNO
GND goes to Ground on Arduino UNO
D0 goes to pin 12 on Arduino UNO
D1 goes to pin 11 on Arduino UNO
CLK goes to pin 13 on Arduino UNO
D3 goes to pin 4 on Arduino UNO

When I run the 'basic' example from the TMRpcm library, everything compiles and uploads properly with no warnings. Looking at the Serial Monitor, I get "SD Fail", which, according to the comments, means that the SD card failed to initialize. The card is present, and works in my computer. Do I have something wired wrong, or is there another issue?
EDIT
I have tried using a different pin for D3, and changed the code as needed. Still no luck.

Without a ton of knowledge about your situation, it seems like the SD card isn't the proper format, the reader is bad, or the card isn't in all the way. Can you try a different card? Is the read only switch enabled?

The card is in all the way. It clicks into place. I don't see a read-only switch on the card or the reader. The reader may be bad, but the LED on board the reader comes on when the arduino is plugged in, which leads me to believe that is not the case. I don't have a second card on hand at the moment. What format does the card need to be in? FAT32?

As far as I can tell, FAT32. Also, a SDXC might be a problem here...

Didn't know what that was before now, but it looks like they're all larger than 32 GB. Mine is 8. I'm fairly certain it's FAT32. I had trouble with a FAT32 header it was trying to pull in earlier with the wrong path.

See  https://github.com/greiman/SdFat
Ensure it works with the sdinfo example, and then you can just use the sdformatter example to format the card.

Check if the reader is plugged in correctly. This will give a PEBKAC error.


text:
Knowing the Arduino memory capacity
I am using Arduino uno. My data is storing into EEPROM whenever i run my program, it will store multiple data depend on the loop. For my program it calculate 10 sample in 0.1 sec, so 100 sample in 1 sec. How can i know how much memory i can run?
I have added this code to my program it display 895.
#include <Arduino.h>
int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void setup(){
Serial.begin(9600);
Serial.println(freeRam());}
void loop(){}

The freeRam() method you are suggesting calculates the "space" between the heap and the stack, thus it returns the free SRAM.
There is no way to calculate free remaining EEPROM (if that is what you are asking), since it just contains some arbitrary data at arbitrary locations. Get the EEPROM capacity from the device data sheet and make sure to write within its boundaries.

Writing to EEPROM is relatively slow. Check EEPROM speed (older and new EEPROM differs greatly, some only do page write, some do byte write) and your sample size (number of byte to write) to see if 10 sets of sample in 0.1 sec is ok.

@JohnWilliams: ATMEGA internal EEPROM is indeed very slow. One erase/write operation takes easily 3ms. Thus, writing 10 values every 100ms (OPs requirement) you spend >30ms only storing the data. This is assuming that one value only has 1 Byte width.

I wonder if it is against rules to response with 'not asked' info, when the info is important for success of the original poster. EEPROM in UNO and Mega2560 is 100,000 times write life (less than 1 day in this case), as per Arduino web link to factory data sheet, page 1 http://www.atmel.com/dyn/resources/prod_documents/doc8161.pdf  People actually test it to death in http://hackaday.com/2011/05/16/destroying-an-arduinos-eeprom/  EEPROM was designed to store in frequent changing data, like calibration data, last power down and restore, etc


text:
LCD showing weird characters when using two 1-wire temperature sensors
I have a sketch to display a temperature obtained from 1-wire DS18B20 sensors. The sketch works fine, however when I connect two sensors to my board, the text on the LCD displays gets corrupted (### and other symbols shown instead of a temperature).
I have tried plugging each of the two DS18B20 sensors individually and it works with both of them, the problem shows only when I use both at the same time. I am connecting them both with black to ground, red to 5V and white to Dx and to 5V via a 4.7 kOhm pull-up resistor.
I have little idea how to check what is wrong - is it some kind of interference, insufficient voltage, or a SW problem?

After some more searching I have found Arduino forum topic LCD text corrupts after Arduino runs for length of time. I have followed this advice:

In particular, try running the LCD ground wire directly to a ground pin on the Arduino (not to the breadboard) and keep it short.

This seemed to solve the issue, therefore it was likely some kind of interference on the ground wiring. (Before this, the ground to the LCD went trought the breadboard power bus).


text:
Why is my LCD 16*2 is not displaying any characters, although all the wiring is correct?
Recently I have linked up a typical 16*2 LCD (Liquid Crystal Display) display to my Arduino Uno and have linked all the pins up.
Here is my connection:(LCD pin first)
1=GND, 2=+5v, 4=11, 6=12, 11=5, 12=4, 12=3, 14=2, 15=backlight positive, 16=backlight negative
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis()/1000);
}

This is the code that is the default for the LCD, I didn't write it.
So I have done all this and when I turn it on the screen is blank and nothing is happening. Could anyone explain what I have done wrong?

What is connected to LCD pin 3? It is the contrast V0 and need to be connected with a 10 Kohm potentiometer. https://www.arduino.cc/en/Tutorial/HelloWorld

I found connecting the LCD v0 (pin 3) to a 1k resistor to ground worked and provides a fairly viewable contrast.

Check out this tutorial on Adafruit. It will walk you through setting it up. In the tutorial they change the pins, which I believe is the issue here. Here is a snippet.

And change your pins:
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

Recently I also faced similar problem, with connection as:
1=GND, 2=+5v, 4=11, 6=12, 11=5, 12=4, 12=3, 14=2, 15=backlight positive, 16=backlight negative
Solution: I just connected VEE (pin 3) of LCD to Ground (GND) without use of potentiometer as it worked.

This will get you by in a pinch but at some viewing angles the LCD is hard to read.

If you don't need to constantly adjust the LED backlight brightness you can use a fixed resistor in place of the potentiometer.

This solution also worked for me. Just connect the ground with VEE(pin3) and showing display

worked for me as well

What is connected to LCD pin 3? Pin 3 is the contrast V0 and needs to be connected with a 10 KOhm potentiometer.
Some LCD's need a negative contrast voltage, check the datasheet of the display.
If the contrast voltage is not correct the display will stay blank.
I came across the same problem until i saw the negative voltage must be applied :-)