text:
How to detect if more than one button was pressed
I am designing a turn signal bicycle blinker using two pushbuttons as input, one for each side, with a corresponding light for each button.
The idea is this:

Pressing one side makes same side start blinking;
Pressing same side again to turn it off;
Pressing other side turns off this side and turns other side on;
(now the tricky part!) if both buttons are pressed (or more precisely, if one button is pressed before the other is released), then - and only then - I start blinking both sides ("warning signal" feature).

As I see it, the problem is that I need to wait until I release a single button (that would be one complete click) to turn a single side on, because if I press the second while the first remains pressed, that would be another event/gesture ("both_click", for lack of a better name).
Another design option would be to turn a single light on immediately on press, and if I press the second before release the first, then in would also turn the other light (thus comprising the "warning", both-lights-blinking mode). While that sounds feasible, there is all the debouncing logic in the Button ("Botao") class, and I am afraid I painted myself into a corner with the specific object-oriented design choices I've made.
EDIT: a third design option would be to add a run method on each button and, instead of only running the tested "pseudo-event" method, save the current state and event in variables, testing those variables in loop() (property button.wasPressed instead of method button.wasPressed(), for example).
I'm posting my current code (relevant parts only). Note there is a comment in the loop where I think I should detect double click.
Main .ino file:
#include "PiscaPisca.cpp"
#include "Botao.cpp"

PiscaPisca pisca;

Botao botao1;
Botao botao4;

void setup() {

  pisca.configure(LEFT, RIGHT, BUZZER);

  botao1.configure(BUTTON1);
  botao4.configure(BUTTON4);
}

void loop() {

  // HOW SHOULD I DETECT BOTH WERE PRESSED??
  // if (bothPressed()) { pisca.toggleWarning(); }

  if (botao1.wasPressed()) { pisca.toggleLeft();  }
  if (botao4.wasPressed()) { pisca.toggleRight(); }

  pisca.run();
}

Botao.cpp (this is a button class with debounce)
#include <Arduino.h>

class Botao
{
    int _pino;

    const int DEBOUNCE_DELAY = 30;

    int buttonState;
    int lastState = HIGH;

    int lastDebounceTime;

    public : void configure(int pino)
    {
        _pino = pino;
        pinMode(pino, INPUT_PULLUP);
    }

    public : boolean wasPressed()
    {
        return debounce(LOW);
    }

    public : boolean wasReleased()
    {
        return debounce(HIGH);
    }

    public : boolean debounce(int state)
    {
        boolean gotEvent = false;

        int reading = digitalRead(_pino);

        if (reading != lastState) {
            lastDebounceTime = millis();
        }

        if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
            if (reading != buttonState) {
                buttonState = reading;

                if (buttonState == state) {
                    gotEvent = true;
                }
            }
        }

        lastState = reading;

        return gotEvent;
    }
};

PiscaPisca.cpp (the state-machine itself)
#include "Arduino.h"
#include "PwmPin.cpp"
#include "Beeper.cpp"

typedef enum {
    NONE        = 0,
    RIGHT_LIGHT = 1,
    LEFT_LIGHT  = 2,
    BOTH        = 3
};

class PiscaPisca
{
    PwmPin _left;
    PwmPin _right;

    Beeper _beeper;

    long _timeReference = 0;

    const int PERIOD = 350;

    boolean
        _running = false,
        _lightState = false;

    int _sides_to_turn = NONE;

    public : void configure(int leftPin, int rightPin, int buzzerPin)
    {
        _left.configure(leftPin);
        _right.configure(rightPin);
        _beeper.configure(buzzerPin);
    }

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

    public : void toggleLeft()
    {
        checkRestart(LEFT_LIGHT);
    }

    public : void toggleRight()
    {
        checkRestart(RIGHT_LIGHT);
    }

    void checkRestart(int lightSide)
    {
        _timeReference = 0;

        // some clever bit-twiddling can never hurt too much:
        _sides_to_turn = lightSide & ~_sides_to_turn;

        Serial.println(lightSide);
        Serial.println(_sides_to_turn);

        if (_sides_to_turn > 0)
        {
            _running = true;
        }
        else
        {
            lightsOff();
            _running = false;
            _lightState = false;
        }
    }

    void evaluateBlink()
    {
        if (!_running)
        {
            return;
        }
        else
        {
            long currentMillis = millis();
            if (currentMillis - _timeReference > PERIOD) {
                _timeReference = currentMillis;
                _lightState = !_lightState;
                performBlink();
            }
        }
    }

    void performBlink()
    {
        if (_lightState)
        {
            _beeper.beepIn();
            lightsOn();
        }
        else
        {
            _beeper.beepOut();
            lightsOff();
        }
    }

    void lightsOn()
    {
        if (isLightSet(LEFT_LIGHT))
        {
            _left.on();
        }
        if (isLightSet(RIGHT_LIGHT))
        {
            _right.on();
        }
    }

    boolean isLightSet(int lightSide)
    {
        return (_sides_to_turn & lightSide) == lightSide;
    }

    void lightsOff()
    {
        _left.off();
        _right.off();
    }

};

Where is your state machine?

@IgnacioVazquez-Abrams I'm posting it, see my edit.

Interesting question, and tricky to get perfect. :)
I wrote a switch manager class a while back. It's just a .h file which you can put in your libraries folder (or add to your sketch).
SwitchManager.h
#include <Arduino.h>

class SwitchManager
  {
  enum { debounceTime = 10, noSwitch = -1 };
  typedef void (*handlerFunction) (const byte newState,
                                   const unsigned long interval,
                                   const byte whichSwitch);

  int pinNumber_;
  handlerFunction f_;
  byte oldSwitchState_;
  unsigned long switchStateChangeTime_;  // when the switch last changed state
  unsigned long lastLowTime_;
  unsigned long lastHighTime_;

  public:

     // constructor
     SwitchManager ()
       {
       pinNumber_ = noSwitch;
       f_ = NULL;
       oldSwitchState_  = HIGH;
       switchStateChangeTime_ = 0;
       lastLowTime_  = 0;
       lastHighTime_ = 0;
       }  // end of constructor

     void begin (const int pinNumber, handlerFunction f)
       {
       pinNumber_ = pinNumber;
       f_ = f;
       if (pinNumber_ != noSwitch)
         pinMode (pinNumber_, INPUT_PULLUP);
       }  // end of begin()

     void check ()
       {
       // we need a valid pin number and a valid function to call
       if (pinNumber_ == noSwitch || f_ == NULL)
         return;

        // see if switch is open or closed
        byte switchState = digitalRead (pinNumber_);

        // has it changed since last time?
        if (switchState != oldSwitchState_)
          {
          // debounce
          if (millis () - switchStateChangeTime_ >= debounceTime)
             {
             switchStateChangeTime_ = millis ();  // when we closed the switch
             oldSwitchState_ =  switchState;  // remember for next time
             if (switchState == LOW)
               {
               lastLowTime_ = switchStateChangeTime_;
               f_ (LOW, lastLowTime_ -  lastHighTime_, pinNumber_);
               }
             else
               {
               lastHighTime_ = switchStateChangeTime_;
               f_ (HIGH, lastHighTime_ - lastLowTime_, pinNumber_);
               }

             }  // end if debounce time up
          }  // end of state change
       }  // end of check()

     unsigned long getLastStateChangeTime () const { return switchStateChangeTime_; }
     unsigned long getLastStateLowTime ()    const { return lastLowTime_; }
     unsigned long getLastStateHighTime ()   const { return lastHighTime_; }

  };  // class SwitchManager

More details here.
Put that into a folder called SwitchManager, put that into your sketch folder -> libraries folder and restart the IDE.
That basically handles:

debouncing
detecting state changes (eg. now on, was off)

Using that we can now write a sketch that does the indicators:
#include <SwitchManager.h>

typedef enum {
    NONE,
    LH_DOWN,
    RH_DOWN,
    LH_LIGHT_ON,
    RH_LIGHT_ON,
    BOTH
};

const unsigned long BLINK_INTERVAL = 500; // ms

// pin assignments
const byte LH_SWITCH_PIN = 2;
const byte RH_SWITCH_PIN = 3;
const byte LH_LIGHT = A4;
const byte RH_LIGHT = A5;

SwitchManager LHswitch;
SwitchManager RHswitch;

byte state = NONE;

void handleLHPress (const byte newState, const unsigned long interval, const byte whichPin)
  {
  // switch down?
  if (newState == LOW)
     {
     switch (state)
       {
       // if other switch down, switch to warning mode
       case RH_DOWN:
         state = BOTH;
         break;

       // if already on or warning signal, turn all off
       case LH_LIGHT_ON:
       case BOTH:
         state = NONE;
         break;

       // otherwise switch is now down, but not yet released
       default:
         state = LH_DOWN;
         break;
       }  // end of switch
     return;
     }  // end of LH switch down

  // switch must be up

  if (state == LH_DOWN)  // if down, switch to down-and-released mode
    state = LH_LIGHT_ON;
  }  // end of handleLHPress

void handleRHPress (const byte newState, const unsigned long interval, const byte whichPin)
  {
  // switch down?
  if (newState == LOW)
     {
     switch (state)
       {
       // if other switch down, switch to warning mode
       case LH_DOWN:
         state = BOTH;
         break;

       // if already on or warning signal, turn all off
       case RH_LIGHT_ON:
       case BOTH:
         state = NONE;
         break;

       // otherwise switch is now down, but not yet released
       default:
         state = RH_DOWN;
         break;
       }  // end of switch
     return;
     }  // end of RH switch down

  // switch must be up

  if (state == RH_DOWN)  // if down, switch to down-and-released mode
    state = RH_LIGHT_ON;
  }  // end of handleRHPress

void setup ()
  {
  LHswitch.begin (LH_SWITCH_PIN, handleLHPress);
  RHswitch.begin (RH_SWITCH_PIN, handleRHPress);
  pinMode (LH_LIGHT, OUTPUT);
  pinMode (RH_LIGHT, OUTPUT);
  }  // end of setup

unsigned long lastBlink;
bool onCycle;

void blinkLights ()
  {
  lastBlink = millis ();
  onCycle = !onCycle;

  // default to off
  digitalWrite (LH_LIGHT, LOW);
  digitalWrite (RH_LIGHT, LOW);

  // every second time, turn them all off
  if (!onCycle)
    return;

  // blink light
  switch (state)
    {
    case NONE:
      break;

    case LH_DOWN:
    case LH_LIGHT_ON:
      digitalWrite (LH_LIGHT, HIGH);
      break;

    case RH_DOWN:
    case RH_LIGHT_ON:
      digitalWrite (RH_LIGHT, HIGH);
      break;

    case BOTH:
      digitalWrite (LH_LIGHT, HIGH);
      digitalWrite (RH_LIGHT, HIGH);
      break;

    }  // end of switch on state

  }  // end of blinkLights

void loop ()
  {
  LHswitch.check ();  // check for presses
  RHswitch.check ();  // check for presses

  if (millis () - lastBlink >= BLINK_INTERVAL)
    blinkLights ();

  // other stuff
  }  // end of loop

The state machine has a number of states:

NONE  -> all lights off
LH_DOWN  -> LH switch depressed, not yet released
RH_DOWN  -> RH switch depressed, not yet released
LH_LIGHT_ON  -> LH switch depressed, and released
RH_LIGHT_ON  -> RH switch depressed, and released
BOTH  -> Warning lights mode (flash both lights)

If we get a LH down while the RH is still pressed, or vice-versa, we switch to warning mode.
On a button release we switch from "switch down" to "switch released".
A second press, while either or both lights are on cancels them.
Note that my switches were wired to ground with the internal pull-up, so they are LOW when pressed and HIGH when not pressed.

Amazing! Well this is a lot of stuff to digest, and as you said it's a bit hard to fully understand, but surely I'm gonna test it tonight and bring some feedback. Thank you very much for now!!


text:
Run Arduino on USB and at the same time BreadBoard on higher voltage?
I am trying to design a bicycle LED lighting system, and for that I bought an Arduino yesterday (so very beginner with Arduino).
My final system will operate at 6V, so I plan to put everything on a breadbord and tune everything (blinking times, resistor values, etc.) and for that I want to keep my Arduino plugged to USB during development.
So my question is:
How should I connect USB-powered Arduino to a higher-voltage-powered breadbord (between 6 and 12V) safely?

I think as far as i understood the problem, the system or whatever you call is will run on what ever power as long that power is not fed to the arduino that will not be a problem, just connect the two grounds together and power the arduino through the computer and connect the pins to the system accordingly. i think this will solve thus the trivial problem.

You're right. After I figured it out (some days ago already), I got a little surprised no one pointed it out sooner. Thanks for your answer!

Datasheet can be found here: http://www.atmel.com/devices/atmega328.aspx?tab=parameters
From this, the absolute rated voltage on the ATMega (aka, the chip at the heart of the Arduino) is 6V.  Above that... above that you risk magic smoke.  But you can just, maybe get away with running your whole system on 6V.
Important point - do not rely on using 4 AA batteries for this.  Regulate your 6Vish to exactly 6V.  Just remember that this is at the extreme limit of the spec.  If you try this, before you start repeat to yourself "I have just voided my warranty.  It is now my fault when it dies."
Alternatively, why are you so wedded to 6V?  What are you trying to achieve?

Thanks for your answer! I am "wedded" to 6V because a lot (all?) of bike accessories are expected to run at 6V, and this include lights which would be an important part of my system. Since these lights nowadays use LEDs instead of bulb lamps, they are quite sensitive to voltage drops (some won't even turn on at 5V), so I'll stick to what's common practice for the sake of modularity and "swappability" between sub-systems. By the way, I ended up using an LM2940 low-dropout regulator, which successfully regulates 6V to 5V, or so it seems (I have just tested it quickly once)

Unless you intend to run both supplies simultaneously, there's no problem. Your ~ 6v input will need to be stepped down and regulated to 5v, and the USB provides a regulated 5v, so the system shouldn't care which one you are using.
If you need to run your system off the 6v during development and need USB communication, I'd suggest using a USB-to-TTL-Serial cable such as this one: https://www.sparkfun.com/products/9718. Connect its Tx & Rx pins to your Arduino's (Uno?) pins 1 and 0, respectively, and it's ground pin to the ground rail served by your battery supply.
Typical regulators will need more headroom above their output voltage to give you a steady, regulated output, and this includes the 5v regulators on Arduino boards which usually specify 7-12v at the Vin (unregulated) input. A 6v battery won't meet this spec so you'd need a buck/boost regulator that could provide a regulated 5v from "0+" to 6v input. Or you might move your system to a bare AtMega328p with a lower clock speed (see the data sheet for max clock speed vs. Vcc), and run it at 3v (for example) which would give a simpler regulator more headroom from its 6v input.

I think you will find that: USB powerable Arduinos, by definition, operate from 5V. This is usually accomplished by using a 3V3 system and an LDO regulator with sub 1 V drop - or direct operation of a nominal 5V system on the USB voltages with a switched FET and perhaps slightly under 5V processor operation.

I tink I might haven't made myself clear. What I would like is to power only the breadboard with, say 6V from a battery, or from wall wart, and connect only output pins from Arduino to the breadboard. This, in the example I gave with transistors, the transistors' collectors and their load would be polarized by the wall wart, the transistor bases would be connected to Arduino outputs, and everything would be grounded together (PC, Arduino and BreadBoard). Would this be possible?

Yes, that sounds right. In fact, the PC needs no connection to the rest of your system beyond what the USB itself provides.

source: Stack Exchange

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

sort: votes


text:
Why doesn't this motor turn?
When I upload the code, the DC motor makes a humming noise, but doesn't turn.
//2-Way motor control

int motorPin1 =  5;    // One motor wire connected to digital pin 5
int motorPin2 =  6;    // One motor wire connected to digital pin 6

// The setup() method runs once, when the sketch starts

void setup()   {
  // initialize the digital pins as an output:
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
}

// the loop() method runs over and over again,
// as long as the Arduino has power
void loop()
{
  rotateLeft(150, 500);
  rotateRight(50, 1000);
  rotateRight(150, 1000);
  rotateRight(200, 1000);
  rotateLeft(255, 500);
  rotateRight(10, 1500);
}

void rotateLeft(int speedOfRotate, int length){
  analogWrite(motorPin1, speedOfRotate); //rotates motor
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
  delay(length); //waits
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
}

void rotateRight(int speedOfRotate, int length){
  analogWrite(motorPin2, speedOfRotate); //rotates motor
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
  delay(length); //waits
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
}

void rotateLeftFull(int length){
  digitalWrite(motorPin1, HIGH); //rotates motor
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
  delay(length); //waits
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
}

void rotateRightFull(int length){
  digitalWrite(motorPin2, HIGH); //rotates motor
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
  delay(length); //waits
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
}

Why doesn't this work?
Update:
I plugged it into a different port (5v) as it is a 5v motor, but now it only turns left, not right. It just hums when it goes right.

If you want to close this, close it is a duplicate of something.  It is anything but "unclear" - in fact, the question is rather admirably complete in presentation compared to the relatively beginner technical mistake being made.  And while no specifications have been provided for the motor, the fact of the matter is that there are very few which would work directly connected like this, so that's almost irrelevant to understanding the problem.

This question does not belong on the Arduino site.  It should be sent back to EE stack exchange (where it was quite properly asked in the first place), as the issue of motor drive electronics would be exactly the same with any small microcontroller, Arduino or otherwise.  Politically motivated question dumping needs to stop.

NEVER directly connect a DC motor to an Arduino Pin! I am surprised you did not burn your Arduino yet...

@jfpoilpret why not?

For the reason, just check the first 2 answers to your question!

@ChrisStratton yes, this does seem like EE could keep it. However, just because it could be on topic there doesn't make it off topic here. Bash scripts are all OK on Super User, Stack Overflow, Ask Ubuntu, and Unix and Linux.

When a poster asks something on a site where it is entirely appropriate, the mere fact that it could be allowed else where if originally asked there is no justification for moving it - this question has been dumped purely based on the bias of many EE users against beginner questions.  Being a dumping ground for EESE bias is not the purpose of the Arduino site - it is an abuse you need to firmly stop.

Although the question may provide the beginning of an answer on EE.SE, an answer here may be better fitted, e.g. using the right components, according to Arduino max pin current, which is specific. Personally I don't see much issue with moving this question here.

The problem with moving the question here is that it becomes divorced from primary technical expertise and so receives poorer answers.  Similarly, any good answers it might receive fail to contribute to the pool of knowledge on the site intended to handle questions of this type (there's nothing relevantly unique about an ATmega used as an arduino)  But mostly, the problem is that it was moved out of political bias.

The IO drivers of most common logic chips or microprocessors such as the ATmega on your Arduino are nowhere near strong enough to drive typical electromagnetic motors.
To drive a motor, you should use a higher current switching device - a standard solution for bidirectional control being an H bridge part such as a TB6612FNG, L293D, L298, etc.
These are commonly sold on "motor shields" which you can plug into your Arduino, if you want to experiment with the concept before building something (and if you do want to build something, reviewing such a working schematic first would be a good idea).
You can in theory put an L293D or its DIP-packaged work-alikes on your breadboard, but you will need some care to get it right, especially if you use one of the other parts which requires external catch diodes.
Finally, you should not be powering most motors from the Arduino's onboard regulator or a USB port, but rather should use an external power supply.
=============
Responding to your edit, by  changing connections to place the the motor between one pin and the 5v supply, you have done two things:
1) You have made it so that the voltage difference across the motor can be applied in one direction only, therefore it can only rotate in one direction.
2) You have made it so that only the N-channel MOSFET in an output driver is involved in powering the motor.  That change is almost a useful idea, as N-channel devices are in fact much more capable than P-channel devices of similar dimension (and practical capacitance, voltage rating, and other tradeoffs) due to the greater mobility of negative charger carriers.
But this is still not really a solution, as it is unlikely that your motor's current rating is within even the current sink rating of the N-channel side of the ATmega output.
If you want a simple, unidirectional motor control, you could pursue this idea using one external N-channel MOSFET (or even a biploar NPN power transistor, which will be less efficient but also less delicate) to connect the unpowered side of the motor to ground.
If you want bidirectional control, you will need either + and - power supplies, or four external switching devices taking the roles of the low current N-FET and P-FET totem poles inside each of the two on-chip IO pin drivers you started with.

This is a huge simplification of @Chris Stratton's post, for beginners.
To put it simply, the power that runs your motor is going through your arduino. Your arduino is not made to carry that sort of power.
What you want is an H-Bridge - see https://itp.nyu.edu/physcomp/labs/motors-and-transistors/dc-motor-control-using-an-h-bridge/ - the H Bridge is specially made to carry the power needed.
Note that this page is for a 9v motor, not a 5v motor like yours - you will need to find a more appropriate power supply than a 9v battery (or, you need to find a 9v motor). If you try to power it through USB, you will be drawing the power through your computer - you may damage it!

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


text:
How to capture good sound with Arduino?
Is it possible to capture good sound with Aduino? I need to record street / birds / nature sounds.
As I found, maximal sample rate, achievable with built-in ADC is 9kHz, which is to low.
So, I require to use some external hardware. But wave shields I saw are to expensive (comparable by price with Arduino itself), probably, because of excess functions (including not only ADC but also DAC and so on).
Simultaneously, there are ICs, providing ADC functionality and even MP3 encoding functionality for relatively low price. But here a schematic design required.
So, how to find appropriate solution here?

I would use something with considerably more grunt than a baby Arduino - something with an I2S interface built in. Maybe a Due, but the best one that I use regularly would be a PIC32MZ based system, like the chipKIT WiFire.

Yes but you want something much faster then the Arduino, normally it is in the 96k~48k bps range.  Try this link, they make a lot of great parts and the bulk of what you have to do is control software.  You can let the chip do the grunt work (analog) and transfer thee data to where ever you want.  Some of the chips will record for 300 seconds plus.
http://www.aplusinc.com.tw/exec/product.php?lg=E&mod=show&cid=43&pid=aPR33A3
I have used there parts they work great.
Have fun,
Gil

Is it possible to capture good sound with Aduino? I need to record street / birds / nature sounds.

The answer is "no" for AVR based Arduino boards. They have simply too low sampling rate, ADC resolution, limited buffering memory and processing speed.
The ADC sample rate is at most 9 K samples per second (112 us per sample) at highest resolution (10 bits). The resolution can be improved (e.g. 12 bits) by using oversampling but this is at the cost of sampling frequency.
The Arduino Uno has only 2K byte memory. Using all that for buffering would give at most 1 K samples. That is little over a second sound data. A SD file could be used but requires a lot of smart programming to not drop samples at max sampling rate.
Low quality, 8-bit samples, then "yes". See here.
Now an Arduino Due is much more powerful, has much more memory, etc. See here.

Is it possible to capture sound with Due?

Added some results from google. See new links above.

This about playing audio, but how about recording? How fast is DAC in Due?


text:
How to wait Arduino ready with ANY method?
Recently I knew, that Arduino restarts any time somebody accesses it's serial port. I was trying to use this feature so that for each request Arduino restarts and give answer on request. Unfortunately, I found this is impossible with shell script, because shell script can't keep port open all time I send requests and wait responses: Arduino restarts on each port touch.
So, I wrote simple C++ program:
#include <iostream>
#include <fstream>

using namespace std;

void help() {
    cout << "bmp180dims usage:" << endl <<
            "bmp180dims port command" << endl;
}

int main(int argc, char* argv[]) {

    if( argc != 3 ) {
        help();
        return 0;
    }

    fstream port;
    string answer;

    port.open(argv[1], std::fstream::in | std::fstream::out);

    port << argv[2] << endl;

    port >> answer;

    cout << answer << endl;

    port.close();

    return 0;

}

Since this program has explicit open and close statements, I was thinking, this program will wait for Arduino answer, because of stream reading functions. But I failed again: this program returns nothing as if it is not waiting.
Why?
Apparently, the only way to communicate with Arduino, is to have daemon program, which always listen it's port. Is this really so?
Arduino-side code is here: How can program/arduino restarted by IDE?

Again, you're not waiting for the bootloader to complete before sending your text:
port.open(argv[1], std::fstream::in | std::fstream::out);
// Board resets and enters bootloader

port << argv[2] << endl;
// You send argv[2] to the bootloader

port >> answer;
// The bootloader doesn't understand what you sent so doesn't reply with anything

You must wait for the bootloader to complete before sending ANYTHING to the Arduino.
The two ways you can do that are:

Insert a sleep(3); immediately after opening the port to give the bootloader a chance to time out and start running your sketch, or
Provide an initial "I Am Ready" message from your sketch that your C++ program waits for before sending the text you want to send to elicit an answer.

I understand that I am not waiting for send, but I am waiting for receive. Why port >> answer not waiting if bootloader sends nothing? Shouldn't port >> answer wait for space or newline?

It can only wait for something if you are sending something. You aren't sending anything because you aren't receiving anything, because what you send isn't getting through to your sketch.

How this is implemented? How >> can know that I didn't send anything? How it can distinguish silence from delay between request and response and initial silence? Suppose I implement your suggestion on "I Am Ready" how can I wait for "I Am Ready" if >> will just drop waiting when it wants?

P.S. Note that my questions are for understand what is happening

If the port is opened in non-blocking mode then it will never wait for anything, ever.  I don't use fstream so don't know how it opens the port - if it's non blocking then you cannot use >> to read from it.  You should be using low level IO for talking to a serial port, not file IO.  Use open(), read() and write(), with a good smattering of select() to see if there is actually anything to read from the port.


text:
How to scroll data in LED dot matrix through multiple modules?
I've been struggling in this issue for a long time, I know there are people who have done it.
But, I don't have much experience in C to have the skills to design or develop such complicated functions.
I want to scroll data, e.g. text, chars or numbers just like the nice projects in YouTube about the dot matrix.
Like this one: How to Make a SCROLLING TEXT Display at Home

I know how to display a char, but I don't know how to scroll it. If I try I don't get the results I want.
This is my function for displaying chars:
void draw(void)
{
  s=0;
  uint8_t data_shift_buf;
  for (l=0;l<26;l++)            // to print 26 letters
  {
    for (row=1;row<9;row++)     // for 8 matrix rows
    {

        SPI_TX_m16(data = (row<<8) | (Alphabet[s]),4);// trying set data by column
        s++;_delay_ms(300);
    }
  }
}

what does this mean ? LED dot matrix throw multiple modules ... what are you throwing?

It's obviously "through". Feel free to improve the question, as I just did.

What module do you have exactly? Maybe this will help: http://www.gammon.com.au/forum/?id=11516

@NickGammon Thanks for the edit :) Like, this one: http://www.belajarduino.com/2016/08/4in1-dot-matrix-led-module-32x8-pixel.html

Yep, the MAX7219 - you can scroll with that. See the link above. I don't know how to make an answer without copy/pasting the whole link. :)

@NickGammon Thank you so much, I've looked into the link and found a lot of development with the MAX7219, and found an interesting comment at the end of the posts: "There is also a demo of scrolling text, however that scrolls a chip at a time, not a pixel at a time.
", which is what I'm looking for! I'm looking for scrolling by pixel.

The very next paragraph under that says: Library updated on 2nd October 2015 to have smooth scrolling. A new example has been added which demonstrates this. To achieve this each for each display module (8 x 8 pixels) the code calculates the pixels for the byte before, the current byte, and the byte after. Then it applies the pixel offset to choose a starting point somewhere in those 24 (horizontally) pixels.

WOW that should be amazing, really I'm trying to solve this problem for days. Yes, he calculation for the first and the second display, OK thank you so much for the support.

Take a look at the Parola.h library also.  https://github.com/MajicDesigns/MD_Parola  It can scroll up, down, left, right, and for large #s of displays.

Thank you for response, that library is very difficult for me, so I tried and tried until I did it on my own, I can only scroll to right. But the function is long compared to functions in Parola library it's written in C++, it's really interesting to do such things in small functions.

This is the function for my problem.
void draw(void)
{
uint32_t map_buffer=0;int8_t i,k;
uint8_t data_reg[4] = {0xaa,0xbb,0xff,0xff};      // random data to write
uint8_t dis_buf[4],no_device,no_col;s=0;l=3;

for (i=0;i<4;i++)
map_buffer |= data_reg[i] << i*8;                 // loading data into map_buffer

for (col=0;col<32;col++)                          // for 8 matrix columns
{
    map_buffer >>= 1;                            // start shifting the data by 1 pixel
    for (i=0;i<4;i++)
    dis_buf[i] = map_buffer >> i*8;              // loading shifted data into display buffers
    for (i=0;i<4;i++)
    {
        for (row=1;row<9;row++)                 // for 8 matrix rows
        {
            SPI_TX_m(data = (row<<8) | (dis_buf[i]),i);
        }
    }_delay_ms(1000);
}

}


text:
Time.h rollover after 49.7 days
I'm developing a arduino based system, which includes a alarm system.
Searching on the Internet, I found these lybraries "Time.h" and "TimeAlarms.h".
In the requirements, it says: "Time does not require any special hardware. Internally, Time depends upon Arduino's millis() function to keep track to elasped time."
Considering Arduino's millis() rollover after 49.7 days, how can I ensure these lybraries are handling the rollover well?
I don't think that waiting 49.7 days to test it is the better way.

See this answer to a related question. Specifically, the section titled How do I test my sketch against the millis rollover.

Have you considered using a RTC?

As this is a duplicate of the question and answer Edgar Bonet linked to I'm going to close this question.

As long as the date is before 2038, and your code calls one of the time functions at least once every 49 days, rollover won't affect you.
Internally the library uses Unix epoch time. Every time you call a function it checks to see if 1 or more seconds have past since the last time it was called and then updates the epoch time accordingly. Only for this check it uses millis(). And in only checks the difference between the last call's millis-value and the current millis-value, and rollover has no effect on time differences (as long as they are less that 49 days).

I have a lengthy post about this.
To avoid going to the link if you don't want to, the simple answer is to subtract when calculating time intervals, eg.
unsigned long startTime = millis ();
unsigned long interval = 60000;

...

if (millis () - startTime >= interval)
  {
  // do something
  }

This always works! - even after 49.7 days - because of the way that unsigned arithmetic works.
The only time it would fail is if you needed to time an interval of over 49.7 days - in which case a real-time clock is an obvious answer.
Another example:
startedFeedingFish = millis ();

...

if (millis () - startedFeedingFish >= 20000)  // feed them for 20 seconds
  {
  // stop feeding the fish
  }


text:
Barebones AVR - Connecting RESET pin to Vcc
I want to build my first barebones AVR circuit.
I plan on NOT having a RESET button. For this reason, is it valid if I connect the ATMEGA's RESET pin to Vcc directly?
What I mean by this, is that in this scenario, I will not be using a pull-down resistor as well. Just straight to Vcc.
EDIT: This is a part of the schematic:

what does the datasheet say about allowable voltages on the reset pin?

what you are proposing makes no sense ... what advantage do you gain by removing the external reset function? ... you are not using the pin for some other function ... you could bridge two solder pads with a screwdriver if you don't want a physical switch

What Atmega are you using exactly? If you really don't want to connect anything for resetting and also not using it otherwisen you can probably leave this pin unconnected, if there is an internal pullup on it. You can check in the controllers datasheet. This is true for the Attiny controllersn so probably also for the Atmegas

How do you intend to program the ATmega328P if the reset pin is tied to Vcc ?

I updated the question with a pic. I am using ATMega328. I intend to program the chip using Sparkfun's AVR Programmer.

If you are intend to build your own MCU board, you would need to read datasheet. This kind of question can be answered by reading the datasheet, see page 40 of the Reset Logic diagram.

Also read the section on "Serial Downloading", even you don't want to use RESET, there is a dude called Avrdude who help you to upload your code would issue an RESET, if you tied your RESET to VCC, by then it will short it to GND...

If you tie the RESET pin of your ICSP connector directly to Vcc like shown in your schematic, programming via this connector will not work and you might also damage the programmer by shorting one of its outputs to Vcc. Just use a pullup resistor.

Why are you running /RESET to J2? This could conflict with what might be sent by that connector. In fact, what is the purpose of J2 at all? It looks a bit like you intend to program the chip with it. If you can't pull /RESET low you won't be programming the chip (via ICSP anyway).

According to the datasheet linked to by hcheung in their comment, datasheet, on page 41 it states "Figure 10-2. MCU Start-up, RESET Tied to VCC".
I believe it would be OK to tie the pin directly to Vcc.
I also believe the graphical data presented in "Figure 10-2" could be miss-leading if the reader didn't know what Vcc meant, and also because there is no horizontal axis to specify that they are talking about elapsed time, not voltage change.
EDIT
Regarding your comment "Thanks, but now I am not sure if this setup will work with Sparkfun's Pocket AVR Programmer.".
Looking at page 40 of the datasheet, a internal pull-up resistor is built into the MCU.

You could leave the reset pin not connected and see if it still works as expected. Perhaps a high impedance DVOM would show Vcc on that pin. Some people say leave it disconnected if there are no issues from EMI. EEV Blog - Is it ok to leave atmega328p reset pin floating?
The data sheet also mentions the power on reset timeout which may allow you to program the MCU with your programmer once it first starts, (assuming you have tied the reset pin to Vcc and you leave the reset pin disconnected on your programmer).
Another option would be to program the MCU, then connect the reset pin to Vcc through a couple of solder pads you can bridge with a blob of solder.
Once the reset pin is tied to Vcc, using a programmer connected to that pin will likely result in the magic smoke being released from the MCU, your programmer, or both.

FWIW, I have an ATtiny at home with RST tied to Vcc. It has been running flawlessly 24×7 for the past six years.

Thanks, but now I am not sure if this setup will work with Sparkfun's Pocket AVR Programmer.

I updated the question with a pic. I am using ATMega328. I intend to program the chip using Sparkfun's AVR Programmer.

Then don't tie /RESET to VCC. The programming won't work. What are you doing? Trying to save one resistor? If you have J2 as a programming interface, then /RESET needs to be able to be pulled low to start the programming sequence. Either remove J2 altogether and program the chip in advance of going on the board, or use the pull-up resistor. Don't tie it to VCC.

Is it OK if I use a pull-down resistor and omit the button? Or should I include the button in the design, but never solder it?

@user1584421 What pull-down resistor? The ATmega328P reset pin already has a weak pullup resistor. However, it is usual to supplement this with a 10k pullup to Vcc. It is very unusual to tie the reset pin to Vcc because you cannot then program it, as already mentioned several times. You can simply omit the reset button if you don't need to do manual resets.

@user1584421 If you use a pull-down resistor, and it is stronger than the internal pull-up then the processor will be constantly held in Reset, which hardly seems useful.

Or should I include the button in the design, but never solder it? - an imaginary button? Include a pull-up resistor (not a pull-down) to VCC and perhaps have a couple of adjacent pads connected to Reset and Ground, so you can short them with a screwdriver if you need to reset the processor.

Also, since the design appears to have a (6 pin) ICSP header which includes the  ground pin and the (adjacent)  reset pin,  a manual reset can be forced, if required, by momentarily shorting those two pins together.

Unless they tie /RESET to VCC, then it just blows a fuse somewhere.

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


text:
What is the best way to establish wireless communication between the Lilypad and a Mac?
I want to build a wearable device for a dancer using the Lilypad and I need to first send the programme from my Mac to the Lilypad board and then transfer the data read by sensors back to my Mac.
I want to know what is the best wireless solution to use here. I've seen various options such:

the Xbee or Bluetooth modules (http://www.hobbytronics.co.uk/bluetooth-mate-silver)

Have you considered using one of those 315MHz or 433MHz modules with a UART?

What is "best?" Can you please add your requirements (price, range, speed, size, etc.)...

@AnnonomusPenguin The size is important to me because it is a wearable device. But what I want to know is which the most reliable one.

I have been using a hc-06 module very successfully. http://www.dx.com/p/hc-06-wireless-bluetooth-serial-pass-through-module-for-arduino-works-with-official-arduino-board-238364#.VLg153WjlIc
Connect pins to +5v, Gnd, and digital pins 0 and 1 (rx & tx).
Do not try to connect to USB and this at the same time, as communication will get garbled.


text:
Decode PNG on an ESP8266
I'd like to decode a PNG on an ESP8266 and access to some pixels of the result. Has anyone got experience with PNG on Arduino? Is it feasible at all? I've done some research on PNG decoding libraries, found UPNG. Will check if it can be used in Arduino/ESP.

Is it feasable depends on the the size of your picture, where it stored, and how you want to store the decompressed data. On an ESP8266 you have ~40kB of free RAM and a decoded picture with RGBA8888 format (2 bytes per pixel) and 128x128 px will take 32kB to store the decompressed image. Notice that the libray always decodes whole pictures, not blockwise -- you must be able to fit the complete decoded image into RAM.

Thanks. Image comes from network stream, base64 encoded (urlData), with a maximum of 128x128 pixels size. I feel this is on the limits.

If you also have the base64 string of the compressed PNG in RAM (how much % of the original image size is that?), plus network / TCP buffers, this will be quite the tough call. You might have to change your logic to transfer smaller images (either resolution or pixel depth), or directly decoded images so you don't have to decode them. You might want to look into an ESP32 (512K RAM) or the ESP-WROVER (ESP32 + 4 MegaByte PSRAM)

With those small images and decompression overhead for png, I got the feeling you might be better of sending uncompressed bitmap images instead. Also try avoiding base64, as that makes things 30% larger, or decode the base64 on the fly.

UPNG is simple to port to a microcontroller. I just did it in an afternoon to run on a 200MHz PIC32MZ with 512kB RAM. It wouldn't run on an 80MHz PIC32MX with 32kB RAM. That's with a 100x100 pixel RGBA8 image. I need to test it with intermediate chips to see what the minimum memory for that image size is.  Also that's with the image source held in flash.

Update: a 128kB PIC32 works, but not a 64kB - so I'd say you need a couple of hundred kB to work with small images. 128kB is OK for things like small icons held in flash.

@Majenko I'm now dealing with an ESP32 which I guess is able to decode small PNGs. Would you be so kind and share the version of UPNG you ported? Thanks!

It's ported to DisplayCore which is for the chipKIT environment. You are welcome to use my code as an example of how to call the UPNG code though.  https://github.com/DisplayCore/PNG

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


text:
Low-Pulse Occupancy and Voltage Divider
I have a PPD42NS dust sensor I'd like to hook up to an ESP8266-01 microcontroller. The ESP8266 uses 3.3v logic, but the PPD42NS uses 5v. The PPD42NS uses low pulse occupancy as output.
I'd like to use parts I have on hand, and I was wondering if a simple voltage divider built from 2 resistors can reliably shift the voltage without distorting the signal.
If not, could an NPN transistor do the job instead?

That should work. You just don't get very crisp edges on the signal. But I don't think that a problem with the PPD42NS as it probably uses relatively slow speeds.

While the PPD42NS has a 5-pin connector, it is shown at seeedstudio.com and howmuchsnow.com connected up with three wires: +5V, Ground, and an LPO or “Low Occupancy Output” signal, which goes low when a particle occludes an LED beam path.  LPO is used as an input to let sketches measure the fraction of time the beam's  occluded, which correlates with number of dust particles.
Yes, a resistive voltage divider will let you use the 0-to-5V occupancy signal as an input to your 3.3V-tolerant ESP8266.
What values of resistors should be used?  Because input pin capacitance is small (eg under 10 pF), signal "crispness" should be about the same over a broad range of resistances – say from a 100Ω+200Ω divider up past 1KΩ+2KΩ;  even 10KΩ+20KΩ might be ok.
The Grove_-_Dust_sensor.pdf data sheet at seeedstudio.com says:

Output Method  Negative Logic, Digital output,
  Hi : over 4.0V(Rev.2) Lo : under 0.7V
  (As Input impedance : 200kΩ) OP-Amp output, Pull-up resistor : 10kΩ

This suggests (but doesn't clearly indicate) that some sort of open-drain output might be used.  If so, instead of using a voltage divider one could remove the 10kΩ pull-up on the sensor, and pull the output to 3.3 V instead of 5 V, via either an external resistor or using an INPUT_PULLUP pinmode setting (if available on the ESP8266).
Edit: Regarding the comment, “I'm considering use it in conjunction with an MCP23017 I/O expander IC. The GPIO pins on the chip appear to be rated at a max capacitance of 50 pF. Will that affect the range of resistors available? How does resistor choice affect the crispness of the signal, and how can I determine it for myself?”:
The “max capacitance of 50 pF” spec, which is parameter D101 in table 2.1 of the MCP23017 spec sheet, refers to “Capacitive Loading Specs on Output Pins”, ie, how much capacitance MCP23017 outputs can drive.  It doesn't refer to input pin capacitance, so isn't relevant here.
In general, when a signal edge (a rise or fall) arrives at an input pin, the input pin's voltage doesn't change instantaneously.  The input pin's capacitance needs to charge or discharge.  (It charges for a rising edge, discharges for a falling edge.)  The speed of change depends on the RC time constant of the circuit.  A delay occurs, probably 1–3 time constants long, before the pin starts to switch.  (The switch may take a few tens or hundreds of nanoseconds.)
For example, if input circuit capacitance is 10 pF and its effective resistance is 100kΩ, RC = 10 pF · 100kΩ = 10⁻¹¹·10⁵ = 10⁻⁶ seconds = 1 microsecond.  Whether that's large enough to matter for your measurements depends on how many time constants have to occur before the pin starts switching, and on how narrow the LPO signals are.
In short, compute RC, and if it's more than a few microseconds, use a smaller value of R.  Alternately, if you have access to an oscilloscope, attach it to the input and try various resistance values in the voltage divider, to get a feel for how the signals degrade as the resistors in the divider get bigger.
Note, using a voltage divider causes different RC values for falling edges than for rising edges.  For example, suppose an actively driven 0-5V signal enters a divider with 10KΩ in series with 20KΩ, and the 0-3.3 V signal is taken from the resistors' junction.  Then R is 10KΩ for a rising edge, and 20KΩ for a falling edge.  If the 0-5V signal weren't actively driven high, but instead pulled up via a pullup resistor R' when a transistor turns off, then the rising edge R value would be R'+10KΩ for this example.

I'm considering use it in conjunction with an MCP23017 I/O expander IC. The GPIO pins on the chip appear to be rated at a max capacitance of 50 pF. Will that affect the range of resistors available? How does resistor choice affect the crispness of the signal, and how can I determine it for myself?

@user1569339, see edit


text:
Voice recognition module: avrdude: stk500_getsync(): not in sync: resp=0x00
I am using a GeeeTech voice recognition module, I have recorded my voices using CoolTerm, and imported these voice commands in my sketch. However, when I plug in that voice recognition module, an error gets thrown: avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00; otherwise, it uploads normally. How can the computer and the Arduino lose connection when the voice recognition module gets plugged in? . I have checked my com ports, and checked the everything that it is connected to is correct.
#include <avr/sleep.h>
#include <avr/power.h>
//#include "math.h"
//This sketch is a metronome, in which each led pin shows one beat.
/**************************************/
const int speaker = 13;//speaker at pin 13
int ts = 6;//highest led pin
int count = 3;//"beat 1 pin"
const int keyPin = 11;//button to change time signature
const int keyPinR = 10;//button to change rhythm
const int keySwitch = 2;//sleep mode/wake up button

//All pins below use a pull-up resistor, so the states are inverted
int buttonState = LOW;
int buttonState2 = LOW;
int switchState = LOW;
int silentState = LOW;

int bpm = 120;//you do not need to know this,
//it's just a variable for the potentialmeter to change the tempo
int comdata;

int rthm = 1;//rhythm
int pressed = 0;//
long silent = 0;

byte com = 0; //reply from voice module
/**************************************/

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

 for(int thisPin = 3;thisPin <= ts;thisPin++)
  {
     pinMode(thisPin,OUTPUT); //initialize thisPin as an output
     pinMode(12, INPUT); //potentialmeter for changing tempo

   //Pin 9 to 11, along with pin 2, are all push buttons with pull-up resistors
    for(int i = 9; i<=11; i++)
    {
      pinMode(i, INPUT);
      digitalWrite(i, HIGH);
    }
    pinMode(2, INPUT);
    digitalWrite(2,HIGH);
  }
delay(2000);

//imported voice commands
Serial.write(0xAA);
Serial.write(0x37);
delay(1000);
Serial.write(0xAA);
Serial.write(0x21);

 Serial.print("Type in beats per minute");

}

/****************************************/
void loop()
{
  turnOn();
  getTS();
  getVoiceCommand();
}

void turnOn()
{
    buttonState = digitalRead(keyPin);//key for
    buttonState2 = digitalRead(keyPinR);
    switchState = digitalRead(keySwitch);
    silentState = digitalRead(9);

    if(switchState==LOW) pressed++;

    if(pressed!=0)
    {
      sleep_enable();
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      attachInterrupt(0, interrupt, LOW);
      sleep_cpu();
    }

  else{
    //The beat starts at pin 3, runs in consecutive pins, and ends at pin 8 at maximum

     if(buttonState==LOW){//changing time signature - up to 5 beats
            ts++;
          if(ts==8) ts = 3;  //8 - 3 = 5 beats max
     }
     if(buttonState2==LOW){//changing rhythm - quarter note to eighth, then
             //triplets and sixteenths, back to quarter notes
           rthm++;
          if(rthm==5) rthm = 1;
     }
     if(silentState==LOW) silent++; //if silent key pressed, go to silence (only LED's showing)

      runMetronome();//Run the metronome
     }
  }

  void runMetronome(){
    for(int thisPin = 3;thisPin <= ts;thisPin++)
      //LED's blinking beats (thisPin - LED pin (beat number + 2))
      {
           for(int r = 1; r<=rthm; r++){//nested loop for the rhythm
               bpm = pulseIn(12, HIGH);//pin 12 - tempo potentialmeter
               digitalWrite(thisPin,HIGH);//each LED blinks
               pinMode(13,OUTPUT); //pin 13 - speaker

              silent%2==0 ? noTone(13) : (count==3 && r==1 ? tone(13,4400,80) :
                   r==1 ? tone(13,2500,80) : tone(13,2200,60));
              delay((bpm-52)/rthm);
              digitalWrite(thisPin,LOW);//turn each off as we proceed to the next beat (LED)
              pinMode(13,INPUT);//speaker input
            }
          count++;//beat++

          if(count>ts) count = 3; //go back to beat 1
        }
    }

  void interrupt()  {
      sleep_disable();
      detachInterrupt(0);
  }

   void getTS(){
      if(Serial.available()>0){
          comdata = Serial.read();
          switch (comdata){
              case '1': ts = 3; break;
              case '2': ts = 4; break;
              case '3': ts = 5; break;
              case '4': ts = 6; break;
              case '5': ts = 7; break;
            }
     }
   }
     void getVoiceCommand(){
        while(Serial.available()){
            com = Serial.read();
            switch(com){
                case 0x11: ts = 3; break;
                case 0x12: ts = 4; break;
                case 0x13: ts = 5; break;
                case 0x14: ts = 6; break;
                case 0x15: ts = 7; break;
              }
          }
      }

It's not loosing connection, there just can't be two devices on the same serial port (I suppose this setup)
You can use software serial for VR module, arduino with more hardware serials (=mega) or you can use another arduino as ISP programmer.

There is a arduino SoftwareSerial library to use another serial on almost any two pins.

Pins 0 and 1 are usually used for hardware serial port (and bootloader too). Try some other pins..

Actually, I got it working as I tested it out, by using English commands: '2', '3', '4', '5', and '6'. But, sometimes, when I say: '8', '1', the wrong messages get printed out in the serial monitor.


text:
How to make Arduino react to serial information?
I want to write a program that allows me to control the LED connected to pin 13 of the Arduino. When the program is started, the LED should be off. The user should open the serial monitor to communicate with the Arduino. If the user sends the character '1' through the serial monitor then the LED should turn on. If the user sends the character '0' through the serial monitor then the LED should turn off.
So I tried:
void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  int bytenum = Serial.available();
  if (bytenum != 0)
  {
    int bval = Serial.read();
    if (bval != 0)
    {
        digitalWrite(13, HIGH);
    }
  }
  digitalWrite(13, LOW);
}

But when launching it the LED never light up:

Serial Monitor sends a character '0' with ASCII code 48. so 48 is not equal to 0. for other shortcomings read Michel's answer

Do you use real hardware or just a simulator like shown above? If you use real hardware, most Arduino UNOs have a build in LED at pin 13; no external LED is needed. If you use a simulator the ext. LED might be needed. The LED must be connected the right way anode to pin 13 and cathode (the side with the ring) to GND, did you check that? Michel explained you how to code it correctly and gve you tips how to connect an external LED, if your Arduino is missing the builtin LED or you wnat to try a different pin on real hardware.

I see two issues:
1. Sketch
The line:
digitalWrite(13, LOW);

is always executed, meaning the LED (which might be broken, see below), is on for a very small time, probably not enough to be visible.
You can use the next sketch (for 0 and 1 to switch it off/on):
const uint8_t LED = 13;

void setup()
{
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop()
{
  while (available_characters != 0)
  {
    switch (Serial.read())
    {
      case '0':
        digitalWrite(LED, LOW);
        break;

      case '1':
        digitalWrite(LED, HIGH);
        break;

      default:
        // Ignore
        break;
    }
  }
}

You can make this sketch smaller in case you want '0' for off, and anything else for on:
const uint8_t LED = 13;

void setup()
{
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop()
{
  while (Serial.available() != 0)
  {
    digitalWrite(LED, Serial.read() == '0' ? LOW : HIGH);
  }
}

2. Lack of a resistor
I think your LED is now broken, and hopefully only the LED and not your Arduino.
Always use a resistor just before or after the LED when connecting a LED. As a guideline, use e.g. 220R or 330R.
Remember as formula:  V = I * R
The tricky thing is that LEDs have a forward voltage (Vf), so the actual formula is:
 (V - Vf) = I * R

Now most LEDs can handle mostly 20 mA, but 10 mA is more than enough to make them bright.
Below is a list of typical values for the forward voltage. Let's assume it's 1.8V as you are using a red one in your example.

The MINIMUM resistor value to be used is:
(5 V - 1.8 V) = 0.01 A * R <=>
3.2 V = 0.01 A * R <=>
R = 320 ohm

So use a 330 ohm resistor. (note that 220 ohm will still result in less than 20 mA).


text:
How to split a binary data to form two split binary data?
I want to split a received binary data into two binary data.
Take the following received binary data for instance:
uint32_t data = 0xFFFF0001;

In binary format it is: 11111111111111110000000000000001
If we need to split this above binary into two new binary data how could it be done?
As an example from the 0xFFFF0001, how can we obtain the first 17-bit as as data1 = 11111111111111110 and then the remaining 15-bit as data2 = 000000000000001 ?

You can use the bit shift and and operator, like:
uint32_t data = 0xFFFF0001;

The following line will shift all bits 15 places to the right, meaning the least significant 15 bits will be removed, and the other bits shifted to the right.
uint32_t dataLeft = data >> 15;

11111111111111110000000000000001
>>>>>>>>>>>>>>>11111111111111110000000000000001
| Bit shift   || orig. bits    ||Removed bits |

For the other 15 bits,  you can use the and operator, which just makes all 1's 0's for those bits not in the bit mask (0x7FFF).
uint16_t dataRight = data & 0x7FFF;

value:              11111111111111110000000000000001
bit mask (0x7FFF):  00000000000000000111111111111111
                    -------------------------------- & / AND
                    00000000000000000000000000000001


text:
Is there some kind of timer function that returns the amount of time passed?
I'm doing a project and I want to get the amount of time between two sensor inputs.  i.e. the sensor detects something, and it triggers a timer, and when the sensor picks up something else, it stops the timer and stores the amount of time the passed in a variable.  Is there a library or a specific function that exists?

Just adding a few notes to the perfectly valid answers you already got:
On your typical AVR-based Arduino, micros() has a resolution of
4 µs and millis() is updated every 1024 µs. This last point
implies that millis() increments most times by 1 ms, but
occasionally by 2 ms. Keep this in mind if time resolution is an
issue.
Both millis() and micros() return 32-bit unsigned numbers. This
implies that millis() overflows (it rolls-over to zero) roughly every
49.7 days and micros() every 71.6 min. This limits the
maximum interval length you can measure with each of those functions. It
does not limit the maximum run time of your program, since
subtracting two timestamps does work fine across a rollover
event.

It's simple enough to make a "helper" function to give you the number of milliseconds between each call of the function:
uint32_t millisSince() {
    static uint32_t lastMillis = millis();
    uint32_t now = millis();
    uint32_t diff = now - lastMillis;
    lastMillis = now;
    return diff;
}

Every time you call that it will return the amount of time that has passed since you last called it. The first time it will return 0 since it has never been called before.

Yes, you can use millis() or micros() which give the milliseconds resp microseconds since the board started up.
However by substracting two values taken close within time you can measure a time period (for example for your sensors).
With this functionality you can program the timer yourself.
See https://www.arduino.cc/en/Reference/HomePage and search for micros/millis.

Yes, read and store the value from millis() at the first event. Then read millis() again at the second event. Subtract the stored value and you'll have the time, in milliseconds, between the events. millis() returns a long unsigned int and your memory variables for storing its value need to be of the same type.


text:
WS2812B only works while I measure the voltage
I'm going crazy, there is clearly something I'm missing here.
I have a NodeMCU V3.0 and a 5V LED strip WS2812B with 10 diodes.
I tested this first with a 5V 0.3A power supply, only powering 3 diodes, this worked fine.
Than I changed the power supply to a 5V 2A (Measured to 5.2V) and now the colours are way off, they even change everytime its updating, even though nothing is changed. I put my voltmeter across "D3" and "GND" and suddently the LEDs were perfect and stable.
If I remove it again, the LEDs change to random colours again, I tried pulling "D3" to ground with a 10 kOhm resistor, but this doesn't change anything.
What is going on here, why isn't it working, and why does it work with the voltmeter?

Code:
#include <ESP8266WiFi.h>
#include <FastLED.h>

#define LED_PIN     3
#define NUM_LEDS    10

CRGB leds[NUM_LEDS];
int R = 255;
int G = 90;
int B = 10;

//Set up MQTT and WiFi clients
WiFiClient client;

void setup()
{
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  Serial.begin(9600);

  //Connect to WiFi
  Serial.print("\n\nConnecting Wifi... ");
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
  }
  Serial.println("OK!");
  pinMode(D4, OUTPUT);
  digitalWrite(D4, HIGH);
}

void loop()
{
    leds[0] = CRGB(255, 0, 0);
    leds[1] = CRGB(0, 255, 0);
    leds[2] = CRGB(0, 0, 255);
    FastLED.show();
    delay(5000);
}

Have you tried another pin?

Remove the resistor. There is also way way to use one WS2812 as a booster for the rest of the WS2812, check out http://www.elec-tron.org/wp-content/uploads/2015/10/ws2812bconverter.jpg

if the resistor in your DMM (likely 10m) pulls down the signal and makes it work, it stands to reason that you can simply add your own pull-down resistor to make it work the same.

That was my first thought as well, but adding a 10k OHM to pull down the data pin (same spot I measured) did nothing, so I’m still puzzled why measuring didn’t anything

WS2812B LEDs are 5V devices. The NodeMCU is 3V.  Your first 5V supply will probably have been somewhat under 5V once the NodeMCU had taken a big chunk of the current (see Voltage Droop). This would mean that the Logic High Threshold would be within the bounds of the 3.3V output by the NodeMCU.
However, with your new high powered power supply that voltage droop will be less prevalent (added to the fact that it's measuring 5.2V), and so the logic high threshold will be higher. At, or very close to, the 3.3V that is output by the NodeMCU. That makes it rather unstable at communicating, since the logic HIGH may not always be above that required HIGH threshold.
Adding your voltmeter obviously changes that logic signal so that it stabilizes above the required threshold (the volt meter input has capacitance. That will help hold the line higher for longer).
To drive 5V devices from a 3.3V MCU you really need to add a logic level shifter, or ensure that the power supply isn't too high.
The WS2812B has a logic HIGH of 0.7 × Vdd. At 5V that's (0.7*5=) 3.5V. That's close, but not quite there. Your original power supply was probably putting out more like 4.75V under load. That would be 3.325V for a logic high - just about manageable by a NodeMCU.
However at 5.2V the logic HIGH will be 3.675V, which is way above the 3.3V that the NodeMCU outputs.
So you either need to:

Add a 3.3V to 5V logic level shifter, or
Reduce your LED power input voltage to below 4.75V.

The latter can be done by adding a single series diode with a suitable current handling capacity to the VDD connection. That will (depending on the diode) drop around 0.7V taking you to about 4.5V (the actual drop usually depends on the current to a certain extent).  The WS2812B will happily run from 3.5V to 5.3V.

I think I understand, thank you
This diode, could it be like this: 1N4001 ? And will it create a loss of power?

I'd probably go for a 1N5402. The 1N4001 is only 1A rated. The 1N5402 is 3A rated. Yes, it will lose some power. But losing some power is what you want - you have too much at the moment ;)

@Yoshidk I think you can lower the voltage for the first chip only. Its output will be up to its power supply voltage

@Yoshidk Or, maybe adding diode between power ground and NodeMCU ground could provide the same service without cutting the LED strip.

I added a diode in series to lower the voltage to 4.6V, and now everything works, thank you


text:
Using Analog Comparator on ATmega32u4
I am (currently) parsing a PPM analog signal using an Arduino Uno R3 using the analog comparator ASCR and analog hardware interrupts using AIN0 and AIN1. I am applying a specific negative comparison voltage using a linear voltage regulator on AIN0 and the signal on AIN1.
Code snippets:
setup
  ACSR  = B00011011;

outside other closures
ISR(ANALOG_COMP_vect) {
   CRCArduinoPPMChannels::INT0ISR();
}

I am trying to move this project to an Arduino (compatible) Pro Micro from SparkFun. The datasheet specifies AIN0 on ATmega32u4 pin 1 but do not see a reference to AIN1.
The datasheet outlines use of the analog comparator on page 289:

AIN+ can be connected either to the AIN0 (PE6) pin, or to the internal
  Bandgap reference. AIN- can only be connected to the ADC multiplexer.

I have connected the signal to Arduino pin 7, the comparison voltage to Arduino pin 20 (analog 2) and set the following options of the ADMUX register:
ADMUX = B11000101;

The interrupts trigger but the comparator voltage (AIN-) is not being observed. Any help would be appreciated.

Did you forget to set ACME?

Yes! Setting ACME bit to 1 and ADEN to 0 did it. Thank you

3 years 9 months later, do you still happen to have your code handy by chance, would you mind to share the whole analog comparator setup please? (This is of course not an answer, sorry, I'm unable to just write a comment, I get "You must have 50 reputation to comment".)

Actually... I do. https://github.com/jjluebke/PigeonPPM/blob/master/PigeonPPM.ino

AIN- won't be connected to the ADC mux unless ACME is set and ADEN is cleared. Don't forget to do so.


text:
Send AT commands to ESP8266 from Arduino Uno via a SoftwareSerial port
GOAL
From Arduino UNO, send AT commands to ESP8266 via a SoftwareSerial port and receive results.
CURRENT STATUS
I either send AT commands and get nothing back (wiring scheme 1) or I send AT commands and get garbage back (wiring scheme 2).
Using the Arduino as a pass through (as explained in the tutorial listed in the resources section), I can send AT commands. I have found that I can communicate with the ESP8266 at 115200 baud.
This is the results of running AT+GMR:
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

WIRING SCHEME 1
!! I have the green wire attached to pin 3 on the Arduino Uno and the yellow wire attached to pin 2; not 1 and 0 as the picture suggests !!

WIRING SCHEME 2
Same wiring as above, but I have RX and TX reversed. The green wire is attached to pin 2 and the yellow wire is attached to pin 3.
CODE
This is running on Arduino Uno
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2, 3);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Started");

  // set the data rate for the SoftwareSerial port
  esp8266.begin(115200);
  esp8266.write("AT\r\n");
}

void loop() {
  if (esp8266.available()) {
    Serial.write(esp8266.read());
  }
  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

RESULTS FROM RUNNING SKETCH
Wiring Scheme 1
Started

Wiring Scheme 2
Started
�����

I have tested the ESP8266 via the instructions listed in the tutorial in the Resources I've Used section below. The ESP8266 works just fine when sending it instructions via the Serial Prompt.
RESOURCES I'VE USED
http://rancidbacon.com/files/kiwicon8/ESP8266_WiFi_Module_Quick_Start_Guide_v_1.0.4.pdf
QUESTION
Does anyone know if what I am trying to do is possible? And if it is, what am I doing wrong?

Try as sugested in the PDF to use arduino as a bypass to the serial (use the connections as in image). After try set baud at 115200 and test it using serial monitor. You need to send \r\n as line ends also. If esp doesn't respond try 9600 baudrate. If you get good output then move to software serial with the working baudrate. You can also try to update the firmware of esp to the latest version if you haven't already.

Can you post the software serial code?

@Personagem, Thanks. I have done that troubleshooting (ie. checking that I can send AT commands by using Arduino as a bypass). I have found that I can communicate with the esp at 115200. I'll try updating the firmware as you suggested.

@Magic-Mouse SoftwareSerial is a library provided by, I believe, Arduino. Thanks for you help on the question but I don't think posting the library here would be helpful.

I know what the software serial library is, i want to se the code where you use the software serial.

Ok i read it again the variable naming made me think that was the ESP8266 library, not the software serial, disregard my comments.

The link you shared is amazing!!!!!!!!!!!!!!!!!!!!!!!!!!

Why did you map ports 2 and 3 via software serial instead of using the built in Rx and Tx pins?

Does anyone know if what I am trying to do is possible?

Absolutely possible :)

And if it is, what am I doing wrong?

SoftwareSerial isn't capable of 115200 baud rate (despite "allowing" this as a setting).  Some reports suggest as high as 57600 is workable, though in my experience 9600 is best for reliability.  How to change the baud rate on the ESP8266 will depend on the firmware version.  I've had success with AT+IPR=9600.  You only need to run this command once (it's a persistent setting).  I'd suggest, based on your description, that this is the most likely culprit that's causing the "garbage" output you describe.
A couple of other notes:

The ESP8266 runs on 3v3, not 5v, so you shouldn't have it directly connected to the digital pins—you need to run through a logic level converter.  Running 5v can fry your ESP8266.
The Arduino's 3v3 output has insufficient current to support the ESP8266 reliably (50mA Arduino vs up to 300mA for the ESP8266 by some accounts)—try running the ESP8266 off a separate supply.  It probably won't affect simple commands like AT but when you try to connect to a network etc. it may cause unexpected device resets.
As noted by others, you need to send \r\n — so make sure your Serial window is set to send both (this is a drop-down in the serial window)

Please note that AT+IPR can sometimes brick ESP8266. More details are at: http://arduino.stackexchange.com/questions/24156/how-to-change-baudrate-of-esp8266-12e-permanently/

Well you may try this:
Start by uploading blink sketch to your Arduino then connect it to your ESP8266 like this: TX-TX and RX-RX.
Now open Serial Monitor and send AT command and see if it responds. If so then you can control it using your Arduino by wiring it back to TX-RX and RX-TX.
PS: Don't forget to set the line ending in the Serial Monitor to Newline or Carriage Return.
Use this code to connect to ESP8266:
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  ESP8266.println("AT");
  delay(30);
  while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}

Since the Hardware Serial interface will be busy when connected to Computer, then you have to use another Serial interface to communicate with your ESP8266. In this case, Software Serial comes handy.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - From Review

Yes, I guess you're right. I edited my answer.

@KiraSan why delay(30) is required?

@RahulRastogi just for this example, you can use delay to allow the ESP to respond, 30ms is only a random value but in a real life program, you should avoid that and use another mechanism to check for the response.

I had lot of problems as well. In my case problems are almost solved by switching from SoftwareSerial to AltSoftSerial. It seemed that on the Uno the standard software serial library was not working for me. After switching I started to get results back for the first time. (I also used level shifting and external power supply for 3.3V)

And by almost solved I mean - I still get, from time to time, gibberish on the terminal. So even AltSoftSerial isn't a perfect solution.
I was using the ESP-07 with a 115200 bps data rate.

Can you add to your description? It would be helpful to know how you wired the connection between the Uno and the ESP. Thanks!

Does anyone know if what I am trying to do is possible?
It is possible, i've done it with 2 arduinos where one was simulating ESP8266 (waiting for ebay order).
And if it is, what am I doing wrong?
What you are doing is wrong on most levels, but i think you got most sorted out.
An idea is to implement this little fella: Logic level shifter it will save you many troubles later.
On your "WIRING SCHEME 1" you are using the arduino's Hardware serial port to talk directly to the device as if it was connected through a TTL cable or FTDI cable.
This means that the arduino device would in theory read from the hardware when talking too the ESP8266, if you have another arduino or a TTL cable, try and connect it to gate 2 and 3 on the "main" arduino and you should get a similar result as for your example result 2. Since you would that way proxy through the arduino. If not that would be a place to start debugging.
Beside that i could only recommend you in investing in either a TTL 3,3v or a logic level converter. When i got my cable everything worked out of the box.

We found that many of the problems with the ESP - Arduino Uno serial software integration had to do with incompatible baudrate. We created this short tutorial (including a Github library) which you are welcome to test and see if it solves these issues. http://www.instructables.com/id/Simple-ESP8266-Arduino-Uno-Software-Serial-Integra/

Here are a few tips when using ESP8266 Module.

Don't use software serial as it's unreliable especially at higher baud rates.
Always connect ESP module to computer and test all AT commands before interacing with Arduino to ensure that you are working in right direction
Make a power adaptor board to make ESP module compatible with Arduino 5v supply

Also check out this link for more details


text:
Several XBee End devices sending simultaneously; Only one packet recieved on coordinator

I'm trying to configure a Zigbee sensor network. My "gateway (coordinator)" and "End devices" are made with XBeePro S2B model and configured in API mode "2". The "gateway (coordinator)" also has a SIM900 module, for uploading data to website (recieved on XBee), and Atmega 328p for codes (for "gateway (coordinator)" I'm using a Gboard device here), and for "End devices", I make/print a PCB with a atmega328p, XBee and PIR sensor.
The configuration works fine with several "End devices" (sincerilly, I have only tested with two "End devices", because it is expensive)...
The problem is when the "gateway (coordinator)" recieve data from more than one "End devices" at the same time. In this situation ("End devices" sending simultaneously) the "gateway (coordinator)" only recieves one packet (and only uploads that data to the website). I'm sure that I have a trouble with my code (sorry for the desestructurated and chaotic code, I'm a newbie).
Can anyone help me with the code?
code "gateway (coordinator)":
#include <elapsedMillis.h>
#include <SoftwareSerial.h>
#include <Streaming.h>
#include <XBee.h>
int xbeeRecibido;
char urlArreglo[100];
uint8_t slCmd[] = {'S','L'};
uint8_t dbCmd[] = {'D','B'};
char adr_part[8];
char rssiValor_part[8];
String adr="";
String rssiValor="";
AtCommandRequest atRequest = AtCommandRequest();
AtCommandResponse atResponse = AtCommandResponse();
elapsedMillis timeElapsed = 0;
unsigned long interval = 1800000 ;////en milisegundos  cada 30 min.
String direccionRed;
int bateria;
String valorRssi;
int actividadPir;
String datosHttp; ///concatenacion de datos para enviar por HTTP
int8_t answer;
char data[512];
int data_size;
char aux_str[100];
char aux;
int x = 0;
XBee xbee = XBee();//XBee object
Rx16Response rx = Rx16Response();
SoftwareSerial mySerial(2, 3); //PARA GPRS SIM900
//int b00;  //este seria el primero, que se pierde al buscar el 0X7E
int b01;
int b02;
int b03;
int b04; //source network adress 64Bit
int b05; //source network adress 64Bit
int b06; //source network adress 64Bit
int b07; //source network adress 64Bit
int b08; //source network adress 64Bit
int b09; //source network adress 64Bit
int b10; //source network adress 64Bit
int b11; //source network adress 64Bit
int b12; //source network adress 16Bit
int b13; //source network adress 16Bit
int b14;
int b15; //pir digital
int b16; //bateria
int b17; //checksum
void setup() {
   pinMode(14, OUTPUT);////led debug en 14 ((A0)DEBUGGGG!!!!
   pinMode(6, OUTPUT);///para encender SIM900 ...en pin6 HIGH de arduino GBOARD
   digitalWrite(6, HIGH);///para encender SIM900 ...en pin6 HIGH de arduino GBOARD
    mySerial.begin(9600);
    Serial.begin(9600);
///////GPRS////////
    power_on();
    delay(3000);
    sendATcommand("AT+ipr=9600", "OK", 2000);///////MIO PARA BAUDERATE A 9600 (por defecto 0=auto..¿se apaga?)
    // sets the PIN code
    sendATcommand("AT+CPIN=****", "OK", 2000);
    delay(3000);
    while (sendATcommand2("AT+CREG?", "+CREG: 0,1", "+CREG: 0,5", 2000) == 0);
    sendATcommand("AT+SAPBR=3,1,\"Contype\",\"GPRS\"", "OK", 2000);
    sendATcommand("AT+SAPBR=3,1,\"APN\",\"gprsmov.pepephone.com\"", "OK", 2000);
    sendATcommand("AT+SAPBR=3,1,\"USER\",\"\"", "OK", 2000);
    sendATcommand("AT+SAPBR=3,1,\"PWD\",\"\"", "OK", 2000);
    while (sendATcommand("AT+SAPBR=1,1", "OK", 20000) == 0)
    {
        delay(5000);
    }
////FIN GPRS////
lanzarHttpAutoControl();
delay(15000);
}

void loop() {
if (timeElapsed > interval)
    {
        lanzarHttpAutoControl();
        delay(15000);
    timeElapsed = 0;
    }
if (Serial.available()==18) {//make sure the frame is all there
  if (Serial.read()==0x7E) {
     b01 = Serial.read();
     b02 = Serial.read();
     b03 = Serial.read();
     b04 = Serial.read(); //source network adress 64Bit
     b05 = Serial.read(); //source network adress 64Bit
     b06 = Serial.read(); //source network adress 64Bit
     b07 = Serial.read(); //source network adress 64Bit
     b08 = Serial.read(); //source network adress 64Bit
     b09 = Serial.read(); //source network adress 64Bit
     b10 = Serial.read(); //source network adress 64Bit
     b11 = Serial.read(); //source network adress 64Bit
     b12 = Serial.read(); //source network adress 16Bit
     b13 = Serial.read(); //source network adress 16Bit
     b14 = Serial.read();
     b15 = Serial.read(); //pir digital
     b16 = Serial.read(); //bateria
     b17 = Serial.read();  //checksum
     direccionRed =  String(b04, HEX);
     direccionRed +=  String(b05, HEX);
     direccionRed +=  String(b06, HEX);
     direccionRed +=  String(b07, HEX);
     direccionRed +=  String(b08, HEX);
     direccionRed +=  String(b09, HEX);
     direccionRed +=  String(b10, HEX);
     direccionRed +=  String(b11, HEX);
     actividadPir = b15;
     bateria = int(b16);
     digitalWrite(14, HIGH);//FOR DEBUG LED
     delay(1000);//FOR DEBUG LED
     digitalWrite(14, LOW);//FOR DEBUG LED
     xbeeRecibido = 1;
        } //fin if 0x7E
  }///fin recorrer bytes
   else {
         if (xbeeRecibido == 1) {///si se ha recibido info de xbee sensor
         colectorDatos();
         xbeeRecibido = 0;
        }
   }
delay (10);
}//fin loop

void rss() {  ///PARA RSSI
   /* returns received signal strength value for the last RF data packet */
   union {byte B; char C;} atCmd[3];
   AtCommandRequest atCmdReq;
   AtCommandResponse atResp;
   byte respLen, *resp, dBm;
   strcpy(&atCmd[0].C, "DB");
   atCmdReq = AtCommandRequest(&atCmd[0].B);
   atResp = AtCommandResponse();
   xbee.send(atCmdReq);
   if (xbee.readPacket(5000)) {
       if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
           xbee.getResponse().getAtCommandResponse(atResp);
           if (atResp.isOk()) {
               respLen = atResp.getValueLength();
               if (respLen == 1) {
                   resp = atResp.getValue();
                   dBm = resp[0];
                   valorRssi = (String)dBm;
               }
               else {
               }
           }
           else {
           }
       }
       else {
       }
   }
   else {
   }
}///fin rss()

void power_on(){
    uint8_t answer=0;
    // checks if the module is started
    answer = sendATcommand("AT", "OK", 2000);
    if (answer == 0)
    {
        // waits for an answer from the module
        while(answer == 0){
            // Send AT every two seconds and wait for the answer
            answer = sendATcommand("AT", "OK", 2000);
        }
    }
}

int8_t sendATcommand(char* ATcommand, char* expected_answer1, unsigned int timeout){
    uint8_t x=0,  answer=0;
    char response[100];
    unsigned long previous;
    memset(response, '\0', 100);    // Initialize the string
    delay(100);
    while( mySerial.available() > 0) mySerial.read();    // Clean the input buffer
    mySerial.println(ATcommand);    // Send the AT command
        x = 0;
    previous = millis();
    // this loop waits for the answer
    do{
        if(mySerial.available() != 0){
            response[x] = mySerial.read();
            x++;
            // check if the desired answer is in the response of the module
            if (strstr(response, expected_answer1) != NULL)
            {
                answer = 1;
            }
        }
        // Waits for the asnwer with time out
    }
    while((answer == 0) && ((millis() - previous) < timeout));
    return answer;
}

int8_t sendATcommand2(char* ATcommand, char* expected_answer1,
char* expected_answer2, unsigned int timeout){
    uint8_t x=0,  answer=0;
    char response[100];
    unsigned long previous;
    memset(response, '\0', 100);    // Initialize the string
    delay(100);
    while( mySerial.available() > 0) mySerial.read();    // Clean the input buffer
    mySerial.println(ATcommand);    // Send the AT command
        x = 0;
    previous = millis();
    // this loop waits for the answer
    do{
        if(mySerial.available() != 0){
            response[x] = mySerial.read();
            x++;
            // check if the desired answer 1 is in the response of the module
            if (strstr(response, expected_answer1) != NULL)
            {
                answer = 1;
            }
            // check if the desired answer 2 is in the response of the module
            if (strstr(response, expected_answer2) != NULL)
            {
                answer = 2;
            }
        }
     // Waits for the asnwer with time out
    }while((answer == 0) && ((millis() - previous) < timeout));
    return answer;
}

void colectorDatos(){ ///funcion para recolectar datos recibidos del xbee y gestionarlos para enviarlos por GPRS
    rss(); ////recupero rssi que se pone en variable valorRssi
    datosHttp = direccionRed +";"; ///cualquier valor del array, todos deverian tener mismo valor (direccion64bits)
    datosHttp += bateria;
    datosHttp += ";";
    datosHttp += valorRssi;
    datosHttp += ";";
    datosHttp += actividadPir; //pir
    envio(datosHttp); ///envio por gprs
}///fin colectorDatos

void lanzarHttpAutoControl() {
  adr="";
  atRequest.setCommand(slCmd);  // set command to SL to get low part of MAC address
  while (!sendAtCommand()) {};
  for (int i = 0; i < atResponse.getValueLength(); i++) {
    mySerial.print(atResponse.getValue()[i], HEX);
    sprintf(adr_part, "%lX", (unsigned long)(atResponse.getValue()[i]));
    if (atResponse.getValue()[i]<=0xF)
        adr += 0;
        adr += adr_part;
  }
  envio(adr); ///envio por gprs

}

void envio(String entrada){///envio GPRS...recibe String con datos (o control o sensor)
   memset(urlArreglo, 0, sizeof(urlArreglo));///a cero el array
    answer = sendATcommand("AT+HTTPINIT", "OK", 10000);
    if (answer == 1)
    {
        // Sets CID parameter
        answer = sendATcommand("AT+HTTPPARA=\"CID\",1", "OK", 5000);
        if (answer == 1)
        {
      sprintf(urlArreglo,  "AT+HTTPPARA=\"URL\",\"www.pestmonitors.com/dream/prueba_gsm_get.php?datos=%s\"",entrada.c_str());
      answer = sendATcommand(urlArreglo, "OK", 5000);
       delay(5000);
            if (answer == 1)
            {
                answer = sendATcommand("AT+HTTPACTION=0", "+HTTPACTION:0,200", 10000);
            }
    else
    {
    }
    sendATcommand("AT+HTTPTERM", "OK", 5000);
    delay(5000);
      }
    }
}

int sendAtCommand() { // used here to sens AT command to the Xbee to get information such as the MAC address
  xbee.send(atRequest);
  if (xbee.readPacket(5000)) {
    if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
      xbee.getResponse().getAtCommandResponse(atResponse);
      if (atResponse.isOk()) {
        if (atResponse.getValueLength() > 0) {
          mySerial.println(atResponse.getValueLength(), DEC);
          for (int i = 0; i < atResponse.getValueLength(); i++) {
            mySerial.print(atResponse.getValue()[i], HEX);
          }
        }
        return 1;
      }
      else {
      }
    } else {
      mySerial.print(xbee.getResponse().getApiId(), HEX);
    }
  } else {
    if (xbee.getResponse().isError()) {
    }
    else {
    }
  }
  return 0;
}

code "End devices":
#include <Sleep_n0m1.h>
#include <XBee.h>
XBee xbee = XBee();
uint8_t payload[] = { 0, 0 };
XBeeAddress64 addr64 = XBeeAddress64(0x0, 0xFFFF);
ZBTxRequest zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
ZBTxStatusResponse txStatus = ZBTxStatusResponse();
boolean apagar;
int battVolts;
int PinEntradaBat = A0;
int valorBateriaTotal;
int valorBateria;
int mapeoValorBateria;
Sleep sleep;
unsigned long sleepTime; //how long you want the arduino to sleep
int salida = 7; ////pin salida 7 para DTR xbee
int entradaInterrumpirSleep =2; ////pin desde pir para interrumpir/despertar
boolean abortSleep; //cancel sleep cycle
int modo;
int cicloTiempoSleep;///establecer ciclo alarma
int numeroCiclos; ///para retomar ciclo si falsa alarma
boolean enviado; ///para comprobar si recepción de xbbe, sino, reenviar!
uint8_t atdCmd[]={'D','5'};
uint8_t value[]={4};///pongo DIO5 a output LOW
uint8_t length=1;
AtCommandRequest atRequest = AtCommandRequest(atdCmd, value, length);
AtCommandResponse atResponse = AtCommandResponse();
//boolean saltarPrimerPir = true; ////PARA NUEVO PIR, SALTAR LA ALARMA AL ARRANCAR ¿PORQUE?
void setup()
{
  analogReference(DEFAULT);
  enviado = true;
  numeroCiclos = 0;
  apagar = false;
  pinMode(salida, OUTPUT); //para DTR en xbee
  pinMode(6, OUTPUT); //para MOSFET (en digitalPin6 PWM)!!
  digitalWrite(salida, LOW); //EMITE 5V HACIA DTR, ENVIAR EN XBEE
  delay(120000);//2 minutos para evitar primer interrupt!y dar tiempo a comprobar tecnico la asociación
  abortSleep = false; //can be used to cancel the sleep cycle
  sleep.setCalibrationInterval(1);
  sleepTime = 1000;//set sleep time in ms, max sleep time is 49.7 days (1/2 1 min)
  modo = 0; //para empezar con modo CONTROL
  numeroCiclos = 0;
  Serial.begin(9600);
  xbee.setSerial(Serial);
  xbee.send(atRequest);// set command to ATD50 to stop LED Assoc...////DESCOMENTAR PARA APAGAR LED ASSOC!!!!!!
  delay(5000);
}//fin setup

void loop()
{
if (apagar == true) { ///APAGAR SI BATERIA MUY BAJA!!!!
  detachInterrupt(0);
  while (apagar == true) {
  }
}
  if (modo == 0) {
    detachInterrupt(0);
    digitalWrite(salida, LOW); //EMITE 0V HACIA DTR, ENVIAR EN XBEE
    digitalWrite(6, HIGH); //EMITE 5V HACIA mosfet/regulador, ENCIENDE XBEE
    cicloTiempoSleep = 21600; //6 horas
    delay(10);
    enviarXbee(0);
    digitalWrite(salida, HIGH);//EMITE 5V HACIA DTR, ACTIVAR DTR (XBEE SLEEP)
    digitalWrite(6, LOW); //EMITE 0V HACIA mosfet/regulador, APAGAR
    delay(30000);///30seg de inactividad post envio control!
    attachInterrupt(0, interrumpirPir, RISING);
  } //fin modo0 CONTROL
  if (modo == 1) {
        detachInterrupt(0);
        digitalWrite(salida, LOW); //EMITE 0V HACIA DTR, ENVIAR EN XBEE
        digitalWrite(6, HIGH); //EMITE 5V HACIA mosfet/regulador, ENCIENDE XBEE
        modo = 0; //modo CONTROL
        numeroCiclos = 0;
        cicloTiempoSleep = 21600; //6 horas para enviar CONTROL despues de ACTIVIDAD
        delay(10);
        enviarXbee(1);
        digitalWrite(salida, HIGH);//EMITE 5V HACIA DTR, ACTIVAR DTR (XBEE SLEEP)
        digitalWrite(6, LOW); //EMITE 0V HACIA mosfet/regulador, APAGAR
        delay(120000);///2 minutos de inactividad post envio alarma! (para no enviar otra enseguida)
        attachInterrupt(0, interrumpirPir, RISING);
  }//fin modo1 ACTIVIDAD
  abortSleep = false;
  for (int i=0; i < cicloTiempoSleep; i++){ /////ARREGLO CON FOR PARA REITERAR 1000ms (1seg) x VECES (hace extraños el int0 con SleepDelay juntos)
        numeroCiclos = i;
        sleep.pwrDownMode(); //set sleep mode
        sleep.sleepDelay(sleepTime,abortSleep); //sleep for: sleepTime
        if (abortSleep == true) {
          break;
        }
   }//fin contador tiempo
  if (cicloTiempoSleep <= 1 || numeroCiclos == --cicloTiempoSleep) { ///estos dos -- restan 1 al valor de la variable
    modo = 0;
  }
}//fin loop

void interrumpirPir() // si disparo PIR por interrupt0 (isr)
{
  if (numeroCiclos != 0) {/////AQUI EVITAR PRIMERA INTERRUPCION AL INICIARSE EL SENSOR/////
  abortSleep = true;
  cicloTiempoSleep = cicloTiempoSleep - numeroCiclos;
  modo = 1;
  }//fin saltar primer PIR
}///fin interrumpir! ISR

void enviarXbee(int valorPir) // si disparo PIR por interrupt0 (isr)
{
battVolts=getBandgap();
valorBateriaTotal = 0;
for (int e=0; e < 20; e++)
    {
       mapeoValorBateria = map(analogRead(A1), 0, 1023, 0, battVolts);
       valorBateriaTotal = valorBateriaTotal + mapeoValorBateria;
     delay(10);
    }
valorBateriaTotal = valorBateriaTotal/20;
if (mapeoValorBateria <= 95) {///APAGAR SI BATERIA MUY BAJA!!!!
apagar = true;
}
    payload[0] = valorPir; ///PIR
    payload[1] = mapeoValorBateria & 0xff;
    delay (10000);
    xbee.send(zbTx);
    //delay (15000);
    if (xbee.readPacket(5000)) {
      if (xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE) {
        xbee.getResponse().getZBTxStatusResponse(txStatus);
        if (txStatus.getDeliveryStatus() == SUCCESS) {
         // enviado = true;
        } else {
        //  enviado = false;
        }
      }
    } else if (xbee.getResponse().isError()) {
    } else {
    }
}//end enviar xbee

long leerBateria()//para ver estado bateria
{
}
int getBandgap(void) // Returns actual value of Vcc (x 100)
   {
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    // For mega boards
    const long InternalReferenceVoltage = 1115L;  // Adjust this value to your boards specific internal BG voltage x1000
       // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc reference
       // MUX4 MUX3 MUX2 MUX1 MUX0  --> 11110 1.1V (VBG)         -Selects channel 30, bandgap voltage, to measure
    ADMUX = (0<<REFS1) | (1<<REFS0) | (0<<ADLAR)| (0<<MUX5) | (1<<MUX4) | (1<<MUX3) | (1<<MUX2) | (1<<MUX1) | (0<<MUX0);
#else
    // For 168/328 boards
    const long InternalReferenceVoltage = 1056L;  // Adjust this value to your boards specific internal BG voltage x1000
       // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc external reference
       // MUX3 MUX2 MUX1 MUX0  --> 1110 1.1V (VBG)         -Selects channel 14, bandgap voltage, to measure
    ADMUX = (0<<REFS1) | (1<<REFS0) | (0<<ADLAR) | (1<<MUX3) | (1<<MUX2) | (1<<MUX1) | (0<<MUX0);
#endif
    delay(50);  // Let mux settle a little to get a more stable A/D conversion
       // Start a conversion
    ADCSRA |= _BV( ADSC );
       // Wait for it to complete
    while( ( (ADCSRA & (1<<ADSC)) != 0 ) );
       // Scale the value
    int results = (((InternalReferenceVoltage * 1023L) / ADC) + 5L) / 10L; // calculates for straight line value
    return results;
   }
int sendAtCommand() {
  xbee.send(atRequest);
  if (xbee.readPacket(5000)) {// wait up to 5 seconds for the status response
    if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {// should be an AT command response
      xbee.getResponse().getAtCommandResponse(atResponse);
      if (atResponse.isOk()) {
        if (atResponse.getValueLength() > 0) {
          for (int i = 0; i < atResponse.getValueLength(); i++) {
          }
        }
      }
      else {
      }
    } else {
    }
  } else {
    if (xbee.getResponse().isError()) {
    }
    else {
    }
  }
}

Thank you very much. I really appreciate your help.

I didn't parse through your code, nor have i used the xBee Pro you mentioned.  I did however solve a similar problem once by having each send transmission occur 3 times with a random delay from 400-1200 milliseconds between transmissions (used trial and error to determine those values).  With multiple transmissions with randomly generated delay between each most transmissions should make it on at least one of the tries,  of course the receiving end then needs to be able to decide if it got dup packets and throw out the extra data.

This looks like a good solution, Tyson! I understand that you suggest to send several data packets from the "End device" spaciated by a random delay, to make sure that at least one gets to the "gateway (coordinator)".
So, how do I modify my code to make the "End device" repeatedly send the same message? Also, I have the same problem with how to modify my code for the "gateway (coordinator)" to discriminate the identical packages. Thanks a lot for your answer and time and to all the altruistic people here like you, Tyson. You rule! Can anyone help me to try to implement this solution?


text:
Arduino SoftwareSerial library basic example doesn't work

I come to you again because I have a problem with the Arduino SoftwareSerial library. With a basic example I fail to see results in the serial monitor.
The basic code example:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);
void setup() {
  mySerial.begin(4800);
}
void loop() {
    mySerial.println("HELLO");
    delay(100);
}

I guess it should show the string "HELLO" on the serial port, but nothing appears. I have found that the baud setting is correct. The hardware is simple. Only an Arduino Uno v3 without any connected component.

If your Arduino is connected via the built-in USB port then you need to use the hardware serial port (pins 0 and 1). To do that, call Serial.begin(..) and Serial.println(..), instead of mySerial....
SoftwareSerial is used when you want to connect via serial on some other pins. It allows your program to emulate serial input/output in software instead of relying on dedicated hardware. In this case, your program is trying to setup software serial on pins 10 and 11. That won't show up on the serial monitor because it's not connected to those pins.

Thanks for your answer.
Yes, I am aware that I can use the serial hardware, but the fact is that I need to connect a device to these two pins (10 and 11), because in the serial hardware and I have a connected device is busy.
I try to make a mySerial.print to test the serial communication with the "virtual serial" but does not show anything printed on the serial monitor.
thank you very much

Addition to Peter R. Blommfield
What is your problem?
Connect your device, run this sketch and you are good to go :)
/* TEST */
#include <SoftwareSerial.h>

/* Connect device Rx - 10, Tx - 11 */
SoftwareSerial mySerial(10, 11);

void setup() {
  Serial.begin(9600);   // This will communicate with PC via USB
  mySerial.begin(4800); // This will communicate with device via 10,11 pins with 4800 baud rate
}
void loop() {
    Serial.println("HELLO");   // Sends string to PC to Serial Monitor
    mySerial.println("HELLO"); // Sends string to device
    delay(100);                // Waits here 100ms and then goes on
}

Thanks for your answer,
With the example you've happened to me, I open the serial monitor and print me "hello" well at 9600 baud, but when I set the serial monitor at 4800 baud, it prints very strange characters, not the word "hello" as I think it is expected.
Thanks for your help!

In serial monitor you have to change the baud rate manually. At the bottom right corner there is drop down menu. Choose 4800

Also let me ask, what is the device you connect?

yeah, I've changed but I keep getting weird characters...

...its a module gprs by http://www.cooking-hacks.com/gprs-quadband-module-sim900-for-arduino .But I put the RX/TX pins on a 10/11 pins oin arduino board

If you change Serial.begin(9600); to Serial.begin(4800); and change serial monitor to 4800 then you have to get HELLO

Thanks, but I need to recibe the HELLO in virtualSerial, not in hardware serial

Let us continue this discussion in chat.

You already do it. The line Serial.println("HELLO"); prints it to PC, mySerial.println("HELLO"); prints it to your device

Thanks a lot!!! I have a misunderstanding of what SoftwareSerial is for!

Xavi so that link helped? Google translate : Xavi para que enlace ayudó?