text:
coding problems
I'm working on a Arduino controlled solenoid motor project that I found on Instructables. I have been able to piece together what I think is most of the code but I'm getting some syntax errors and was wondering if I could get some help? Here is the code and the errors.
   // Including Libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <math.h>

LiquidCrystal_I2C mydisplay(0x27,16,2);

// Define Input/Output Pins
#define solenoidpin 9
#define potpin 1
#define ignitioninputpin 2
///#define interruptnumber 3
#define isr_rpm(INT0_vect)

// Defineing Variables
 int previousstate;
 byte buttonstate;
 int counter1;
 int start;
 int finish;
 int elapsed;
 int RPM;

// Main setup
void setup(){
  pinMode(ignitioninputpin,INPUT);
  digitalWrite(ignitioninputpin,HIGH);
////  attachInterrupt(3,isr_rpm, FALLING);
  counter1=1;

  mydisplay.init();
  mydisplay.backlight();
  mydisplay.setCursor(0,1);
  mydisplay.print(" Soleniod Motor ");

  previousstate=HIGH;
  Serial.begin(19200);
  buttonstate = digitalRead(ignitioninputpin);
}

// Main program loop
void loop() {
  buttonstate = digitalRead(ignitioninputpin);
  Serial.println(buttonstate);
  Serial.write("previousstate");
  Serial.println(previousstate);
  Serial.println(counter1);
  float elapsed=start=finish;
  float RPM= (6000/elapsed);
{

if  (buttonstate==LOW && previousstate==HIGH && (counter1%2)==0){
    digitalWrite(solenoidpin,HIGH);
  }

if  (buttonstate==HIGH && previousstate==LOW && (counter1%2)==0){
    digitalWrite(solenoidpin,HIGH);
  }

if  (buttonstate==LOW && previousstate==HIGH && (counter1%2)==0){
    digitalWrite(solenoidpin,LOW);
  }

if  ((counter1%2)==0){                                            for rpm calcs
    finish=start;
    start=millis();
  }

if  ((counter1%6)==0){
    mydisplay.setCursor(0,0);
    mydisplay.print(" RPM ");
    mydisplay.print(RPM);
    mydisplay.setCursor(0,1);
    mydisplay.print(" Solenoid Motor ");
  }

void ISR1();
  buttonstate=LOW;
  counter1=counter1+1;
  previousstate=HIGH;
  }
 }

Error messages:
Binary sketch size: 7,594 bytes (of a 32,256 byte maximum)

A good starting place may be: "'isr_rpm' was not declared in this scope"
That should be fixable. Then ..

Another thing you might consider is losing the extraneous spaces in your include filenames.  <[space]Wire.h[space]> is not the same as <Wire.h>

Another thing to watch out for is making sure you balance your brackets properly.  You seem to have an extra one there.  Fix your indenting and you'll soon spot it.

One more thing I have just noticed - check your usage of & in your if() statements...  It may not be causing a problem, but it's certainly bad programming style since & doesn't mean what I think you think it means.

@Majenko I also noticed the use of &, there are also a few other things the OP has done, also a redundant if() statement.

@RSM There are numerous flaws in the methodology of the program, yes.  Including the use (or lack of use) of previousstate and the copious amount of expensive modulus operations...  Also this line: float elapsed = start = finish;...  I mean... well...  Also local variables (float RPM & elapsed) conflicting with global variables (int RPM & elapsed)...!

@Majenko: modulus 6 may be expensive, but modulus 2 is cheap.

@Majenko I have taken the time to write an answer and point the elapsed equation out. But the OP rightly stated they are new to it.

Do not name a function ISR(): this name is already used by a macro.

@EdgarBonet If the compiler optimizes it right, yes.  Better to do it properly than assume the compiler will fix it for you.

@Majenko: If you do not trust your compiler for this kind of trivial stuff, then write in assembly, not in C.

@EdgarBonet I am right not to trust the compiler.  % 2 causes a call to __divmodhi4 which is hardly efficient - certainly not as efficient as just doing & 1.  One of the things you soon learn with embedded programming is efficient programming where you can second guess the compiler and do it better.

@Majenko: What compiler are you using? I would not use a compiler dumb enough to call __divmodhi4 for % 2, and I suggest you consider switching to a decent compiler.

@EdgarBonet The standard avr-gcc.  The compiler has no concept of what % is.  It just knows that to do a % operation it has to call the libc function that performs that operation.  It can't know that, just because the second argument is a 2 that it'd be better done with a completely different set of operations since it doesn't know what % does.  Just like if you call "sin(0)" it can't know that it'd be better to substitute that with "0" since it doesn't know what sin() does.  It's just a function, which is all % is.  To the compiler it's the same as %(counter1, 2)

Let us continue this discussion in chat.

@KeyPrice Since your last edit you have made some fundamental errors with your program.  Most notably with your ISR1() function.  Fix your indenting so you can see where the error lies.  Good indenting makes for easy to understand programs. You cannot understand your program because you have a very broken layout.  Start with fixing the layout and you will see your errors as plain as day.  If you can't fix your layout then use an autoformatter to do it for you.

Where did the error messages go? They appear to have been deleted by edit #7. All that is left is a compile status message

Welcome to Arduino.SE. I am not going to rewrite the code for you but from this and other answers and comments you should be able to correct the code for yourself from constructive criticism.
To start at the beginning.
You have defined interruptpinnumber but you don't use it in the attachInterrupt function as you declare interrupt pin 1(digital pin 3) and not 0 as the interrupt pin, this will cause problems in your code.
Next, for your timing variables, they need to be unsigned long as the millis() function will return unsigned long. There is also no need to declare them volatile as you are not using them in the ISR routine.
On the topic of the ISR, you have used the arduino attachInterrupt() and you have used the actual ISR() routine from the AVR libraries, also without including it. In the ISR you need to give it a vector which is not there and that is going to give errors later on. You also do not need the ISR routine if you have used the function from Arduino. You need to ensure that what you declare as the routine( that being isr_rpm) in the attachInterrupt() function to be executed when the interrupt occurs, actually exists.
Also there are some basic arithmetic issues with the elapsed time calculation, that is if you were trying to determine the difference.
As @Majenko also pointed out and I was going to too, that the use of a bitwise AND, & in your if() statements might not be a problem but best to learn now that you should use logical AND for comparison &&.
There is also a redundant if statement, that I will leave to you to find as it is your code and you can determine if it is of use or not. Also you need to keep track of you braces as this will cause the errors you are seeing too.
Edit
I think I need to elaborate on a few things as I think you got confused a bit more.
Concerning the whole arduino attachInterrupt function, the isr_rpm() needs to be a function and not a define, I think this caused it

 In the ISR you need to give it a vector which is not there and that is going to give errors later on. You also do not need the ISR routine if you have used the function from Arduino. You need to ensure that what you declare as the routine( that being isr_rpm) in the attachInterrupt() function to be executed when the interrupt occurs, actually exists.

A function of that would be:
void isr_rpm(){

   //code

}

As @Majenko has kindly done you a favor and annotated your code, look at the stuff related to the interrupt routine (and other stuff) and compare it with the below avrfreaks tutorial, and the original code if you have it, the problem to begin with was that you had too many braces:
void ISR(){
      buttonState = LOW;
      counter1 = counter1 + 1;
      previousState = HIGH;
    }
    }

it should be:
ISR(INT0_vect){
      buttonState = LOW;
      counter1 = counter1 + 1;
      previousState = HIGH;
    }

There is no need to give your own special name to ISR either, this is from the newer code.
AVRfreaks tutorial concerning interrupts and the ISR stuff it will give you an explanation on the volatile stuff too.
I cannot stress the point more but, look through your code that Majenko has annotated and see where you can fix the code.

Thanks guys so much, I have been able to fix about 90% of it and I think I'm down to just a few little brackets and indents and such. after having about a pot of coffee and reading some more reference material along with all of your comments I chose to stick with the actual ISR(). Majenko thanks for mentioning the curly brackets it helped a lot and RSM i could not have made it through the morning with out the coffee and your guidance. as soon as i figure out how the formatting on these posts go i will put up the new and improved code.

@KeyPrice - I am sure I helped but I should have possibly been more exact about the use of an ISR as I think that has lead to the completely new code problems. I would review the annotated code by Majenko and compare that with my notes. Also if you have your original code also look at that as that had some formatting errors mainly and the ISR would have been fine if you put the vector in those brackets. Have she more coffee and read through the ISR() link in my post. Also try http://www.avrfreaks.net/forum/tut-newbies-guide-avr-interrupts?page=all. It is a good tutorial.

Ok, I swore I wasn't going to do this, but I have re-formatted your latest code and I am going to go through and annotate it.
// Including Libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <math.h>  /// << WHY?!  You're not using it!

LiquidCrystal_I2C mydisplay(0x27, 16, 2);

// Define Input/Output Pins
#define solenoidpin 9
#define potpin 1
#define ignitioninputpin 2
///#define interruptnumber 3
#define isr_rpm(INT0_vect)  /// << What is this hoping to achieve?

// Defineing Variables
int previousstate;
byte buttonstate;
int counter1;
int start;  ///
int finish; /// << These should be unsigned long
int elapsed;///
int RPM;

// Main setup
void setup() {
    pinMode(ignitioninputpin, INPUT);
    digitalWrite(ignitioninputpin, HIGH);
    ////  attachInterrupt(3,isr_rpm, FALLING);  /// << This will never work with that #define I pointed out...
    counter1 = 1;
    mydisplay.init();
    mydisplay.backlight();
    mydisplay.setCursor(0, 1);
    mydisplay.print(" Soleniod Motor ");
    previousstate = HIGH;
    Serial.begin(19200);
    buttonstate = digitalRead(ignitioninputpin);
}

// Main program loop
void loop() {
    buttonstate = digitalRead(ignitioninputpin);
    Serial.println(buttonstate);
    Serial.write("previousstate");
    Serial.println(previousstate);
    Serial.println(counter1);
    float elapsed = start = finish;  /// << You already defined these as ints in the global
    float RPM = (6000 / elapsed);    /// << scope. Why are you defining them again as floats?!  Also,
                                     /// << elapsed = start = finish?!?!  I think you have an = instead of a -
    { /// << Why are you starting a new block here???
        if (buttonstate == LOW && previousstate == HIGH && (counter1 % 2) == 0) {  /// << counter1 % 2 is very inefficient since counter1 is signed.
            digitalWrite(solenoidpin, HIGH);
        }

        if (buttonstate == HIGH && previousstate == LOW && (counter1 % 2) == 0) { /// << previousstate never changes from HIGH - this will NEVER run!
            digitalWrite(solenoidpin, HIGH);
        }

        if (buttonstate == LOW && previousstate == HIGH && (counter1 % 2) == 0) {  /// << You have already checked this state above with a different outcome.  WHY?!?!
            digitalWrite(solenoidpin, LOW);
        }

        if ((counter1 % 2) == 0) {
            for rpm calcs /// << This isn't even C!!!
            finish = start;

        start = millis();
        }

        if ((counter1 % 6) == 0) {
            mydisplay.setCursor(0, 0);
            mydisplay.print(" RPM ");
            mydisplay.print(RPM);
            mydisplay.setCursor(0, 1);
            mydisplay.print(" Solenoid Motor ");
        }

        void ISR1(); /// << This is a function prototype, not a function definition.
        buttonstate = LOW;       /// << I guess these should be inside
        counter1 = counter1 + 1; /// << a function called ISR1() but that
        previousstate = HIGH;    /// << function hasn't been written.
    }
}

You're trying to mess around writing low-level interrupt routines without having a clue how to work with low level interrupt routines.  Go back and read the manuals on how to do external interrupts with Arduino.  It's very very simple.
There are things about your program that just make me thing "What?!?!" and things that are just plain missing.


text:
Disconnect Ethernet Shield
I'm trying to use the Ethernet Shield and the EasyVR (voice recognition) together.
The Ethernet shield uses the same pins that the EasyVR, but the easyVR works fine if I don't call Ethernet.begin(). Is there a way to disconnect the ethernet shield in order to be able to use the EasyVR again?
I haven't seen any method like "release" or "disconnect" in the Ethernet's class.
Thanks!

EasyVR only uses pins 0 and 1 (UART) (or 12 and 13 if SW-serial is selected). The ethernet shield doesn't seem to use those at all (only SPI and a few other digital pins). Seems more likely that the two libraries are conflicting with each other.

Oh! okay thanks!. But it works if I import all the libraries needed. The easyvr stops working when I use the Ethernet for the first time. So I wonder if I can disconnect the Ethernet shield after using it. Thanks

What happens after you call Ethernet.begin()? Also, are you sure that your board has enough memory?

I'm using the same system, how can I define new ports for easyVR? Thanks.

You have correctly determined the root of the problem, both shields are trying to use the same pins. To work around this we need to know which pins are being used, and for what.
The Ethernet Shield documentation reveals the following:

The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.

https://www.arduino.cc/en/Reference/Ethernet
The documentation for Sparkfun's EasyVR library isn't as explicit, but one of the examples gives us another clue:
#if defined(__SAMD21G18A__)
  // Shield Jumper on HW (for Zero, use Programming Port)
  #define port SERIAL_PORT_HARDWARE
  #define pcSerial SERIAL_PORT_MONITOR
#elif defined(SERIAL_PORT_USBVIRTUAL)
  // Shield Jumper on HW (for Leonardo and Due, use Native Port)
  #define port SERIAL_PORT_HARDWARE
  #define pcSerial SERIAL_PORT_USBVIRTUAL
#else
  // Shield Jumper on SW (using pins 12/13 or 8/9 as RX/TX)
  #include "SoftwareSerial.h"
  SoftwareSerial port(12, 13);
  #define pcSerial SERIAL_PORT_MONITOR
#endif

#include "EasyVR.h"

EasyVR easyvr(port);

EasyVR-Arduino/examples/TestEasyVR/TestEasyVR.ino
This block of code is determining how to set up the serial communication. The first two if statements are for different boards, but the third one sets up the software serial connection... and it says there are two options, pins 12/13 OR 8/9! If there are two options, there must be a way to switch it on the board itself.

And sure enough! Check out that white box labeled "SW Serial Pins". Jackpot!
Here's what the manual has to say:

On the bottom side of the board there are two SMD resistors that you can move to select the two pins of
  Arduino that the EasyVR will be connected to when in Software Serial mode (Mode Jumper on SW).

RX – Software Serial Receiver pin

D12 – Use digital pin 12 as serial receiver (default)
D8 – Use digital pin 8 as serial receiver

TX – Software Serial Transmitter pin

D13 – Use digital pin 13 as serial transmitter (default)
D9 – Use digital pin 9 as serial transmitter

The choice of pins 12-13 is maintained for backward compatibility with the previous hardware revisions of
  the EasyVR Shield. However those pins may also be used for the SPI interface, so another choice of pins 8-
  9 is provided. If you want to use different pins make sure the receiver pin supports change interrupts.

the question is from 2015 when the EasyVR had only the pins 12 and 13 for SW Serial

I excited because this question popped up on "unanswered", but you're totally right. I didn't realize it was 3 years old. :-/

source: Stack Exchange

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

sort: votes


text:
How to read pinMode for digital pin?
Is there a way for me to read the pin mode for one of the digital pins on Arduino?   In other words, can I determine whether a pin's been set to an input or output?

Yes, you can use the data direction registers (DDRB, DDRC, DDRD depending on which port) to check what mode a pin is in.
If a pin is in output mode then the corresponding bit in DDRx will be 1.
One complication is that the Arduino functions give each pin an "Arduino" pin number, and you have to look at a pin map to figure out which DDR register and bit corresponds to the pin you want to check. You can find a pin map for Arduinos based on the ATMEGA168/ATMEGA328 (including Uno) here...
https://www.arduino.cc/en/Hacking/Atmega168Hardware
So, for example, if you want to check if Arduino digital pin #4 is set for output, you'd look at the map and see that corresponds to PD4. That means "port D" and "bit 4", so you could say...
if ( DDRD & _BV(4) ) {   // Check bit #4 of the data direction register for port D
    // If we get here, then Arduino digital pin #4 was in output mode
} else {
    // If we get here, then Arduino digital pin #4 was in input mode
}

If you want to check Arduino digital pin #14, then you would use DDRB & _BV(5).
(_BV(x) is a macro that shifts 1 x bits to the right.)

There are functions which can get you the registers and bit numbers from a pin number built into the Arduino API.
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
volatile uint8_t *reg = portModeRegister(port);

if (*reg & bit) {
    // It's an output
} else {
    // It's an input
}

This answer is also right and I will be using these functions in the future. Thanks for pointing them out!

Seems like the Arduino core is missing a function to read the pinMode(). Here is a possible implementation:
int pinMode(uint8_t pin)
{
  if (pin >= NUM_DIGITAL_PINS) return (-1);

  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *reg = portModeRegister(port);
  if (*reg & bit) return (OUTPUT);

  volatile uint8_t *out = portOutputRegister(port);
  return ((*out & bit) ? INPUT_PULLUP : INPUT);
}

It handles illegal pin numbers (return -1), and all pin modes; OUTPUT, INPUT and INPUT_PULLUP.
Cheers!
BW: I have added this as an issue on the Arduino github repository.

Nice solution. They should add it to the standard.

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

authors: Серго Селиванов


text:
Put ATmega328 in very deep sleep and listen to serial?
I have investigated the sleeps options of the ATmega328, and read a few articles about it, and I would like to understand if there are more options.
So I would like to get as low current as possible, so that anything less that 100uA would be good - as long as I can listen to uart and interrupts for waking up.
I am using a custom PCB (not the UNO), with ATmega328p.
Setting the chip to deep sleep:
 set_sleep_mode (SLEEP_MODE_PWR_DOWN);
 sleep_enable();
 sleep_cpu ();

would not wake it up with serial communication,according to this.
You will need to put it in IDLE mode, to listen to serial, but this would consume a few mA -bad.
I have found this link where you can connect in hardware the serial to the interrupt - which is dangerous so you can loose data, and moreover, I need these 2 interrupts pins.
I also read this article of Gammon, where you can disable some things, so you can get IDLE sleep with much lower power - but he didn't mention how exactly you get from this:
 power_adc_disable();
      power_spi_disable();
      power_timer0_disable();
      power_timer1_disable();
      power_timer2_disable();
      power_twi_disable();

So, bottom line, is there any option out there, to get less than 0.25mA at least, and also listen to serial port, without any hardware manipulation?
For example, waking up with long serial data input?

@NickAlexeev this is an ATmega328 question not an Arduino one as it is deals directly with the chip far below the level of Arduino.  Stop with the improper migrations already!

Hardly. Wanting to wake an Arduino from sleep can't really be dismissed because it has an ATmega328 chip in it. At that rate you'll be able to bounce all the question about Arduinos back to the EE site.

A board we make does this.

The RX pin is wired to INT0
INT0 pin set to input or input pullup depending on how the RX line is driven
On sleep, INT0 low level interrupt is enabled
//Clear software flag for rx interrupt
rx_interrupt_flag = 0;
//Clear hardware flag for rx interrupt
EIFR = _BV(INTF0);
//Re-attach interrupt 0
attachInterrupt(INT_RX, rx_interrupt, HIGH);

INT0 interrupt service routine sets a flag and disables the interrupt
void rx_interrupt()
{
    detachInterrupt(INT_RX);
    rx_interrupt_flag = 1;
}

On wakeup, we check for the flag (there are other interrupt sources)

On the comms side of things we use a message protocol that has a start character > and end character \r. e.g. >setrtc,2015,07,05,20,58,09\r. This give some basic protection against losing messages, as incoming characters are not processed until a > is received. To wake up the device we send a dummy message before transmission. A single character would do it, but we send >wakeup\r hehe.
The device stays awake for 30 seconds after the last message is received in case of new messages. If a new message is receive the 30 second timer is reset. The PC interface software sends a dummy message every second to keep the device awake while the user has it connected for configuration etc.
This method gives absolutely no problems at all. The board with a few peripherals uses about 40uA when sleeping. The actual current consumed by the ATMega328P is probably around 4uA.
Update
At look at the datasheet shows that the RX pin is also pin change interrupt pin 16 (PCINT16)
Thus another method without wires may be

Before sleep: Set the port change interrupt mask bit in PCMSK2 for PCINT16, clear the pin change port 2 flag in PCIFR, enable the pin change port 2 interrupt (PCINT16-PCINT23) by setting PCIE2 in PCICR.
Setup an ISR for the pin change port 2 interrupt and continue as before.

The only caveat with the port change interrupt is that the interrupt is shared across all the 8 pins that are enabled for that port. So if you have more than one pin change enabled for the port, you have to determine which triggered the interrupt in the ISR. This is not a problem if you are not using any other pin change interrupts on that port (PCINT16-PCINT23 in this case)
Ideally this is how I would have designed our board but what we have works.

Thanks very much . Is there no other way than hardware tricks??? So you only connect rx to int0/int1 with 1 line ??

Actually I just had a look at the data sheet and you might be able to use a pin change interrupt

Thanks,what would be the different? Anyway i would have to wake up with rx on int1?

You only need 1 interrupt pin. I posted some more above - you could use the RX pin as a pin change interrupt. I haven't done this though so there might be a few catches like maybe you will have to disable RX / enable pin change before sleep and disable pin change / enable RX after wakeup

thanks, i am not sure why should be a problem with just connecting rx to INT1,set the to interrupt on high ,than disable interrupts when int1 happens, and enabling them again when go to sleep ?

Yep sounds good. The pin change way I just put there in case you couldn't make the mod on the board. IIRC the MCU has to generate a clock source for the UART subsystem, which is probably why it is one of the first systems to be disabled as the sleep level is increased. This is why you can only do deep sleep and UART with interrupts.

ok great thanks, so you trust this configuration on mass production ? :))

also should you put on the int1 pin a pulldown/up ?

I think using a pin change interrupt as in Nick's answer is the most elegant solution. When I first was making the board I mistakenly thought only INT0 and INT1 worked in sleep mode. (Note 3 under the sleep mode table seemed to imply this)

As for production either method should work fine. We've never had a problem. On our board an RTC wakes the atmega328p up every 0.5s on INT1 and that has never failed.

INT1 pin as a pullup (atmega328p can do this internally) if for any reason the pin will be left floating. The default state of UART pins is VCC when there is no activity so the pullup wont consume any current.

The code below achieves what you are asking:
#include <avr/sleep.h>
#include <avr/power.h>

const byte AWAKE_LED = 8;
const byte GREEN_LED = 9;
const unsigned long WAIT_TIME = 5000;

ISR (PCINT2_vect)
{
  // handle pin change interrupt for D0 to D7 here
}  // end of PCINT2_vect

void setup()
{
  pinMode (GREEN_LED, OUTPUT);
  pinMode (AWAKE_LED, OUTPUT);
  digitalWrite (AWAKE_LED, HIGH);
  Serial.begin (9600);
} // end of setup

unsigned long lastSleep;

void loop()
{
  if (millis () - lastSleep >= WAIT_TIME)
  {
    lastSleep = millis ();

    noInterrupts ();

    byte old_ADCSRA = ADCSRA;
    // disable ADC
    ADCSRA = 0;
    // pin change interrupt (example for D0)
    PCMSK2 |= bit (PCINT16); // want pin 0
    PCIFR  |= bit (PCIF2);   // clear any outstanding interrupts
    PCICR  |= bit (PCIE2);   // enable pin change interrupts for D0 to D7

    set_sleep_mode (SLEEP_MODE_PWR_DOWN);
    power_adc_disable();
    power_spi_disable();
    power_timer0_disable();
    power_timer1_disable();
    power_timer2_disable();
    power_twi_disable();

    UCSR0B &= ~bit (RXEN0);  // disable receiver
    UCSR0B &= ~bit (TXEN0);  // disable transmitter

    sleep_enable();
    digitalWrite (AWAKE_LED, LOW);
    interrupts ();
    sleep_cpu ();
    digitalWrite (AWAKE_LED, HIGH);
    sleep_disable();
    power_all_enable();

    ADCSRA = old_ADCSRA;
    PCICR  &= ~bit (PCIE2);   // disable pin change interrupts for D0 to D7
    UCSR0B |= bit (RXEN0);  // enable receiver
    UCSR0B |= bit (TXEN0);  // enable transmitter
  }  // end of time to sleep

  if (Serial.available () > 0)
  {
    byte flashes = Serial.read () - '0';
    if (flashes > 0 && flashes < 10)
      {
      // flash LED x times
      for (byte i = 0; i < flashes; i++)
        {
        digitalWrite (GREEN_LED, HIGH);
        delay (200);
        digitalWrite (GREEN_LED, LOW);
        delay (200);
        }
      }
  }  // end of if

}  // end of loop

I used a pin-change interrupt on the Rx pin to notice when serial data arrives. In this test the board goes to sleep if there is no activity after 5 seconds (the "awake" LED goes out). Incoming serial data causes the pin-change interrupt to wake the board. It looks for a number and flashes the "green" LED that number of times.
Measured current
Running at 5 V, I measured about 120 nA of current when asleep (0.120 µA).
Awakening message
A problem however is that the first arriving byte is lost due to the fact that the serial hardware expects a falling level on Rx (the start bit) which has already arrived by the time it is fully awake.
I suggest (as in geometrikal's answer) that you first send an "awake" message, and then pause for a short time. The pause is to make sure the hardware does not interpret the next byte as part of the awake message. After that it should work fine.

Since this uses a pin-change interrupt no other hardware is required.

Amended version using SoftwareSerial
The version below successfully processes the first byte received on serial. It  does this by:

Using SoftwareSerial which uses pin-change interrupts. The interrupt which is caused by the start bit of the first serial byte also wakes the processor.
Setting the fuses so that we use:

Internal RC oscillator
BOD disabled
The fuses were: Low: 0xD2, High: 0xDF, Extended: 0xFF

Inspired by FarO in a comment, this lets the processor wake up in 6 clock cycles (750 ns). At 9600 baud each bit time is 1/9600 (104.2 µs) so the extra delay is insignificant.
#include <avr/sleep.h>
#include <avr/power.h>
#include <SoftwareSerial.h>

const byte AWAKE_LED = 8;
const byte GREEN_LED = 9;
const unsigned long WAIT_TIME = 5000;
const byte RX_PIN = 4;
const byte TX_PIN = 5;

SoftwareSerial mySerial(RX_PIN, TX_PIN); // RX, TX

void setup()
{
  pinMode (GREEN_LED, OUTPUT);
  pinMode (AWAKE_LED, OUTPUT);
  digitalWrite (AWAKE_LED, HIGH);
  mySerial.begin(9600);
} // end of setup

unsigned long lastSleep;

void loop()
{
  if (millis () - lastSleep >= WAIT_TIME)
  {
    lastSleep = millis ();

    noInterrupts ();

    byte old_ADCSRA = ADCSRA;
    // disable ADC
    ADCSRA = 0;

    set_sleep_mode (SLEEP_MODE_PWR_DOWN);
    power_adc_disable();
    power_spi_disable();
    power_timer0_disable();
    power_timer1_disable();
    power_timer2_disable();
    power_twi_disable();

    sleep_enable();
    digitalWrite (AWAKE_LED, LOW);
    interrupts ();
    sleep_cpu ();
    digitalWrite (AWAKE_LED, HIGH);
    sleep_disable();
    power_all_enable();

    ADCSRA = old_ADCSRA;
  }  // end of time to sleep

  if (mySerial.available () > 0)
  {
    byte flashes = mySerial.read () - '0';
    if (flashes > 0 && flashes < 10)
      {
      // flash LED x times
      for (byte i = 0; i < flashes; i++)
        {
        digitalWrite (GREEN_LED, HIGH);
        delay (200);
        digitalWrite (GREEN_LED, LOW);
        delay (200);
        }
      }
  }  // end of if

}  // end of loop

Power consumption when asleep was measured as 260 nA (0.260 µA) so that is very low consumption when not needed.
Note that with the fuses set like that, the processor runs at 8 MHz. Thus you need to tell the IDE about that (eg. select "Lilypad" as the board type). That way the delays and SoftwareSerial will work at the correct speed.

@NickGammon thanks a lot ! i did it already and it worked . Is that way is common in other products that we use everyday, or they have other ways to listen to comm and sleep ? (all MCU's cant listen to uart at deep sleep?)

I was reading the datasheet and it states that when using internal oscillator, only 14 clock cycles are needed to start the chip, provided that BOD is used. If the power source is always up (batteries), that could be used also without BOD? violating the specs of course. That would bring the chip up very shortly after the incoming UART edge, but still I'm not sure it would be enough to catch the first byte.

Yes, 14 clock cycles isn't long, however possibly the UART would still miss the edge (after all, the edge is when the processor notices the change). So even if it starts up very soon after the edge it might still miss it.

A bit of testing indicates that (even with BOD enabled) it doesn't work. The processor needs to be awake to notice the leading edge (start bit) and thus powering it up after receiving it (even if very shortly after) doesn't work.

The 14 clock cycles are after reset. You only need 6 cycles after power-down, if you use the internal RC oscillator. See additional example code.

I saw the amendment. Amazing job, as usual.

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


text:
Array values won't tokenize
char *p = I2CinBuffer; // array contains "string" "," "string"

but
char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
char *str;       // Temp store for each data chunk
int count = 0;

while ((str = strtok_r(p, ",", &p)) != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
}

does not enter while loop.
Many thanks but the hard coding of the values "6,100" give correct results as it stands. However, I am now aware that the Arduino code is working in C strings and I2CInBuffer is a C string on which the "strtok" or "strok_r" functions will NOT work. My question now is how to parse the C string I2CinBuffer to obtain 2 values separated by a comma i.e. "6, 100".

You're not using strtok_r properly.  You have to treat the first call to strtok_r differently to all subsequent calls, and I don't know what you're trying to do with the &p parameter - that could never work since you're breaking the source pointer with that.
According to the manual page:

The strtok_r() function is a reentrant version strtok().  The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.
On  the  first  call to strtok_r(), str should point to the string to be parsed, and the value of saveptr is ignored.  In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call.

Unless you're doing concurrent tokenising of multiple strings there is no reason to use the reentrant version of strtok.  Instead you should just go:
char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
int count = 0;

char *str = strtok(p, ",");
while (str != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
    str = strtok(NULL, ",");
}

Note how the first call, outside the while loop, passes the string to parse.  All subsequent calls (inside the while loop) pass NULL as the string to parse so it continues from the last point in the string rather than starting the string afresh every time from the start (with a broken string since strtok() is a destructive function).

A sequence of calls to strtok() that operate on the same string maintains a pointer that determines the point from which to start searching for the  next token.   The  first  call  to strtok() sets this pointer to point to the first byte of the string.  The start of the next token is determined by scanning forward for the next nondelimiter byte in str.  If such a byte is found, it is taken as the start of the next token.  If no  such  byte  is  found,  then there are no more tokens, and strtok() returns NULL.  (A string that is empty or that contains only delimiters will thus cause strtok() to return NULL on the first call.)

It is considered destructive because:

The end of each token is found by scanning forward until either the next delimiter byte is found or until the terminating null  byte  ('\0')  is  encountered.   If  a  delimiter byte is found, it is overwritten with a null byte to terminate the current token, and strtok() saves a pointer to the following byte; that pointer will be used as the starting point when searching for the next token.  In this case, strtok() returns a pointer to the  start  of  the found token.

So in other words, your string that started out as:
foo,bar,baz\0

ends up, after tokenizing, as:
foo\0bar\0baz\0

So after the first tokenizing, if you try and pass the string again as the first parameter, instead of "foo,bar,baz", it actually only sees "foo" since the string now ends after foo.
If you wanted to use the reentrant version you'd need to create a separate pointer variable for the save pointer and pass that as the third argument:
char *p = I2CinBuffer; // The data to be parsed e.g. 6,100
int count = 0;
char *saveptr;

char *str = strtok_r(p, ",", &saveptr);
while (str != NULL)    // seperate at each "," delimiter
{
    inParse[count] = str;      // Add chunk to array
    count++;
    str = strtok(NULL, ",", &saveptr);
}

Note that you still need to use the same "pass the string on the first call and pass NULL on all other calls" methodology since it is still destructive.

Many thanks but the hard coding of the values "6,100" give correct results as it stands. I am now aware that the Arduino code is working in C strings. I2CInBuffer is a C string.

@impartit The big question, then, is what is I2CinBuffer and how is it generated?

My question now is how to parse the C string I2CinBuffer to obtain 2 values separated by a comma i.e. "6, 100".

Example code:
int parseit (char * p, int * results, const int maxSize)
{
  int count = 0;
  char *str = strtok (p, ",");   // separate at each "," delimiter
  while (str != NULL && count < maxSize)
    {
    results [count++] = atoi (str);      // Add to array
    str = strtok(NULL, ",");
    }  // end of while
  return count;
}  // end of parseit

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  const int MAX_INTEGERS = 5;
  int inParse [MAX_INTEGERS];
  char  I2CinBuffer [50];

  strcpy (I2CinBuffer, "6,100");
  int found = parseit (I2CinBuffer, inParse, MAX_INTEGERS);
  for (int i = 0; i < found; i++)
    {
    Serial.print (i);
    Serial.print (" = ");
    Serial.println (inParse [i]);
    }  // end of for

}  // end of setup

void loop ()
{
  // rest of code here
}  // end of loop

Results from running it:
0 = 6
1 = 100

Thanks Nick that's great also but I don't wish to hard code the values "6, 100". The two comma separated values will vary and be received into I2CinBuffer from an external python script by a 'write_List' function using I2C.

Doing a strcpy was purely an example for showing the technique. In practice the contents of that would be what you received from wherever.

I2CinBuffer already contains "6, 100" so how will "strcpy (I2CinBuffer, "6,100");"  work.

If it already contains what you want, just omit that line. Be aware, as other answers have stated, that strtok destructively tokenizes. It replaces each delimiter with 0x00 so that afterwards, the variable has been altered. In other words, you can't tokenize it twice. This may or may not matter to you. As an example, if you wanted to display what you received, for debugging purposes, do that before calling strtok, not afterwards.

I am told  by Adafruit support that "strtok won't work on a string object which is what I2CinBuffer is to the Arduino". The data in I2CinBuffer receives the comma separated values from a Python write_list function (Adafruit_I2C.py library file). If I hard card the values as "strcopy(I2CinBuffer, "6,100") the existing strok_r function works just fine. Do you have time to look at the original source code at "http://letsmakerobots.com/blog/unixguru/controlling-raspberry-pi-arduino-bot-internet-part-1-3.? The author does not respond to my emails.

They may be referring to a String object, not a C string. There is a difference. I can't see relevant code on that page. Please amend your question and post a complete sketch that demonstrates the issue. Posting snippets doesn't really help here. It doesn't have to be the whole thing, just enough to demonstrate the problem.


text:
Classes and objects: how many and which file types do I actually need to use them?
I have no previous experience with C++ or C, but know how to program C# and am learning Arduino. I just want to organize my sketches and am quite comfortable with the Arduino language even with its limitations, but I really would like to have an object-oriented approach to my Arduino programming.
So I have seen that you can have the following ways (not exhaustive list) to organize code:

A single .ino file;
Multiple .ino files in the same folder (what the IDE calls and displays like "tabs");
An .ino file with an included .h and .cpp file in the same folder;
Same as above, but the files are an installed library inside Arduino program folder.

I have also heard of the following ways, but have not got them working yet:

Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);
[preferred approach] Including a .cpp file where a class is declared, but without using a .h file (would like this approach, should that work?);

Note that I only want to use classes so that code is more partitioned, my applications should be very simple, only involving buttons, leds and buzzers mostly.

For those interested, there is an interesting discussion about headerless (cpp only) class definitions here: http://programmers.stackexchange.com/a/35391/35959

How the IDE organizes things
First thing, this is how the IDE organizes your "sketch":

The main .ino file is the one of the same name as the folder it is in. So, for foobar.ino in foobar folder - the main file is foobar.ino.
Any other .ino files in that folder are concatenated together, in alphabetic order, at the end of the main file (regardless of where the main file is, alphabetically).
This concatenated file becomes a .cpp file (eg. foobar.cpp) - it is placed in a temporary compilation folder.
The preprocessor "helpfully" generates function prototypes for functions it finds in that file.
The main file is scanned for #include <libraryname> directives. This triggers the IDE to also copy all relevant files from each (mentioned) library into the temporary folder, and generate instructions to compile them.
Any .c, .cpp or .asm files in the sketch folder are added to the build process as separate compilation units (that is, they are compiled in the usual way as separate files)
Any .h files are also copied into the temporary compilation folder, so they can be referred to by your .c or .cpp files.
The compiler adds into the build process standard files (like main.cpp)
The build process then compiles all the above files into object files.
If the compilation phase succeeds they are linked together along with the AVR standard libraries (eg. giving you strcpy etc.)

A side-effect of all this is that you can consider the main sketch (the .ino files) to be C++ to all intents and purposes. The function prototype generation however can lead to obscure error messages if you are not careful.

Avoiding the pre-processor quirks
The simplest way of avoiding these idiosyncrasies is to leave your main sketch blank (and not use any other .ino files). Then make another tab (a .cpp file) and put your stuff into it like this:
#include <Arduino.h>

// put your sketch here ...

void setup ()
  {

  }  // end of setup

void loop ()
  {

  }  // end of loop

Note that you need to include Arduino.h. The IDE does that automatically for the main sketch, but for other compilation units, you have to do it. Otherwise it won't know about things like String, the hardware registers, etc.

Avoiding the setup/main paradigm
You don't have to run with the setup/loop concept. For example, your .cpp file can be:
#include <Arduino.h>

int main ()
  {
  init ();  // initialize timers
  Serial.begin (115200);
  Serial.println ("Hello, world");
  Serial.flush (); // let serial printing finish
  }  // end of main

Force library inclusion
If you run with the "empty sketch" concept you still need to include libraries used elsewhere in the project, for example in your main .ino file:
#include <Wire.h>
#include <SPI.h>
#include <EEPROM.h>

This is because the IDE only scans the main file for library usage. Effectively you can consider the main file as a "project" file which nominates which external libraries are in use.

Naming issues

Don't name your main sketch "main.cpp" - the IDE includes its own main.cpp so you will have a duplicate if you do that.
Don't name your .cpp file with the same name as your main .ino file. Since the .ino file effectively becomes a .cpp file this also would give you a name clash.

Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);

Yes, this compiles OK:
class foo {
  public:
};

foo bar;

void setup () { }
void loop () { }

However you are probably best off to follow normal practice: Put your declarations in .h files and your definitions (implementations) in .cpp (or .c) files.
Why "probably"?
As my example shows you can put everything together in one file. For larger projects it is better to be more organized. Eventually you get to the stage in a medium to large-size project where you want to separate out things into "black boxes" - that is, a class that does one thing, does it well, is tested, and is self-contained (as far as possible).
If this class is then used in multiple other files in your project this is where the separate .h and .cpp files come into play.

The .h file declares the class - that is, it provides enough detail for other files to know what it does, what functions it has, and how they are called.
The .cpp file defines (implements) the class - that is, it actually provides the functions, and static class members, that make the class do its thing. Since you only want to implement it once, this is in a separate file.
The .h file is what gets included into other files. The .cpp file is compiled once by the IDE to implement the class functions.

Libraries
If you follow this paradigm, then you are ready to move the entire class (the .h and .cpp files) into a library very easily. Then it can be shared between multiple projects. All that is required is to make a folder (eg. myLibrary) and put the .h and .cpp files into it (eg. myLibrary.h and myLibrary.cpp) and then put this folder inside your libraries folder in the folder where your sketches are kept (the sketchbook folder).
Restart the IDE and it now knows about this library. This is really trivially simple, and now you can share this library over multiple projects. I do this a lot.

A bit more detail here.

Nice answer. One most important topic, though, didn't became clear to me yet: why everybody says "you are probably best off to follow normal practice: .h + .cpp"? Why is it better? Why the probably part? And most important: how can I don't do it,  that is, have both interface and implementation (thas is, the whole class code) in the same, single .cpp file? Thank you very much for now! :o)

Added another couple of paragraphs to answer why "probably" you should have separate files.

How do you not do it? Just put them all together as illustrated in my answer, however you may find that the preprocessor works against you. Some perfectly valid C++ class definitions fail if they are put in the main .ino file.

They also will fail if you include a .H file in two of your .cpp files and that .h file contains code, which is a common habit of some. Its open source, just fix it yourself. If you are not comfortable doing that, you probably shouldn't be using open source. Beautiful explanation @Nick Gammon, better than anything I have seen so far.

@Spiked3 Is not so much a matter of choosing what I'm most comfortable with, for now, it is a matter of knowing what's available for me to choose from in the first place. How could I make a sensible choice if I don't even know what my options are, and why each option is the way it is? Like I said, I have no previous experience with C++, and it looks like C++ in Arduino might require extra care, as shown in this very answer. But I'm sure eventually I'm getting a grasp of it and get my stuff done without reinventing the wheel (at least I hope so) :)

Thanks for the extra explanation! Now it's a lot clearer to me, and it's working fine with the .h and .cpp files like you explained!

@heltonbiker sorry, I was just saying, some people (myself included) get very frustrated when we get free code and it doesn't work. I either have to fix it myself, or look elsewhere. Fortunately there is helpful people like Nick to explain things, but very often there is no, or an out of date explanation. 'what is available' may not always be the same as 'what works', so depending on your comfort, it might not meet your needs.

For example, nick has excellent suggestions on how to write Arduino code. I can't think of a single library I've seen that follows it. A library I am dependent on at the moment was written back before Arduino was Arduino (it was wiring) and has not been updated since. It took several days to figure out how to make it work like a standard C++ program would behave.

This explaination is better than the arduino build process documentation :-). thanks

What about UECIDE? Does it does the apply the same treatment?

I don't know as I haven't used it.

My advice is to stick to the typical C++ way of doing things: separate interface and implementation into .h and .cpp files for each class.
There are a few catches:

you need at least one .ino file - I use a symlink to the .cpp file where I instantiate the classes.
you must provide the callbacks that the Arduino environment expects (setu, loop, etc.)
in some cases you will be surprised by the non-standard weird things that differentiate the Arduino IDE from a normal one, like automatic inclusion of certain libraries, but not others.

Or, you could ditch the Arduino IDE and try with Eclipse.
As i mentioned, some of the things that are supposed to help beginners, tend to come in the way of more experienced developers.

While I feel that separating a sketch into multiple files (tabs or includes) helps everything to be in its own place, I feel like needing to have two files to take care of the same thing (.h and .cpp) is a sort of unnecessary redundancy/duplication. It feels like the class is being defined twice, and everytime I need to change one place, I need to change the other. Note this applies only to simple cases like mine, where there will only be one implementation of a given header, and they are going to be use only once (in a single sketch).

It simplifies the work of the compiler/linker and allows you to have in the .cpp files elements which are not part of the class, but are used in some method.
And in case the class has static memers, you cannot place them in the .h file.

Separating .h and .cpp files has long been recognized as unneeded. Java, C#, JS none require header files, and even cpp iso standards are trying to move away from them. The problem is there is too much legacy code that could break with such a radical change. That is the reason we have CPP after C, and not just an expanded C.  I expect the same will happen again, CPX after CPP?

Sure, if the next revision comes up with a way to perform the same tasks that are done by headers, without headers ... but in the meanwhile there are plenty of things that cannot be done without headers: I want to see how distributed compilation could happen without headers and without incurring major overheads.

I'm posting an answer just for completeness, after finding out and testing a way of declaring and implementing a class in the same .cpp file, without using a header. So, regarding the exact phrasing of my question "how many file types do I need to use classes", the present answer uses two files: one .ino with an include, setup and loop, and the .cpp containing the whole (rather minimalistic) class, representing the turning signals of a toy vehicle.
Blinker.ino
#include <TurnSignals.cpp>

TurnSignals turnSignals(2, 4, 8);

void setup() { }

void loop() {
  turnSignals.run();
}

TurnSignals.cpp
#include "Arduino.h"

class TurnSignals
{
    int
        _left,
        _right,
        _buzzer;

    const int
        amberPeriod = 300,

        beepInFrequency = 600,
        beepOutFrequency = 500,
        beepDuration = 20;

    boolean
        lightsOn = false;

    public : TurnSignals(int leftPin, int rightPin, int buzzerPin)
    {
        _left = leftPin;
        _right = rightPin;
        _buzzer = buzzerPin;

        pinMode(_left, OUTPUT);
        pinMode(_right, OUTPUT);
        pinMode(_buzzer, OUTPUT);
    }

    public : void run()
    {
        blinkAll();
    }

    void blinkAll()
    {
        static long lastMillis = 0;
        long currentMillis = millis();
        long elapsed = currentMillis - lastMillis;
        if (elapsed > amberPeriod) {
            if (lightsOn)
                turnLightsOff();
            else
                turnLightsOn();
            lastMillis = currentMillis;
        }
    }

    void turnLightsOn()
    {
        tone(_buzzer, beepInFrequency, beepDuration);
        digitalWrite(_left, HIGH);
        digitalWrite(_right, HIGH);
        lightsOn = true;
    }

    void turnLightsOff()
    {
        tone(_buzzer, beepOutFrequency, beepDuration);
        digitalWrite(_left, LOW);
        digitalWrite(_right, LOW);
        lightsOn = false;
    }
};

This is java-like and slaps the implementation of methods into the declaration of the class. Apart from the reduced readability - the header gives you the declaration of the methods in a concise form - I wonder if more unusual class declarations (like with statics, friends etc) would still work. But most of this example is not really good, because it includes the file only once an inclusion simply concatenates. The real problems start when you include the same file in multiple places and you start getting conflicting object declarations from the linker.


text:
Triggering the push button on the analog input of the L293D motorshield
I'm trying to drive a 12v dc motor using three push buttons, one to turn clockwise, the other counter-clockwise and the other to stop the motor completely.
However the code below is not working, apparently it feels like I'm doing something wrong in the code on the connect buttons on the analog part of the engine shield L293D.
The Arduino is powered by a 9v battery and motor shield **L293D with an external power.
#include <AFMotor.h>

    AF_DCMotor motor(1);

    int val;

    #define btnleft A0
    #define btncenter A1
    #define btnright A2

    void setup()
    {
      pinMode(btnleft, INPUT);
      analogWrite(btnleft, HIGH);
      pinMode(btncenter, INPUT);
      analogWrite(btncenter, HIGH);
      pinMode(btnright, INPUT);
      analogWrite(btnright, HIGH);
    }

    void loop()
    {
     val=digitalRead(btnleft);
       if(val!=1)
        {
        Serial.print("LEFT: ");
        motor.setSpeed(255);
        motor.run(FORWARD);
        delay(3800);
        }

     val=digitalRead(btncenter);
       if(val!=1)
        {
        Serial.print("CENTER");
        motor.setSpeed(255);
        motor.run(BACKWARD);
        delay(3800);
        }

     val=digitalRead(btnright);
       if(val!=1)
        {
        Serial.print("RIGHT");
        motor.run(RELEASE);
        delay(3000);
        }
    }

Why are you using analogWrite() on an input?

I thought it was to be an analog input in motorshield

So then why would you treat it as an output regardless?

Maybe he means digitalWrite, to set the internal pull-ups. Doing an analogWrite of 1 doesn't make a heap of sense.

As noted in Nick Gammon's comment, digitalWrite(btnleft, INPUT) (etc.) would make a lot more sense than does analogWrite(btnleft, INPUT) (etc.).

Edit: INPUT is a constant defined in wiring.h (as in following extract), and is intended for use in pinMode() calls that set an IO pin's mode to one of INPUT, OUTPUT, or INPUT_PULLUP.  It's inept to use it in a call of either digitalWrite() or analogWrite().
    #define HIGH 0x1
    #define LOW  0x0
    #define INPUT 0x0
    #define OUTPUT 0x1
    #define INPUT_PULLUP 0x2

Note that digitalWrite to an input-mode pin leaves the pin in input-mode, while an analogWrite to an input-mode pin changes the pin to output-mode.
When you want a pin to be input-mode with pullup, it is simpler to use INPUT_PULLUP as the mode parameter, rather than using two separate calls.  That is, instead of saying pinMode(pin, INPUT); followed by digitalWrite(pin, HIGH);, just say
pinMode(pin, INPUT_PULLUP);

Actually digitalWrite(btnleft, INPUT) is not correct. You should only call digitalWrite with a HIGH or LOW parameter, to avoid misunderstandings. Ok, for arduino INPUT = LOW = 0x0 and OUTPUT = HIGH = 0x1, but... I don't think that someone writing digitalWrite(btnleft, INPUT) wants the pin set at 0


text:
Reading iBeacon Data using HC-05 bluetooth module
I have bought a HC-05 bluetooth module for Arduino.
My requirement is to read data transmitted from iBeacon, is it possible using HC-05 or I have to shift to HM-10?

did you come up with a plan? Because I am dealing with the same issue, would love to see an answer without having to post the same question.

The HC-05 doesn't support BLE, which is used for iBeacons.

Is it possible to read ibeacon data with Arduino using HM-10 module? If not then what's the best option?

Probably yes. But I'm not into BT.


text:
esp8266 not getting programmed
I am working on an esp8266 and I am connecting it with Arduino Uno. I have programmed the Arduino but when I write AT command on the serial monitor it doesn't show anything.The connections which i have made are:
tx uno - rx esp
rx uno - tx esp
gnd uno -gnd esp
vcc and ch_pd - 3.3v supply

I am using an external supply and not the 3.3v from the Arduino.
I need help with this.

And how exactly do you think the ESP8266 is connected to the USB-UART bridge?

It is connected via the connections which i have mentioned.

No, it isn't. It is connected backwards.

what do u mean by backwards?

You have RX of the bridge connected to RX of the device, and the same with TX.

While it is true that the TX/RX are running at 5V, I have been playing around with it without issue (so far!). But yes, connect the RX to RX and TX to TX. I got mine working. Also check the baud rate. I was convinced mine was running at 9600, but then it worked at 115200...

I have connected RX to TX and it is working.There was a problem in my wifi module.I changed it and now it is working.

Be careful, you could fry your ESP like that.  You need to get the signal lines down to 3.3V, not the 5V used by the Arduino Uno.  There are many ways to do this, from voltage dividers, to transistors, or you can use a 3.3v Arduino Pro Micro.  I would also recommend starting out with just a 3.3v FTDI board, and interface that directly to the ESP to remove the Arduino and its code from the picture.
I would also make sure that your grounds on the external supply and the Arduino are tied together, or just power the ESP from the 3.3v out of the Arduino.
Other than that, double check your baud rate, some come shipped at 9600, some at 115200, and i'm sure that there are others out there too shipping at different baud rates.

Sorry if these are stupid questions but these are the things I would check.

Why are you connecting to an Arduino, why not connect directly to the
HOST and use a terminal emulator program?
What ESP8266 are you using?
Are you connecting the Vcc connector of the ESP8266 to 3.3v?
I think you need to pull the RST pin high to enable normal running,
is it high?

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


text:
Arduino Micro and MPU-9150
I'm trying to connect an Arduino Micro to MPU-9150 using the  MPU6050_DMP6 example.
It runs for couple of seconds then the board Hangs, I sometimes see the "FIFO overflow" message.
The same code runs well when i connect the MPU-9150 to Arduino UNO and Arduino Duemilanove.
I tried to lower the serial baud rate but no success with that. I even tried connecting an external 12V to the Micro but it's the same.
should I lower the i2c clock (not sure how to do it)?
another interesting thing i have noticed is that with the Duemilanove i can use a longer line for the i2c (5m of cat5e), with the Uno it only works with less then 2m cables, can anyone tell why?

I have seen a lot of variations with the 6050.  Code I know works fine for me, will not run on someone else's system.  Code fixes suggested by others has zero effect for me.  My understanding is the DMP code is a reverse engineered sample that the manufacturer will not release actual documentation on. So it is a gamble to begin with.
That being said, I usually reset the FIFO buffer after every read.  I get an occasional over flow (1-2 per minute) with a lot of other code running at the same time, and NOT using interrupts.  The resulting AHRS data is reliable and solid (UNO) at default rate (100hz).  Ive lowered the AHRS rate (you have to modify data tables in a .H file) and I get the same error rate, it seems to have no effect.
As far as line lengths go, it is I2C. It is some magical combination of wire size and length, internal pull up resistors plus external ones.  I have usually heard people have success adding some pull-up resistors  I2C is a ground sink signal - so it doesn't care if it is 5 volts or 3.3 - only that everything on the bus be the same.  Obviously you will do better at 5V on a longer line vs 3.3V.  Some will argue the pull ups need to be at termination, some say it doesn't matter. I don't know anything other than the spec is very hard to understand and I have not had problems, especially the kind that require some of the elaborate schemes some people come up with (replacing caps and resistors).
Anyhow, 2 meters would seem to be pushing an Integrated circuit to Integrated circuit spec beyond what it was intended for, communication within a board. You might get it to work, but you also might rethink it.


text:
(Arduino + official GSM shield + ultrasonic HC-SR04 sensor) inaccurate measuring
I'm using an Arduino Uno, 1.0.5 r2 version of the IDE with and ultrasonic HC-SR04 sensor for measuring a tank water level. I want to send the data obtained over internet using the official arduino GSM shield sending them on the plot.ly servers with their API using a GPRS connection. When I'm doing all the tasks I get inaccurate values as these:

When I use the only ping sensor without the GSM shield all works well getting good data. The same using a potentiometer + GSM shield + plot.ly.
The function I use for getting the distance is:

long distCalc() {
  long durata, distanza;
  digitalWrite(TRIG_PIN, LOW);  // TRIG_PIN = pin 12
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  durata = pulseIn(ECHO_PIN, HIGH);  //ECHO_PIN = pin 11
  distanza = durata / 29.1 / 2 ;
  return distanza;    // in uscita la distanza in [cm]
}

and the one for posting the data on plot.ly servers is (loop function):
void loop() {
  long distanza;
  distanza = distCalc();  //fase di calcolo distanza
  Serial.print(distanza);
  Serial.println("cm");
  graph.plot(millis(), int(distanza), tokens[0]);  //fase di invio su plot.ly
  delay(20);
}

Could it be a software serial interrupt that hangs the pulseIn measurement?
How could I avoid this?

Hi @em1lio189, could be an issue with delay / delayMicroseconds. You may try to put another delay between distCalc() and Serial.print().
On a separate note, how are you going to install this setup in the tank? Water-proofing, etc.
I am also working on a similar project and planning to use Bluetooth / Wifi for transmitting data. This is a personal project not commercial for my home.

hi @theghostofc, I tried with the delay with no results. I think that the measure is noisy because the softwareserial library uses interrupts. I solved powering off the gsm shield, making the measure, starting it again and sending data in the main loop.

That's great that you got it working, even though with a hack :)

Could you please let me know how you are going to place the hardware (in the tank or outside). In my case it is placed outside under the Sun, with no power outlets nearby. Main concern that I have is to make the setup weather-proof. Any suggestions?


text:
Arduino IRremote stops working
I'm using a standard 38kHz receiver with Arduino-IRremote library and it works fine for a while but then it stops working. The loop function is running time after time as expected but at some point the library decode function starts returning false until I reset the board.
This example code works for me with any arduino nano or bare atmega328p at 8Mhz but for both of them it freezes after some receptions.
The code is the library example itself:
#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  delay(100);
}

Some times this happens fast and other times it is after 20 or more receptions.
I only added a led blink later to test if the board is frozen or is only the infrared that stops receiving and it was the second case.

HI, are you the same user who posted the issue on Github

@RSM Yes I am. I don't know if it's a bug or what. First I tested on Nano with RGB leds driven with PWM and thought the problem was with that so I isolated the IR part on a bareduino that only receives from IR and writes to soft serial and sometimes it freezes too. When I reset the bareduino it works again.

I ran the code on an UNO and a pro micro with a continuous spool of IR data pointer at it for 15 minutes? so I don't know whats up the code on yours

I never saw it failing when connected to computer so I thougth had something to do with serial output so I removed all the serial prints but still the same result.

When running 'standalone' the nano is connected to a cell phone charger via USB and later when added the bareduino it is powered by the nano vcc.

I take it you have the latest version of the Library too?

I don't think the VCC is going to be a problem.

I got the latest version before noticing it was not stable. Did small edits myself (defines and so, no code changes) to be able to use it. If you think the problem might be that i'll try to change it this week to the stable tagged release. Now it is embedded on a device and it is not so easy to update.

If you have the library within the last three months it should be the latest. What definitions did you change, maybe put those in the question or link a file, possibly not the problem as it shouldn't cause it to freeze.

My current version of the library is this one https://mega.nz/#!6cwVVKpI!U3uWmixxSzxI5iRXUIXbOknbpRrv6JNWJFbleoWnXoo. I think I copied a change to support arduino pro micro/leonardo (tested but not much), dealt with half-done defines/ifdefs per brand and renamed it because of conflict with RobotIRemote.

Try adding a capacitor to the power rail of you bareduino. It might just be that the processor hangs, and there is nothing wrong with the code. Try toggling a led inside the loop to see whether the code is still running.

@Gerben There is a capacitor on the nano input. I think the processor does not hangs. Currently with nano+bare the nano does not hang at all. I am sure of that. RGB leds keep changing. I'll add a led to bareduino to make sure it is not hanged.

I was having similar problem (but not the same )
And it was due to software serial pins which keep on filling the buffers of MCU.
Some times it happen that pwm pins keep on receiving data e.g. GPS also keep filling the buffer and due to that arduino freeze .
To solve this problem I open new dummy software serial port.( select any pins which is free ) and do listen to your software serial pins when you want to read it otherwise make dummy listen.

This seems completely irrelevant to me. The question does not mention software serial.

Arduino tutorials I've seen don't mention it but the datasheets from the ir receptors manufacturers advice to stabilize vcc with a resistor and a capacitor.

It seems without that the receptor fail to correctly report the received wave so the library may decode it wrong. In my case the problem started to happen when I added RGB leds controlled by PWM on the same (stabilized) power supply.

In short: The IRremote Library has bugs that lead to unresponsiveness of the board.
There were some updates and now IRremote.h library 3.01 runs about a day with a FastLED.h WS1211 led stripe connected to it.
My approach to make it run reliable more than 24h with the latest library you could connect a digital pin to the reset pin on the Arduino.
Then use EVERY_N_HOURS to occasionally pull that pin low.
The Software reset via timer (watchdog timer library) every 2 seconds f.e. worked occasionally but not reliable.
That should even make every 2USD board clone run as reliable as it could/hardware allows it.
Have fun :)


text:
0 value integer does not enter If
I'm sure this is a very basic coding mistake...
I'm picking up a reading from A0. If the value is 0, I want the value of the serial to be written to the Serial Monitor.
I also want it only to write to the Serial Monitor for the first time that the value falls to 0.
I don't understand why, when the value for SensorValue = 0, the if is not performed.
This is my code:
boolean must_print = true;
int sensorValue = 0;

// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  sensorValue = analogRead(A0);

  if (sensorValue = 0) {

     if (must_print = true)
    {
     must_print = false;
     Serial.println(sensorValue);
    }
  else
    must_print = true
  }

   delay(500);        // delay in between reads for stability
}

Thanks!

  if (sensorValue = 0) {

That assigns zero to sensorValue, which then tests false. You want:
  if (sensorValue == 0) {

No problem. And in case you didn't spot it, you have the same problem with if (must_print = true). That should also be ==.


text:
Counting revolutions of a DC motor with a Photo Interrupter
I have a DC motor which is rated at 11 200 RPM.
I would like to count the actual RPM (it seems to be maybe 1500 RPM from what I can tell manually.)
I bought a Photo Interrupter, and have connected it to pin A0. When the beam of the Photo Interrupter is broken, the reading drops to zero.
All seems to work well when using a delay of 100, but as soon as I drop the delay to less than about 50, I get multiple reads.
This is my code:
int must_print = 1;
int sensorValue = 0;

//the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  sensorValue = analogRead(A0);

  if (sensorValue > 0)
    {
      if (must_print == 1)
      {
        must_print = 2;
        Serial.println(sensorValue);
      }
    }

  if (sensorValue == 0) {
    must_print = 1;
  }

  delay(100);        // delay in between reads for stability
}

At delay(100) the Serial Monitor looks like this for a single interrupt of 10 seconds:
354

At delay(50) the Serial Monitor looks like this for a single interrupt of 10 seconds:
298
312
328
336
349
360
366
371

Thanks!

You shouldn't use an analog pin with a photointerruptor.  The photointerruptor is a digital device.  Connect it to, preferably, an interrupt pin and use an interrupt to count your revolutions at high speed.

Thanks for the advice. I just read up on the interrupt pins and I see that it's definitely the way to go. I just don't understand how you would write to the Serial Monitor when using an interrupt.

You wouldn't.  You just count in the interrupt - everything else is done in loop().

I'm using the following code, but I don't see anything in the Serial Monitor. :
int pin = 13;
int tcnt = 0;
volatile int state = LOW;
void setup()
{
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, CHANGE);
}

void loop()
{
   Serial.println(tcnt);
   digitalWrite(pin, state);

}

void blink()
{
   tcnt = tcnt + 1;
   state = !state;

}

@DanielGee - You also need to make tcnt volatile and initialize Serial with Serial.begin(9600);

It seems that the Interrupt is incredibly sensitive. If I even touch the wire running from the Arduino Pin 2 to the Photo Interrupter the Interrupt fires - multiple times. Have I done something wrong or is this expected?

@DanielGee - interrupts are sensitive, especially if you have a long cable between sensor and Pin, try adding a small decoupling cap at the microcontroller pin.

You must set the input pin to be INPUT_PULLUP

@Majenko - +1, good point


text:
Sodaq Moja — Accessing SW2/SW3 user switches
I have a Sodaq Moja, from supporting the project on Kickstarter, and I didn't have much time until now to play with it. Unfortunately, the online documentation for the Moja has disappeared, and only the docs for the new version, the Mbili, is accessible. And nowhere can I see where to access the user switches. Which, to boot, have been reordered in the Mbili, can cut down from 3 to 2.
Would anyone have an idea?
Cheers,

It took me about 15 seconds to get all the information you could ever want about the Moja, including the schematic.  You didn't try very hard.  Here's the schematic: https://github.com/SodaqMoja/SodaqMojaBoard and there is tons more stuff in other repositories: https://github.com/SodaqMoja

I went through the github repository but didn't find any code related to sw2/sw3. Did you? The 15 seconds you spent were obviously lazy and useless...

I have to ask: what "user switches" are you thinking you are trying to use?  The Moja has no user switches as you can tell by looking at your board and cross-referencing what you see there with what is on the schematic I pointed to.

According to the schematics and pictures of the Moja, the Sodaq Moja has no "User Switches".
There are 2 buttons and 1 switch.  The switch is a general power on-off switch.  One button (SW2) is the master reset button for the ATMega328P.  The other button, SW3, is the reset for the X-Bee daughter board.
None of those can be used programmatically.


text:
Sending a double message for action to occur
I'm currently designing a system for my GCSE coursework. For the coursework, I am making a bollard system, controlled by the internet / traffic lights.
I've been experimenting with an Arduino Uno and Ethernet shield, in order to fulfill the control by the internet.
When I telnet into my Arduino, and send it the command "S#UP", the red LED comes on, and stays on for 30 seconds. If I send the command again, the Arduino does not turn on the LED, unless the command was send twice, consecutively. Also, if I were to send a different command, for example "S#DOWN", the LED does not even turn on, no matter how many times I send it.
Does anyone have any ideas for my? Anything I've blatantly missed or got myself confused on?
#include <SPI.h>
#include <Ethernet.h>
String authcode, newstatus, command;
bool UP, DOWN, EMERGANCY;
long UPTime, DOWNTime, EMERGANCYTime, LastFlash;
bool NextFlash;

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

IPAddress ip(192, 168, 1, 177);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

EthernetServer server(1265);

char serverHost[] = "LambdaLaptop";
EthernetClient phpClient;

int R = 8;
int G = 9;

void setup() {
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  Serial.begin(9600);
  Serial.println("=----------------------=");
  Serial.println("=- Traffic Management -=");
  Serial.println("=-    System Loaded   -=");
  Serial.println("=----------------------=");

  Serial.println("");

  authcode = String("4b4fec50eaa13b98934c36863293b5cf");
  LastFlash = millis();
  NextFlash = HIGH;

  pinMode(R, OUTPUT);
  pinMode(G, OUTPUT);
}

void loop() {
  EthernetClient client = server.available();
  if (client) {
    if (client.available() > 0) {
      char thisChar = client.read();
      command += thisChar;
      ProcessCMD( command );
    }else{
     if(command.length() > 0 ){
       command = String("");
     }
    }
  }
  if( UP ){
    if( UPTime > millis() ){
      digitalWrite(G, HIGH);
    }else{
      UP = false;
      digitalWrite(G, LOW);
    }
  }else if( DOWN ){
    if( DOWNTime > millis() ){
      digitalWrite(R, HIGH);
    }else{
      DOWN = false;
      digitalWrite(R, LOW);
    }
  }else if( EMERGANCY ){
   if( EMERGANCYTime > millis() ){
     if( LastFlash + 100 < millis() ){
       digitalWrite(R, NextFlash);
       if(NextFlash == LOW){
         NextFlash = HIGH;
       }else{
         NextFlash = LOW;
       }
     }
    }else{
      EMERGANCY = false;
      NextFlash = HIGH;
      digitalWrite(R, LOW);
    }
  }
}

void ProcessCMD( String CMD ){
  if(CMD == "S#UP"){
    UP = true;
    UPTime = millis() + 30000;
    if(CMD.length() > 11){
      command = String("");
    }
  }else if(CMD == "S#DOWN"){
    // Make the thing go DOWN.
    // GREEN LIGHT
    DOWN = true;
    DOWNTime = millis() + 30000;
    if(CMD.length() > 11){
      command = String("");
    }
  }else if(CMD == "S#EMERGANCY"){
    // Make the thing go DOWN.
    // Flash RED beacon.
    EMERGANCY = true;
    EMERGANCYTime = millis() + 15000;
    if(CMD.length() > 11){
      command = String("");
    }
  }else if(CMD == "TEST"){
    UP = true;
  }else if(CMD == "TEST2"){
    UPTime = millis() + 30000;
  }else{
    if(CMD.length() > 11){
      command = String("");
    }
  }
}

void SetStatus( String newstatus ){
  if (phpClient.connect(IPAddress(192,168,1,10), 80)) {
    phpClient.println(String("GET /setstatus.php?authcode=") + authcode + String("&status=") + newstatus + String(" HTTP/1.1"));
    phpClient.println("Host: LambdaLaptop");
    phpClient.println("User-Agent: arduino-ethernet");
    phpClient.println("Connection: close");
    phpClient.println();
    phpClient.stop();
  }
  else {
    Serial.println("Couldn't connect to the system!");
    phpClient.stop();
  }
}

Two things: don't use String it is very inefficient and messy. Secondly, you have misspelled "emergency".

Another problem is with your times.  Not only should they be unsigned long (or better, uint32_t), but your method of dealing with elapsed time will fail at millis() rollover.

A third issue: your whole method of building up (and clearing, and indeed everything about) your command string is flawed.  What's so special about the magical number 11...?

It would be far better to use char arrays instead of the String class (perhaps 11 bytes, if that is the largest command?).
eg.
const int MAX_COMMAND = 11;
char command [MAX_COMMAND];

 if (client.available() > 0) {
      char thisChar = client.read();
      command += thisChar;
      ProcessCMD( command );

You appear to be processing the command for every received byte. This means you will process "S", "S#", "S#D", "S#DO" etc. You need to wait until the whole command has arrived.
Then, once the command has been processed, empty out the command ready for next time.

void ProcessCMD( String CMD ){

Also all upper-case is usually reserved for constants, not variables like CMD.

Finally, your detection of end-time by addition will fail when millis() wraps. This might not matter in a small test, but you may as well teach the right way. Instead of adding an interval, remember the start time and detect when the interval is up, eg. instead of:
if( UPTime > millis() ){

You would write:
if (millis () - UPTime >= 30000) {

Where UPTime is now the start of the interval (that is, you remember when the interval starts, and do the above subtraction to find the end of it).

References

Processing incoming serial data - the same techniques apply to Ethernet

millis() overflow ... a bad thing? - how to handle millis() wrap-around

State machines - managing events happening on the fly

I do not have and ethernet shield at this moment to test on it your code but hopefully the next observations will help to solve your issue.

If I send the command again, the Arduino does not turn on the LED,
  unless the command was send twice, consecutively.

It seems that your string is not correctly processed, probably caused by "garbage" from previous received string or incomplete string. I think is from this part of the code
 if (client.available() > 0) {
  char thisChar = client.read();
  command += thisChar;
  ProcessCMD( command );

You are trying to append a char (one byte) to your command string; by doing this you are not getting the received string necessarily because the "+=" is for retrieve char by char (for example, inside a while loop). First try to print thisChar variable to ensure what are you getting and also you can print client.available() to see how many bytes you got.
Second, for your ProcessCMD function it could be better to use pointers to handle the command variable, meanwhile you must clean command variable always (and not only when CMD.lenght > 11 ), i.e,
if(CMD.length() > 11){
  command = String("");
}

must be at the end of the ProcessCMD function
  command = String("");

Also you can ensure that when you set UP=true, also set DOWN=false and so on. I prefer the Switch-Case structure to handle commands.
Try to follow arduino examples to better understand.
Cheers.


text:
Arduino can't see any library I have installed for nrf905?
nrf905\
nRF905-All-In-One-Shield\
RadioHead-master\
RadioHead\
None any of them are compiled with their examples without getting errors.
Error message:
nRF905_RX.ino:4:20: fatal error: NRF905.h: No such file or directory
compilation terminated.
Error compiling.

Libraries used:
Elechouse
RadioHead Github
RadioHead Doxygen
zkemble/nRF905

Which Arduino? What version of the IDE? Where did you get those libraries from? (link). What error messages? Try to give a bit more detail.

actally I have the same problem in 1.5.2 and 1.6.5
the links are : https://github.com/elechouse/nRF905
https://github.com/PaulStoffregen/RadioHead
http://www.airspayce.com/mikem/arduino/RadioHead/
https://github.com/zkemble/nRF905
I intend to connect it with arduino uno when the code will be verified  correctly .

the error message is : NRF905.h : No such file or directory compilation terminated

@SalamEtaiwi - where have you put the libraries?

in the libraries folder at arduino  folder  that I use

no error when using examples of this library "RadioHead"  after added it to the library folder , but when trying of another examples there are  errors .

@SalamEtaiwi - I have tried to compile the one from elechouse and that one gives continuous errors, even if the ide is given the exact location, it will throw more errors. If the radiohead one works why not just use it?

@RSM I will try it , I just was confused why not  all  of them work right !
thanks for reply

@SalamEtaiwi - I have just got the zkemble one to compile, which didn't before.

@RSM so is there  error ?

I am writing an answer to explain as  I have all the libraries compiling

about zkemble one after I add the library I  create a new folder called "src" and place the .cpp and .h files into the new folder . as he explain when I emailed him . but still have problem with "nRF905_config.h" it appears now in the error message

I shall explain the problem in the answer as I also tried that and the same result happened

thanks for continuity in this ,,
for correction I used 1.5.8 and 1.6.5 not 1.5.2

@Salam - Let us know if you get it working ;)

The errors you were getting when you compiled was because if the libraries were extracted straight to the Arduino library folder from the .zip, the file path becomes too long for the compiler to find it.
So what you need to do is to create a new folder in the libraries folder for each library.
Note: you cannot do the standard libraryName\src\foo.cpp as this seems to give errors for these libraries (in that it does not find them).
What you need to do is to make a file in the libraries directory; for the zkemble one you can create a main folder called nRF905, then take the files under nRF905/arduino/nRF905 from github and place them in the folder created earlier. It should look like this:

You should repeat this for the Elechouse one as well as it solved the problem too. i.e.

C:\\...\libraries\NRF\examples\
C:\\...\libraries\NRF\NRF905.cpp
C:\\...\libraries\NRF\NRF905.h
C:\\...\libraries\NRF\keywords.txt

Also of importance is that once you have the library from Elechouse compiling you need to open up the .cpp file and go to line 16, where there is
PROGMEM unsigned int freq_tab[10] = {

and to this add const, like so:
PROGMEM const unsigned int freq_tab[10] = {

thanks alot I did what you said ,actually most of the examples give no errors , but there are others give anyway I am now satisfy with this and I tried with a couple of a code (transmitte and recieve ) no errers was in transmite one and the serial monitor showed the right things but the problem was in the recieving side , the Rx led didnt lighting on ’ and not any data in the serial monitor. these are the codes ( transmitte , recieve):

sorry , it cant be sending , but they are the examples from "RadioHead" library ,, nrf905_client ,,, nrf905_server ...

@Salam - first off, glad it worked.  I would recommend posting a new question here. And then I would recommend you open an issue on the RadioHead github page so you can bring it to the attention of the libraries author, he might also be able to give you a accurate answer. I am also on a phone at the moment so can't do much.

I will do that in sha`a Allah .. thanks again ^^


text:
Arduino Mega XBee Limited inputs
I'm currently using an Arduino Uno with the Wireless SD shield with an XBEE attached so I can wirelessly send voltages from sensors to a computer. This works great but I am limited to 5 analog inputs. I am thinking of using a Mega but the Wireless SD Shield is the same for both models. Are there any shields/techniques were  I can wirelessly transmit up to 15 analog inputs to a PC using XBEE or otherwise,
Many Thanks,
AH

Why 5 inputs? The Uno has 6. (A0 to A5).

Sorry I meant 6!

See 74HC4051 multiplexer / demultiplexer. That describes how you can use a multiplexer chip to multiplex analog inputs.
The 74HC4051 multiplexes 8 inputs into one, and the 74HC4067 multiplexes 16 inputs into one. Thus you would only use one analog input, plus 3 or 4 pins to tell the chip which input you want at a particular moment.
The general way a multiplexer works is like this:

By outputting a binary pattern to the A/B/C pins you select which input you want active at a particular moment. That is then copied to the output pin (pin 3 in this case). You would connect that to your analog port on the Arduino.
The code would rotate between each of the 8 pins (or 16 pins with the bigger chip), and then do an analogRead.

Example wiring

Example code
// Example of using the 74HC4051 multiplexer/demultiplexer

// Author: Nick Gammon
// Date:   14 March 2013

const byte sensor = A0;  // where the multiplexer in/out port is connected

const byte addressA = 5; // the multiplexer address select lines (A/B/C)
const byte addressB = 6;
const byte addressC = 7;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Starting multiplexer test ...");
  pinMode (addressA, OUTPUT);
  pinMode (addressB, OUTPUT);
  pinMode (addressC, OUTPUT);
  }  // end of setup

int readSensor (const byte which)
  {
  // select correct MUX channel
  digitalWrite (addressA, (which & 1) ? HIGH : LOW);
  digitalWrite (addressB, (which & 2) ? HIGH : LOW);
  digitalWrite (addressC, (which & 4) ? HIGH : LOW);
  // now read the sensor
  return analogRead (sensor);
  }  // end of readSensor

void loop ()
  {
  // show all 8 sensor readings
  for (byte i = 0; i < 7; i++)
    {
    Serial.print ("Sensor ");
    Serial.print (i);
    Serial.print (" reads: ");
    Serial.println (readSensor (i));
    }
  delay (1000);
  }  // end of loop

That only does 8 ports, but the 16-port chip would be conceptually similar.


text:
What is the use of decoupling capacitor?
I dont understand what does the word "decoupling" mean? Where and Why it is used? Can anyone give me a brief idea>?

Quite simply put, it's a little reservoir of energy for a chip or other device to dip into when it needs to get a little extra power.
In Electronics nothing happens instantly.  When a chip needs more power it has to get it from the power source.  The power source then has to respond to that by providing more energy, and that then has to make its way down the wires or traces to where it needs to be.
By placing a small capacitor near where the power is consumed the capacitor can respond to that call for more power much faster than the power supply.

So by responding in that way, I understand that it helps maintain the voltage and provide necessary current to the chip? Am i right?

Yep, that's right.  Think of it like the tank on your toilet.  You have a local supply of water for flushing, then the normal water supply fills it up slowly afterwards.  You can't flush with just the normal water supply, it's not fast enough.

What about it's use as a high-frequency transient suppresant or for AC-DC (de)coupling? The term bypass capacitor is often interchanged with decoupling capacitor so frequently - whether erroneously or not - that it deserves an inclusion, n'est pas?

That's too technical for an Arduino user.

@chaaarlie2 You may want to direct that question to the electronics stackexchange, found at http://electronics.stackexchange.com/

@Butters The questions were rhetorical; I know the answers, my point was to discover why Majenko omitted two of the three facets of "the decoupling capacitor".

@Majenko I wouldn't have thought the high-frequency aspect was too technical; it can be explained as succinctly as your existing answer and it is a reasonably fundemental principle. You almost always get two capacitors bundled with each IC on a PCB - one larger electrolytic to act as a power reservoir and one small ceramic job to negate transients. Each is invariably as important as the other, so it's a shame you haven't addressed both.

@chaaarlie2 The high frequency aspect of the capacitor isn't just down to the capacitor, but the impedance of the traces since the two together form a low-pass filter.  To properly explain that aspect it is necessary to also explain impedance, filters, Q, etc.  Far too much for an Arduino user to cope with.  If they want more detail then they can go to EE.SE where they will get an EE-centric answer covering all those aspects.

@Majenko And how would the OP know to go to EE.SE for more detail if you fail to mention that these aspects exist?

@chaaarlie2 If they are capable of understanding the concepts without first undertaking some formal learning they'll already know of the existence of EE.SE and will probably have been there many times before.  If not, and they do want more clarification, then there is this magical thing called "migration" which will send them to EE.SE. In the context of the Arduino, though, just the basics are all that are required. It's enough to know that you DO need decoupling caps, and some rough idea why you need them so you remember to use them. You don't need to know all the quantum mechanics of them.

@chaaarlie2 IF I were answering this on EE.SE then yes, there would be a huge amount more information.  You have to remember: this is an arduino site, and people that come here looking for answers generally lack even the most basic knowledge.  Giving them too much too soon is bad for them.  Look up "Wittgenstein's Ladder", better known by Pratchett fans as "Lies to Children".

Every time a logic circuit switches from a 0 to a 1 or a 1 to a 0, the 1 and 0 transistors are on at the same time for a short period of time.  In MOS circuits, this is combined with the need to charge the gate of the 1 or 0 transistor (Charge is what capacitors store, gates of MOS transistors are capacitors!).
Since all wiring is inductive, the faster the current, the higher the impedance from the main power supply and the switching device (Your processor or sensor etc).  The terms bypass and decoupling mean the same thing:  You are providing a local charge well to supply fast current demands by bypassing the main power system, i.e. supplying current via a different path and thus decoupling the switching device from the inductively isolated main supply.
This is also why we used to use two types of capacitors for decoupling: A 0.1uF ceramic and a 1uF electrolytic for instance...  You couldn't get the whole 1uF in a low resistance ceramic to cover both the Low and High speed transients without paying a lot so you used two or more parts, each covering a portion of the spectrum.  Nowadays a single SMT ceramic with low ESR, low ESL and no lead wires can do the whole job and is usually pretty economical.
Another factor is radiation:  A ringing voltage transient current through inductive wiring acts just like an antenna.


text:
What changes I have to take care while coding from Atmel Studio instead of Arduino IDE?
-Are there any changes in Bootloader?
-Why is the coding different for same chip in different softwares?
-How to upload the program from Atmel Studio?

Atmel cpp projects do not currently provide an option to upload using Arduino bootloader. Atmel only provides upload using hardware programmers.
The bootloader is deleted when you upload using a hardware programmer either from Atmel Studio or from the Arduino ide.
The underlying Atmel toolchain is not very different from the latest Arduino toolchain however Atmel does not know about the Arduino hardware/cores. You have to copy the Arduino core sources to your Atmel project if you want to compile for Arduino compatibility but that still does not give you bootloader upload.
It is not clear from your question if you have the Arduino sources in your cpp project already. If you do have the sources in your project then you can use avrisp mkII or other programmer to upload but the Arduino libraries might be an issue for you if you are using them.
There is another option in Atmel Studio however it might not be what you require ...
You can install the Visual Micro plugin for Arduino from the Atmel Gallery and work with standard Arduino sketch projects inside Atmel Studio.
The Visual Micro plugin provides full Arduino compatible sketch build and bootloader upload in Atmel Studio. Because of the nature of Arduino, the Visual Micro plugin automatically manages the include paths and Atmel project properties so that intellisense works in projects that contain .ino source code files. If the project does not contain .ino files then Visual Micro sleeps (does not interfere with cpp projects)
The plugin also provides other features such as a serial usb debugger, library manager, board manager, Arduino examples etc.
More about Visual Micro is here
Tutorials are here
Debugger overview is here

Update:
There is no difference in program execution between uploading using a physical hardware programmer or using a usb cable via bootloader.
The Arduino libraries sources can be more complicated to include/compile in a project because they often include additional folders with private source code. This is more of an issue with older Arduino libraries that have a sub folder called \utility.

You mention hardware programming. So as I understand, Bootloader is part of Hardware Programming and Atmel Studio helps in hardware programming, am I right? What is the difference between hardware programming and programming using Arduino IDE? and one more question, What is the difference between Arduino Sources and Arduino Libraries as you have mentioned it above? Assume, Blink project is my project need to be uploaded from Atmel Studio.

Have updated the answer