text:
How to properly use volatile variables in Arduino?
I was doing a small project with an Arduino Uno. It involved interrupts as I am using encoders to measure how much the differential wheel system moves forward. My robot moves only forward. So I use only a single channel from each encoder. Here are my two interrupt routines:
ISR (INT0_vect){

      encoderRPos = encoderRPos + 1;

}

ISR (INT1_vect){

  encoderLPos = encoderLPos + 1;

}

The variables encoderRPos and encoderLPos are of type volatile int. I understand that the variables which undergoes change in any interrupt routine need to be of type volatile. This is to warn other parts of the code that use these variables that it may change anytime.
But what happened in my code was a bit strange and I could not explain it. Here is how I compute the distance moved by the left wheel:
  #define distancePerCount 0.056196868
  float SR = distancePerCount * (encoderRPos - encoderRPosPrev);
  float SL = distancePerCount * (encoderLPos - encoderLPosPrev);

  encoderRPosPrev = encoderRPos;
  encoderLPosPrev = encoderLPos;

But when I print the following on my serial monitor, I notice an anomaly:

If you look at the third column, (SL) it's value is too high just for some time. This is upsetting all my calculations.
The only clue I can get it, if I take the value of SL that I got (3682), which is always a constant, and calculate back (encodeLPos - encoderLPosPrev), I will get 65519.66, which is close to the max value of unsigned int. Which means (encoderLPos - encoderLPosPrev) is causing an overflow while both the values whose difference is taken is somewhere around 5000 only!
And I managed to solve it. It was by luck. This is how I modified the code:
  static int encoderRPosPrev = 0;
  static int encoderLPosPrev = 0;

  int diffL = (encoderLPos - encoderLPosPrev);
  int diffR = (encoderRPos - encoderRPosPrev);

  float SR = distancePerCount * diffR;
  float SL = distancePerCount * diffL;

  encoderRPosPrev = encoderRPos;
  encoderLPosPrev = encoderLPos;

I can't comprehend what has happened. Is there something about volatile variables that I should have known about?
Update: Here is the entire code if you ever want to take a look. And it's working very well after changing it to what was suggested in the accepted answer.

Your question says what the third column of output is ... what are the other columns?  Please edit question and add column headings

@jwpat7 I intentionally removed them because that will only confuse  the reader. But the question has already been answered well by Majenko.

It is hard to give detailed answers from your snippets. could you explain why it is not happening randomly but at a specific time every time I run the code? Also why does it give the particular value?  - I could probably do that if I saw the whole code. Meanwhile read this: http://www.gammon.com.au/interrupts

@NickGammon Here you go: http://paste.ubuntu.com/14085127/

3683 / .056196868 = 65537 so it looks like it incremented at the wrong moment, yes? You are accessing a variable that might be changed in an interrupt multiple times in that code, so getting a local copy, while interrupts are off, would be much safer.

@NickGammon Yes, that's what I ended up doing.

You need to learn about critical sections.
What is probably happening is that the variables are being changed by the interrupt routines mid-way through the calculations. Your 'fix' reduces the time spent doing the calculation with the volatile variables thus making it less likely that there is a collision.
What you should do is copy the volatile variables to local variables with interrupts disabled for that brief period.
cli();
int l = encoderLpos;
int r = encoderRpos;
sei();

Because the Arduino is an 8 bit CPU it takes multiple assembly instructions to perform mathematical operations on 16 bit values. Floating point is even worse using many many instructions for a simple addition. Division and multiplication use considerably more. An interrupt has plenty of opportunity to fire during that list of instructions. By doing an assignment like that and then using the new local variables in your calculations the instructions needed to deal with the volatile variables is kept to an absolute minimum.  By turning off interrupts during the assignment you guarantee that the variables can't ever be changed while you are using them. This snippet of code is called a critical section.

This might just be the case. Just wondering, could you explain why it is not happening randomly but at a specific time every time I run the code? Also why does it give the particular value?

Here is a great reference to the cli/sei. http://www.nongnu.org/avr-libc/user-manual/optimization.html#optim_code_reorder. With the memory barrier volatile declaration is not really needed in the code above. Here is some fun reading on this subject. https://www.kernel.org/doc/Documentation/volatile-considered-harmful.txt

@MikaelPatel Nice, but not that relevant for MCUs. Volatile is required in this situation to prevent the compiler from optimzing out instances where it thinks it's not being used (value never changes). The cli/sei is there to make the operation atomic WRT the only other thread (interrupts) that execute.

Did you try compiling the code with and without volatile? But with the critical section (cli/sei). What I am trying to discuss is the concept of the memory barrier and how that provides volatile access (and correct ordering) from the compiler with having to declare variables as volatile. Most programmers are taught that any variable accessed in an ISR must be declared volatile but there is so much more to this story.

I don't think the compiler has much concept of what cli() and sei() do and how that would affect things like optimizing out of variables that shouldn't be optimized out.  All sei() and cli() do is manipulate the global interrupt enabled flag in its register. They do nothing for the flow of code.

After all, they just map to an assembly instruction: # define sei()  __asm__ __volatile__ ("sei" ::: "memory")

It is the magical word "memory" that tells the compiler that it is also a memory barrier. https://gcc.gnu.org/onlinedocs/gcc/Volatiles.html

That stops instruction re-ordering. It has nothing to do with the complete removal of suspected dead code.

@MikaelPatel Here's an extreme example (extreme so it forces the kind of optimization I am after demonstrating): http://pastebin.com/u9bfiN4R

@Majenko That was an extreme example. Did you try both volatile and cli/sei? A contra example is Cosa/RTT https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/RTT.cpp, it has no volatile. All accesses are synchronized instead.

/*
Hi all and thanks for sharing.
From my personal experience here is what I found useful
"A DTMF decoder stores the last DTMF code in bytes in its memory
It's STQ pin goes HIGH every time a a new DTMF is detected
This is just part of the code focused on ISR (Interrupt) "
   Tips when using ISR with Arduino nano and IDE 18.19

1: HIGH or LOW only,  RISING of FALLING will not get triggered properly with Nano using external digital interrupt.
2: Watch out when using LOW. As per using HIGH in example you need to use  flags(event bytes) and possible counters.
3: When you type the attachInterrupt don't use brackets for the void of function you are you are calling, or every time the ISR is triggered it will go from begging of code re-initializing/resetting all global variables no matter if you declare them volatile or static!
4: Delay doesn't work only delayMicroseconds()
5: Keep it short, byte size variables and no complex math if possible
6: Arduino nano external digital ISR pins are 2,3
7: Don't run the void you call in your ISR in the loop().
8: Keep in mind all other comments posted from the other programmers.
*/
/////////////////    Example /////////////////////////////

byte CFlag;     // GLOBAL

byte Counter;   // GLOBAL

#define STQ  3  // GLOBAL

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

pinMode(STQ, INPUT);

attachInterrupt(digitalPinToInterrupt(), DragonBalls, HIGH);
//WhenSTQ PIN GOES HIGH it runs a void function called DragonBalls()

}//end setup

void DragonBalls()

{
    Dpin = digitalRead(STQ);
    delayMicroseconds(10000);
    if      (Dpin == HIGH &&  CFlag ==LOW) {
                                                CFlag=HIGH;
                                                Counter++ ;
                                            }//end if

    else if  (Dpin == LOW  &&  CFlag == HIGH) {
                                                CFlag=LOW;
                                                DragonPrint();//Serial.print staff

                                                }//end else if

}// end DragonBalls(void)

void DragonPrint()

{
    Serial.print(CFlag);
    Serial.print(" = CFlag, Counter = ");
    Serial.println(Counter);

}//end void DragonPrint

what question does this answer? I am sure not that one above


text:
Arduino Mega 2560 not showing up in Serial Port in IDE
I recently purchased an Arduino Mega 2560. As soon as I connected it for the first time with my macbook pro the led was blinking (default blink program). To stop the blinking, I uploaded an empty sketch to Arduino. Now the arduino is not showing up in serial port in any operating system. The LED is constantly on and not blinking. Please help

Are you using the same cable as before?

Yes, using the same cable. Have also tried it with a different cable.

What does the Arduino IDE show for Ports? None?

Did you try:-

Unplugging and reconnecting the board?

or

Holding down the reset button (on the board) during compile and then letting go when the Ide says "Uploading to ..."? (Make sure the sketch has a setup(){} and loop(){} so is not entirely empty)

If that doesn't work then ...

The pin13 on all the time with an empty sketch might indicate a hardware problem. Is anything connected to the board apart from the usb cable? Green LED simply means the board has power unless you are talking about the tx/rx Led's?

for windows users ...

Look in "Control Panel>Device Manager" to see if there is an exclamation mark against any devices, or "Unknown/Other" devices? If you can see the board but it has an error against it look at the properties to see if you can see what the error is. Re-installing the arduino ide will attempt to install the usb drivers again but they can also be found in the \drivers sub folder below the Arduino Ide.
If you can see an entry in control panel but it is not showing in the Arduino Ide try changing the port to a different COM number (right click>properties)
If you can't see anything in Control Panel try a different usb port on your computer.
Is the board connected directly to the pc via usb or via a usb hub? Make sure direct connect. If power externally make sure enough power.

I have tried unplugging and reconnecting the board and also pressing the reset button. As of now, the Green LED is ON and the ORANGE LED at pin 13 is constantly ON.

I've added some more suggestions and questions

source: Stack Exchange

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

sort: votes


text:
Adafruit TLC5947 breakout board is not working with my Arduino Uno
I am trying to use this board (setup tutorial on left hand nav) with my Arduino Uno.  I have tried using their example code, as well as my own simplified code, to turn on a single blue LED.
The simplified code I "wrote" is as follows:
#include "Adafruit_TLC5947.h"

#define NUM_TLC5974 1

#define data   3
#define clock   5
#define latch   6

Adafruit_TLC5947 tlc = Adafruit_TLC5947(NUM_TLC5974, clock, data, latch);

void setup() {
  tlc.begin();
}

void loop() {
  tlc.setPWM(0, 4095);
  tlc.write();
}

Scroll to the bottom for reference. (TLC5947)

This compiles and uploads successfully.  I have DIN connected to 3, CLK to 5, and LAT to 6.  V+ is connected to the Arduino 5V pin, and GND to Arduino ground.
Using this setup, the LED does not turn on when connected to channel 0 on the board.  Using a multimeter, I have verified that the voltage between common ground and the channel 0 pin is ~0V.  Checking voltage on the board between GND and V+, I see 4.8V, which looks good.  Connecting the LED directly to the V+ line lights it up, but obviously isn't switchable.
I have no clue why I'm not seeing anything on channel 0's output when I directly write it to 100% duty cycle.
Why is this not working?

... the LED does not turn on when connected to channel 0 on the board. [...] Connecting the LED directly to the v+ line lights it up, but obviously isn't switchable.

From this I suspect that you have connected the LED between pin 0 and ground. The problem with doing this is that the TLC594x LED driver outputs are current sinks, and connect the output to ground when on. The LEDs must connect between V+ and the output as shown in the datasheet.

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


text:
DHT11 and DHT22 unused pin
The DHT11 and DHT22 is a 4 pin temperature and humidity sensor, where one of the pins is labelled as NC (not connected).
I'm curious what the unused pin is used for.
Factory calibration?

I have wondered the same, however I think that is just is not connected.

On the DHT11 it's connected to pin 6 of the SOIC14 inside. So it's at least connected to something. But who knows what it's for.
It has a (internal) pull-up resistor to VCC of around 100kOhm on this pin.
I connected my logic analyzer to it, there is no signal, even while reading the sensor. Also connecting the arduino's signal wire to this (incorrect) pin does nothing.
Factory calibration or testing would be my guess too, but who knows.

in this datasheet both 3. and 4. pins are marked GND :
https://www.adafruit.com/datasheets/Digital%20humidity%20and%20temperature%20sensor%20AM2302.pdf

Only on the DHT22.


text:
Arduino clone with ch340G and correct w7 x64 driver cannot connect to IDE
I have an Uno R3 with CH340G which works perfectly at my home w7 x64 notebook.
It worked properly right away with the CH341s64.sys driver. I tried revs from 2009, 2011 and 2014 and it is working with either one.
On my w7 x64 desktop though the drivers somehow do not communicate properly.
If I plug in the device, windows recognized it and a new port (port 8 in my case) shows up in device manager.
When I try to transfer a sketch to the device it fails with error message
avrdude: stk500_recv(): programmer is not responding.
I have tried CH341s64.sys rev 3.3.2011.11  and 3.4.2014.8 without success.
I have no clue how I can troubleshoot this as windows shows the port properly and there are no signs of error on the driver. There are no entries in the event logs.
Is there possibly a log file from the IDE which could shine a light?
I already tried with firewall disabled but no change.
My IDE is the latest 1.6.6 on both systems.

Are you using the same cable in both cases? Could be a cable issue if you're not.

Solved:
The issue was due to an USB Hub which I have at my desktop.
After I connecting the arduino directly to an USB port at my desktop everything was fine.
Unfortunately there is no hint about this in the arduino troubleshooting guide. A hub is only mentioned in conjunction with a MAC.


text:
A good water flow meter to monitor home usage with Arduino
I'm searching for a good water flow meter to add to my home controller project with Arduino. I have been searching in several pages and I only found some devices that work for low flow.  I need to control the water usage in my home and I thought to add a flow meter at the point where the water enters my home, and view the data with Arduino.
Do you have experience with any flow meter with good quality?

Don't you have a water meter in your house. These units can be read quite easily. Some have a rotating magnets, or like mine, a rotating dial with a large reflective surface.

I have, but not in my house. I'm living in a flat and flow meters they are in a room  that I don't have access easy.

I have a similar situation with my power meter not being in my apartment. I have an Arduino running on batteries, and sending the data wireless to an arduino in my apartment. If this isn't possible, I'd just buy a second water meter, similar to the one outside your apartment. Those units are made exactly for your purpose. I wouldn't want to risk having a water leak.

It would help to know more about the meter that you need – can you tell us the size of the pipe going into your flat where you would attach the meter and give us a rough idea of the flow rate that you need?

I don't know how is the size of pipe, but I think that it isn't too significant. I always can buy an adapter. But the most important, the flow rate, well, I don't know how to size this. This is a normal house, we have only a bathroom.
I found a project in the net in which  some guys uses this flow meter: Koolance INS-FM17N. His flow rate range is 1.0-15LPM. I think that 15 litres per minutes is quite and enough, but i don't sure. What do you think?

I've not used anything like it, but maybe http://forum.thethingsnetwork.org/t/smart-water-measurement/160 can give some ideas (and if it does, then I guess you'll know what to quote here as an answer). Success!

I've used an arduino with an irrigation flow meter.
I think I'm getting accurate results, but I haven't checked against a bill. It can handle high flow, and the sensors will attach to any size pvc line. The sensor are a bit expensive, however. $150 for the sensor and $35 for the T junction that it plugs into.
However, as you are living in an apartment, you'll probably need a non-invasive sensor. Perhaps an acoustic one.


text:
433mhz range optimization
I would like to get the best range possible from my 433MHz modules. After A LOT of searching and reading, I'm convinced I should be able to cover 10m indoors with free line of sight.
[update]
After some tips in the comments I changed a few things. It looks like with an Arduino receiving in stead of a Pi, I get an extra meter, 1,5m now so still terrible. And 'as a bang on the fire arrow' as we say in Dutch, I now use two whip antenna's parallel to each other.
Before moving to fix the reception on my Pi, I now first try to maximize the reception on the receiving Arduino. This makes it much more simple to investigate.
[update 2]
After some more tests I got to about 6 meters range. When the transmitter is behind 1cm of wood, this goes back to 30cm.
My current 433MHz modules are going into the garbage bin, I thank you all for your time. I will look for a more stable alternative and maybe try some other/better433MHz modules like these: http://www.ebay.com/itm/433MHz-Superheterodyne-RF-Link-kits-3400-ARM-MCU-Transmitter-and-Reveiver-/281169560721?hash=item4177030491:g:SUcAAOxyaTxTRKJn
[update 3]
The new modules made an enormous change. I can now send my data from across my house with no problems at all. No ground plane (will try that TwoD!) yet. Still on 5V transmitter voltage!
I've asked a question before about my 433MHz setup so for full disclosure:
433MHz sending not receiving
My current range is about 40/50cm, this is not much since I use a straight antenna ~17cm at the receiver and a coil antenna at the transmitter:
http://www.instructables.com/id/433-MHz-Coil-loaded-antenna/
These are the modules I use:
http://www.ebay.com/itm/-/221524421949?roken=cUgayN&soutkn=xKBBUo
And just FYI, I use these awesome working pumps:
http://www.ebay.com/itm/-/321779742264?roken=cUgayN&soutkn=hk1lrB
I have tried many antenna combinations and also upping the transmitter voltage to 12V but it doesn't help much. My aim is to reach 10m line of sight at the least.

I notice that my Pi outputs 4.77V to the receiver.
The 4 penlites now output around 5V so transmitter power is low.
What I also like to test is adding 10uF caps to the V and GND of the transmitter but I have to wait for them to get delivered.
I have the 10mw version of the transmitter, they may be just useless.
The receiver stands in front of a speaker and a subwoofer, I turn those off when I test.
The 433MHz modules came in pairs. I did not respect this and use any receiver with any transmitter, wonder if this is a problem. My end-goal is 3 transmitters on one receiver.
Since I have multiple Tx/Rx modules, I swapped them to exclude DOA modules.
Also tried these Helical antenna's, only made range worse; http://www.ebay.com/itm/-/171271811976?roken=cUgayN&soutkn=TmOnpH

My Arduino usses VirtualWire to send with 1000 baud to my Raspberry Pi, on the Pi side I use PIGPIO and the following code:
if __name__ == "__main__":

   import time
   import datetime
   import pigpio
   import vw
   import json
   import requests
   from requests.auth import HTTPDigestAuth

   # Setup receiving 433MHz port
   RX=27

   # Setup Baud rate 433MHz
   BPS=1000

   # Connect to local Pi.
   pi = pigpio.pi()

   # Specify Pi, rx gpio, and baud.
   rx = vw.rx(pi, RX, BPS)

   # Empty message
   msg = 0

   # Save the time
   start = time.time()

   # Run for 3 seconds
   while (time.time()-start) < 36000:

      # Count msg per cycle
      msg += 1

      # Sleep for .4 second
      time.sleep(0.4)

      # Run while receiver is ready
      while rx.ready():

         # String join received characters into message
         message = ("".join(chr (c) for c in rx.get()))

         # Print the received message to screen
         print(message)

         # Create data dictionary
         data = {}
         data['meting']    = message[8:11]
         data['bericht']   = message[4:7]
         data['plant']     = message[1:3]
         data['timestamp'] = str(datetime.datetime.utcnow().isoformat())

         # Print the data to the screen
         print(data)

         # Setup filename for local data backup
         filename = str('data/' + data['plant'] + data['bericht'] + data['meting'] + '.json')

         # Write JSON data file to disk
         with open(filename, 'w') as outfile:
            json.dump(data, outfile)

         # Sending data
         url = 'http://server:8000/v1/documents?database=plantjes&extension=json'

         # Setup headers
         headers = {
            'Content-Type': 'application/json'
         }

         # Execute request
         r = requests.post(url, json = data, auth=HTTPDigestAuth('plantje', 'password'))

         # Print request response
         print r

   # Cancel the receiving of data
   rx.cancel()

   # Stop PIGPIO listening on pins
   pi.stop()

This script sends the measurement of the Hygro sensor to a database in JSON. This works like a charm.
The Arduino uses this code:
#include <VirtualWire.h>
#include <Sleep_n0m1.h>

String pid = "p02";
const int led_pin = 11;
const int transmit_pin = 12;
const int hygroSensor = 0;
int hygroPower = 8;
const int pump_pin = 5;
int watering_level = 900;

int count = 0;
Sleep sleep;
unsigned long sleepTime;

void setup()
{
  // serial console setup
  Serial.begin(9600);
  Serial.println("setting up");

  // cycle sleep time in ms
  sleepTime = 10000;

  // virtualwire setup
  vw_set_tx_pin(transmit_pin);

  // setting of pin modes
  pinMode(hygroPower, OUTPUT);
  pinMode(led_pin, OUTPUT);
  pinMode(pump_pin, OUTPUT);

  // Bits per sec
  vw_setup(1000);
}

void loop()
{
  // delay to allow serial output to be ready after wake up
  delay(100);

  // cycle counter
  count++;

  // turn on hygro sensor module
  digitalWrite(hygroPower, HIGH);

  // wait a bit for hygro sensor to start
  delay(1000);

  // read the input on analog pin 0:
  int measure = analogRead(hygroSensor);

  // Start light to show transmitting
  digitalWrite(led_pin, HIGH);

  // log moment of sending
  Serial.println("Sending: " + String(measure));

  // create & send random message id
  String mid = "m" + String(random(100, 999));

  // Sending data
  String hygrodata = "d" + String(measure);
  dataSend(pid + mid + hygrodata);

  // Stop light to show transmitting
  digitalWrite(led_pin, LOW);

  // Wait a second
  delay(1000);

  // sleep code
  if(count >= 3)
  {
    // reset counter
    count = 0;

    // run pump routine
    //waterpump(measure, mid, pid);

    // log sleeping to serial console
    Serial.print("Going to sleep now..");

    // set sleep mode
    sleep.pwrDownMode();

    // turn off hygro module power
    digitalWrite(hygroPower, LOW);

    // sleep for: sleepTime
    sleep.sleepDelay(sleepTime);
  }
}

// Data sending funtion
int dataSend(String data) {
  // declare int for length of message
  int msglen;

  // set length of message +1
  msglen = data.length() + 1;

  // declare array of characters
  char envelope[msglen];

  // put string in array
  data.toCharArray(envelope, msglen);

  // log data to serial monitor
  Serial.println(data);

  // send data
  vw_send((uint8_t *)envelope, sizeof(envelope));

  // wait for sending to finish
  vw_wait_tx();

  // return 1 for succes
  return 1;
}

// Pump function
int waterpump(int measure, String mid, String pid) {
    // Log measure
    Serial.println(measure);

    // Water when needed
    if (measure > watering_level) {
      // Turn on pump 2 seconds
      digitalWrite(pump_pin, HIGH);
      delay(3000);
      digitalWrite(pump_pin, LOW);
      // Send pump data
      dataSend(pid + mid + "pump");
    }
}

This controls the sensing of the messages and also the water pump I use to water my plant automagically when needed. This also works like a charm.

That "helping hands" antenna stand is highly suspect - did you model that as part of the antenna?  It very much is, and probably not in a good way.  Try holding the board with the antenna projecting, and possibly an opposing ground wire of the same length, radials, or a ground plane - depending on what the theory of how your chosen antenna is supposed to work is.  That said, what is the usual range for these modules?

Have you tried receiving to an Arduino (with RX module) with serial printout to Pi? Just to compare the performance (assuming Pi is missing RX). I have several RF433/Arduino modules for sensor data transmitting over 5 m through up to three walls indoor (at 4000 bps, 3V7). This is with a modified version of VirtualWire with a Hamming(7,4) encoder with bit-error correction. Please see https://github.com/mikaelpatel/Cosa/blob/master/libraries/VWI/VWI.hh, https://github.com/mikaelpatel/Cosa/blob/master/libraries/HammingCodec_7_4/HammingCodec_7_4.hh and https://github.com/mikaelpatel/Cosa-Domotica.

the helping hands are just for the photo :) so I didn't have them there while testing. the usual range is 1 wall + 10 meters or 50m outside with two straight antenna's. but this is Google science...

Using an extra Arduino with the receiver I get messages further away. So this indicates that my Pi is the culprit. Now I'll try to dump the receiver on the Pi to the console to see what comes in..

I don't think you should combine helical and whip antennas. Also, building helical antennas requires a bit of precision in length, inner diameter, number of turns, spacing between turn, and probably more. I'd go with whip antennas on both sides, and make sure they are parallel to each other. I'd also experiment with the length of the antenna. Some people say you have to subtract the length of the little loop of wire already on the board. Just make it a bit to long, and keep cutting it shorter, and see what effects it has on range. Also more the units around; there may be dead spots.

The PI might be generating a lot of "background noise". Might need to protect the TX module from that.

You could've just made a loop like windings out of that antenna instead of that helping hands set-up. It really doesn't matter so much.

I've had the same problem, couldn't get past 2 meters range.
Until i noticed that the TX-Frequency was off by about 150kHz.
I adjusted the RX Frequency (the module has a trimmer) and now 40-50m is possible with a wall in between.

On the transmitting side (with cheap AC switches as receiver), I've actually had good results with the cheap green squares, and the equally cheap 5 for a dollar 'Helical antenna 433MHz' you find everywhere on ebay :)
I can reach all three levels of our house with that, and that's with only 5v supply on the green square, and it just sitting on a breadboard.
On request, picture of the antenna, soldered onto one of the cheap green  transmitters, this one works well for me on 5V:

This antenna was bought as a set of 5 from:
http://www.ebay.com/itm/171271811976
There's about 21 windings, with 5mm diameter, so that makes roughly 5mm * 3.14(=Pi) * 21 = 33 cm of wire in the coil.

could you please attach a picture of the antenna?

Done, see the answer

Keep in mind they're specific to a frequency, you want ones sold specifically for 433mhz :)

The 433mhz modules can be sensible on the power lines, place a cap on the power input. Also a straight antenna works most of the times, but if you want some more distance, look into making a dipole antenna, there is a coil loaded diy antenna you can make that helps a little bit up from straight wire.

thanks! I was just reading about that cap on the power input, how and why it works. Wondering how much uF and why..

I've used anything from 10uF and up, it's for power smoothing so the value is not critical.

Have you ever tried the Nordic nRF24L01 based modules? They are available on eBay for very low cost, and operate in the 2.4 GHz band.  They should offer a range of at least tens of meters indoors.  I have had good success with these, and they are very easy to interface to Arduino.

I've ordered one of those to check it out! What I also have is an ESP8266 module but it seems to be more used as a stand-alone solution than as an Arduino module. Until the nRF24L01 is here, I'll be testing with that one.

Yes, ESP8266 is better suited to connecting to a wireless router.  The nRF chips are better suited to mesh-type networks.

I have the same TX/RX modules and two Arduinos and can get pretty good transmission reliability all throughout my house but it took some experimenting to figure out the largest factors in play (for me).
Module pairs should not matter, I got my 5 pairs jumbled up in a plastic bag, think only one was DOA. I use them together with Nexa wireless electric outlets and remotes since they operate on the same frequency and give me a decent reference point.
One thing I've noticed about the [receiver] modules is that they tend to auto-adjust to the signal strength. Blast at them with a transmitter at close range for a while and they will become worse at picking out the signs, from the noise at long range for some time. This appears to be true of the 433Mhz Nexa devices too.
When starting to transmit from further away, it may take longer before the receiver figures out it's found a signal.
Remember, these modules output only 1 or 0, not an analog signal, so they have to decide which level of noise to accept as 0 and when there is a 1.
My first mistake was not using a well attached antenna. A simple piece of strong wire is good enough in itself, but only if it makes good contact with the module. Good soldering skills always  recommended.
My second mistake was not giving the transmitter enough power. It can handle 12V, so give it 12V (not on the data pin!). Only go lower after you got it to work at the needed distance.
Try with a large ground plane for both transmitter and receiver (no contact with the device itself!). I got a very good range with my receiver on my computer case and the transmitter on my fridge!
I could even get a reliable reading from a temp sensor from inside the garage 10m away from the house when getting about 2m off the ground, using 17cm plain straight wires as antennas with good ground planes. (Monopoles antennas need ground planes to bounce the signal off.)
Try visualizing the signal on the receiving side with an oscilloscope. If you gave an analog receiver it's probably easier to tell apart noise and real data. But if all you got is the RX module, hooking up the data pin to some kind of logged visualization will at least let you see how difficult it is to spot the data patterns.
Try increasing the length of your preamble before the actual data. It'll let the receiver adjust before it gets to the interesting bits.
Repeat your transmitted data. Include a piece of id data which changes with each message, but not with each repetition, and store the last received id for comparison before relaying it to wherever.


text:
"No more addresses" when using multiple DS18B20 sensors
I want to build a scheme to get data from several DS18B20 sensors and write their temperature to serial. Before I connected them using parasite mode and using 2,7k resistor (because I didn't have 4,7k at home). Back then, it worked for 1 device, if I plug in another, it won't detect any of them (it writes "No more addresses"). Now I replaced 2,7k resistor with 4,7k and it doesn't detect any device connected. But if I do one little thing, which is replacing 4,7k resistor back with 2,7k, it will detect one device.
How to fix it?
Here is exactly how it is all connected now:

and here is the default sketch I am using:
#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library

OneWire  ds(10);  // on pin 2 (a 4.7K resistor is necessary)

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

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.print("ROM =");
  for ( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

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

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  }

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

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

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

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");
}

Is there anything I am doing wrong? Because I somehow managed to get it working some time ago.

Wow, switching the resistor to 620R worked. Guess I have a problem within my breadboard.

Have you tried without parasite power, or you have any particular reason for using parasite power?

Breadboard create a bit of capacitance on the data line. Try placing the second module right under first (so sharing the same breadboard "columns").

@Personagem it was just easier to connect, in my opinion. Is there any difference?

Some sources advise to not use with multiple devices ( http://openenergymonitor.org/emon/buildingblocks/DS18B20-temperature-sensing). However data sheet says it is possible as long a strong pullup is present. I would go with the normal power with 4.7k pullup. Be very carefull connecting vdd to correct PIN in sensor. It will burn in seconds if you reverse polarity.

A problem with what you are doing on the breadboard is that you show no bypass capacitors.
What makes the pull up "strong" is the ability to provide current to move the data line from zero back to one.  The load on the data line is its capacitance.  To move the data line from 0 to 1, you have to charge that capacitor.  Working on a bread board, you are correct that you have a larger capacitive load.  So you require more current to move the data line from zero to one quickly.
You are correct that the lower 620 ohm resistor will provide more current.  The large current will move the capacitance load of the data line more quickly.  But you are not paying attention to the other side of the resistor, the 5V rail.
The layout you have has inductance in the wires from the Arduino power supply out to the bread board.  An inductor has a voltage drop across it proportional to the rate of change of the current through it:
V = L  di/dt

The analogy is that inductance is a flywheel: if it is not spinning, it will take force to get is moving.  Similar, once it is spinning, it will take force to stop it.
So when the resistor starts conducting to pull up the data line, the inductance in the wires and breadboard cause a voltage drop.  The +5 side of the resistor voltage drops.  This inductance in the wires leading to the resistor prevents it from rapidly charging the data line back to 1.
That is the role of bypass capacitors.  You place 1 or 2 right at the resistor between the +5 and GND strips on the bread board.  Now when the resistor draws current, it initially pulls from the energy stored in the capacitors.  After a short time, the current will start pulling from the +5 wire.  Thereby, you have bypassed the inductance of the +5 supply, hence the name.
Add a 0.1 microFarad ceramic capacitor on your breadboard where the wires connect to the contact strips.  You will see this on schematics for anything that has a DC supply off board.  Right next to the power connector will be 2 or 3 capacitors, usually one big 2-10 uF tantalum and one smaller 0.1 uF or so.  Similar across circuit boards you see bypass caps placed at the supply voltage pin of every chip, commonly two: a 0.1 uF and a smaller 10 nF.
It might seem pointless to place a small capacitor in parallel with a larger capacitor.  The values just add, yes?  But again, the time response is different.  Capacitors are not perfect and have internal series resistance.  A big 10 uF electrolytic capacitor may store a lot of energy, but it is not fast in terms of how quickly it can start providing current.  A little 100 nF ceramic monolithic capacitor is very fast, but doesn't have much energy.
So with two bypass caps in parallel, you have the small one for the initial burst of current, the larger cap for the heavy lifting, and last and slowest the 5V wires and traces to supply to steady current.

0.1uF == 100nF.

A strong-pullup seems to be the key to having multiple sensors in parasitic mode, as described in the datasheet for the DS18b20 devices. Though they suggest using a MOSFET to pull up the 1-wire bus, I've had good results (3 meters of wire, 3 devices more than 2 meters out) by tying an output port directly to the 1-wire bus, bypassing the 4.7K resistor.
// One wire bus strong-pullup:
//
//    +------------+     +5v            +---------+     +---------+
//    |    MCU     |      |             | DS18b20 |     | DS18b20 |
//    |            |  R_pu = 4.7K       | g  d +5 |     | g  d +5 |
//    | Strong-    |      |             +-o--o--o-+     +-o--o--o-+
//    | Pullup   > o------o               |  |  |         |  |  |
//    |            |      |               +--|--+         +--|--+
//    |            |      |               |  |            |  |
//    |    Data <> o------o---------------|--o------------|--o------ - - -
//    |            |                      |               |
//    +------------+                      V               V

Initialize the strong-pullup port by setting the port as an output and HIGH, the disable and enable it by changing the port mode, not the output value. (Setting the port mode to input floats it, rather than grounding it as setting it LOW would do. This technique was suggested to me by Dave Tweed in Electrical Engineering Stack Exchange.)


text:
powering the arduino uno
I need to power an arduino uno with a battery but for a very long period of time. And I read a lot of thing about this. Some say do not use a 9V battery with a regulator some other say that it is the best way. SO I am really confused and I need to know what's the best solution for this (taking into consideration the fact that I need my board to last a week at least, if it is possible?)
Thanks!

The Arduino Uno is not really designed for that. Simply keeping the power indicator LED, regulators and extra circuits on for a week will require in the order of 1500-2000 mAh (10*24*7=1680mAh). That is without any application at all on the MCU.
Now it is possible to modify the board and reduce this extra power requirements to less than 1 mA and as low as 0.1 mA. Or even better buy a Pro Mini clone and cut the wiring to the LED and regulator, and power with a 3.7 V/1500mAh battery directly.
Here is a great reference on the subject.
Cheers!

As I've said this below too. Pro Mini 3.3V is already really stripped of unnecessary components and really the best for battery powered things.

I didn't quite understand why it's 10247. What does the 10 represent?

No problem! 10 mA x 24 hours x 7 days. 10 mA is lower boundary of power consumption for all the extra circuits on the Uno board. It is actually higher but this is an easy way to get a rough estimate.

You will definitely not get a week out of a 9V cell - they have very small capacities (and are expensive relative to other types of cell).
Your Uno already has a regulator in it and this regulator wastes a certain amount of energy converting between different voltages. I'm certainly no expert, but from what I've gleaned over the last month or so of owning an Uno, powering it from batteries can be tricky if you want to do it for long periods of time.
It's probably worth trying a 12v sealed lead acid battery - these have capacities measured in Amp Hours, rather than milli-amp hours like most other types of cell. The built-in voltage regulator in the Uno is good up to 20V, just be sure to connect to the barrel jack on the board.
Of course, without knowing more about what you're actually trying to power along with the Uno, it's difficult to make proper recommendations.
I would also suggest looking at building your system with a naked MCU and a voltage regulator tailored to your application. That way you can throw away a lot of the stuff that uses power on the board that you don't need. (Start with a Breadboarduino and take stuff out from there!)

Instead a higher capacity battery. I think using a Pro Mini 3.3V would be a better idea.

Three main things to do to decrease the Uno's power consumption:

Remove the power LED (you can Google for instructions if you're not sure how to do it)
Bypass the voltage regulator by providing ~5V of power to the 5V pin. You can arrange three sets of AA batteries in series to get about 4.5V which should be fine except that the crystal may run at a different speed (and you may get incorrect results from the millis() function for example). Obviously if that is unacceptable then you will need to provide a constant 5V voltage either by using the Arduino's regulator (which is quite inefficient) or buying a more efficient third-party regulator. The voltage provided by the batteries will vary somewhat, and over time the batteries will start putting out less voltage and eventually your Arduino may start to behave erratically or not at all. If reliability is of high importance then this may not be acceptable to you.
Use sleep modes to the greatest extent possible (see http://playground.arduino.cc/Learning/ArduinoSleepCode). If your Arduino only needs to wake up for a few seconds every hour, you can make a few batteries go a very long way. Note that if you're using a regulator, it will still draw significant power even while the Arduino is sleeping.

Bonus tip: buy a micro instead, or build your own board. (Avamander suggests a Pro Mini 3.3V in the comments below, he's probably right, I don't know much about that board)

Pro Mini 3.3V is the best idea for battery powered things.


text:
XBee + Arduino Problem
I've been doing some XBee experiments with Arduino Pro Mini 5V. I knew that XBee S2 is 3.3V only, so I've connected its Vcc to 3.3V from external supply, but I had also connected XBee RXTX to arduino TXRX, in this order, and since that i can't use my XBee Explorer to communicate with XCTU on my notebook. The connections with an 5V Arduino RXTX can cause damages to the XBee, even if the XBee was powered with 3.3V?

Try to add a voltage divider on Arduino's TX to shift it to 3.3v logic. This might solve your problem.

The thing is, I can't even communicate with the XBee with a XBee Explorer to my computer, since I did that. Its problaby bricked or damage. What I wanna know if it can get damaged from the RXTX pins.

Did you try the opposite wiring? TX --TX and RX -- RX ?

I've tryed it eventualy as some guides for bricked XBee sugested, but nothing happend.

Is this the first time you tried to work with this xbee? Was it working before this time? Please tell me how do you connect it to your computer?

I just started working with XBee this week. Yes, I could do some thing before it "bricked". I've connected it to my computer with an XBee Explorer from Parallax. http://www.hobbytronics.co.uk/wireless/zigbee/xbee-usb-adapter

Just found this on Digi website. "The XBee is a 3.3V only device, connecting 5V to any pin may damage the radio. If you had connected the XBee to a 5V microcontroller or power source, it's possible that the radio is damaged beyond repair". On this link, the last topic, http://knowledge.digi.com/articles/Knowledge_Base_Article/Recovery-procedure-for-ZigBee-XBees. I really think that the XBee is gone. :/

Just found this on Digi website. "The XBee is a 3.3V only device, connecting 5V to any pin may damage the radio. If you had connected the XBee to a 5V microcontroller or power source, it's possible that the radio is damaged beyond repair". On this link, the last topic, knowledge.digi.com/articles/Knowledge_Base_Article/…. I really think that the XBee is gone. One way to avoid this problem is to get one of this regulated breakout board. http://www.hobbytronics.co.uk/xbee-explorer-reg. As it says in the description, it regulates ALL pins to 3.3V, making me believe that I needed to take care of that before making such a mistake. Hopefully this prevent someone from doing this mistake in the future. So, bye-bye XBee.

Based on the information found here: https://www.faludi.com/bwsn/xbee-level-shifting/ . It seems that xbee isn't that sensitive and maybe you can apply 5v logic to RX pin.


text:
None of the programs in Arduino example is compiling
I am new  to Arduino. I have connected the Arduino to the computer and I have installed the necessary drivers. But when I am compiling the Blink.ino program and other programs, which is present in the example, I am getting an compilation error. I have the IDE folder in D:\ drive
exec: "D:\\Arduino\\arduino-nightly\\tools-builder\\ctags\\5.8-arduino5/ctags": file does not exist
    Error compiling.

I don't know what to do. Please help me

A couple of things here look odd – but then I don't use Windows very often – I'd suggest that you download a fresh copy of the stock (not development) Arduino IDE. You can get it here.
What's odd looking too me is:

The double backslashes, they could be causing the file to appear not to exist, and
The arduino-nightly component in the path. That suggests to me that you're using a "bleeding edge" version of the IDE where problems are likely to creep in. These versions are for developers and people who like living on the edge (or who want to help with testing new features and the like).

One thing to do to check out the first oddity is to actually try to follow that path (both with and without the double backslashes). If the file is there (without the double backslashes) then it seems like something is odd with the path construction in the IDE.

The link which you gave is for downloading arduino 1.6.6 which is arduino- nightly

Hmm, did you try the Windows Installer (in the box on the right hand side) rather than the Hourly build? You might also try an older version. I'm on a Mac and my install (of 1.6.6) does not mention being "nightly."

Also, double check that the missing file, and the path to it, actually exist.

Yeah it worked perfectly well for older version i.e 1.6.5. Thanks @dlu


text:
Arduino Nano Atmega328P doesn't work on Macbook
I've bought and Arduino Nano compatible on eBay:

But by the time I connect it to my Macbook Pro (OS X El Capitan 10.11.2) doesn't appear under "Tools -> Port" in Arduino IDE:

I've followed some instructions by other posts here in StackOverflow:

Arduino Nano no serial port for MacBook Air 2013
Arduino Nano with Mac OS Yosemite 10.10

But none of them worked :(
If someone could help me out with this issue I'll be grateful.
Thanks.

What serial chip is on that board?

The chip is an Atmega 328P

No, I said SERIAL chip. Turn it over. That one, right there.

So sorry Majenko. CH340G is in the serial chip. Thanks.

Ah, I guessed as much. Good luck with that then - that chip has real problems with Yosemite.

Sorry I can't help with it since I don't use a Mac. I just know there are often problems with Yosemite.

Actually you really helped me. Because of your question about the "serial chip" I was be able to look for a solution for that chip in Yosemite! thanks :)

I was be able to solve the issue.
By looking for the serial chip my board has: CH340G I found this blog post:
http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html
So I downloaded the signed driver for my chip and now it works :D
Driver: http://kiguino.moos.io/downloads/CH34x_Install.zip


text:
Can I increase the 10 event limit in Simon Monk's Timer library?
On Dr. Monk's library page here, he states: "You can attach up to 10 events to a timer." I am wondering if this is a hardware limit, or if it was an arbitrary number he chose for his library.
In Timer.h, he defines the maximum number of timed events like this:
#define MAX_NUMBER_OF_EVENTS (10)

Can you foresee any problems if I changed that to a higher number? My sketch is already approaching the limit of 10 timed events running at the same time, so it would help me if I was able to increase the maximum number of timed events to about 20.

I don't see anything that would cause any issue. Just don't exceed 255.

Thanks! I'll mark this as the answer if I don't notice any problems by tomorrow. I wonder why he would choose such a low arbitrary number. Even the forked updated versions on github keep the 10 limit.

This is due to memory. The library creates 10 Event objects and stores them in an array. That is at least 11 bytes per object.


text:
Can I run a Mega 2560 on 14v?
I have a Mega 2560 with a ramps 1.4 shield. I noticed when I turn on the 14v power supply the mega would also power up and run.
Am I damaging it running it at 14v? If not is there a solder or jumper somewhere that I can set it to only run the mega/logic on the usb power? The 14v is just for the stepper motors.

Input Voltage (limit)  6-20V

http://reprap.org/wiki/RAMPS_1.4#Power_Supply

Where is the 14v being supplied to? You Seem surprised that it's receiving power this way, so I assume it's not through the 'usual' channels. I'm not familiar with the board, but as above, it will run on 14V, just make sure they are going into the correct hole!

@MikaelPatel If your board does not have this diode soldered in (or if you cut it), you will need to power the Mega through the USB connector or through a separate 5v line I read that page but missed this sentence! I'll always have usb power (To push gcode) so that looks like the answer.

You can, but you shouldn't, because the the board will heat excessively, as you're out of the recommended range for the input voltage on vin (7-12V).
Unless you have a switching regulator (the one on the board is linear), then you shouldn't' have too much of a difference between the operating voltage and vin as an operating principle because of efficiency (and thus heat) issues.

Thanks! It looks like I can remove a diode on the ramps board to stop it from supplying power to the mega and that will solve the problem completely.

Incidentally, most of the cheap barrel jack sockets you can get, like the one on the Arduino boards, are only rated for 12V maximum. That, more than the regulator's heat dissipation, is the limiting factor.


text:
Light only half of the LEDs
How can I only let half of the LEDs light up,
for example, LED 1 on, LED 2 off, LED 3 on...and so on.
I did it this way
(this example fades also all LEDs on and off)
   int x = 1;
   for (int i = 0; i > -1; i = i + x){
      leds[0] = CRGB(i,0,0);
      leds[1] = CRGB(0,i,0);
      leds[2] = CRGB(i,0,0);
      leds[3] = CRGB(0,i,0);
      Serial.println(i);
      FastLED.show();
      if (i >= 55) x = -1;             // switch direction at peak
      delay(10);
   }

but that is not so nice if you have 100 LEDs or so.

Change int x = 1; to int x = 2;.

I don't know much about neopixel but as a general coding practice if you want to do something for every other object, you use the modulus operator like so
if(i % 2 == 0)
{
  //i is even
  //off
}
else
{
  //i is odd
  //on
}

So just wrap your current for loop in another one and to the above with the iterating variable.

int x = 1;
   for (int i = 0; i > -1; i = i + x){
     // using modulo
     if(i % 2 == 0){
     leds[i] = CRGB(i,0,0)}else{
     leds[i] = CRGB(0,i,0);}

      Serial.println(i);
      FastLED.show();
      if (i >= 55) x = -1;             // switch direction at peak
      delay(10);
   }

or
int x = 2;
   for (int i = 0; i > -1; i = i + x){
     leds[i] = CRGB(i,0,0);

      Serial.println(i);
      FastLED.show();
      if (i >= 55) x = -2;             // switch direction at peak
      delay(10);
   }

This is, for the most part, exactly what others have said. However, nobody has managed to actually use a for loop properly; they've carried forward your inefficiencies for some unknown reason.
The whole point of a for loop is to execute a block of code a predetermined number of times. In your code, you create a loop that loops for a ridiculous length (65,536 times) but each time checks how many loops there have been.
Once the for loop has been constructed properly there are two approaches:
int NUMBER_LEDS = 100;      // you only ever have to change this
                            // if the number of LEDs change - and it's really
                            // easy to find if you put it at the start of
                            // your code.

for (int x = 0; x < NUMBER_LEDS; x++)
{
    if (x % 2 == 0)
        leds[x] = CRGB(x,0,0);
    else
        leds[x] = CRGB(0,x,0);
    Serial.println(x);
    FastLED.show();
    delay(10);
}

The above code is fine if you just want two LED subsets. If you want more than two, you can use a switch/case statement:
int NUMBER_LEDS = 100;      // you only ever have to change this
                            // if the number of LEDs change - and it's really
                            // easy to find if you put it at the start of
                            // your code.
int NUMBER_SETS = 4;        // this will give four groups.

for (int x = 0; x < NUMBER_LEDS; x++)
{
    switch (x % NUMBER_SETS)
    {
        case (0):
        {
            leds[x] = CRGB(0,0,0);
            break;
        }
        case (1):
        {
            leds[x] = CRGB(x,0,0);
            break;
        }
        case (2):
        {
            leds[x] = CRGB(0,x,0);
            break;
        }
        case (3):
        {
            leds[x] = CRGB(0,0,x);
            break;
        }
    }
    Serial.println(x);
    FastLED.show();
    delay(10);
}

You don't have to write a case block for every outcome of x%2; you might want a certain group of LEDs to stay on for two iterations, for example. More information on switch/case can be found here, towards the bottom of the page.
I recommend you read this article on Operators in C++, starting from "Compound Assignement". It helps make code more readable and can considerably decrease the amount of typing you have to do - i = i + 1 neatly becomes i++.


text:
How to shake hands (Atheros-ATmega comms)
How does one assert, from the Linux user land (root-er land?) on the Atheros AR9331, the 32u4's arduino-pin 7 for communication handshake?


text:
Is there any realy working setup for multicopter with codes
I'm searching pc controlled quadrotor code projects.  I tried to do strangedev's project but not works for me. Is any one test this project. PID commands works like relays. suddenley speeds up and down. I tried to tune PID constants with Ziegler nichols but no success. Is there any realy working code and setup. Can you share your experiences?

I've not used the (unmaintained) code you reference, but if a PID is responding much too fast in a new system, cut the parameters down significantly, first focusing on P and later I.  Turn off the D, and the I terms, then slow the P down until it is behaving reasonably.  Once Proportional control is working then try bringing I up in proportion to the change you did with P.
The https://github.com/strangedev/Arduino-Quadcopter/blob/master/quadcopter/quadcopter.ino#L62 code starts with (P,I,D) values of (0.5,0,1), so back off to (0.25,0,0) or (0.05,0,0) or lower to get the speed or response more as you expect, and then experiment.
Higher P will make it faster and saturate to the PID limit values quicker and make it more-relay like.  If your system is in a relay-like bang-bang mode, then Zeigler-Nichols tuning will be hard to do well. Reduce P until you get a non-relay-like response.    Show your code and add in some print/debugging to see what sort of pitch values give you what sort of outputs.  PID isn't magical, if you want a pitch measurement of -30 to cause a control output of +10, P=10/(-30)=0.3 might be a good starting point.
The way the unmaintained code looks, value of P=20 will saturate at your output limits of +/-20 with only a pitch measurement of +/-1 degrees.
Show your actual code and values in your question, slow down the PID, and add debugging output.

I did it with ziegler-nichols. But it behaves like relay. I tried pitch tuneup with increase of P slowly but each P constant from 0.1 to 20 gives suddenly  speed up. Also sample time change gives nothing.

Higher P will make it faster and saturate to the +/-100 values quicker and make it more-relay like.  If your system is in a relay-like bang-bang mode, then Zeigler-Nichols will be hard to do well. Reduce P until you get a non-relay-like response.    Show your code and add in some print/debugging to see what sort of pitch values give you what sort of outputs.  PID isn't magical, if you want a pitch measurement of -30 to cause a control output of +10, P=10/(-30)=0.3 might be a good starting point.


text:
How to connect HC-05 to an arduino Galileo?
I connected a logic analyzer on digital pins 0 and 1 (Rx and Tx). Using Serial. functions on Galileo and the integrated terminal on Arduino IDE, I noticed this UART port was not used when chars were received and transmitted, what is sustained by the blocks diagram of Galileo here.
So, if UART1 is used on PC communications, I would like to use UART0 to other things, like a bluetooth adapter. Any tips?

This might answer your questions about the Serial mapping on Galileo. Seems like you should use Serial1 for UART0 and Serial2 for UART1.
Cheers!


text:
Multiple Arduino Uno Slaves
I am working on an Arduino project where I need more digital and analofgpins than the Uno offers. I was wondering how to hook up multiple Arduinos (4) together so I can use their digital and analog pins. Thanks in advance.

http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem

I suggest using a single Arduino Mega.  It offers 54 digital I/O and 16 analogue inputs.
I suppose you could also use I2C or SPI to communicate between multiple Uno's.

Ryan Griggs' suggestion of the Mega is likely to be easier and more economical than using multiple Unos. That said can you say more about what you want to do with your proposed design? There are good reasons for distributing the load and the problems are interesting – so it is not obvious that the "right" answer is just to use a bigger central machine.
Besides tightly coupling them with the SPI or I2C you could also consider using Ethernet or Bluetooth. Arduino Ethernet shields tend to be expensive, but there are some wireless devices like the Adafruit Huzzah that are more economical.
You may find this post on I2C by Nick Gammon helpful. There is a similar example in this question.

I can only use Uno's for the project so that is why... I am using them to read multiple voltages


text:
Having issue using Arduino IRQ handler in nRF51822
Could anyone please help me as I currently using nRF51822-Arduino library with a nRF51822 chip and I couldn't call the interrupt function, wakeUp().
Currently I connect the external interrupt pin to nRF51822 pin: P0_1 or arduino pin: A0 after pin transform in the nRF51822-Arduino library. Maybe I know what value should I put for the variable pin for the function below:
attachInterrupt(pin, wakeUp, CHANGE);

so that when there is an interrupt change, it will call the wakeUp() function?

Have to managed to get the example, External_Interrupter.ino, running correctly?

Reading the source code for the attachInterrupt() shows that you should use the Arduino Pin number:
https://github.com/RedBearLab/nRF51822-Arduino/blob/S130/arduino-1.6.x/hardware/RBL/RBL_nRF51822/cores/RBL_nRF51822/wiring_interrupter.cpp#L70
The Arduino Pin number for A0 is 19 according to the pin transformation:
https://github.com/RedBearLab/nRF51822-Arduino/blob/S130/arduino-1.6.x/hardware/RBL/RBL_nRF51822/cores/RBL_nRF51822/pin_transform.cpp#L64
Cheers!

Hi Mikael, what you trying to say is to put value 19 for the pin variable? I have try it but it is not working as well.

I can setup the interrupt and trigger to check whether any interrupt is coming out from the Adxl345 chip. It change between 1 and 0 but it can't trigger the Interrupt handler.

As I understand in Arduino, for example Arduino Uno digital pin 2 and 3 is for interrupt and the "pin" variable should put to 0 when using D2 and 1 when using D3.


text:
invalid conversion from 'char' to 'const char*'
My intention was to overload a function to handle optional parameters. My code looks like
void functionA(const char *errorMsg) {
  functionA('0', errorMsg);
}

void functionA(char errorCode, const char *errorMsg) {
    ...
}

The line functionA('0',... generates the error
invalid conversion from 'char' to 'const char*'

How do I fix that?

The compiler needs the prototypes of the functions before the body containing the call to the overloaded function otherwise if starts complaining that the parameters does not match the known function (at this point in the source code).
// The function prototypes
void functionA(const char *errorMsg);
void functionA(char errorCode, const char *errorMsg);
...
void functionA(const char *errorMsg)
{
  functionA('0', errorMsg);
}

void functionA(char errorCode, const char *errorMsg)
{
  ...
}

Cheers!

What do your prototypes look like? I suspect that the compiler thinks that it is calling the first instance of functionA() and is trying to cast '0' to a 'const char *` and that isn't going to work…
If you don't have prototypes for both signatures, then adding the second one may solve your problem. If you do, I'm puzzled.


text:
How to set address for using more than MPU9250
I am trying to build a project that contains more than one MPU 9250, until now I'm still confused to MPU9250. If I were going to that, does anybody here know how to set addresses to each of the MPU's I am going to use? Thank you for spending time reading my question. I hope someone will help me get through this.

It is possible to have up to two MPU 9250 devices on an I2C bus without any extra logic. Pin 9 (AD0/SD0) defines the lowest bit in the I2C address of the device. Please see Chap 7.2 I2C Interface
If you need to connect more than two devices this can be done by connecting the AD0/SD0 pin of each device to a chip select pin on the arduino. This pin is asserted when addressing the device (This solution was provided by @Gerben, see comments below).
An example with three MPU 9250: Arduino D4-D6 are used as chip select pins. MPU1 AD0/SD0 pin connected to D4, MPU2 pin to D5, and MPU3 to D6. D4..D6 are initiate to HIGH. When addressing a MPU the chip select pin is set to LOW and the lower I2C address is used for access. The other MPUs will be listening for the higher I2C address.
Cheers!

You could connect the AD0/SD0 pin to an arduino pin (source). That way you can set the unit you want to communicate with to one address, and all the other units to the second address.

@Gerben Please explain how this would work. Sounds like you are talking about chip select for SPI. For I2C, one of the MPU 9250 should have the AD0/SD0 pin tied to GND and the other to VCC (preferable with resistor).

By connecting the AD0/SD0 address pin to the arduino, you can change the address "on the fly". So you set the pin to HIGH on every module except one, and then use address 1101000 to connect to the one module with AD0/SD0 set low. This however assumes that the module allows changing the address on the fly, and doesn't e.g. only read the AD0 pin on powerup. See also; http://hackaday.com/2015/03/27/using-i2c-addresses-as-chip-selects/

@Gerben Thanks that explains the idea. It is actually a bit like SPI chip select addressing but with the I2C address match instead. Thanks for sharing that!

This is the type of information which a Data Sheet is intended to communicate.  In I2C mode the AD0 pin selects between two possible addresses,
1101000 for AD0=0 and
1101001 for AD0=1.
In SPI mode you can presumably have as many as you like by giving each its own chip select.
That said, using multiple sensors may not be very useful unless your apparatus is flexible - only the 3 accelerometer axis would be expect to yield different values based on position relative to the center of rotations.


text:
Can I receive data on the Arduino by sending data to /dev/ttyACM0?
I'm working on a Raspberry Pi connected to an Arduino.
When I execute
echo 'Hello' > /dev/ttyACM0

, the Arduino receives the data, as indicated by its LED. How can I read the data on the Arduino and process it?

start with a simple google search "arduino serial data read" or any similar combination, you will find a myriad of written tutorials and videos. If you've followed such tutorials, edit your question and show us which one (with a link), post your code and tell us a little more about what you've done and what's exactly not working. Then you might get a real answer to this question, although if you do that (above) you will arrive at the answer all on your own, I'm sure of it

Use Serial.read() there are plenty of examples that come with the Arduino IDE, just make sure the baud rates on the Raspberry Pi and Arduino match.


text:
Arduino Mega 2560 ADC sampling instant and other timings
Hello Everyone (I might be making some mistake in asking this "question", bear with me as I am new to these sites... I honestly think this is the best way to frame my inquiry because it's rather elaborate)
I'd like some help in understanding the "timings" of Arduino MEGA 2560's ADC module, especially with respect to the command analogRead.
I read ATmega2560 microcontroller Datasheet
Let's assume, for now, that our conversions are normal ones ( the other type being a "first" conversion, which takes 25 ADC clock cycles instead of 13, due to the time required for the initialization of analog components )
From what I understood, on a normal single conversion, the sample and hold happens after 1.5 ADC clock cycles from the start of the conversion.
Let's say that I set the prescaler to 32 with the following commands:
const unsigned char PS_32 = (1 << ADPS2) | (1 << ADPS0);
const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

ADCSRA &= ~PS_128;  // remove bits set by Arduino library
ADCSRA |= PS_32;  // set our own prescaler to 32

hence 16MHz / 32 = 500 kHz should be the new ADC clock frequency
( or 2 microseconds ADC clock period )
since a normal single conversion takes 13 ADC cycles, the entire conversion should take about 26 microseconds
If I'm not mistaken, (2 microseconds * 1,5)  = 3 microseconds after the ADC conversion starts, my analog pin value is set on hold, right?
I measured the elapsed time using the micros() function and, like I'd expect,
I found out that there's a little overhead introduced with analogRead function
because it takes about 28 \ 32 \ 36 microseconds (these are empirical measures).
analyzing the code in wiring_analog.c
( which is located in the folder [...]/arduino/hardware/arduino/cores/arduino/ )
the actual conversion seems to happen at line 77
// start the conversion
sbi(ADCSRA, ADSC);

does that mean that this is the instant from which the actual ADC conversion start, and so 1.5 ADC clock cycles from here, my analog pin value is set on hold?
how can I know how much time passed before that sbi function call is issued?
I saw that a single instruction on arduino won't take more than 4 microseconds (but micros() function has that resolution so I don't exactly know!)
Now, considering the so called "first" conversion, which take 25 ADC clock cycles
does this conversion happen just the first time I call analogRead since I powered on Arduino?
or does it happen even after some time , because the ADC module gets powered off? (of course, I consider the case when Arduino remains powered on all the time)
Judging by the timings I measured it seems like that the former is the one really happening, even if I don't use ADC for some time, but can anyone confirm?

does that mean that this is the instant from which the actual ADC
  conversion start, and so 1.5 ADC clock cycles from here, my analog pin
  value is set on hold?

Yes. After between 3μs and 5μs. This is because conversion start at the following rising edge of the ADC clock cycle. This rising edge might have just happened, which means you need to wait 31 (main) clock cycles.

how can I know how much time passed before that sbi function call is
  issued?

You could copy the original code and create your own analogRead2 function that measures the time before setting ADSC.

I saw that a single instruction on arduino won't take more than 4
  microseconds (but micros() function has that resolution so I don't
  exactly know!)

A single instruction will take 1 or 2 clock cycles (if I remember correctly). So at 16Mhz that will mean 62.5ns (nano seconds) per clock cycle. Not 4ms

Now, considering the so called "first" conversion, which take 25 ADC
  clock cycles
does this conversion happen just the first time I call analogRead
  since I powered on Arduino? or does it happen even after some time ,
  because the ADC module gets powered off? (of course, I consider the
  case when Arduino remains powered on all the time)
Judging by the timings I measured it seems like that the former is the
  one really happening, even if I don't use ADC for some time, but can
  anyone confirm?

This first conversion is after the ADEN bit changes from 0 to 1. If you don't unset this bit, all further conversions will take the shorter time.
PS on the first conversion, the sample-and-hold takes place after the extra 12 ADC clock cycles, so between cycle 12 and 13.5.
PPS this info is actually based on the ATMega328, but should be pretty similar in the 2560.

First of all, thx Gerben.
"Yes. After between 3ms and 5ms. [...]"
Just to be crystal clear: you meant microseconds, right? I'm asking because I work with that magnitude: I need to read within 40 microseconds
"A single instruction will take [...] 62.5ns per clock cycle."
if it gets translated into one machine instruction, yes, but like you suggested, I can create my copy of AnalogRead and get the info I need;
Nice advice, thanks! :D
the first sbi() call took about 52 microsecs, the next ones took nearly 24 microsecs.

Yes, sorry. I meant μs.


text:
Using a phone battery as a power source possible?
Use
I am assuming that this is possible for any phone model's battery. I am making this vague on purpose (this isn't for a specific project). The goal is to have the most compact and long-lasting battery possible for my arduino projects.
Note
I don't care about the cost. This would be for personal use (not selling this or using it for school), so I don't care about patenting or copyright issues.
Question
I want to know if this even makes sense for a portable arduino power source option. I want to benefit from newer phones' long battery life, as well as their compact size.
Also:
Are there better alternatives to this using different batteries? (I have looked at Nick Gammon's posts over setting sleep cycles to extend battery life (http://www.gammon.com.au/power); If utilizing his methods on different batteries are better than using a phone battery please let me know...)
If Possible...
Does it make sense for something like a:

LED suit (lasting 12 hours)
Portable gaming system (lasting 8 hours) - similar to: (https://www.adafruit.com/products/2510)
I Know this is for Raspberry Pi
BlueTooth Speaker (lasting 6 hours)

etc...

There's nothing inherently special about phone batteries; they're usually just Li-ion/Lipo batteries with an integrated thermistor.

@IgnacioVazquez-Abrams - I understand that, but I'm primarily interested in them for their low profile. Like the new iPhone and Samsung smartphones. Would it make sense to add these to an Arduino as a power source? (i.e. are there any implications to using them)

It makes sense to use a Li-ion battery as a power source for a microcontroller. It makes slightly less sense to use one with a bog-standard Arduino Uno or Mega due to all the other stuff on the board.

@IgnacioVazquez-Abrams - Are you saying that the "other stuff" draws too much power to make sense for a Li-ion battery?

The boards are fine for prototyping, but once you're done with that you should move to a breakout board or bare MCU.

@IgnacioVazquez-Abrams - So a breakout board or MCU would help with the compact designs I'm looking for, but are these incapable of being powered by certain batteries? (just trying to understand; sorry if questions are naive)

The MCU itself can only handle a specific range of supply voltages. This range is given in the datasheet.

Sounds like a good solution.
Just note that most cellphones use Lithium batteries. Those are typically around 3.7 volt. They require some special way of charging, or they may explode or catch on fire. They also get damaged if discharged too much.
These batteries may have some protection circuitry inside them. This would be ideal in your case, as it protects against over-discharge, and accidental shorts.
An alternative would be the cells used in notebooks called 18650s. These are available with protection and without. The advantage is that you have a standard size. You can buy battery holders for them. That way you can easily exchange batteries. You can also combine cells to create higher voltages.
As for the runtime; you can make a rough calculation of it.

Thanks for the advice! I hadn't thought of using the batteries found in notebooks. I also appreciated the calculator.

I've done this before, but not very practical as a bare "flat-pack" outside its case presents other "issues", the battery "may" catch fire if punctured or shorted too long.  (read fire hazard when punctured) Lithium fires are like thermite, you can't put them out, tossing water on it will only make it worse.
Then there's the voltage mismatch (unless you're using a DUE). A POL  boost converter is needed for best efficiency to get 5-5.2V from a 3.7V cell. And a specialized charging IC is needed so that you don't overcharge/over-rate the current charging the pack. (constant-voltage/constant-current regulator type is needed). I think Adafruit has a lithium breakout board for the 3.7V lithium cell charger, it's for their lilypad stuff i think.


text:
Handling double (8 byte) in Arduino mega 2560?
I am receiving 8 bytes from serial.
I want to convert and save in double variable.
This is how i tried.
union u_data
    {
        byte b[4];
        double fval;
    } u;

double BytesToDouble (byte b8,byte b7,byte b6,byte b5,byte b4,byte b3,byte b2,byte b1)
{
    u.b[0] = b1;
    u.b[1] = b2;
    u.b[2] = b3;
    u.b[3] = b4;
    u.b[4] = b5;
    u.b[5] = b6;
    u.b[6] = b7;
    u.b[7] = b8;
 return u.fval;
}

But i am getting 0.00. Because here double size is 4 bytes.
Is there is any other way to do this?
Thanks

How is u.b[7] = b8; supposed to work on an array that is of size 4? How are you calling BytesToDouble?

In the Arduino there is no such thing as a double. A double is just another name for a float.
So you will have to either:

Manually interpret the double format data and calculate that into a float value, or
Send the value as some other format, such as float (32-bit), ASCII text, or (a selection of) integer values.

Since you can't actually use anything more than float, sending data with a higher resolution is pointless, so you are probably best off just sending it as a float.

avr-gcc doesn't support binary64. You can use 8 bytes to treat it as an opaque data type, but attempting to manipulate it beyond manually converting to/from binary32 will be naught but pain.


text:
Arduino Power - DC adapter
I have a 12V 2.5 ampere Dc adapter.Can i use it to power arduino uno board?
It says on the arduino website that i can use 9-12V and upto 1 ampere. I am concerned with current limit here..

Note that the higher the voltage, the hotter the voltage regulator on the Arduino will get.  Arduino requires 5V, so anything above must be regulated to 5V with the linear regulator on board (LM7805?).

If you go in through the barrel jack the power will be regulated.

Don't worry about the current limit. The board will only draw what it needs. The spec is telling you that the board can draw as much as 1 amp, so in general the power supply should be able to supply that – more is no problem, but less could be if you have a lot of devices attached to the board that are drawing power as well.
As is pointed out in the comment above the higher the input voltage the more power the on-board regulator will need to dissipate (as heat). If you are using the barrel jack (which you should if you aren't providing power through an external regulator or other stable source) there is a diode (D1 in the reference design) in the input path and the MC33269D-5.0 regulator is spec'd with a max dropout voltage of 1.25 V so you will need an input voltage of at least 6.95 V (assuming a 0.7 V drop across the diode).

So i shouldn't worry about 2.5 amperes? everything else is ok.

Not at all. The 2.5 A is a capability of the power supply. I can provide up to 2.5 A if you need it, but it will not "force" more current into the load than the load is asking for. Think about it as being like a water pipe – a larger pipe has the capability of moving more water than a smaller one, but the amount of water that flows is determined by the valve at the end. All other things being equal (which they never are :-)) a larger supply is a good thing, it gives you excess capacity for driving loads (for example if you wanted to attach a string of LEDs or some motors to your project).

Make sure that the adapter you have is the correct polarity for the arduino or it won't work.
The barrel jack is centre positive, so look for this symbol on your adapter:

The barrel jack should have reverse voltage protection so it won't work if it's the wrong way around. The Vin pin doesn't have this protection, so be extra careful connecting things there.

If you're not sure and have a meter of some sort (or even an LED and a resistor where you know the polarity), check to confirm it. That said, it looks like the input is protected against reverse polarity (see the diode D1 in the upper right hand corner of the reference design). It looks like the board will not work if you have the polarity revised (the power LED should not come on).

Yep, you're right, sorry. The barrel jack does have reverse voltage protection, it's the Vin pin that doesn't have it.

No problem. I had to look at at the schematic and it is way better to be safe than sorry :-) Good to add the point about the Vin pin, that's worth noting.

Polarity is not the issue..i just wanted to know if 2.5 amps of adapter will kill my board or not.

Can anyone tell me what the DC “barrel” adapter size is? I can’t find anything about this adapter on the Circuit layout (actually the Reference design only seems to show the USB in - I can’t figure out which component is the DC plug!)


text:
How can I attach sensors without a shield for a wearable project?
I am looking for a solution regarding the gsr, accelerometer, heart rate, skin temperature. From this other question seems that Grove isn't clear enough with their documentation. So I am looking for other ideas. I already know cooking hacks and I am afraid that with their hardware I can't make my Arduino wearable and comfortable enough, because at the end I'd like to attach a lithium battery with a case (that's why I don't want the extra bulk of a shield).
More details of what I am looking for.
Accelerometer:
Range: +/- 1.0g
Minimum resolution: 0.01g
Galvanic Skin Response
Range: 56k Ohms to 20M Ohms
Two-standard-deviation error of +/- 4.0% otherwise
Skin Temperature
Range: 20.0°C to 40.0°C
Resolution: 0.05°C
Error: +/- 0.8°C

Shield are just for lazy people :-). Also, stacking shield will lead to problems a lot of time. Use regular breakouts and wire them yourself to the appropriate arduino pins. You can move them around, till you have the best fit for your enclosure.

"tacking shield will lead to problems a lot of time" Why?
"Use regular breakouts and wire them yourself to the appropriate arduino pins." I'm totally new in this field and what I know at the moment is that I have to see which kind of wire goes in which kind of holes. These things are typically written with letter and numbers (on the board), right?

Sorry, I meant to say 'shields' not 'shield'. A lot of times different shields use the same pins, leading to problems. This forum is full of those cases. As to which connection on the breakout, goes to which pin on the arduino; sometimes it doesn't matter which arduino pin. Sometimes it has to be a specific pin (e.g. SPI or I2C pins). That's the advantage of shield. They've already done this for you. You however miss the flexibility using different pins, when required.

I ran into a similar quandary when making a prototype for a device that needed real test-data from an external, glove-worn accelerometer. I wound up running the data/power/etc pins from my Arduino board to a female RJ-45 jack (I've used a telephone jack on another project where only 4 wires were needed). Then I cut an old cat-5 network cable in half and soldered the wire-ends to data/power/etc pins on my external sensor board. This allowed me to separate one component's wiring scheme from the other's. (FYI: longer lengths of cable between components does increase the risk of noise/interference corrupting digital signals. This can usually be resolved by reducing data rates or by adding a few resistors/capacitors to filter the signal, but I have limited knowledge on this)
Even if you don't have any old RJ45 cables/jacks laying around, it can really help to find some way to "modularize" the various pieces that will be working together when your device is complete. If you're familiar with object oriented programming, think of it as "designing an interface" for each component. Then, even if you completely redesign the wiring for a particular component, you only need to ensure that your "interface" (aka connection) is the same, and you wont need to resolder anything on the other end of the line.

The accelerometer may be pretty easy (since it may not need to be in close contact with the person), but the GSR and skin temperature will need to be touching the person to work.
The first thing you will want to do is to identify the sensors that you want to use, and then come up with some ideas for how to make them wearable so that you can measure the parameters that you're looking for. Will you be able to attach them with straps, or does the attachment need to be more subtle or more comfortable? Small breakout boards are handy, but they may make the sensor uncomfortable to wear.
I'd suggest taking at look at the Adafruit site for some ideas on wearables and sensor interfacing. There is a lot of useful information there and much of it focuses on Arduino based designs. For the most part the sensors they sell and use are well documented either with data sheets or code (or both).

Do you advice specific tutorials?

Then on adafruit there is only one sensor :(

What you'll want to do is figure out which sensors you want to use. Some will interface with a voltage that is proportional to the value being sensed. Those are easy, you just connect those to one of the analog pins. In most cases you could just change the pin being used if there is a conflict. There are also devices that use an interface like 1-Wire that permit multiple devices on a single pin. It will help a lot of you can say more about your project and sensors that you are interested in using.

For accelerometer sensing I used LIS3DH from STMicroelectronics, its low power(down to 2uA), small (LGA package 3x3x1 mm) and has cool build-in features (like orientation, tap and doble tap detection among other things). http://www.st.com/web/catalog/sense_power/FM89/SC444/PF250725?icmp=pf250725_pron_pr_feb2014 and there are a lot of libraries like https://github.com/adafruit/Adafruit_LIS3DH
For intro to GSR check this project http://cwwang.com/2008/04/13/gsr-reader/ Pretty easy ;) More advanced design will require a signal generator and an instrumentation amplifier. An example of such design can be found here https://www.maximintegrated.com/en/design/reference-design-center/system-board/6147.html/tb_tab1 Another interesting project is the truth wristband http://produceconsumerobot.com/truth/
The temperature part can be done with a thermistor (IC temperature sensors do not compliant with your resolution spec) and a bridge circuit. For reference check this sensor http://www.digikey.com/product-detail/en/PR103J2/615-1069-ND/2651611 and also some literature about Wheatstone Bridge http://www.ametherm.com/thermistor/ntc-thermistors-temperature-measurement-with-wheatstone-bridge
Hope be helpful.


text:
Const Array still using dynamic RAM during compile, causing failure
Using win7 and arduino 1.6.7 IDE
I have a rather large CONST array of chars and upon compile using atmega2560, it fails and says:
Sketch uses 11,216 bytes (4%) of program storage space. Maximum is 253,952 bytes.
Global variables use 8,414 bytes (102%) of dynamic memory, leaving -222 bytes for local variables. Maximum is 8,192 bytes.
processing.app.debug.RunnerException: Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.
    at cc.arduino.Compiler.size(Compiler.java:319)
    at cc.arduino.Compiler.build(Compiler.java:156)
    at processing.app.Sketch.build(Sketch.java:1108)
    at processing.app.Sketch.build(Sketch.java:1083)
    at processing.app.Editor$BuildHandler.run(Editor.java:2011)
    at java.lang.Thread.run(Thread.java:745)
Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.
When I delete the CONST array the program compiles successfully, but when I put it back in, the compiler tells me that I'm using too much dynamic RAM.  If I am to understand correctly, consts should store in ROM not RAM.
Here's the even weirder part I put the program in Arduino IDE for Linux and it compiles, but it makes my robot act all crazy.
Any help would be much appreciated.

In a Princeton architecture const arrays are stored purely within the text (i.e., flash / read only / ROM) area.
In a Harvard architecture (which is what the Arduino is) the RAM and Flash both use completely different memory spaces, and instructions that work on RAM don't work on Flash, and vice versa.
Because of that it has to copy the const array from Flash into RAM so it can be accessed as normal variables.
To combat this you can use PROGMEM to force it to remain only in Flash, but then you have to use special functions to access the data - you can't use it like normal variables.
You can read more here: https://www.arduino.cc/en/Reference/PROGMEM

Const data may be stored in ROM but the standards don't require it; you usually have to specify in some (non-standard) way that it be placed there. I.e., const-ness is a necessary, but not a sufficient, condition for locating into ROM. Placing Data into ROM with Standard C by Dan Saks is a short, well-written paper (as is typical of Saks) describing what the standards do and, particularly, do not say about ROMming of constant data. It is well worth a few minutes to read it.


text:
How to extract the last byte out of an IP adress
Newbie question:
I need to pass the last byte of a local IP as a parameter.
Eg.: when Ethernet.localIP() returns 192.168.0.100,
I need to extract the 100 and put it in a char array or string.
Anyone any ideas? Thx!

localIP() returns an IPAddress object.  That object has an operator for [] allowing you to access the individual parts of it.
IPAddress ip = Ethernet.localIP();
Serial.println(ip[3]);

As simple as that :-) Thx!


text:
NTP Client Library. Set sync provider pointing to public class function. Possible?
I am trying to develop a NTP client library for ESP8266/Arduino to make adding NTP sync an easier task.
Basically, I've thought about a constructor as NTPClient(String host, int interval); and a NTPClient.begin() function to register sync function.
My problem is with that registering.
I have a public function: time_t ntpClient::getNtpTime() that connects to NTP server, decodes the response and returns a time_t variable.
Then, inside boolean ntpClient::begin() function I try to run setSyncProvider(ntpClient::getNtpTime). I've also tried to use setSyncProvider(this->getNtpTime).
I get a compile error here:
ntpClient.cpp:In member function 'boolean ntpClient::begin()
ntpClient.cpp:79:39: error: cannot convert 'ntpClient::getNtpTime' from type 'time_t (ntpClient::)() {aka long int (ntpClient::)()}' to type 'getExternalTime {aka long int (*)()}
  setSyncProvider(ntpClient*:getNtpTime)
Error compiling project sources

What could I do to allow registering this function as sync provider to hide NTP internals to my sketches?

Perhaps you should show us your code...?

What could I do to allow registering this function as sync provider to hide NTP internals to my sketches?

The function should be a static member function. A "normal" member function does not have the right prototype as there is a hidden parameter ("this").
static time_t getNtpTime();

To solve this you need a single-ton (an instance of the client class) that the static function can use.
class NTPClient {
public:
   NTPClient() ...
   {
     ...
     s_client = this;
   }
   time_t getNtpTime();
   ...
   static time_t getNtpTime() ( return (s_client->getNtpTime()); }
   ...
protected:
   static NTPClient* s_client;
   ...
};
...
NTPClient::s_client = NULL;
...
NTPClient ntpClient;
...
setSyncProvider(NTPClient::getNtpTime)

Alternatively a global function and a known instance:
class NTPClient { ... };
extern NTPClient ntpClient;
...
time_t getNtpTime() { return (ntpClient.getNtpTime()); }
...
setSyncProvider(getNtpTime)

Cheers!

It was that, thank you. I've tried to change getNtpTime() to static but doing that makes impossible to access variables and non static funcions. So, the only possibility I see is adding a static funcion in main program that wraps a non static ntpClient.getNtpTime().  I'm not an expert C++ programmer at all. Do you think there is any other possibility? I'll upload my code to github and publish here the link.

That is what the last line was all about. You need an instance that the static member function may use. For instance, add a static ntpClient pointer to the class and assign it in the constructor. The static member function can then use that to call the implementation.

I've uploaded my code to https://github.com/gmag11/NtpClient. I'll check the link about single-ton design pattern.

Please see the update code example above. Cheers!

I got it working finally. I've done sync provider registering in setup() function. I will try to add a begin member function in a later moment. Last version is on GitHub. Thank you for your recommendation about singleton.

Great! Here is a link to my own implementation of NTP for Cosa. It uses a Socket interface so there is no need to implement it again for WiFi or other IP devices as long as the device driver implements the Socket interface. https://github.com/mikaelpatel/Cosa-NTP. Please note that it does not implement clock synchronization. That would be done by the Cosa Clock class.