text:
How to prevent the Serial Monitor from closing upon re-uploading sketch?
I'll be teaching a year 10 class on the Intel Galileo gen2 and there'll be a wide (but high-level) programming curriculum, which includes introduction to console printing, using Serial.
I'd like the students to be able to write their printing code in setup() so that it's only printed once and easily readable by them. However, it's impossible to be fast enough to upload a sketch and open the Serial Monitor (which flat out refuses to open before the sketch has started), and the Serial Monitor closes itself upon re-uploading code.
Without unnecessary (and potentially for the students, confusing) use of the delay function in setup(), it's impossible to read any output originating from setup(); only things printed in loop() (which are constantly re-printed) are ever discoverable.
So; is there a way to somehow keep the Serial Monitor open, or make it capture output from before it's opened, or delay the entire running of the sketch (rather than chucking in delays)?
We'll be using the standard Arduino IDE.
EDIT
This script was run in one of two conditions...
void setup() {
  Serial.begin(9600);

  // ensure Serial is ready
  delay(1000);

  for (int i=0; i < 10000; i++) {
    Serial.println(i);
  }
}

void loop() {
}

When the Serial Monitor was opened immediately after upload, all numbers from and including 0 to 9999 were recorded in the monitor.
When the Serial Monitor was opened around 5s after upload, only numbers upward of 2243 were observed. This suggests the sketch WAS being re-run (else no numbers would have been captured; the sketch runs in significantly less time than 5s) but that all numbers between 0 and 2243 were not captured by the monitor; as if opening the Serial Monitor late enough to cause a re-run causes some monitor overhead.
This strange loss of numbers is NOT time dependent: increasing the initial delay from 1s to 4s (and waiting longer after upload before opening the Serial) did not at all vary the soonest number recorded, suggesting it is some 'line' based overhead
(but of course, how could anything fail for 2243 lines?!)
With that mystery aside, this negates the automatic re-running of the sketch upon Serial Monitor opening from being actually useful.

Opening the serial monitor normally resets the Arduino anyway. I have no problem outputting stuff from setup on a Uno. Is this different with the Galileo?

Serial Monitor is only a convenience (although the need to close and reopen it is APITA). There is nothing stopping you from using any other serial program; e.g. I have used Minicom, but most often use a dedicated serial program for logging.

@RogerRowland On the Galileo, the sketch 'appears' to restart, but actually a lot of early Serial is not captured.
See my edit.

@Milliways The objective outcome of this question is to avoid confusion in highschool students, something that wouldn't be worsoned by only the most absolutely intuitive, minimal, usable serial program.

Have you tried hitting the reset button while the serial monitor is open?  I have done this on other Arduino boards to capture stuff in the setup loop that was occurring too fast.  Otherwise using Serial1 for output connected via a FTDI cable may be the way to go.

Of course! Pressing reset does not require a re-upload, keeping the Serial Monitor open to capture all printing (no buffer filling). Perf

I assume you are uploading the code over USB - the same USB that you want to monitor for output from the sketch? If so, the serial monitor has to release the port for the uploader to be able to use it, and vice-versa, as your computer's OS will only assign a USB port to one application at a time.
It may seem like the IDE is one application containing an uploader and a serial monitor, but the IDE is not much more than a "pretty face" that runs separate compiler and uploader applications on your behalf.
Several work-arounds are possible (although I think a delay() statement in setup() is the clearest of the choices):

Add a delay statement in the setup function. If you must this, you can put it in main() just before the setup() call, but you'd take away a learning opportunity.
Use a separate hardware or software serial channel for the monitor which you could leave connected and wouldn't interfere with uploading;
Use the loop() function instead, and put a forever loop at the bottom to prevent it returning, thus making it a runs-once function.

Does this really explain that strange 'missing lines' anomaly described in my edit? I can give the computer 10s of delay to switch back to the monitor after uploading, but it still misses information.

Also, there's nothing special about the setup function, right? If I made loop a runs-once with no delay in setup, I'd have the same symptoms wouldn't I?

The only reason to put the printing code in loop() is that it is conventional to use setup() for initializing stuff, and loop() for doing work. Otherwise, you're right - no difference. As to the missing lines, I suspect it's something to do with the serial buffer filling before you connect to let it empty, but I'm not sure, without some testing, what the interaaction is. But in my projects I typically print the revision # at start-up. Without a brief delay, my terminal usually displays a bunch of garbage at connect, before it gets synchronized.


text:
Using an Arduino to switching a grounded load powered by a 12 Volt supply
I wish to use a MOSFET to drive a 12V rated LED strip from an Arduino.
The negative side of the LED strip must be connected to ground, so that means that the driving MOSFET must be between +12V and the LED strip.
This is what I have tried so far.

The load must be between my mosfet and my car battery GND.

In your existing arrangement.
Swap to P Channel FET
Swap drain and source leads (right hand two).
This will work for up to 5V feed to LEDs.
To get 12v operation you will need to add a driver between the FET gate and the Arduino.
see circuit diagram below.

To operate with FET on the HIGH (V+) side when V+ is greater than the rduino's supply voltage, the FET must either

Be P Channel with FET source to +12V and FET drain to load+ or

An N Channel with gate drive above V+.
The gate drive to the FET must go to about +12V to turn it off.
The Arduino will only drive it to +5V.

As you are unlikely to want to provide an extra high side drive the P channel option is preferred. This could be eg:

A "jellybean" bipolar transistor or small FET worth a few cents) and a few resistors, or a small N Channel MOSFET and one resistor

or

An opto isolator.

Transistor driver:
Bipolar transistor NPN (BC337 / BC817 or similar)(ANYTHING NPN will work).
R1 = 10k resistor Arduino out to base.
R2 = 10k FET gate to +12.
If an N Channel MOSFET is used for Q1 then R1 is not needed.
This could be a  5LN01SP IF you can get them - no stock Digikey.These have a very low Vgsth (turn on voltage)
Otherwise you can use a 2n2222, VN2222, BS108 or similar logic-gate N channel MOSFET.
eg VN2222. Many variants of these are widely available and low cost.

simulate this circuit – Schematic created using CircuitLab

won't it drain the 12v battery to have a link beetween +12 and GND throuth R2 ? 2) I have multiple led strips, can i simplify the circuit if i use it multiple times (reuse some components) ?

@hanoo You should be able to work out the current drain answer yourself. Treat all such as a learning exercise and not just blind copying or you will not progress BUT :-) ->  (1) R2 is 10k Ohms (see text). Current in 10k is I=V/R = 12/10k = 1.2 mA. Current in LED strip = Power_Watts/V. Here for say 5 Watts = 5/12 = 0.417A = 417 mA. ie R2 current is about 0.3% of LED current at 5 Watts = trivial. (2) You can place any load that works on 12V at output of M1 - so eg N x 12V LED strips as long as the FET current rating is adequate. ....

.... | If you want to drive multiple FETS at once you can connect FET gates to Q1 collector directly. This works if M1 is MOSFET. If M! is a bipolar transistor you need a resistor between Q1 collector and M1 base in each case.

source: Stack Exchange

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

sort: votes


text:
Servo Buzz / millis()
I am having a problem with Servo Buzz that I have ascertained is from the millis() function using too much time for Arduino to generate a steady pulse for the servos.
I looked at this thread but was unable to figure out a solution from the code (I'm a novice)
Stack Exchange Servo Buzz
I am including my code even though it is very large, the only time I need to servos to run smoothly is in case 4 of my switch/case.
#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
#include <Adafruit_MotorShield.h> //LIBRARY FOR MOTOR DRIVER SHIELD
#include "utility/Adafruit_PWMServoDriver.h"
#include <Servo.h> //LIBRARY FOR SERVOS

Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);
Adafruit_StepperMotor *myStepper = AFMS.getStepper(200, 2);
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
#define WHITE 0x7

Servo pan;
Servo tilt;//DECLARE SERVOS
int yy = 0; //STEP COUNTER
//declares ints
uint8_t i=0; //BUTTON INPUTS
int x = 1; //case statement movement
int input_stage = 0;
int time = millis(); //time from when the thing turned on

//user inputs
int total_hour = 0;
int total_minute = 0;
int slide_min = 0;
int slide_max = 0;
int pan_min = 800 ;
int pan_max = 2200;
int tilt_min = 800;
int tilt_max = 2200;

//Integers used for calculations for later
int total_steps = yy;
long total_time = 0;
long step_duration = 0;
int total_pan = 0;
int total_tilt = 0;
long pan_duration = 0;
long tilt_duration = 0;
long step_millis = 0;
long pan_millis = 0;
long tilt_millis = 0;
int step_percent = 0;

// Integers for real time program sliding action
int cur_step = 0;
int pan_pos = 0;
int tilt_pos = 0;
long run_dur = 0;
long start_time = 0;
int total_slide = 0;
long display_refresh = millis();
long display_dur = 1000;
int d = 1;
long end_time = millis();
int m = 0;

void setup(){
  lcd.begin(16, 2);
  lcd.setBacklight(WHITE);
  lcd.print("Welcome to LapsR");//initialize
  delay(2000);

  AFMS.begin();  //initialize motor shield
  pan.attach(10); //attach servos to pins
  tilt.attach(9);

  myStepper->setSpeed(30); // set speed

  lcd.setCursor(0, 0);
  lcd.print("By Doug E FresH!");
  delay(2500);
  lcd.setCursor(0, 1);
  lcd.print("Thanks to: Dave");
  delay(2000);
  lcd.setCursor(0, 1);
  lcd.print("Thanks to:  Max");
  delay(2000);
  pan.writeMicroseconds(1500); //set pan and tilt servos to centre ish
  tilt.writeMicroseconds(1500);
  delay(5000);
  pan.writeMicroseconds(1000); //Jitter Test
  tilt.writeMicroseconds(1000);
  delay(5000);
  pan.writeMicroseconds(2000); //Jitter Test
  tilt.writeMicroseconds(2000);
  delay(5000);
}

void loop(){
  uint8_t buttons = lcd.readButtons();  //read lcd buttons
  lcd.blink(); //set cursor to blink
  int limit1 = 4;  //declare limit switch
  pinMode(limit1, INPUT_PULLUP);  // sets pin mode to button

  //begin case statement
  switch(x){
  case 1:

   if(m==0){ //move slider backwards until it finds a limit switch
    if((digitalRead(limit1) == HIGH)){ // digital read reads the limit switch pin - HIGH means the switch is open
      myStepper->step(2,BACKWARD,DOUBLE);
      lcd.clear();
      lcd.print("stage 1");
      delay(10);
    }
    else{ //move to the next step
      myStepper->release(); //release motor
      m = 1; //set program to 2nd stage
    }
  }
  if(m==1){ // moving ahead jus a bit so there is some pad for innacuracy
    yy = 50; //step counter is initialized
    lcd.clear();
    lcd.print("stage 2");
    delay(1000);
    myStepper->step(50,FORWARD,SINGLE); //move forward 50 steps
    m = 2;//move to the next step
  }
  if(m==2){ //stage 3 dawg
    if((digitalRead(limit1) == HIGH)){//count steps til limit is hit
      myStepper->step(1,FORWARD,SINGLE);//move forward 1 step
      lcd.clear();
      lcd.print("stage 3");
      yy++; //step counter move up one
      delay(10);
    }
    else{  //display step percentage and total steps
      x=2;
      lcd.clear();
      lcd.print("step %");lcd.print((yy-100)/100);
      delay(5000);
      lcd.clear();
      lcd.print("total: ");lcd.print(yy-100);
      delay(5000);

      myStepper->step((yy - 50),BACKWARD,SINGLE); // reset to start position (minus 50 steps for pad)
      myStepper->release(); // release motor
      step_percent = (yy-100)/100; //make calculations
      total_steps = yy-100;
    }
  }

break;

  case 2:

    if(input_stage == 0){ //enter duration
      if(d==1){
        lcd.clear();
        lcd.print("Total Duration?");//start asking for inputs - start with total overall duration hours
        lcd.setCursor(0, 1);
        lcd.print("H: ");
        lcd.print(total_hour);
        lcd.print("  M: ");
        lcd.print(total_minute);
        lcd.setCursor(3,1);
        display_refresh = millis();
        d = 0;
      }
      if (buttons & BUTTON_UP) {  //sets hour up - slight debounce delay
        total_hour = total_hour++;
        delay(250);
        d=1;
      }
      if (buttons & BUTTON_DOWN) { //sets hour down
        total_hour = total_hour--;
        delay(250);
        d = 1;
      }
      if (buttons & BUTTON_SELECT){
        input_stage++;delay(250); //select button moves to next stage
        lcd.clear();
        d=1;
      }
    }
    if(input_stage == 1){
      uint8_t buttons = lcd.readButtons();
      if(d==1){  //when d == 1 update display
        lcd.clear();
        lcd.print("Total Duration?");//ask for minutes
        lcd.setCursor(0, 1);
        lcd.print("H: ");
        lcd.print(total_hour);
        lcd.print("  M: ");
        lcd.print(total_minute);
        lcd.setCursor(9,1);
        d=0;
      }
      if (buttons & BUTTON_UP) {
        total_minute = total_minute++;  //set minutes
        delay(100);
        d=1;
      }
      if (buttons & BUTTON_DOWN) {
        total_minute = total_minute--; //set minutes
        d=1;
        delay(100);
      }
     if (buttons & BUTTON_SELECT){
       input_stage++; // select moves to next stage
       delay(250);
       lcd.clear();
       d=1;
     }
     if (buttons & BUTTON_LEFT){
       input_stage--; //back moves to previous stage
       delay(250);
       d=1;
     }
   }
   if(input_stage == 2){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.clear();
       lcd.print("Slide%start-fin");//ask for minimum slide percentage
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(slide_min);
       lcd.print("  F: ");
       lcd.print(slide_max);
       lcd.setCursor(3,1);
       d=0;
     }
     if (buttons & BUTTON_UP && slide_min < 100) {
       slide_min = slide_min++; // select start position in percentgae
       d=1;
       delay(100);
       myStepper->step(step_percent, FORWARD, DOUBLE); //move forward one percent - allows user to preview positions
     }
     if (buttons & BUTTON_DOWN && slide_min > 1) { // do not allow motor to move below 0 percent
       slide_min = slide_min--;
       myStepper->step(step_percent, BACKWARD, DOUBLE);//move forward one percent - allows user to preview positions
       d=1;
       delay(100);
     }
     if (buttons & BUTTON_SELECT){ //moves to next stage
       input_stage++;
       delay(250);
       lcd.clear();
       slide_max = slide_min; //sets ending position to set min position
       d=1;
     }
     if (buttons & BUTTON_LEFT){
       input_stage--;delay(250); // previous stage
       d=1;
     }
   }
   if(input_stage == 3){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.clear();
       lcd.print("Slide%start-fin");//ask for max slide percentage
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(slide_min);
       lcd.print("  F: ");
       lcd.print(slide_max);
       lcd.setCursor(9,1);
       d=0;
     }
     if (buttons & BUTTON_UP && slide_max < 100) {
       slide_max = slide_max++;
       d=1;delay(100);
       myStepper->step(step_percent, FORWARD, DOUBLE);  //shows set stepper position
     }
     if (buttons & BUTTON_DOWN  && slide_max > 1) {
       slide_max = slide_max--;
       myStepper->step(step_percent, BACKWARD, DOUBLE);
       d=1;
       delay(100);
     }
     if (buttons & BUTTON_SELECT){ //moves to next stage
       input_stage++;
       delay(250);
       lcd.clear();
       myStepper->step((step_percent*slide_max), BACKWARD, DOUBLE); //sets platform back to home position
       d=1;
       myStepper->release();
     }
     if (buttons & BUTTON_LEFT){
       input_stage--; //moves to previous stage
       delay(250);
       d=1;
     }
   }
   if(input_stage == 4){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.clear();
       lcd.print("Pan start-fin");//ask for min pan
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(pan_min);
       lcd.print("  F: ");
       lcd.print(pan_max);
       lcd.setCursor(3,1);
       d=0;
     }
     if (buttons & BUTTON_UP) {
       pan_min = pan_min + 10;  //sets displays pan parameters
       pan.writeMicroseconds(pan_min);
       d=1;
       delay(10);
     }
     if (buttons & BUTTON_DOWN) {
       pan_min = pan_min - 10;
       d=1;
       delay(10);
       pan.writeMicroseconds(pan_min);
     }
     if (buttons & BUTTON_SELECT){
       input_stage++;
       delay(50);
       lcd.clear();
       pan_max=pan_min; //sets max to min to not cause a brownout
       d=1;
     }
     if (buttons & BUTTON_LEFT){
       input_stage--;
       delay(50);
       d=1;
     }
   }
   if(input_stage == 5){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.clear();
       lcd.print("Pan start-fin");//ask for max pan
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(pan_min);
       lcd.print("  F: ");
       lcd.print(pan_max);
       lcd.setCursor(9,1);
       d=0;
     }
     if (buttons & BUTTON_UP) {
       pan_max = pan_max + 10;
       d=1;
       delay(10);
       pan.writeMicroseconds(pan_max);
     }
     if (buttons & BUTTON_DOWN) {
       pan_max = pan_max - 10;
       pan.writeMicroseconds(pan_max);
       d=1;
       delay(10);
     }
     if (buttons & BUTTON_SELECT){
       input_stage++;
       delay(250);
       lcd.clear();
       d=1;
     }
     if (buttons & BUTTON_LEFT){
       input_stage--;
       delay(250);
       d=1;
     }
   }
   if(input_stage == 6){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.clear();
       lcd.print("tilt start-fin");//ask for min tilt
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(tilt_min);
       lcd.print("  F: ");
       lcd.print(tilt_max);
       lcd.setCursor(3,1);
       d=0;
     }
     if (buttons & BUTTON_UP) {
       tilt_min = tilt_min + 10;
       d=1;
       delay(10);
       tilt.writeMicroseconds(tilt_min);
     }
     if (buttons & BUTTON_DOWN) {
       tilt_min = tilt_min - 10;
       tilt.writeMicroseconds(tilt_min);
       d=1;
       delay(10);
     }
     if (buttons & BUTTON_SELECT){
       input_stage++;
       delay(250);
       tilt_max=tilt_min;
       lcd.clear();
       d=1;
     }
     if (buttons & BUTTON_LEFT){
       input_stage--;
       delay(250);
       d=1;
     }
   }
   if(input_stage == 7){
     uint8_t buttons = lcd.readButtons();
     if(d==1){
       lcd.print("tilt start-fin");//ask for max tilt
       lcd.setCursor(0, 1);
       lcd.print("S: ");
       lcd.print(tilt_min);
       lcd.print("  F: ");
       lcd.print(tilt_max);
       lcd.setCursor(9,1);
       d=0;
     }
     if (buttons & BUTTON_UP) {
       tilt_max = tilt_max + 10;
       tilt.writeMicroseconds(tilt_max);
       d=1;
       delay(10);
     }
     if (buttons & BUTTON_DOWN) {
       tilt_max = tilt_max - 10;
       delay(10);
       tilt.writeMicroseconds(tilt_max);
       d=1;
      }
      if (buttons & BUTTON_SELECT){
        input_stage++;delay(250);
      }
      if (buttons & BUTTON_LEFT){
        input_stage--;delay(250);
      }
    }
    if(input_stage == 8){   //confirm parameters
      lcd.noBlink();
      uint8_t buttons = lcd.readButtons();
      lcd.clear();
      lcd.print("SL: ");
      lcd.print(slide_min);
      lcd.print(" - ");
      lcd.print(slide_max);
      lcd.setCursor(0,1);
      lcd.print("PN: ");
      lcd.print(pan_min);
      lcd.print(" - ");
      lcd.print(pan_max);
      delay(2500);
      lcd.clear();
      lcd.print("TI: ");
      lcd.print(tilt_min);
      lcd.print(" - ");
      lcd.print(tilt_max);
      lcd.setCursor(0,1);
      lcd.print("Dur: ");
      lcd.print(total_hour);
      lcd.print(":");
      lcd.print(total_minute);
      delay(2500);
      lcd.clear();
      lcd.print("Left for back");
      lcd.setCursor(0,1);
      lcd.print("Select to go");
      delay(2500);
      if (buttons & BUTTON_SELECT){
        x = 3; //if user is happy with set parametres - continue to run move program
      }
      if (buttons & BUTTON_LEFT){
        input_stage--;delay(50); // if user made a mistake they can press left to go back
      }
    }

break;

    case 3:

    //calculate moving time durations
    total_time = total_hour*60;
    total_time = total_time + total_minute;
    total_time = total_time*60000;
    total_slide = slide_max - slide_min;
    step_duration = total_time/(total_slide*step_percent);
    total_pan = pan_max - pan_min;
    total_tilt = tilt_max - tilt_min;
    pan_duration = total_time/total_pan;
    tilt_duration = total_time/total_tilt;

    //display values for debuging
    lcd.clear();
    lcd.print("total time");
    lcd.setCursor(0,1);
    lcd.print(total_time);
    delay(5000);
    lcd.clear();
    lcd.print("total slide");
    lcd.setCursor(0,1);
    lcd.print(total_slide);
    delay(5000);
    lcd.clear();
    lcd.print("step duration");
    lcd.setCursor(0,1);
    lcd.print(step_duration);
    delay(5000);
    lcd.clear();
    lcd.print("total pan");
    lcd.setCursor(0,1);
    lcd.print(total_pan);
    delay(5000);
    lcd.clear();
    lcd.print("total tilt");
    lcd.setCursor(0,1);
    lcd.print(total_tilt);
    delay(5000);
    lcd.clear();
    lcd.print("pan duration");
    lcd.setCursor(0,1);
    lcd.print(pan_duration);
    delay(5000);
    lcd.clear();
    lcd.print("tilt duration");
    lcd.setCursor(0,1);
    lcd.print(tilt_duration);
    delay(5000);
    step_millis = millis();
    pan_millis = millis();
    tilt_millis = millis();
    pan_pos = pan_min;
    pan.write(pan_pos);
    tilt_pos = tilt_min;
    tilt.write(tilt_min);

    //sets pedestal to user input slide min position
    myStepper->step((step_percent*slide_min), FORWARD, DOUBLE);
    x = 4;
    start_time = millis();
    end_time = millis() + total_time;

break;

    case 4:
    long remaining = end_time - millis(); //make a couple of run time calculations
    run_dur = millis() - start_time;

    if(millis() - step_millis > step_duration){ //take one step after step duration
      myStepper->step(1, FORWARD, SINGLE);
      cur_step++;
      step_millis = millis();  //resets step duration
      myStepper->release();
    }
    if(millis() - pan_millis > pan_duration){ //same as slide
      pan_pos++;
      pan.writeMicroseconds(pan_pos);
      pan_millis = millis();
    }
    if(millis() - tilt_millis > tilt_duration){//same as slide
      tilt_pos++;
      tilt.writeMicroseconds(tilt_pos);
      tilt_millis = millis();
    }
   if(run_dur > total_time){   //resets to top of user input once total duration runs out
     x = 0;
     input_stage = 0;
     myStepper->step(cur_step, BACKWARD, DOUBLE); //sets motor back to home position
     myStepper->release(); //release motor
    }
  }
}

The thread says the underlying implementation of millis is to blame, not the actual use of the millis function. Even if you never call millis, the interrupt, that is used to count the milliseconds in the background, is still running.

You're calling millis() a lot in case 4. A very simple improvement would be to call it once at the start of loop(), storing the result in a variable. Throughout the rest of the function, simply use the value stored in that variable instead of calling millis() directly.
I doubt it will solve the problem entirely, but hopefully it will improve it a little.

It will also eliminate the probable bug of times not matching because millis() has rolled over during the execution.

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


text:
Sending large structs via nrf24l01 leads to cliping of some structs members
I started with building of the wireless temp/hygro/other values probes. I use 2 arduinos, both with nf24l01+ wireless transceivers, library used is rf24.h (https://github.com/maniacbug/RF24). Basically ping/pong test works for me - so each arduino communicates properly via nrf24l01+.
I added dht22 temperature sensor and just for testing I started with sending structure:
typedef struct{
  int A; // just counter to see if receiving new data
  float B; // temperature
} data;

data payload;

I send it from Arduino1 like this:
radio.write( &payload, sizeof(payload) );

Other Arduino2 receives the payload:
radio.read( &payload, sizeof(payload) );

This works perfectly and I am able to print the counter value as well as the temperature value on the oled display o Arduino2. The problem is when I add float C to the struct for sending/receiving hygrometer values. Then Arduino2 does not receive/display any valid hygro value, but there is just value of 0.00.
I think I know where my problem is - nrf24.h has possibility to set payload size for nrf24l01+ - both Arduinos have to use the same payload size (default is 16, min is 8, max is 32). I use 8 - as this looks to be the most reliable value when using larger distances between Arduinos.
When I tried to set payload size to 32 on both Arduinos:
radio.setPayloadSize(32);

Then it works and I can receive and display counter, temp, hygro values.
So it looks the nrf24l01+ sends a payload of either 8 or 32 bytes and when sending struct with INT, FLOAT, FLOAT - 8 bytes is not sufficient and 32 bytes of payload is needed. But when I will use many other values, I can reach also limit of 32 bytes payload.
I do not have much skills in C programming and also I do not fully understand how data packets are being transferred between nrf24l01+ modules- maybe I just need to adapt my send/receive code to handle sending of the larger structures. Maybe somebody could give me a hint.

It seems you have answered your own question: payload size is the key; you cannot transmit packets larger than the payload size. If your packets exceed the max 32 bytes size, then you will have to split them in smaller apckets and transmit them one by one.

I thought the nrf24 will take care and if I am sending more than payload size, it will send it piece by piece until all data is sent. And then the receiving side will receive it piece by piece until complete. So no way? I have to split the data manually into several "pieces" and then send more times?

Ok, clear. Found it explained here as well -http://arduino.stackexchange.com/questions/8185/increasing-payload-size-above-32-bytes-using-nrf24l01

correct, you must split it

Your payload is too big. You will have to split it to smaller pieces.
NOTE: If you'd use a library like RF24Mesh then you'd not have to worry about it.

as stated above, it all has to do with the size of your payload. To clarify things, you need to keep in mind how many bytes a certain data type uses/needs:
char: 1 byte
int: 2 bytes
float 4 bytes
(above is based on the Arduino reference, see https://www.arduino.cc/en/Reference/Float )
Thus, if you set payload size to 8 bytes in the NRF24L01 and then try to send a struct with int, float, float you will have 2 + 4 + 4 = 10 bytes, which does not fit in the payload size.


text:
How do I read from an SD card on the Yun?
I'm trying to read a small file off the SD card installed in a Yun. Here's the sketch:
#include <FastLED.h>
#include <FileIO.h>

#define WIDTH 32
#define HEIGHT 1
#define NUM_LEDS (WIDTH * HEIGHT)

#define DATA_PIN 9

CRGB leds[NUM_LEDS];

void setup() {
  // put your setup code here, to run once:
  FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
  Bridge.begin();
  Serial.begin(115200);
  FileSystem.begin();
}

void loop() {
  File f = FileSystem.open("/mnt/sd/single-line-testpattern.ppm", FILE_READ);
  f.seek(29); // seek past the header bytes
  Serial.print("position = "); Serial.println(f.position());
  for (int i = 0; i < NUM_LEDS; i++) {
    uint8_t r = f.read();
    uint8_t g = f.read();
    uint8_t b = f.read();
    Serial.print("r = "); Serial.print(r, HEX);
    Serial.print(", g = "); Serial.print(g, HEX);
    Serial.print(", b = "); Serial.println(b, HEX);
    leds[i] = CRGB(r, g, b);
  }
  f.close();
  FastLED.show();
}

Here's the contents of the PPM file:
50 36 0A 23 20 3A 20 62 79 20 54 6F 79 56 69 65 77 65 72 0A 33 32 20 31 20 32 35 35 0A FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF 00 00 FF

This looks pretty straightforward to me, but the output I'm getting is absolutely baffling:
position = 5888
r = 6, g = A9, b = A
r = B9, g = 0, b = 5
r = 0, g = E9, b = 5
r = 0, g = 0, b = 4
r = 8, g = 21, b = 0
r = 0, g = 0, b = 0
r = 0, g = E5, b = A
r = E0, g = A, b = 0
r = 0, g = 0, b = 0
r = A, g = DA, b = 0
r = 0, g = 0, b = 0
r = 0, g = 0, b = A
r = E5, g = 0, b = 4
r = 2, g = 71, b = 5
r = 1, g = 32, b = 80
r = 9, g = 12, b = 58
r = 58, g = 31, b = 30
r = 30, g = 58, b = 58
r = 58, g = 58, b = 58

WAT?! Where are those numbers even coming from? What does file.read() think a byte is? How come it's trying to read from 5888 bytes into a 125 byte file?
Note this is the FileIO library from the Yun Bridge package to read from the SD card built into the Atheron side of the Yun. The "normal" Arduino SD card library isn't relevant here.

You might try first  reading and printing out the header as a consistency check, then you could try a version that seeks a few bytes into the header.  How would you expect this library to respond to a failure, such as the file not being found?  And do you really want to close and reopen it in loop()?  Is your output from the first cycle of loop() or a subsequent one?

You are not testing if the FileSystem.open succeeded. If it did not, subsequent calls using f would possibly give undefined results.


text:
How to identify Arduino Mini Pro 5v vs 3.3v
I have many Arduino Mini Pro, every from different seller.
Few are 3.3v and most 5v.
I had to clean table for Xmas and now I do not have any idea how to identify 3.3v Arduinos.
They do not have any marks. I bought them on ebay.
I know 3.3v has 8mhz clock but only one my arduino has big crystal with 16.000-30.

Look at the central chip. 5V pro mini has 328p printed, 3V3 pro mini has 168.

The regulator should be marked K850(5.0V) or K833(3.3V).
A 5 volt part has a 16MHz resonator may be marked with "A1" or "A'N"
A 3.3 volt part has a 8MHz resonator may be marked with "80'0"
As others have indicated, you can apply up to 12V at the RAW pin, and measure the output of the regulator.

I have some 3.3V with resonator marked "80.0M" and some 5V marked "AE"

I have resonator marked as 80'Y, (Atmega 328P AU 1710) And I measured the output ACC-pin (same as VCC) is 3.3V

Consideration (go down for the actual solution)
If you have a lot of different China-Arduino-clones, the easiest way will be to just test it. The cloned Arduinos use a lot of different voltage regulators and often you won't even be able to find datasheets for them on Google.
Someone here provided an Arduino sketch which helps you identify the frequency with which the Atmel is running and the comments say "it is the safest method". But why? It is complicated (you need to connect the USB-TTL-converter to each of the different Arduinos and sometimes they have different pinouts, so it's error-prone - you could easily fry your Arduino if you connect the wires to the wrong pins)...

Solution
I think the safest way is just connecting a voltage in the range of 6V-12V to the RAW-pin and measuring the (regulated) output of the VCC-pin.
There is no reason why this would kill your Arduino (in case your Arduino isn't broken - which would be good to know anyway; and of course you shouldn't short anything).
I've done a short sketch of how you should connect your Arduino Pro Mini:

RAW <---> 6V-12V
VCC <---> multimeter (5V = 5V Arduino, 3.3V = 3.3V Arduino)
One GND pins to the GND of the power source and one GND pins to the GND of the multimeter (you can take any of the Arduino pins labeled with GND)

Don't worry if your Arduino looks a little bit different, just look for the pin labels. For instance, one of my 5V Arduino Pro Minis looks like this, but also has RAW-, VCC- and GND-labels (just one of the GND pins is at a different position, make sure you check your Arduino pin-labels):

Alternative
You don't want to use the method above for some reasons? Then you need sharp eyes and some luck that the following list includes you components (some of these are collected from the other posts, some of them from my Arduinos):

3.3V:

Voltage regulators: KB33, S20K, F34V, L0RA, L0RB
Oscillators: 80e., 80'0

5V:

Voltage regulators: KB50, L05, L0UA, L0UB
Oscillators: R160JAC6s, 16.000-30, A1, A'N, A'a

(no limit or warranty for these details...)

More Suggestions
Some of the Arduino Pro Minis come with MHz and V markings on the back. In my case, none of these were checked. Make sure you check them as your new Arduinos arrive, so you won't have any problems identifying them later!

@Paul -> Sure this question is old, but still relevant - and that's the charm of stackoverflow / stackexchange -> you often can choose between multiple answers and most of the time there is still an up-to-date answer. Most people (just like me) will come here via Google, but none of the answers satisfied me completely, so I went to write my own one (and for sure I will come here again in the future when I need this again and forgot how to do it again ;) )

S2RA is also 3V3.

Warning - some Chinese Arduino clones do not accept higher than 11.5V and you can fry them when testing. So, to play it safe, use something lower in RAW.

The safe way (i tested it).
First connect to 3.3V USB-TTL output first (also 5V Mini can work with 3.3V).
Now prepare this sketch:
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  delay(10000);
  digitalWrite(13, LOW);
  delay(10000);
}

Choose "Arduino Pro/Mini" with 5v/16MHz board and upload sketch.
If you see that the blinking is correct (10 sec ON/10sec OFF) - you have 5V/16MHz Arduino. Otherwise it will blink at 5 sec intervals instead of 10 sec.

Thanks, I thing this is the safest method ;)
(and you don't need a magnifying glass!)
I just tested it and the 5V mini can work fine with 3.3V

Thank you also. For me this is the simplest solution and works with arduino clones also.

Otherwise it will blink at 5 sec intervals instead of 10 sec. should be 20 seconds since, when running at 8MHz, things take twice as long versus 16MHz. Tested experimentally.

I hope you are all wrong otherwise it would mean the specifications of delay() function are not acurate since they would depend on the crystal frequency, I believe the function takes the clock frequency into account...so this test cannot be relevant...10000 ms would run the same delay on any arduino model (hopefully)

No, they are not wrong. When you program your sketch into the Pro Mini you have to select whether you are using the 3.3v 8Mhz part or the 5v 16Mhz part. The timing delays are adjusted accordingly. You can, in fact, program Blink into a 5v part using the 3.3v settings and it will blink twice as fast as it should and talk to the Serial monitor at 19200 instead of 9600.

Plug it in and measure the voltage on pin 4 of the MCU.

Is it safe to plug it in 5v FTDI ?

The way you ask that, it sounds like what you have isn't a Pro Mini at all, or even a clone.

I have this boards http://arduino.cc/en/Main/ArduinoBoardProMini Some have a bit different pins.

Check the label of the voltage regulator, KB50 for 5V and KB33 for 3.3

The only difference would be the regulator and crystal (8MHz on 3.3V). As @IgnacioVazquez-Abrams suggest supply power to the "raw" and measure Vcc.

Supply 5v to RAW and measure VCC ?

On my board the regulator is marked L0UA which is the code for a 5V regulator type LP2985, L0UB is also 5V.
A 3.3V regulator would be marked L0RA or L0RB.

Some clones on ebay labeled "the simple" come with 4B2X. They are 3.3v but the maximum voltage is 10v instead of 12v so beware to not burn it out.

AVR isn't specified to work at 16MHz at a 3.3V supply; it only can work at this high frequency at 5V supply. So you'll be able to tell them apart from reading the crystal. (It's possible, but unlikely, that you have a 5V version working with an 8MHz crystal. In any case 16MHz is safe for 5V.)

I wish to know if I have 3.3v 8Mhz or 5v 16Mhz. (The correct answer right is now is The regulator should be marked K850(5.0V) or K833(3.3V). But regulator is too small I can't see K850(5.0V) neither K833(3.3V).

Please post a photograph of it. Also, try shining a light on it at a 45-ish degree angle and attempt to read the reflection, rather than the ink itself.

On my board, the voltage regulator is marked F34V.  On the back is listed "The Simple" and Arduino-Pro-Mini"  I purchased it as a 3.3 v board off e-Bay, and I assume it is.  I have not yet applied vcc to it and measured the output.

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


text:
How to control 19 RGB LED strips with one arduino?
I need to light up 19 RGB LED strips, which it seems would require 19*3=57 PWM outs and 57 transistors.  The transistors aren't an issue, but of course the 57 PWM's is.  Even if I hacked the digital IO ports to work as PWM, I still wouldn't have enough.
How can I do this more simply?  Is there some kind of device I can get that would let me just pass data to it, perhaps over I2C, and it would control many PWMs? Is there another solution I haven't considered?  Maybe whatever is used to control those 8x8 RGB LED dot matrixes?
Any help would be greatly appreciated.  Thank you!

There is "set and forget" hardware available to do this, but a simple processor intensive method is to use either a 57+ long serial shift register or 9 x 8 bit parallel latches and write them with on/off patterns fast enough to PWM them. Depending on what PWM frame rate is acceptable this is "easy enough" or hard. At say 1 kHz rate you need to each of write 9 parallel latches every 100 uS or so. That's scrambling but doable.

You can use addressable LEDs that allow chaining from one LED to another using a serial protocol.
Like this :

This would alow you to set the first row blue, the second purple, each one can be controled independently.
Take a look at Ada Fruit's neopixels to start. These are basically skillfully branded WS2811 & WS2812 LEDs, but they are very well documented and well built. They feature 8 bit per channel RGB color (24 bit color) and take care of PWM internally. You could even chain the end of one strip to another, allowing all control to come from two pins of an arduino.
Assuming you go this route, consider the following:

You will need enough RAM to store the full array of pixels in memory, which is 3 bytes per pixel.  Alternatively, you can create a custom library with reduced bit depth, or one that stores pixels in clusters, because at the end of the day you are just operating a giant shift register.
You will need to supply enough current (60mA per led), and supply it at several points along longer strips.  You will likely need to use external power sources.  You can drive a decent amount of LEDs from Vin (before the power regulator), but not anything near 19 strips.

Now if you already have the strips, and they are analog strips, I think you can find similar drivers that output more power to drive strips, but still use a serial protocol.
You can use my example code here:
// NeoPixel Demo minimum
// By leo etchaas
// released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library

#include <Adafruit_NeoPixel.h>
#include <avr/power.h>

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1
#define PIN            6

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      55

// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int delayval = 500; // delay for half a second

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
#if defined (__AVR_ATtiny85__)
if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
// End of trinket special code

pixels.begin(); // This initializes the NeoPixel library.
}

void loop() {

// For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.

for(int i=0;i<NUMPIXELS;i++){

// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
pixels.setPixelColor(i, pixels.Color(25,255,255)); // Moderately bright green color.

pixels.show(); // This sends the updated pixel color to the hardware.

delay(delayval); // Delay for a period of time (in milliseconds).

}for(int i;i>0;i-=1){

// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
pixels.setPixelColor(i, pixels.Color(255,5,255)); // Moderately bright green color.

pixels.show(); // This sends the updated pixel color to the hardware.

delay(delayval); // Delay for a period of time (in milliseconds).

}
}

There are several ways you can do this:
Option 1 - the easy way: You can use a serial-in-parallel out. Google "Arduino SIPO", and you will find examples. You basically send out 8 bits at a time, to a SIPO chip, then "enable" the chip; this changes the 8 "output" pins of the sipo to combinations of high/low as per the 8 bits that went in. You can pwm the "enable" pin. The best part is that each SIPO chip has an overflow - if you put a ninth bit in, you will get the first bit out of the overflow pin, which you can hook up to the input pin of a second SIPO, and so forth.
This option uses about arduino 4 pins, for an unlimited number of output pins.
This also has the advantage that SIPO chips can normally carry much more power than an arduino. Check the spec sheet on the SIPO to see how many milliamps it can carry at once (maximum). An example of a SIP is 74HC595.
Option 2 - Control the common pin for each strip.
Basically, you will be using e.g. 3 pins to select the colour, 19 to select which strip - I think some arduinos have that many pins? To light up red on strip 3, you would put the red pin high (and green & blue low); then you would put the pin for strip 3 low, and all the others high. You would step through each pin you want to light, or you could light them in groups - first red goes high (green/blue low), and all the strips you DONT want red on have their cathode high, and those you DO want red on would have their cathode low. drop red down; then do the same for green and blue. This does mean that you can't light up leds more than 1/3 of the time. This can be combined with the SIPO chip above - it may be easier. This does mean that you need to break out the "common" (cathode, normally to ground).
None of these allow very fine-grained control like pwm - you can't just say "led 3, green, 40%"; you will have to do a lot more work. You may burn all your Arduino time just doing the LEDs; this may or may not be a problem. You have the option of offloading your work onto another AtMega chip, or even an AtTiny; I think I would use an AtTiny and three SIPOs - 4 pins of the AtTiny to control the SIPOs, and 4 for SPI to receive the new settings (e.g. send the AtTiny 57 half-bytes, would give you 12-bit colour depth). You would need to do your own "fake pwm", but you could devote the entire AtTiny to running the light show. The AtTiny is programmed the same way as an Arduino; you would use a USBISP to send the program. Just hook up the power and away you go! An AtTiny will set you back around $2, depending on how many you get and where you get them from.
ADDITIONAL!
What about using something like a TLC5940? I haven't looked at the specs, but I found a reference to Arduino code. 16 Channel, 12 bit duty cycle per channel; you would need 4 of them. Apparently they can be daisy-chained as well. http://playground.arduino.cc/Learning/TLC5940

The DM13A is similar to the TLC5940, so that's an alternative.


text:
Want to play short voice recordings, with fast switching between them
I want to output a chosen sound (e.g a singer singing a D, or E, or F note) which I have recorded.  I can change the filetype to whatever is neccessary, e.g mp3 or whatever.  The recording could be 10ms, or longer if that helps.
I want to be able to switch between notes quickly (ideally 1ms delay), is this possible?  I read about using a WTV020-SD Mini but this has a gap of 20ms between tunes sadly.
At the very least I don't want a 20ms noiseless 'gap' as it switches between one note to the next.  If it plays the old noise that would be ok, but ideally i'd like it to be able to switch between the notes in a millisecond or so.
What is the best way to accomplish this?
Ideally, the solution would be narrow, to fit in a 10mm radius cylinder, up to 100mm in length, although ideally smaller.

You're never going to fit an Arduino into those dimensions. Consider using a bare MCU instead.

The audio files can be on whatever - i'd only have about 10 of them - so not sure if they'd fit on 32KB arduino memory, or could use a microsd or anything else that would help.

The dimensions are not a huge importance if it doesn't fit, it's fine, just would be ideal if it did.  What is an MCU?  Google didn't help.  Apologies for typo - meant radius not diametre.

It's the fourth link. And fifth. And sixth.

OK thanks for that.  Do you have any information on the main topic, i.e not about the size of it?

Store the sounds interleaved in a SPI flash. Change the index of the byte you output. Since all three sounds are loaded at the same time, there will be only a few microseconds delay maximum.

Agree on the SPI flash, but no need for interleaved.  An ATtiny25/45/85 is probably sufficient, and has better PWM than an ATmega anyway.


text:
Arduino Ethernet and Uno R3 as a firewall
Is there a way to program the Ethernet Shield and Uno R3 to act as a firewall without using a huge chunk of the allowed bytes on the R3?  I plan on using a DC adapter to plug the R3 into a wall, and use the mini-SD card to keep logs while having the ethernet shield plugged into my router.
I know that it is possible to program it to do this but I want to know if there is a simple modification I can make to the web-client library or if I should use the web-server library and modify that?

You're going to be very, very, very unhappy if you use an Uno as a firewall. It simply isn't powerful enough.

Not to mention that after adding the Ethernet shield, it costs more than things which are powerful enough.

it is mostly an experiment, as I have other firewalls in place....

Statefull packet inspection would probably require more memory than the atmega has. I'd suggest looking into reflashing some router with OpenWRT. That was a great learning experience for me.

As an entry level board, I wouldn't suggest trying this on the R3. You can do it to an extent on the Yun which comes with both a network port and wifi.
Now that said, your internet speed will be severely hampered by the lack of resources on the yun. In which case, you might want to steer closer to the Intel Edison, which you can use with the arduino IDE. It is considerably more powerful.

Either one will still cost 2-3x what a platform designed for this purpose does.  If you want the challenge of do-it-yourself you can take your typical router, strip open/dd-wrt down to a bare embedded linux pre-ported to the hardware, and rebuild the routing/filtering configuration atop that from scratch.  Generally speaking, you want a board with two network interfaces for a firewall, as otherwise you are relying on the wan adapter and clients to behave by talking through you and not simply bypass you as they potentially could in a single-interface case (if misconfigured/compromised).


text:
modbus slave ID setting
I have small problem in setting device ID for Mosbus slave arduino. Here is simple example
In Modus library; device ID being configure hardcode while program. This code works for Me.
Modbus slave(1,0,0);

Now I wanted to recognise 0-255 device ID , I am using 8:1 digital Multiplexer & DIP switch to select the port. I am reading status of digital pin & depend on status of 8 DIP pin i come to know whats device ID. Below function return device ID. I have checked Serial it returns value properly. If i assign the value to Device ID it wont work . Please let me know how can i solve this.
unsigned int ID_Check() {
      unsigned   int ID_value;
      for(int row=0;row<8;row++)
      {
        digitalWrite(SO_enable,array[row][0]);
        digitalWrite(S1_enable,array[row][1]);
        digitalWrite(S2_enable,array[row][2]);
        Status_Out[row]=digitalRead(Output_Read);

      }

  ID_value = 1 * Status_Out[0] + 2 * Status_Out[1] + 4 * Status_Out[2] + 8 * Status_Out[3] + 16 * Status_Out[4] + 32 * Status_Out[5] + 64 * Status_Out[6] + 128 * Status_Out[7];
  return(ID_value);
}

Below is complete code.I tried to call function loop But it wont work
#include <ModbusRtu.h>
int SO_enable=5;
int S1_enable=4;
int S2_enable=3;
int Status_Out[8];
int Output_Read=2;
Modbus slave(ID_Check(),0,0); // this is slave @1 and RS-232 or USB-FTDI
int array[8][3]={
  {
    0,0,0    }
  ,
  {
    0,0,1    }
  ,
  {
    0,1,0    }
  ,
  {
    0,1,1    }
  ,
  {
    1,0,0    }
  ,
  {
    1,0,1    }
  ,
  {
    1,1,0    }
  ,
  {
    1,1,1    }

};

unsigned int ID_Check() {
  unsigned   int ID_value;
  for(int row=0;row<8;row++)
  {
    digitalWrite(SO_enable,array[row][0]);
    digitalWrite(S1_enable,array[row][1]);
    digitalWrite(S2_enable,array[row][2]);
    Status_Out[row]=digitalRead(Output_Read);

  }

  ID_value = 1 * Status_Out[0] + 2 * Status_Out[1] + 4 * Status_Out[2] + 8 * Status_Out[3] + 16 * Status_Out[4] + 32 * Status_Out[5] + 64 * Status_Out[6] + 128 * Status_Out[7];
  return(ID_value);
}

uint16_t au16data[16] =
{
  3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1
};

void setup() {
  slave.begin( 9600 ); // baud-rate at 19200
  pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
  pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
  pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
  pinMode(Output_Read,INPUT);
}

void loop() {
  slave.poll( au16data, 16 );
}

The other way i tried
void Modbus_Setup()
{
  Device_ID=ID_Check();
     delay(100);
    Modbus slave(Device_ID, 0, 0);
     slave.begin(9600);
  //slave.setID(Device_ID);

}

It looks like the problem may be initialisation order. In C/C++, global variables/objects are usually initialised in the order they are declared, and before any global functions run.
In your case, this means ID_Check() gets called before array is populated, and before setup() runs.
It looks like you need to make sure everything else is setup before your attempting to initialise the Modbus object. I'm not familiar with the library, but perhaps there's a way to set the device ID after it's been constructed (i.e. not in the constructor)?
If not, you could declare slave as a global pointer, and then instantiate it using new in setup().
As a side note, I'm guessing your Modbus_Setup() function didn't work because the slave object in there is completely separate from the slave object that's declared globally and used in loop().

can you show how can do it. How can declare slave as global pointer. As given in example ; if declare slave as globally & assign the device ID with No. code work. But my intension is to device id being update hw read

If i cant configure using mux & DIP switch . I need to configure manually. or i need to remember each device ID being used so to avois conflict.

I have tested their example code. When i declare slave globally. it will work. If i declare inside setup & assign slave ID . It wont work. How can assign my slave ID here.

@AMPS Declare it globally as Modbus *slave = 0. In setup(), instantiate it using slave = new Modbus(...). (That's standard C++. I'd recommend looking up a tutorial on pointers if you're not familiar with them.)


text:
Will the 3.3V regulator on an Arduino Leonardo work when powered from USB?
Will the 3.3V regulator produce 3.3v when the Arduino is powered from the USB port?

Will the 3.3V regulator on an Arduino Leonardo work when powered from USB?

Yes, provided that

it is an "official" Leonardo or a competent clone and
as long as you do not load the power supply excessively with external loads.

Official circuit diagram here
The USB supply feeds the 3V3 regulator via MOSFET T1 at the bottom of the sheet and U3, an LP2985 LDO regulator. If your board has the same circuitry as this it should provide 3V3 from USB.

The 3.3V regulator is fed by the 5V, whatever that comes from. If you don't use a separate power supply like a wall-wart, the 5V switches automatically to the USB's 5V. That feeds the regulator for the 3.3V.
So yes, it will produce 3.3V.


text:
Does the compiler generate intermediate assembler?
My source files are *.ino, but after compilation there aren't any other files placed in the folder. Does the compiler generate intermediate assembler, and if so, where does it leave them? Or is the machine code available somewhere?

If you switch to a Makefile build or in some other way can customize arguments then you can ask avr-gcc to produce assembler ouput.  2) Alternately you can use avr-objdump to disassemble binary (or with the aid of objcopy, hex) ouput back to assembly mnemonics.  With an original unstripped elf binary objdump may be able to print many symbols (the usual way of producing a list file), but with a raw binary or hex file those are permanently lost.

@ChrisStratton: Thanks. Can you elaborate on 1)? I know makefiles are commonly used by software developers, but I don't have any experience with them.

There are various stock Makefiles you can find online to build an Arduino project with greater control of the details.  Not able to dig one up for you right now.  There may also be ways to customize the IDE's commands, but the IDE has so many other problems I'm not sure it's worth the bother.

You can find Arduino compatible makefiles in the embedxcode repository at http://embedxcode.weebly.com You will probably look at the arduino15avr.mk file in particular. You can change this file to have assembler output save and place where you want it to be.

My source files are *.ino, but after compilation there aren't any other files placed in the folder.

Correct. The Arduino IDE performs compilation in a separate temporary directory, whose location you can see if you enable verbose compilation in the IDE options.

Does the compiler generate intermediate assembler, and if so, where does it leave them?

By default GCC (which the Arduino IDE uses) does not leave intermediate assembly language files on disk. You must pass the --save-temps argument to have it leave them in the current directory, or --save-temps=obj to save them in the output directory.

Or is the machine code available somewhere?

The machine code is available in the .elf and .hex files generated in the temprary directory.

Yes.
Arduino compilation is set up with link-time optimization (LTO), and the assembly files created during C compilation don't contain any assembly code - just the intermediate representation used later in the LTO stage to generate actual assembly code. We want the latter.
It so happens, rather nicely, that the very last time assembler is invoked in the entire compilation process, is to take the output from the LTO stage, and turn it into a whole-application object file.
To get at this assembly file, do the following (on Windows):

Open %LOCALAPPDATA%\Arduino15\packages\arduino\hardware\avr\1.8.3\platform.local.txt (create it if it doesn't exist). Add the following line
compiler.c.elf.extra_flags=-save-temps=obj -fverbose-asm

If there already is such a line there, just add the above options (to the right of =).
Note: If you can't find the folder, look for the following files: boards.txt, platform.txt, programmers.txt. If you find these files in multiple locations, the one you want should be inside your home directory (i.e. not in Program Files or /Applications or /usr), and should be correlated at least partially to the version of Arduino you're using (should you have multiple versions installed).

Build the sketch again.

Look for a file named %TEMP%\cc*.ltrans.s. Each build will create a new such file. If you sort them by timestamp, the newest one is for the most recent build.

Note: The environment variables, enclosed by % signs, are valid in the Windows dialog boxes. You can directly paste such a path into e.g. an Open or Save As... dialog box, and it'll work. Paths with globs (*) will act as filters (IIRC).
To know which exact cc*.s file was generated, add the verbose option to the final binary generator pass:
compiler.c.elf.extra_flags=-save-temps=obj -fverbose-asm -v

Rebuild, and copy-paste all the output from the compilation status window in Arduino to e.g. Notepad++, and search for ar.exe. The sole line that contains ar.exe ends with the name of this cc file:
 c:/users/[...omitted...]/avr/bin/as.exe -mmcu=avr6 -mno-skip-bug
    -o C:\Users\[...]\AppData\Local\Temp\cc3XhU2F.ltrans0.ltrans.o
    C:\Users\[...]\AppData\Local\Temp\cc3XhU2F.ltrans0.ltrans.s

How does the file look? This is a short extract, just to show that both the C source and the assembly are intermingled - and this represents exactly the binary embedded in the .hex file and sent to the target.
.LBE33:
.LBE32:
.LBB34:
.LBB35:
 ;  C:\Users\[...]\Documents\Arduino\sketch_jul01a\sketch_jul01a.ino:29:   pinMode(ledPin, OUTPUT);
    .file 4 "C:\\Users\\[...]\\Documents\\Arduino\\sketch_jul01a\\sketch_jul01a.ino"
    .loc 4 29 0
    ldi r22,lo8(1)   ; ,
    ldi r24,lo8(13)  ; ,
    call pinMode     ;
.LVL55:
 ;  C:\Users\[...]\Documents\Arduino\sketch_jul01a\sketch_jul01a.ino:30:   pinMode(relayPin, OUTPUT);
    .loc 4 30 0
    ldi r22,lo8(1)   ; ,
    ldi r24,lo8(12)  ; ,
    call pinMode     ;
.LVL56:
 ;  C:\Users\[...]\Documents\Arduino\sketch_jul01a\sketch_jul01a.ino:31:   pinMode(ldrPin, INPUT);
    .loc 4 31 0
    ldi r22,0    ;
    ldi r24,lo8(54)  ; ,
    call pinMode     ;
.LVL57:
.LBE35:
.LBE34:
.LBB36:
.LBB37:

This approach also works on Linux and MacOS, except that the paths are slightly different, and path expansion uses different syntax. The two files of concern still are platform.local.txt - a file you must create, since it doesn't exist at first, and the ${TEMP}/cc*.ltrans.s files.


text:
Can I connect to WiFi with an Arduino, "wireless SD shield" and XBee
I want to create a growhouse sensor system. I have an Arduino UNO, wireless SD shield and I have just ordered a series 2 XBee XB24.
Any info I find seems to revolve around having 2 Arduinos and 2 XBee modules, why is that?
I am presuming that once I connect the XBee to the shield that I can then connect to my Arduino on the network and send and receive data, am I wrong?
I'm a developer and sysadmin but a noob to Arduino so any help is much appreciated.

The xbee network and the wifi network are both wireless networks, but, they do not communicate with each other.
You have two options.

Attach a second XBEE to your computer using one of these
https://www.sparkfun.com/products/11812
Get a WIFI shield http://arduino.cc/en/Main/ArduinoWiFiShield

Do you remember the term mesh network? Xbee's create a mesh network or multipoint network using 802.15.4 (hurray for google) protocol. This is not compatible with 802.11, the wifi protocol.
If you want everything to talk, you are either going to need to get an Xbee for everything, or wi-fi for everything (or wi-fi + ethernet for that matter).


text:
project not working when switching to battery power

I have a project which involves a photocell, an led, a push button, and a small hobby servo (tower pro sg5010) - the project works as expected when the arduino is powered by usb, but when I switch to battery power (4 AA batteries) - it doesn't work.
When powered by batteries, the servo actually starts right up and moves to the correct angle, so I feel like it should be getting enough power, but when I push the push button, it doesn't move to the new angle. I can hear a clicking noise of the servo on a regular interval, like a clock, and my LED flickers on and off at about the same interval.
If I'm doing something wrong, can anyone point it out? If it's just that the servo is not getting enough power, is there a way to add a transistor or something so that I don't have to add a separate power supply for the servo (I'm not sure there's room in my project's enclosure).
I've attached a fritzing diagram as well as my project code.
CODE:
#include <Servo.h>

const int buttonPin = 2;     // the number of the pushbutton pin
boolean buttonPushed = false;

const int ledPin =  13;      // the number of the LED pin

const int servoPin = 9;
Servo servo;
int angle = 0;
int servoStartAngle = 90;
int servoEndAngle = 10;

boolean servoActivated = false;

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

int photoCellPin = 2;
int photoCellThreshold = 500;
int photoCellActivated = false;

void setup() {
  Serial.begin(9600);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);

  servo.attach(servoPin);
  servo.write(servoStartAngle);

}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  int photoCellVal = analogRead(photoCellPin);

  if (photoCellVal > photoCellThreshold){
   photoCellActivated = true;
  } else {
   photoCellActivated = false;
  }

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW && buttonPushed == false) {
    // turn LED on:
    buttonPushed = true;
    Serial.println("button pushed");
  } else if (buttonState == LOW && buttonPushed == true){
   buttonPushed = false;
   Serial.println('deactivate');
  }

  if (buttonPushed == true){
   digitalWrite(ledPin, HIGH);
  } else {
   digitalWrite(ledPin, LOW);
  }

  if (buttonPushed && servoActivated == false && photoCellActivated == true){
    servoActivated = true;
    Serial.println("activate motor");

    for(angle = servoStartAngle; angle > servoEndAngle; angle--){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
  } else if (buttonPushed == false && servoActivated == true){ //deactivate
    for(angle = servoEndAngle; angle < servoStartAngle; angle++){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
    delay(200);
    servoActivated = false;

  }

  delay(200);
}

You may find that, with a high load on batteries, it's depleting the battery quickly; batteries often recover after a while, which may be confusing things further. Try using a multimeter to measure the voltage on the battery, when your program is running.
The Arduino (actually, the chip that runs the Arduino) has brown-out detection - if the voltage drops below a certain level, the Arduino will shut down; if the power comes back up, the Arduino will start up again - but reset. The chip has settings for 1.8v, 2.7v, and 4.3v brownout detection (or none at all!); something I read on the interweb (if you can trust that) said the default was 4.3v. It may be worth flashing an led on startup, so you can tell when the chip is reset.
Also, if you are powering the Arduino through the voltage regulator (using the power socket on the Arduino), then you need about 6-7 volt in just to get 5 volt at the Arduino - this causes further power loss. If using 4 AA batteries through the voltage regulator, you will get 6 volts (probably a little more when the batteries are fresh) going into the regulator - barely or not quite enough! - and the voltage on the Arduino is likely to be below the 5v it needs. Any load (in one of my projects, two large 7-segment displays) can cause the voltage to drop enough to trigger a reset. If you are using the voltage regulator, check the voltage between the 5V and GND pins.

I had an even simpler project only involving a TMP sensor and 433 MHz RF module. On a 9V (150 mAh) block battery it lasted only about 2,5 hours.
The Arduino is great for prototyping this sort of stuff, but when you want to build something for battery operation I found  that it draws 56 mA just looping without RF or motor!
Counting 2 digital outputs, 1 digital input and 1 analog input in your project, you can run that of an ATTiny85 or ATTiny45. It's the same family and after setup can be programmed with the Arduino environment. You can also opt for a lower speed bootloader 1 MHz or 8 MHz instead of 16 MHz for the Arduino to save energy, you don't seem to calculate that much. The ATTiny will draw about 10 mA looping this way.
Next you'll find also that you can disable the brown out detection in the bootloader, so it just drains the battery until completion.
Saving space in you enclosure by swapping Arduino board for ATTiny chip will allow you to put in more batteries, say 8 AA in two parallel packs of 6V each.
When that doesn't help you'll discover about the sleep modes and disabling ADC when not in use, where you go to sleep for specific intervals and allow the chip to be woken up by interrupts. In sleep mode I found the ATTiny to consume only 0.03 mA.
Some more information
Program an ATtiny with Arduino
ATTiny files for Arduino IDE


text:
One FTDI on Three Atmega
I'm doing a schematic for an arduino project-based and I can not proceed. I'm facing a problem which I have no idea how can I solve it so that's the reason I'm writing back to you.
The thing is: I have three atmega 328 and I want to program them using a single ftdi or a USB-UART converter. I can not put the chip outside the board and program them one by one, so the ftdi should be in the PCB.
I was wondering if I can do it using a switch with three positions with the help of 3 MOSFETs but I found it impossible, is it? Do you have any idea how can I solve this clue?
Many Thanks!

Have you considered putting in 6-pin programming headers and using a programmer and a program like avrdude?

Sounds like you are talking to serial bootloaders, so you need to both block data input to the wrong ones, and only connect data output from the right one.  You could indeed do that with MOSFET pass gates, discrete or integrated.  Ultimate simplicity would be jumper blocks.  You could probably also come up with a clean software solution using a 16u2 instead of FTDI and soft serial to the targets - see the firmware source for the one on the Uno.

I want to use a usb as an external socket so the ftdi must be in the board.
I want to provide a plug and play solution so the user just need to plug an usb cable to upload new firmware for each microcontroller.

@ChrisStratton how I can solve this clue just using Mosfets?

Doesnt the ftdi chip just facilitate programming via JTAG?

@JonRB  No, the FTDI chip doesn't facilitate programming through JTAG.  (It seems to me that you've got some reading about AVR and Arduino to do.)

This is off topic as it is an EE design problem, not an arduino question.  It belongs on EESE where it was properly asked.


text:
Eeprom write function does not seem to write in more than 100 locations
I am trying log my sensor data (1 byte each) on my Arduino Uno Eeprom. I have an ATmega328 on it, so it should allow me to write up to 1Kb on it, however I've tried the Eeprom write command and it does not seem to write to more than 100 locations on it (the first 100 bytes!)
I am using the Eepromex library.
Any thoughts on what's causing this?
Edit:
These are the excerpts from my code related to Eeprom logging:
int addr1 = 0;
int addr2 = 256;

  // Store Data in EEPROM

  EEPROM.write(addr1,FinalMoisture[0]);

    delay(5);

  EEPROM.write(addr2,FinalMoisture[1]);

    delay(5);
  // advance index pointer to the next location.  There are 256 bytes assigned for each sensor in the EEPROM, so go back to 0 when we hit 255/511.

  addr1 = addr1 + 1;

  if (addr1 == 255)
    addr1 = 0;

  //same for addr 2 :

   addr2 = addr2 + 1;

  if (addr2 == 511)
    addr2 = 256;

  // delay until next measurement (msec)
 Sleepy::loseSomeTime(30000);

PS: As mentioned earlier I've included the EepromEx library. Each sensor stores only first 50 locations. Also, I've noticed that if I run a single loop instead of storing data in two locations, I can write 100 straight entries. In any case it seems that the write function is limited to 100?
Could this be a setting in the library? How to disable/modify it? I tried looking at the info on the lib author's postings but didn't help.

Are you sure it is failing to write, or could it be failing to read? can you post the code? Does the stock eeprom library have the same issue?

When the simple eeprom write and read commands didnt work beyond 50 locations in my sensor logger code, I tried using the standard samples from the Arduino Website and same thing...  ...Tried pasting the code in here but the formatting  screws it up (never done this before!)

@Ameya, you can edit your question, and add the code there.

@Gerben thank you for the suggestion. Please find the code  included in the original question.

Try using no library. eeprom_read_byte((const uint8_t *)addr1,FinalMoisture[0]);

The address is a single byte, so you can only access the first 256 bytes of eeprom.

Looking at the library at https://github.com/thijse/Arduino-EEPROMEx/blob/master/EEPROMex.cpp it seems they limit the number of writes to 100:
EEPROMClassEx::EEPROMClassEx()
  :  _allowedWrites(100)
{
}

There seems to be a way of changing that:
/**
 * Set global maximum of allowed writes
 */
void EEPROMClassEx::setMaxAllowedWrites(int allowedWrites) {
#ifdef _EEPROMEX_DEBUG
    _allowedWrites = allowedWrites;
#endif
}

Perused the source there... the '100 write limit' should ONLY be enforced when the _EEPROMEX_DEBUG macro is defined.  Sounds like the copy of the library OP is using has the debug macro defined, thus limiting usage.


text:
Serial communIcation from OS X app to Arduino Mega
I am new to stack overflow. I have a question regarding using the USB serial communication sending data from an OS X app to the Arduino Mega 2560.
What happens is, when I have the Arduino running with the Serial monitor open, then I run the OS X app to send data, the Arduino does receive the data for a few seconds, then it stops.
This is the simplified Object-C code on the Mac side:
-(IBAction)sendData:(id)sender{
    NSString *toSend=[NSString stringWithFormat:@"echo %f > /dev/tty.usbmodem1a1341" ,vector.x];
    //vector is the continuous data generated by the Mac
    const char *toCSend =[toSend UTF8String];
    //converting to c string
    printf("%s", toCSend);
    popen(toCSend, "r");
}

This is the code on the Arduino side:
// Read Serial input:
void setup() {
  // Open Serial commurial1.beginnications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    // wait for Serial port to connect. Needed for Leonardo only
  }
}

void loop() {
  // Read Serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();
    if (inChar != '\n') {
      inString += (char)inChar;
      Serial.read();
    } else {
      // if you get a newline, print the string,
      // then the string's value as a float:
      Serial.println(inString.toFloat(), 6);
      // clear the string for new input:
      inString = "";
    }//end of if else
  }//end of while (Serial.available() > 0)
}

I am not sure what the problem, could it be the OS X app send out too much data to quickly? Or could it be the Arduino serial buffer is overflowed?
I really don't know much about serial communication so I don't know what I am missing. Any help will be greatly appreciated.

You should close the serial monitor before you run your custom OSX program.  Just as it auto closes when you upload, only one program should (ordinarily) be using the port at a time.  You may want to build simple output monitoring to the screen/stdout into your custom program.

Like Chris said, opening a serial connection will reset the Arduino, so you probably should add some delay in your OBJC code. Secondly you haven't set a baudrate. Try something like this

Actually, the reset or not is configurable with stty on linux/OSX, and may (perhaps?) not occur if the port is already open by someone else.  But it is indeed one of the several concerns - having the serial monitor grab responses before your program can being another.

One problem is here:

  // Read Serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {
      inString += (char)inChar;
      Serial.read();
    }

Your Serial.available() call guarantees that you have one byte of serial input, but you are attempting to read two of them if the first one is not a newline. This is not valid.
How to process incoming serial data without blocking


text:
Robust communication between Xbee and Python
I am using Xbee API library for Python to process the data received by the Xbee module. I am wondering how to construct the robust protocol for sending and receiving data. What I would like to build is

send the data request message to power monitoring uint (Xbee in remote).
Receive the transmitted power monitoring data and process it in Python.

If the aforementioned process works in just one time, it would be great, but sometimes it does not work. Thus, I would like to code autonomous acknowledging procedure into this communication. That is

send the data request message to power monitoring uint (Xbee in remote).
If the dat is not received, go back to 1.
If the data is received ok.

Here are my code, but it does not work all the time. Would you please look at how can I improve the code further to make it this
def listeningAndClusterData(targetWT):

#targetWT-->this will be used to construct the target address
targetAddress = struct.pack('b',0x00)+struct.pack('b',targetWT)
Data = struct.pack('h',0x0000) #prefix for requesting information
xbee.tx(dest_addr=targetAddress, data=Data)
ser.flush()
time.sleep(0.01)
response = xbee.wait_read_frame(100)#wait for data packet from Xbee, if packet is not recieved within 100ms, return 1

watingData = 1;
while watingData:
    try:

        if response != 1: # if the data is received
            sa = hex(response['source_addr'])
            rf = hex(response['rf_data'])
            datalength=len(rf)
            agentId = int(sa[2:4],24)
            # if datalength is compatible with two floats
            if datalength==16:
                voltage=struct.unpack('f',response['rf_data'][0:4])[0]
                current=struct.unpack('f',response['rf_data'][4:8])[0]
                power=voltage*current
                watingData = 0 # I received the average data and escape the loop
                ser.flush()
            else: #data is received but the format is not correct
                ser.flush()

        if watingData != 0: #if the data is not received--> keep sending the request message to other xbee
            xbee.tx(dest_addr=targetAddress, data=Data)
            print("data is requested again")
            time.sleep(0.01)
            ser.flush()
            response = xbee.wait_read_frame(100)

    except KeyboardInterrupt:
        break

return  voltage, current, power

Why do you flush before you read a frame? Is it not possible to have received the frame before you flushed?
Also how does it fail, is it an error is there sometimes no response from the xbee?

I thought ser.flush() will clear the buffer containing the message sent my xbee.tx(dest_addr=targetAddress, data=Data).I couldn't yet figure it out why the error occurs. Do you have any idea how to wisely use sleep() and ser.flush()?

You can just use xbee.wait_read_frame. The protocol is very fast


text:
How does one use (specically the wiring) the OV7670 camera with the Arduino Uno?
If one could tell me where each of the pins on the back of the camera go to, that would be great. if someone added the code also that would be awesome.

Due to the extreme RAM limitations, "Arduino Uno" and "Camera" are words that generally do not belong in the same sentence, as only in very select applications can you accomplish something useful, and then rarely in a cost effective fashion.

Im using this type of camera. http://bit.ly/1yZEEAZ

As Chris Stratton already replied, SRAM is an issue. You can add easily 128KB for 3 euro. Normally a camera needs more (in GBs) and this might be tricky, you have to get into SMD and/or costly RAM (since cheap DRAM is a no go for Arduino).
However, you probably also will get into problems with the 16 MHz processor which is probably too slow to handle all the data in time.
Maybe an Arduino Due could be better, but I think you have to go to Raspberry or equal/more.

You need to connect A4 and A5 via pullup register to 3V and to I2C interface on Arduino Uno.
And you need to connect A7 to XCLK signal via 2 registers.
You can find schema and code in my blog: How to connect Arduino Uno and OV7670


text:
unable to install usbserial driver for GPRS shield with mac air vs. 10.9
Despite all my efforts and web crawling I can not install the necessary driver to connect my Arduino uno R3 to the GPRS shield from seeedstudio. I have attempted downloading the VCP driver from http://www.ftdichip.com/Drivers/VCP.htm
I have tried the solution offered here https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac for Yosemite and beyond through the AppleUSBFTDI driver as well as the solution offered by FTDI's script. Any help will be greatly appreciated. Please let me know if I can provide any more information.

Shields do not require PC/Mac drivers.

in order to use the GPRS shield you must be able to connect through the /dev/tty.usbserial#### port which requires a driver.

No.  The USB serial connection is provided by the Arduino, not the shield, and the naming pattern for an Uno on OSX will not be tty.usbserial### but rather something else (tty.usbmodem### perhaps?).  IIRC an Uno does not require a driver on OSX though older/unofficial FTDI based boards do.

The USB serial connection is provided by the Arduino, not the shield, and the naming pattern for an Uno on OSX will not be tty.usbserial### but rather something else (tty.usbmodem### perhaps?).
If I recall correctly, an Uno does not require a driver on OSX though older/unofficial FTDI based boards (as well as unofficial boards based on yet other fixed function chips) do require drivers.
(On Linux it is typically /dev/ttyUSB# for fixed function and /dev/ttyACM# for an Uno, both using kernel module drivers shipped with most distributions.  On Windows they are all COM# and drivers are typically required)


text:
Two Arduinos Send data via Analog Pin?
What I want to do is allow Arduino A to send some constant value to Arduino B.
I sense something inherently wrong with my approach, but I cant figure out what it is.
So in the diagram below you will see Arduino A setting its Analog Pin 0 as OUTPUT and write a value 2 every 500ms. On Arduino B we have Analog Pin 0 set as INPUT to receive and print data to Serial. The GND pins of both Arduinos are also connected.
When this setup is executed, Arduino B is constantly receiving data in the form of a 3 digit number starting with 3XX. I am starting to believe this is voltage value?
What is inherently wrong with this idea?

Have you tried connecting the ground pins together too?

@Kynit: Yes, the GND pins were connected (forgot to draw it).

No I do not live in the EE world, but I can try! Excellent answers here, I am trying to absorb it all. Will update soon.

@lucidgold The summary at the start of my answer tells you exactly what to do. The rest tells you why.

This answer provides both Arduino specific knowledge and general electrical knowledge - both are necessary for a good solution (unfortunately).

Summary
To carry out Arduino analog to analog transfer:

Use analogWrite(pin, value) on a valid digital pin (see below)
Use analogRead(pin) on a valid analog input pin.
Connect a series resistor between the two pins - say 10k.
Place a capacitor from the analog input to ground, say 100 nF to 10 uF.

The R & C act as a low pass filter to convert the PWM to DC.
Details below.

Arduino analog pins are ONLY for analog input, not for analog output.
So trying to do analog out on an analog pin dooms your attempt to failure.
Arduino analogWrite(pin, value) only works on DIGITAL pins and then only on the subset of digital pins that have PWM capability. This is typically digital pins 3 5 6 9 10 11.
"analogWrite(pin, value)  produces as others have said - a PWM signal - rail to rail square waves with mark space ratio that varies so the mean DC value changes. For a 5V system  =
V_DC_mean ~~= value/256 x 5V.
Where 'value' comes from analogWrite(pin, value)
To convert the PWM to good-enough DC a low pass filter with a cutoff somewhat below the PWM frame rate is needed. AFAIK Arduino PWM frame rate is about 800 Hz -  so components are usually higher than that. A simple RC filter where R x C is usefully more than about 0.001S will start to work . Larger RC is smoother but with secondary effects. Using a 10 uF ceramic cap and a 10k resistor is probably OK. 10 uF x 10k = 0.1S. 1uF and 1k = 0.001 s = marginal. An electrolytic cap can be used but leakage current may slightly affect accuracy. So -

From somewhere in Arduino land (unknown) I copied the material below.
This is NOT in the basic reference, but should be.

Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.
On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.
The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs.

analogWrite() on the Uno doesn't actually output an analog value. It outputs a PWM wave whose average is equivalent to that value. If you want to turn it into a true analog value then you need to put it through a low-pass filter in order to remove the components that make it a PWM wave instead.

What is this "low-pass filter"?

A low pass filter cuts off the high frequencies (ie the square-wavy bits of PWM). Google it or look around this site - there are tons of examples.

This is hardly unique to arduino/ATmega; very few microcontrollers contain true DACs, excepting sigma-delta blocks uniquely tailored to audio.

If your aim is to send a constant value from Arduino A to Arduino B, then a really easy way is to use SoftwareSerial.
Let's say you are using Arduino Uno - you can use pins 2 and 3 for SoftwareSerial (see which pins are supported for which device at http://arduino.cc/en/Reference/SoftwareSerial)
Cross connect pin 2 and 3 from Arduino A to pin 3 and 2 of Arduino B. You can send any random data between the two Arduinos by uploading a sketch like the following on to each. You can use a program like CoolTerm to have a "SerialMonitor" open to each Arduino (using the Arduino IDE, you can open only one monitor at a time)
The advantage of this approach over using AnalogWrite/AnalogRead is that with AnalogRead, you can only get 1024 values, which is based on the voltage. With SoftwareSerial, you can send any arbitrary data.
// include the SoftwareSerial library so you can use its functions:
#include <SoftwareSerial.h>

#define rxPin 2
#define txPin 3

SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);

void setup() {
    pinMode(rxPin, INPUT);
    pinMode(txPin, OUTPUT);

    mySerial.begin(9600);

    Serial.begin(9600);
 }

void loop() {

    if ( mySerial.available() )
    {
         while ( mySerial.available() )
             Serial.write(mySerial.read());

         Serial.println();
    }

    if ( Serial.available() )
    {
        delay(5);

        while ( Serial.available() )
            mySerial.write( Serial.read() );
    }

}

As has been mentioned above, using analogWrite won't work. (I suppose you could sample the supposed analogue signal with a fast loop and measure the duty cycle...)
Why not use SoftwareSerial to send data between the two Arduinos?
It's a library which creates another serial port, entirely in software, so it's independent of the main UART on the USB port.
It's already part of the IDE and it's easy to use - in fact the demo code on the help page will already work for you, transferring any characters from the USB serial port to the software serial port.

AnalogWrite is perfectly OK as long as a simple 1 x resistor and 1 x capacitor filter are added (see my answer). There may be good reason to use analog which is not evident here.

As others have pointed out, your original suggestion will not work.
You could use PWM output and a filter which may work (you will need quite a large capacitor and/or resistor). The input at the other end would only be an approximation of the output (you could calculate based on detailed knowledge of component values and frequencies). Depending on the rate at which the value changes you may get different values on each read.
There are better ways. As suggested, serial will work (either hardware or software depending on other factors), and is probably easiest. You could use any of the common communication protocols (I²C or SPI) or even send values via IP.

The Analog In does exactly what it says - it only reads (samples) analog voltage levels.
Using AnalogWrite(0,2) does not make pin A0 in Analog In to output the voltage of 2*AVCC/1024, but instead makes the pin D0 to do that instead. (Most D0 pins on Arduino boards do not have a PWM output associated with them, so the behaviour would be undefined.) In the mean time, your A0 is doing nothing.
(I suspect it's floating / not connected, hence the 3xx value. Could check the datasheet to be sure.)
So what should we do instead? For a start, connect Arduino B's A0 to Arduino A's pwm pin. If you're using Uno, you can connect to any of the pins 11,10,9,6,5,3. Then you can use the code:
int PWMPin = 11;
int SignalLvl = 2;
analogWrite(PWMPin,SignalLvl);
Give that a try. And you'll see that it works... sort of.
But then there's a problem. your readings will be close to what you want, but quite erratic. The reason is partly because analog signals are super unreliable and is filled with noise. But the main reason is really that Arduino's analogWrite is actually NOT designed as an analog signal output. It is a PWM, which outputs GND and AVcc levels at variable periods at a fast speed so that it approximates the voltage level you want when averaged.
If you want to experiment with this, you can connect a resistor and capacitor to the output, creating  a low pass filter. (Here's more info: http://provideyourown.com/2011/analogwrite-convert-pwm-to-voltage/)

Having said all that, I guess the question most of us would like to ask is: is there a reason why you want to send data via analog? Analog signals are prone to noise. If data fidelity is critical, your best best is to use serial communication as highlighted by most answers here.
For simplicity, I suggest I2c which uses only 2 wires to communicate. If speed is of essence (like, writing to 10,000 bytes of data every second) you could try SPI or even parallel communication.
Hope this helps and good luck!


text:
Compiling is slow
Compilation of even the simplest program (like Blink) is extremely slow, the progress bar often hangs halfway for nearly half a minute.

Is this normal? I understand that not all computers are equally fast, but there's a huge difference between 3 seconds and 30 seconds
edit
It appears from the report that every time I switch programs they're built anew completely:

Build options changed, rebuilding all

even when nothing has been changed. How can I avoid a complete rebuild?

Have you tried enabling verbose compilation so that you can see exactly what's happening?

@Ignacio: updated the question

Try using version 1.5. 1.6 is just out, so it might have some bugs.

@Gerben: before I upgraded (today) I used 1.0.6, and it acted the same. Thanks for your comment.

Run check disk and also run spin rite on your drive. It's possible your spinning disk is failing.

@portforwardpodcast: That would surprise me. Every other software I use runs smoothly. It just seems to be all this unnecessary recompiling

Try moving all of your third-party libraries and any others you can identify as special-purpose ones, to a differently-named folder temporarily. Try recompiling Blink, which will only need the standard Arduino ones, and see if its compile-time changes. Then you might move them back a few a at a time until the compile time jumps back up again - the last added group contains something strange. It certainly takes me longer to compile the world, than to compile and link one sketch, but 30 seconds is insane! BTW, what is your dev machine?

I have found that this is a common issue across my development machines, however using Visual Micro for Visual Studio reduces this time by a significant factor.
I primarily use it for other Visual Studio features like Intellisense, refactoring, and solution management. Visual Micro has some compelling features of its own, like debugging tools, however I haven't used them.

Visual Micro
Visual Studio Community Edition

I haven't personally tried, but I would expect that you can avoid the rebuild using the project/solution options in Visual Studio - I found that the compile time is fast enough in most cases with this environment for it to not matter.

Any reason for the downvote? - Visual Micro does consistently compile faster than the Arduino IDE. Even simple programs take a long time to compile in the Arduino IDE at the best of times compared to using other tools.

Setting the option "High Speed Parallel Builds" under vMirco options really speed up the build for me. 'm using VS Studio Communiti Edition with Visual Micro.

If you find compilation slow then yes, it is probably recompiling things that it doesn't really need to recompile.  This has always been a major failing of the Arduino environment, and is one of the major impetuses for the complete re-write of the whole compilation system in my IDE UECIDE.
That includes very aggressive caching of compiled library and core files as proper ".a" files which are stored away separate from your board selection and kept until something really does need compiling.  That way the first time you compile something for a board it may take 30 seconds, 50 seconds, whatever.  All subsequent compilations for that same board, even for different sketches (not including the compilation time of "fresh" libraries) would be around 2 seconds, even less.
That caching is especially important when you're running on a very slow system, such as a Raspberry Pi, when compiling can take many minutes without the caches in place, but only a few seconds on all subsequent compilations.

Do you plan to support FreeBSD? - UECIDE looks promising. For now, I have to run a slow VM with windows. Would like something snappy like this IDE.

The IDE itself is just a Java application. As such it should run fine on FreeBSD. I had it going on there myself once - even made a port for it (in the early days that is). It should still run fine, though may require a little bit of bending. Use the Linux ZIP version and edit the uecide script file to suit. The hard part though will be getting the plugins to work. They need native binaries, such as compilers, programmers, etc. If you can find those kind of things for FreeBSD then you may have some success at making it work - if not, not.

You can try using the FreeBSD Linux Binary Emulation system instead of a Windows VM to run the Linux version of UECIDE along with the Linux binaries. Not sure what the plugin system would make of that though.

Sounds about as painful as expected :/ I'll grab UECIDE for my VM instead ;)

I had the same problem until today. Like many answers around the web, the problem seems to come from the anti-virus. My setup is Windows 10 x64 with a SSD and I use Windows Defender as the AV.
I tried by excluding the main arduino folder in "c:\program files (x86)\arduino", but it didn't improve the compilation time.
I checked the "verbose" option in the Arduino IDE and I've seen that it was calling the compiler from the AppData folder. So I add this folder to my AV exclusion list and it worked!
The compilation time improve by ten folds.
TLDR; In Windows 10, add the folder in %USERPROFILE%\AppData\Local\Arduino15 to the AV exclusion list.

Specifically, look to see if you've got Trusteer Rapport installed. Its some kind of banking protection mechanism, but I found it slowed down my compile horrendously. Removed and it's so much snappier. I've lived with this for soooo long so glad to have nailed the cause.

This thread, Arduino IDE and ESET: Slow compilation, may be helpful if you use ESET (at least one user has reported that it helped), but it didn't help me since I'm using Comodo (and may be there are some other reasons).
Here's another thread, SLOW ARDUINO IDE regarding a solution which helped many users, since 2009 (the latest comment on the forum is dated year 2014).
Several useful posts here as well, Unbelievable slow compilation of simple sketches. Ok, I haven't tested all the solutions myself, but let me collect useful links here so that other guys can find them and I'll check them out, too.

Hi Yakov and welcome to SE Arduino. Thanks for providing the links, I am sure that they are useful. However, it is much better if you can provide answers that you have tested yourself and that have worked for you. If you obtained the solution, that worked for you, from a thread such as those which you have posted, then all well and good. However, try to refrain from just googling links and posting them as answers, without trying them first... :-)

Hi @Greenonline, fair enough, I'll report my results once I test these suggestions. It's just the issue doesn't seem to be simple and many users suffer it because of different causes, so I think some solutions successful for others are no less useful than the one which will help me.
As for the issue, I have to test several things, including

IDE recompiles the whole thing each time? (this is mentioned in some threads, but I have no idea how to check this)
smth consumimg CPU? (don't see anything in task manager)
anything I can configure in Comodo? (HIPS.. looks like all is permitted for )

Ok, there's a simple way to understand weather your firewall (HIPS or other tech) causes the problem: just turn it off and try to compile again. In my case, this didn't accelerate compiling. Interestingly, sometimes even opposite: without firewall compiling seems to be always ~45 sec, but with firewall on it sometimes takes 17 sec.

I would download the non-install version and try compiling the blink sketch in it.  This will let you know if it is a computer specific issue or something related to your install.  I experienced something similar with a library that wasn't updated correctly between versions which caused all sorts of buggy behavior.

The occurrence of “Build options changed, rebuilding all” (as mentioned in edited question and shown in screen shot) probably is causing the large delay.  My belief (correct or not) is that lots of libraries are being rebuilt when that message appears.  Ordinarily, libraries should be rebuilt only upon initial install or when changing target board type.
An arduino.cc thread, “"Build options changed, rebuilding all" even when nothing changes ==> very slow”, from 2014 treats the issue superficially, merely pointing out that Arduino 1.5.8 Beta is suitable for Yún and Arduino Due boards, not “regular Arduino” boards.
A 2011 Google code thread probably is mostly irrelevant, but it's worth trying some steps mentioned in posts #14 and 15  ‒ eg, starting arduino via a path with no spaces in names ‒ if your platform is MS Windows.  If the Arduino IDE cannot find its options or preference files it probably assumes it is starting from scratch.
Note, please edit the question to specify how you started the Arduino IDE running, where the IDE is installed on your system, what your op system is, and what your computer is.


text:
Arduino Uno with crystal
Are there Arduino UNO R3s which use a crystal instead of a ceramic resonator?
(Frankly, I don't understand this cheapness: if you really want to save on component cost you can run both AVRs on the same crystal. The 16U2 always has a crystal.)

It would probably be an easy modification if you do it right at the ATmega pins.  Agree it's regrettable they didn't find a way to share the crystal between the two ATmegas.

Related (not duplicate): Does the Arduino Uno have two crystals?

Some of the Freeduino boards use crystals although the newer ones now use a cheaper USB to serial chip (the CH340) instead of the Atmel chip used on the Arduino Uno.
The diavolino is another build-it-yourself board that has a crystal. I am sure there are many others. The ruggeduino is another that uses a crystal and also markets itself as being practically indestructible. Their "How to Destroy an Arduino" is well worth a read for things to avoid doing to your Uno.

It appears that the Arduino Leonardo uses a crystal:

On the Sparkfun site it's the same price as the Uno R3, so I think I'll go for the Leonardo.