body:
    //Now it will work
    //  https://arduino.stackexchange.com/questions/9731/control-speed-of-dc-fan-using-arduino-pid-library

    #include <PID_v1.h>
    double Setpoint, Input, Output;  //not there in original sketch
    //Define Variables we'll be connecting to double Setpoint, Input, Output;
    //Define the aggressive and conservative Tuning Parameters
    double aggKp = 4, aggKi = 0.2, aggKd = 1;
    double consKp = 1, consKi = 0.05, consKd = 0.25;
    //double consKp=2, consKi=5, consKd=1;

    //Specify the links and initial tuning parameters
    PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, REVERSE);
    void setup()
    {
      Serial.begin(9600);
      //initialize the variables we're linked to
      // Input = map(analogRead(0), 0, 1023, 255, 0);

      //int val = analogRead(0);
      //val = map(val, 0, 1023, 0, 255);
      // analogWrite(9, val);

      Setpoint = 100;
      myPID.SetOutputLimits(0, 255); //MIN,MAX
      //turn the PID on
      myPID.SetMode(AUTOMATIC);  // MANUAL
      myPID.SetControllerDirection(REVERSE);  // DIRECT
    }
    void loop()
    {
      int sensorValue = analogRead(0);
      Input = map(sensorValue, 0, 1023, 0, 255);

      double gap = abs(Setpoint - Input); //distance away from setpoint
      if (gap < 10)
      { //we're close to setpoint, use conservative tuning parameters
        myPID.SetTunings(consKp, consKi, consKd);
      }
      else
      {
        //we're far from setpoint, use aggressive tuning parameters
        myPID.SetTunings(aggKp, aggKi, aggKd);
      }

      myPID.Compute();
      analogWrite(3, Output);
      Serial.print(" PWM = ");
      Serial.print(Output,0);
      Serial.print("       sensor value =  ");
      Serial.print(sensorValue);
      Serial.print("       Input =");
      Serial.println(Input,0);
    }


sender: user

message:
What do symbols like UCSR0C, UMSEL01, etc. means?

I have a code with a connection to serial port:

    // Set baud rate
    UBRR0H = UBRRH_VALUE;
    UBRR0L = UBRRL_VALUE;
    // Disable USART rate doubler (arduino bootloader leaves it enabled...)
    UCSR0A &= ~(1 << U2X0);
    // Set async, no parity, 1 stop, 9bit
    UCSR0C = (0<<UMSEL01)|(0<<UMSEL00)|(0<<UPM01)|(0<<UPM00)|(0<<USBS0)|(1<<UCSZ01)|(1<<UCSZ00);
    UCSR0B |= (1<<UCSZ02); // 9bit
    // Enable rx/tx
    UCSR0B |= (1<<RXEN0)|(1<<TXEN0);

I see the comments but I want to know exactly what does these chunks means. Is there any complete documentation about these symbols?

sender: assistant

body:
Take a look in the datasheet under the "20. USART0" section:

http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

I will list the names of the registers, what they are called, and then what your code is doing specifically:

- UBRR0H and UBRR0L together form the baud rate divider.  Your program probably uses F_CPU and `<util/setbaud.h>` to calculate a divider and set the baud rate.  For more information see Table 20-12.
- UCSR0A  "USART Control and Status Register n A"  --  This line is enabling the U2X0 which doubles the transmission speed
- UCSR0C  "USART Control and Status Register n C" --  This line is enabling the UCSZ01 and UCSZ00 bits to set parity check to "Enabled, Odd Parity".  See Table 20-9.  This line has extra information, all the statements with 0<< actually do nothing.
- USCR0B " USART Control and Status Register n B" -- This line is setting the UCSZ02 bit which is described here: "The UCSZn2 bits combined with the UCSZn1:0 bit in UCSRnC sets the number of data bits (Character SiZe) in
a frame the Receiver and Transmitter use. "  This basically allows you to select 9 bit wide serial if you would like (8 bit is more common)
- The final USCR0B line enables tx and rx


body: I strongly recommend you to read the datasheet. You are confusing UART module with GPIO module. Once you use one pin for one purpose (say serial comunication) you cannot use it for another thing (say general I/O to read a physical button state). Of course it is possible if you write your code in a way it changes all the registers (the ones you call "symbols") on excecution time. But just be carefull that the routines that used those pins for UART don't execute meanwhile!


message:
Arduino Motor Shield and Adafruit CC3000 WiFi Shield Compatibility

My question is similar to this one: https://arduino.stackexchange.com/questions/3892/motor-shield-and-wireless-transceiver-compete-for-same-pins
But not exactly the same!

I would like to know if the solution is as practical, though.

I have an Arduino Mega 2560 R3, with an Arduino Motor shield plugged into it. Now I want to use the Adafruit CC3000 WiFi shield. It plugs in fine, but when reading the specifications, it wants to use pins 13, 12, 11 which are also used by the Motor shield. I also want to use pin 10 as a servo is plugged into it. This is all on a robot so I don't have space to wire the shield separately through a breadboard or similar.

It should perhaps also be noted that I have the motor shield on top of the wifi shield so that the wifi shield can use the ICSP ports which the motor shield doesn't have, therefore any redirecting of pins on the CC3000 will mean that the motor shield pins will also be affected unless I redirect them too, and at that point I feel like it would be all a bit of a mess.

The solution to the other question was indeed to redirect the relevant pins to other free pins on the micro-controller board. However, I noticed that the Adafruit shield has a second row of connector holes next to the main pin holes. In the [shield documentation][1] I found, I didn't find any specific reference to these parts and in what situations they could be used, but maybe this is one of them.

My concern with using these is that (as you can see in the second image below, ignoring the coin!), the ports are wired together in the board. Does this mean that it won't make any difference which I use; if I connect a second row of pins/connectors to these points will it simply transmit the same data down both sides? I don't know enough about how electronics work at that level to understand the consequences.

So really my question is: can I use the outside row of ports for my motor shield and the inside row for the wifi shield?

![Adafruit WiFi Shield][2]

![Underside of shield][3]

**EDIT:**

So I've spent until now on the Adafruit forums trying to get some help with this and I still am not all the way there... maybe at this point someone here can cast fresh eyes over my problem.

The Adafruit CC3000 uses both the dedicated ICSP pins and pins 3, 11-13 to transmit the same data. The reason for this is to do with compatibility between different Arduino boards and their versions. E.g. apparently the Uno uses those pins whilst the mega uses some of the pins in the 50s range. I'm not sure what to make of this as the Uno and most of the boards seem to have the ICSP pins, so if they're not used for this purpose then what's the point of connecting to them? Anyway.

As it was explained to me, even if the board can use the ICSP pins to communicate with the microcontroller, it is still sending data via the other pins. So the main pins are essentially useless at this point. To make them useful again, the idea is that you sever the wires that are sending the data through them (often referred to as trace wires). This means that only the ISCP ones will be active for what they are needed, and the main pins will be free for other uses. This is what I ended up doing to my board for pins 11-13, and then for pin 3 I cut the trace wire and wired up the connection to pin 2 as these can both be used for an IRQ (interrupt request) on the Mega and I need pin 3 for the motor shield. The lighting on these pictures isn't the best, but you can see what I've done (the lower part of the second image shows where I made the cuts and the top image shows the wire connection):
![Top view][4]
![Underside view][5]

After doing that I have been testing the shield connected to both my Mega and my Uno and they both produce the same results. This is using the Adafruit-created library called `Adafruit_CC3000_Library`. It starts the initialisation, then whilst it's trying to run the code it gets stuck. I traced the problem to a while(1) loop of which you can only exit by meeting a condition which is never met in my case: `if (*pucReceivedData == HCI_TYPE_EVNT)`. This may be because `pucReceivedData` is not initialised properly, but I don't know why and whether it has to do with my modifications. This happens in the `hci_event_handler` method of `evnt_handler.cpp`. This is  through the main file and `wlan.cpp` so I won't write it here as it is simple enough to follow.

It should also be noted that this shield doesn't work properly with the later versions of the arduino IDE (1.5+) so I had to reinstall 1.0.6. To be honest, I got the same problem on both versions so who knows.

I realise that this is a very specific problem, but I figure that this may leave someone with a lot fewer issues in the future. If anyone has any bright ideas, even if just for testing then I would be grateful.

  [1]: https://learn.adafruit.com/downloads/pdf/adafruit-cc3000-wifi.pdf
  [2]: https://i.stack.imgur.com/YSc44.jpg
  [3]: https://i.stack.imgur.com/TpAAY.jpg
  [4]: https://i.stack.imgur.com/p88FG.jpg
  [5]: https://i.stack.imgur.com/HdtVH.jpg

body:
It works!

First I'll say thanks to the moderators/support staff from Adafruit. One dude in particular has tried to help me constantly for the past couple of days or so.

So, following on from my edit, Adafruit told me that the ICSP pins are connected to the control part of the board via the main pins. I should have seen it actually, but I obviously didn't examine and understand it properly. This means that although I severed the connection between the main pins and the centre, the ICSP and 11,12,13 were still connected together. What I actually needed was for the ICSP pins to be connected to the controls to receive the data, and the main pins to be detached from them. So I de-soldered the solder jumpers that I had originally put on the connector plates on the underside of the board (which connect the ISCPs to the main pins), then soldered wire from the ICSP side to the associated breakout holes which are the ones on the inside of the cuts that I made on the board. Here is a picture:

![New wiring on board][1]

If anyone tries to do this, beware of where you are wiring to! I was very careful to make sure I matched the connecting wires to the correct pins. I have tested it several times (using the example test file that comes with the library) and it works as it should. It works on my Uno R3 and my Mega 2560 R3, which is great, as now pins 11-13 are free to use for my motor shield, or potentially any other shield which may need those pins.

I hope this helps someone else in the future. There doesn't seem to be any information on this particular combination of shields, but as these projects are becoming more popular this may prove to be useful.

  [1]: https://i.stack.imgur.com/HQFUw.jpg


message:
Is it possible to use two encoders with Arduino Uno?

I would like to control 2 motors with the Arduino Uno board, which provides only two interrupt pins on digital 2 and 3.

I've set one encoder using these pins, and it works. What do you think about the following approaches:

 - Timer Interrupt:

Create a Timer Interrupt.
Connect the seconder encoder to an analog pin.
Set an analog read function in the interrupt service routine.
Change the prescaler of the ADC and increase the acquisition time.

 - PinChangeInt

Use PinChangeInt to capture the pin change interrupt rather than an external interrupt.

> This should allow you to use almost any I/O pins on the Uno for the
> encoder.

> as Ignacio Vazquez-Abrams suggested [here](https://arduino.stackexchange.com/questions/4801/rotary-encoder-on-uno-and-interrupts-issue)

body:
It is very possible. use a separate interrupt pin for Phase A of both motors, then read phase B from a non interrupt pin in the interrupt handler.
http://www.spiked3.com/?p=5501


message:
How to add the Wiring S board to Arduino IDE v.1.6.2?

My Arduino Uno is running out of memory to support my script (yes, I've tried several ways of optimize it already: PROGMEM, EEPROM, no Strings, and so on), so I would like to upload my script to my [Wiring S][1] board.

However, instead of "porting" all libraries to Wiring, I would like to compile my script in Arduino IDE and upload it to my Wiring S. It used to be "easy" in Arduino v.1.0.x. because somwhere I got a Wiring folder (containing, among other things, a boards.txt file) and copied it to Arduino's `hardware` folder getting the Wiring S board listed in Arduino IDE.

Since Arduino 1.5 the [specification for adding other boards changed][2]. I'd say it's more complex now. I simply cannot understand most of the new specification (yes, I'm new into electronics), so I haven't been able to add my Wiring S board.

Running my script in Arduino 1.0.x doesn't seem to be an option, since it throws lots of errors (although the script compiles in Arduino 1.6.2).

Do you have any experience adding other boards (like Wiring S) to Arduino IDE? Could you please give me some hint?

  [1]: http://wiring.org.co/hardware/
  [2]: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification

body:
There are two things I do; I use the Serial.print(F("string/n")); which prints the data from flash rather then copying it to ram.  Keep as many of your variables local as possible, that will save ram.  This is done by defining then in the function, the added advantage nothing outside the function can change them.

Global and Static variables are the first things loaded into SRAM. They push the start of the heap upward toward the stack and they will occupy this space for all eternity.

Variables created in functions, are dynamically allocated objects and data. Unlike Global and Static variables, these variables can be de-allocated to free up space at function exit. But Every function call creates a stack frame that makes the stack grow toward the heap. This data is usable within the function, but the space is 100% reclaimed when the function exits!


message:
Can I damage an arduino by setting pins high with no load

I have an Arduino project that has 15 different output pins set.  Some are currently attached to devices and others are not.  Will testing my program cause a problem / damage if it sets pints to HIGH that do not have anything connected to them?

body:
Nope, you should be just fine.

Having a pin set to any state while unplugged will not cause any problems with your microcontroller.


message:
millis() function with a button press

I am trying to use the `millis()` function to turn on a pin for a specified interval then turn off and turn on a second pin. It is intended to power a relay and offer a visual cue to when the cycle is over. Several of these need to eventually be running, most likely three, so using `delay()` won't work. I plan to add additional "button pins" for each input. The LED lights up but gets stuck in the loop and doesn't cycle out. It seemed like a simple program but I can't crack it for some reason.

Is there a much better method to do this? There will be two optical sensors and one pushbutton switch attached to an air driven crushing machine. The two optical sensors will be used only as time indicators with LEDs and the pushbutton will power the relay. Forgive my shortcomings as a programmer, I am learning the programming language still.

    const int ledPin =  2;      // the number of the LED pin
    const int buttonPin = 3;    // Button pin number
    // Variables will change:
    long previousMillis = 0;        // will store last time LED was updated
    int buttonState = 0;            // Checks if button is pushed
    int buttonPush = 0;             // Toggles between 0 to hold state
    long interval = 1000;           // interval at which to blink (milliseconds)

    void setup() {
    // set the digital pin as output:
       pinMode(ledPin, OUTPUT);
       pinMode(buttonPin, INPUT);
    }
    void loop()
    {
       unsigned long currentMillis = millis();
       buttonState = digitalRead(buttonPin);
       if (buttonState == HIGH) {
          buttonPush = 1;
          if (buttonPush == 1){
             if(currentMillis - previousMillis > interval) {
                previousMillis = millis();
                digitalWrite(ledPin, HIGH);
             }
             else {
                buttonPush = 0;
             }
          }
          else {
             digitalWrite(ledPin, LOW);
          }
       }
    }

Edit: Thank you for looking over the code, you guys are awesome. There were a couple questions regarding clarity of the final application so I will elaborate. I am going to attempt to clean it up. I had a feeling something was wrong with:

    if (buttonState == HIGH) {
       buttonPush = 1;

but I couldn't put my finger on it.

Eventually the system will function with two heating elements to soften plastic, which I will either add an optical sensor to since it will probably get triggered a few hundred times a day, or just a pushbutton to start a timer so the plastic isn't left in too long. A green LED will be illuminated to indicate the system is on. When the plastic object is placed in the heating element it triggers the optical sensor (or the operator pushes a pushbutton to start the timer) that will then illuminate a red LED to indicate heating. When the specified time interval has expired, the LED will revert back to green to show the cycle is complete. The plastic object is then removed and placed in a pneumatic crushing device with a green system on LED. The operator then pushes a pushbutton which turns on a red indicator LED and a relay to power the solenoid on the pneumatic press for a specified amount of time to allow the plastic to cool and crystallise. When that interval has expired, the system will revert back to illuminating the green LED and will end power to the relay allowing the press to release.

The pneumatic press and the heating system works awesome, I just need better control of the time intervals used. The end result needs to be consistent.

I am going to try all suggestions and will post what ended up working if I reach that point or find an answer that functions.

body:
Summary:

A fatal problem is caused by the two lines of code below.
A variable is set and then the same variable is immediately tested to see if it is set.  This means that the IF test always passes and the ELSE never happens.
As the LED is cleared only when the else occurs, the LED stays lit.

Code:
>       buttonPush = 1;
>       if (buttonPush == 1){ ...

When the button is pressed you set buttonPush and then immediately test to see if it is set.

As it always is set, the LED never gets turned off as the "else" condition is never met.

Even when that is fixed you have other issues.
I suggest that "expanding" the code along the lines I have shown in (3) below will help you immensely with visualising what your code does.

There are a large number of editors which handle this task in various ways, but just plain tabbing and white space with a basic editor helps muchly.

___________________

It seems almost certain that your code will NOT do what you intend when it does work "properly", but there are several issues below that need addressing (one fatal, others less so) - see "ISSUES" below.

Apart from those issues, it's not 100% clear how this is intended to be used.
Options include:

 - Switch is pressed and released quickly (say 100 mS) - LED lights for one second and then goes out.

 - Switch is pressed and held - LED lights for one second then turns off even when switch is held on.

 - Other variants are possible.

At present it will not do any of these.

_____________________

ISSUES:
-

(1) You have assigned

> long previousMillis = 0;

This should be

> unsigned long previousMillis = 0;

Mixing the two types gives an uncertain result. At best, an error will occur when the value returned by millis() exceeds the length of a "long" data type and when types are mixed there is no guarantee that the result will be valid.

______________________

(2) I have not checked it, but I'd be wary of the line

> if(currentMillis - previousMillis > interval)

as it depend on operator precedence of the "-" being implemented prior to the ">" comparison.
ie this could potentially evaluate as either

" (A-B) > C " .... which is what you intend,
or
" A - (B > C) " .... which, while it is not what is intended, does have a valid if not useful result.

You can rely on operator precedence if you have confidence in yourself and the system or make it explicit as in eg

> if( (currentMillis - previousMillis) > interval)

______________________

**Making things easier for yourself:**

This has been edited to match my main conclusion which was already covered above (the problem was not nesting but a test that can never fail - as covered above) but the formatting  comments are relevant.

Your code is written in a standard (or usual) manner. Some are able to handle such without problem, but I (and many others) find such layout hard to read and, importantly, easy to bury errors in. The following is overdone - I used existing tabs and expanded it in Word :-) - but to me the following makes it immensely more readable. Layout and style are a matter of personal preference, and there are many opinions re what is "best", but something which allows ease of visualisation of program structure is liable to be useful.

The two adjacent lines

>       buttonPush = 1;
>       if (buttonPush == 1){ ...

are logically grouped together when indented like this at make it clearer that the "set then test"   arrangement can never fail so the subsequent "else" where the LED is turned off is never implemented. So the LED must stay on.

![enter image description here][1]

buttonPush = 0; is bolded for unrelated reasons.

  [1]: https://i.stack.imgur.com/vPdVX.jpg


body:
Some code is shown below to illustrate a method for treating three events independently.

This code might not be completely applicable as-is, because the problem description isn't clear about what should happen when a button is pressed and about whether other events to be added to the code are like the one shown there now.  However, if you understand how it works you probably can adjust it to meet any special requirements of your application.

During each pass through the `loop()` routine, the code does the following for each type of event:

>If the event is not currently active (as denoted by `states[i] < debounced`), the code checks whether the event's button has been pressed (or, if its sensor has turned on).  If so, the code increments a debounce counter.  If the event's counter gets up to `debounced`, then the output for the event is turned on, and the event's end-time is stored in an array entry.
>
>If the event *is* currently active (as denoted by `states[i] >= debounced`), the code tests if the event's end-time has arrived; if so, it turns off the event's output bit and resets its state to 0.

The last statement in `loop()` busy-waits until `milliseconds()` returns a different value than before.  This is done so that switch-debouncing samples are taken at least a millisecond apart.  If your inputs don't need debouncing, you can remove debounce code .

    /* Process three asynchronous activities: Upon a given input going
    true, activate its associated output(s) for specified lengths of time.
    */

    enum { nkinds=3, debounced=5 }; // # of activity kinds;  debounce-criterion
    const byte outPins[nkinds] = {2, 4, 6}; // Output pin numbers
    const byte inPins[nkinds]  = {3, 5, 7}; // Input pin numbers
    const unsigned int actLens[nkinds] = {345, 678, 323}; // Activity lengths, ms
    byte states[nkinds] = {0, 0, 0};
    unsigned long actEnds[nkinds] = {0, 0, 0};

    void setup() {
    // Set input/output modes of pins
      for (byte i=0; i<nkinds; ++i) {
        pinMode(outPins[i], OUTPUT);
        pinMode(inPins[i], INPUT);
      }
    }

    // Once per millisecond, for each kind of activity
    // check for new beginning or deal with ongoing action
    void loop() {
      unsigned long now = millis();
      for (byte i=0; i<nkinds; ++i) {
        if (states[i] < debounced) {  // Is activity off?
          // It's off, look for a turnon
          if (digitalRead(inPins[i])) {
            ++states[i];        // Button is closed at the moment
            // See if button has been debounced
            if (states[i] >= debounced) { // If so, start its action
              digitalWrite(outPins[i], HIGH);
              actEnds[i] = now + actLens[i];
            }
          }
          else {
            states[i] = 0;      // Button is not closed at moment
          }
        }
        else { // It's on, see if end-time has arrived
          if (now >= actEnds[i]) {
            digitalWrite(outPins[i], LOW); // Clear output when done
            states[i] = 0;        // Return to button-seeking state
          }
        }
      }
      while (now == millis()) {};       // Finish current millisecond
    }

The code above compiles ok in the Arduino IDE but I haven't tested it on an Arduino device.

Note, larger systems with numerous events will use priority queues to implement lower-overhead versions of the same ideas.


body:
The direct answer to your first question (LED gets stuck) after formatting and summarizing a section of your code:

      buttonPush = 1;
      if (buttonPush == 1){
         ...
      }
      else {
         digitalWrite(ledPin, LOW);
      }

is that there's a logic error. You can see that the else clause, turning off the LED, will never be executed because buttonPush is always 1 before you enter this section. I think this is the point @RussellMcMahon was trying to make.

The answer to your second question, needing several of these running at once, is: Get the first one to work first. Then simplify it as much as you can. Then you can choose between using polling loop (repeatedly reading the clock and deciding whether it's time to do something) or setting interrupts (making the clock interrupt your main program to run the routine that does the "something").


body:
The simplest way I can think of is something like this:

    unsigned long lastPress = 0;
    unsigned long stateOneTime = 2000; //runs until two seconds elapse
    unsigned long stateTwoTime = 4000; //runs after state one until 4 seconds from first press
    ...
    if(/*input is active*/) lastPress = millis();
    ...
    if(millis() - lastPress < stateOneTime){
        //set output for first state
        //active for 2 seconds
    } else if (millis() - lastPress < stateTwoTime){
        //set output for second state
        //active an additional 2 seconds
    } else {
        //set output to the "off" state
    }

Many improvments could be made, like going more of a state machine route (separating the time checks from the branches) or paramaterizing the state lengths better (durations would make more sense than total time from start, but be slightly more complicated to code).

I think the key to making your life easier while working on this code will be separating the input segment from the output segment. It will help keep the code easy to read and modular.


message:
Arduino serial monitor first message

I'm connect arduino to my PC through serial monitor. Very common situation:

    Serial.begin(9600);
    delay(100);
    Serial.print("Hello, World!");

But I always get an `¤ello, World!`. How can I get the first symbol straight? I've tried on both unix & windows, mega & uno. I've also tried `println`, but with no happiness

body:
I'd have to be pretty quick to connect my serial monitor to see immediate terminal output from my program, if that output uses the same USB I used to load the program. You can test this by resetting the Arduino so it will repeat the output and see if you get a clear message this time. So I leave a couple of seconds' delay in the code to let the slow human catch up. Most of my devices announce their name and code-version on the serial I/O and flash a quick "I'm here" on the LED (if I chose to attach one) when they first wake up:

    const char IdString[] = "Hello.cpp: $Revision: 1.3 $";

    void setup(void)
    {
       Serial.begin(57600);            // open serial port

       // Identify to the terminal
       delay(2000);
       Serial.println(IdString);       // hello (terminal)

       // Init LED pin
       pinMode(LED_PIN, OUTPUT);
       digitalWrite(LED_PIN, LOW);

       nblink(4);                      // hello (LED)
       ...


body:
This is more a wild guess than a real answer... Assuming your terminal
is using a character set more or less like ISO-8859-1 or Windows-1252,
then you are receiving 0xA4 when you expect 0x48. My guess is that the
very first start bit got lost somehow.

Here are the serial port waveforms corresponding to the expected and
received bytes. ‘S’ and ‘T’ are the start bit and stop bit respectively.
The data bits are sent least-significant first. The idle state is HIGH:

• ‘H’ = 0x48 = 0b01001000

    ────┐               ┌───┐       ┌───┐   ┌──────
        │ S   0   0   0 │ 1 │ 0   0 │ 1 │ 0 │ T
        └───────────────┘   └───────┘   └───┘

• ‘¤’ = 0xA4 = 0b10100100

    ────┐           ┌───┐       ┌───┐   ┌──────────
        │ S   0   0 │ 1 │ 0   0 │ 1 │ 0 │ 1   T
        └───────────┘   └───────┘   └───┘

You can see that, if you remove the start bit from the first waveform,
you get exactly the second one. I do not know what may be the cause of
this though.


body:
See the following article:

http://www.arduino.cc/en/Main/ArduinoBoardNano

See the section at the bottom called:

Automatic (Software) Reset

Basically, one has to delay for 1 second (at least) after initializing the serial port before you can read data.  It seems that the Arduino makes an assumption that after the serial port is initialized, what may happen next is a request to load a program.  As such, it looks for a period of time (I guess up to a second) for a string of magic characters that indicate a program load.  If it doesn't find those, then it starts to behave as you would expect ... but only after it times out looking for a program load.


message:
How to read info from an Xbee Pro S2B to an Arduino with a Xbee Pro S2B

I am using two XBee Pro S2B modules. One (Router) connected to the laptop via a UART cable. The other (Coordinator) connected to an Arduino Mega with the sketch below.  All I need it to do is turn a LED on and off and display the status in the IDE serial monitor.  I am using Arduino IDE (v1.6.0).

Arduino sketch:

    #include <SoftwareSerial.h>

    SoftwareSerial xbee (2,3);

    int myData = 0;
    int ledPin = 13;

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

        pinMode(ledPin, OUTPUT);
    }

    void loop()
    {
        if (Serial.available())
        {
             int myData = Serial.read();

             if(myData == '1')
             {
                 digitalWrite(ledPin,HIGH);
                 Serial.write(myData, DEC);
             }
             if(myData == '2')
             {
                 digitalWrite(ledPin,LOW);
                 Serial.write(myData, DEC);
             }
         }
     }

Where did I go wrong?

body:
You have two serial connections. One for the main USB of the board and one for the XBee.

So you need to read from the XBee and write to the serial USB?

I don't know what speed you have configured for your XBee so I have set it to 9600.

This example reads from the XBee and writes to the Serial/USB port

    #include <SoftwareSerial.h>

    SoftwareSerial xbee (2,3);

    int myData = 0;
    int ledPin = 13;

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

        pinMode(ledPin, OUTPUT);
    }

    void loop()
    {
        if (xbee.available())
        {

             int myData = xbee.read();

             Serial.print("Data has arrived on the Arduino");
             Serial.write(myData);
             Serial.println();

             if(myData == '1')
             {
                 digitalWrite(ledPin,HIGH);
                 Serial.write(myData);
             }
             if(myData == '2')
             {
                 digitalWrite(ledPin,LOW);
                 Serial.write(myData);
             }
         }
     }

Note: Your example also used `Serial.write()` with the wrong argument `DEC` which applies to `Serial.print()`. X-CTU and Arduino both send ascii which is also what the `Serial.print()` does. However the `Serial.read()` just reads the byte so we need to use `Serial.write()` to send the same bytes back to the other end.

You can also make life a bit easier by replacing `xbee.available()` with `Serial.available()`. Then use the Arduino IDE serial monitor to both send and receive. This means that you just use the one USB connection to prove the code.


message:
mega include a library

This question is a little related to this one: https://arduino.stackexchange.com/questions/9702/how-to-compile-and-upload-the-specific-cpp-h-code

I've installed [MdbBillValidator](https://github.com/justintconroy/MdbBillValidator) to my arduino libraries collection. I tried both on ubuntu & windows.

How can I include it? Default inclusion, by arduino ide, was:

    #include <MdbSerial.h>
    #include <wiring_private.h>
    #include <MdbBillValidator.h>
    #include <MdbMaster.h>
    #include <Arduino.h>

    void loop() {

    }

    void setup() {

    }

And here is error comes in:

    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: In function ‘void __vector_37()’:
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:289:23: error: ‘TXB8’ was not declared in this scope
           UCSR1B |= (1 << TXB8);
                           ^
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:291:24: error: ‘TXB8’ was not declared in this scope
           UCSR1B &= ~(1 << TXB8);
                            ^
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: In function ‘void __vector_52()’:
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:314:23: error: ‘TXB8’ was not declared in this scope
           UCSR2B |= (1 << TXB8);
                           ^
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:316:24: error: ‘TXB8’ was not declared in this scope
           UCSR2B &= ~(1 << TXB8);
                            ^
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: In function ‘void __vector_55()’:
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:339:23: error: ‘TXB8’ was not declared in this scope
           UCSR3B |= (1 << TXB8);
                           ^
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:341:24: error: ‘TXB8’ was not declared in this scope
           UCSR3B &= ~(1 << TXB8);
                            ^
    In file included from /usr/lib/avr/include/avr/iom2560.h:38:0,
                     from /usr/lib/avr/include/avr/io.h:160,
                     from /usr/lib/avr/include/avr/pgmspace.h:88,
                     from /home/asiniy/sketchbook/libraries/MdbBillValidator/Arduino.h:8,
                     from /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:31:
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp: At global scope:
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:554:135: error: expected ‘)’ before numeric constant
       MdbSerial MdbPort1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1 UCSZ12, UCSZ11, UCSZ10, UPM11, UPM10, UMSEL11, UMSEL10);
                                                                                ^
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:554:189: error: no matching function for call to ‘MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, int, int, int, int, int, int, int, int, int, int, int)’
       MdbSerial MdbPort1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1 UCSZ12, UCSZ11, UCSZ10, UPM11, UPM10, UMSEL11, UMSEL10);
                                                                                ^
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:554:189: note: candidates are:
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:352:1: note: MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t)
     MdbSerial::MdbSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer,
     ^
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:352:1: note:   candidate expects 20 arguments, 19 provided
    In file included from /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.cpp:38:0:
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.h:52:7: note: MdbSerial::MdbSerial(const MdbSerial&)
     class MdbSerial
           ^
    /home/asiniy/sketchbook/libraries/MdbBillValidator/MdbSerial.h:52:7: note:   candidate expects 1 argument, 19 provided

What I need to do to avoid this error and get the code worked?

body:
Could you try adding this to your program?

    #define RXB8 1
    #define TXB8 0
    #define UPE 2
    #define OVR 3
    #define FE 4
    #define UDRE 5
    #define RXC 7

    #define FRAMING_ERROR (1<<FE)
    #define PARITY_ERROR (1<<UPE)
    #define DATA_OVERRUN (1<<OVR)
    #define DATA_REGISTER_EMPTY (1<<UDRE)
    #define RX_COMPLETE (1<<RXC)

I found someone with similar code, who had these defines and as your code seems to miss/cannot find something, this might fix it.
Though I'm not sure if these defines apply in your specific implementation. For that I should have to see the code where the error is pointing at.


message:
How are PCB's programmed?

So recently I have been looking into prototyping my arduino project and there are a lot of tutorials online on how to take your Arduino and using a software such as Eagle to make a PCB layout but I was wondering how you would get the Arduino program onto that PCB. Surely in large scale circuit manufacturing they wouldn't have a usb attached so that they upload a program into each and every one of their circuits?

body:
why not?

Well ok ... they might not connect a USB to each one as there are faster ways - flyingProbe/PogoPins on a "bed of nails"

http://en.wikipedia.org/wiki/In-circuit_test

![enter image description here][1]

This type of temporary connection speeds up testing & pre-programming considerably.

Each card that is made has to go through some form of test process at the end (flying probe or manual).

https://learn.sparkfun.com/tutorials/electronics-assembly

> On boards that require programming or calibration, additional steps
> are taken to load code and verify the output.

  [1]: https://i.stack.imgur.com/QV9BI.jpg


body:
For commercial products where very large quantities are produced, a microcontroller will be "mask programmed" - the (well-debugged) program will be built into the microcontroller as part of the IC production process.

For smaller quantities, the microcontroller may be programmed in a special fixture before being installed on the PC board.  Also, most current microcontrollers have "In System Programming (ISP)" capability, which typically requires a 6 - 10 pin connector on the board, and a special programmer to plug into that board.

I think it is highly unlikely that an Arduino-based program would be used in any commercial product.


body:
Actually, they generally do load a program into each and every one of their devices individually.  They can do a lot more than that as well.  Ever heard of something called JTAG?  For large circuit boards, most of the large ICs are connected to a JTAG scan chain.  Once the board is assembled, they connect a JTAG cable to the scan chain.  Special test software controls the scan chain through the JTAG cable, possibly connected to the control computer via USB.  The software can take control over the I/O pins on the ICs on the scan chain and set test patterns to check for opens or shorts.  It can also perform more complex testing in concert with external test equipment, even including temporarily loading special diagnostic firmware.  Once the test passes, the computer can then initialize ROMs, load firmware, set serial numbers, etc.

This is done one board at a time.  Often, special test and/or programming jigs are built that allow boards to be connected and disconnected quickly, and usually multiple jigs are used in parallel for higher throughput.

For some chips, they can be programmed before installation either with mask ROM or with a standalone programmer.  This is done when volumes are large and testing is not required, or if the devices must be programmed for the automated testing to work correctly.


body:
cheers Brandan :)

I would suggest for you to make your own programmer. Then you will know a lot about programming and so on. If you want to program a chip on pcb, you have to have output pins of ISP. Throw these pins you will pump your code to Atmega chip.

Software [Khazama][1] is "old" and tested one. It really works :) [AVR studio][2] is also good one

Hardware [USBasp][3] There are ready pcb layouts in eagle. Building your own HW will be a bit more expensive than buying one, but if we count in experience it will be priceless :)

 Also you can use bootloader. Check in google there are plenty of tutorials.

  [1]: http://khazama.com/project/programmer/
  [2]: http://www.atmel.com/microsite/atmel_studio6/
  [3]: http://www.fischl.de/usbasp/


message:
Interfacing a CCTV camera (AV output) with Arduino Uno

I have to use a camera to take picture in my major project. I want to use [this](https://i.stack.imgur.com/42CDx.jpg) camera, which has AV output. Please tell me how to interface this camera with my Arduino Uno and use the data from camera and send it to my PC using a Wi-fi Module?

P.S. Please do not suggest me to use wireless camera because firstly they are expensive and secondly I require a board in my project anyway.

body:
Unfortunately, I have to tell you that a UNO isn't enough powerful to work with any type of camera: it hasn't got enough ram and processing power to elaborate your camera's data. ([see atmega328P's specs][1])

I'm not sure you can work with that camera, unless it is digital and has integrated RAM to keep the frames.

A good project which I suggest you to see is [arducam][2].

  [1]: http://www.atmel.com/devices/atmega328.aspx
  [2]: http://www.arducam.com/


message:
I2C or SPI to control 6 motors?

I am a hobbyist & know little about electronics.

I am making a robot arm, like [this one][1]. For which I will need 2 stepper motors (for elbow & shoulder joint) & 4 simple DC motors.

Which means I will need to allocate a lot of pins on my board (Uno).

So I was just reading about I2C & then eventually SPI. My question is:

 1. Is it possible to control 6 motors (or atleast 2 steppers) with I2C or SPI (assuming the motors are powered by seperate source), if so can you point me to someone's example code.
 2. If not possible, how do I overcome the shortage of pins, because I have already dedicated them to many sensors.

  [1]: http://www.lynxmotion.com/c-124-al5a.aspx

body:
For the stepper motors, the easiest way to work with them is by using a very common [A4988 board][1] which is widely used with 3D printers. The controls are very easy and for them I send you [this question][2] which I answered some time ago.

Then, you say that you haven't got a lot of connections left on your UNO board, so I think that SPI would't be very useful, as it takes 3 pins for the data transmission (SCLK, MOSI, MISO) plus one pin for every device you connect.

The best way (even if it is a little slower that SPI) is to use I2C, which needs that you leave unused analog input pins A4 and A5, as they are the I2C BUS. Unfortunately I haven't any knowledge about I2C DC motor drivers.

For the steppers, I suggest to take a look at [this][3], but it depends by your budget for what you can buy.

You could fix the pin shortage problem by adding some [74HC595][4] shift registers. They aren't very expensive (less than a dollar, or if you live in europe, .5€) and they can be daisy-chained. To control them, see the [Arduino website tutorial][5].

Finally, if the pins that you use are inputs, use a [74HC165][6], which is the opposite of a 595. As always, see the [Arduino website tutorial][7].

  [1]: https://www.pololu.com/product/1182
  [2]: https://arduino.stackexchange.com/questions/8965/stepper-motor-controller-using-leonardo-pro-micro/8977#8977
  [3]: http://www.ebay.co.uk/itm/Serial-I2C-Microstepping-Motor-Driver-DC-PWM-CNC-Raspberry-Pi-Aduino-1-2A-/111177026930
  [4]: http://www.nxp.com/documents/data_sheet/74HC_HCT595.pdf
  [5]: http://arduino.cc/en/tutorial/ShiftOut
  [6]: http://www.nxp.com/documents/data_sheet/74HC_HCT165.pdf
  [7]: http://arduino.cc/en/tutorial/ShiftIn


message:
What's the simplest way to get arduino functionality?

I want to control a servo with the least amount of components. But generally, what is the simplest way to do this without actually using a fullblown arduino board?

body:
If you what you're looking for is the cheapest option with the fewer components possible, then you can use a regular ATMega328p chip, with a few passive components attached to it.

You just need to program it with an Arduino Bootloader once, in order to be able to program it easily, but you can use any existing Arduino to do that. After doing this once, you can program it with any FTDI-type USB to Serial converter.

Here's an Instructable that [explains the whole process][1].

  [1]: http://www.instructables.com/id/Program-an-ATmega168328-with-codebender/


body:
Please, take a look at [this guide][1] by Nick Gammon, which explains in detail how to build a breadboard Arduino.

You'll need also an Arduino board without the chip (a good UNO will do the job) because you need to program it some way. It is needed absolutely in the case that you buy an ATMEGA328 that hasn't the bootloader, as you'll have to write it on the blank chip.

To speak directly via serial with the standalone Arduino (and to program it), I suggest you to buy a FT232RL board (just be careful to buy a real one, as there are fakes that FTDI blocked and bricked with drivers)

Then, for the servo you just have to plug it correctly: two cables for power, one for the control.

  [1]: http://www.gammon.com.au/breadboard


body:
This is useful if you don't need all the I/O of the Atmega.

If you want a simple board just to run a servo or two and still have some I/O you could use a ATTiny85 chip and use this [software servo library][1] that works with the attiny. It also works best with the High-Low tech cores.

I used this with a project and it works flawlessly without stalling.

This would give you small setup as you can use the internal clock 8MHz and minimal external components, i.e. regulator and Capacitors.

  [1]: http://projectsfromtech.blogspot.com/2013/03/attiny85-servo-softwareservo-library.html


message:
Don't pee there! Device

I want to make a device with a sensor I can attach to the places my dog likes to mark. When sensor becomes wet I want a buzzer to make a loud noise to scare the animal and notify me I need to encourage the dog to go outside. Any suggestions on what sensor to use.

body:
You probably will want a moisture sensor like [this one][1] (there are many variations of this).

This will return one signal when dry, and another when wet.

You will need a Buzzer to make a sound as well (Or a piezo speaker if you feel like getting more advanced) in order to make a sound.

Your sketch should have, in its `loop`, an `if` statement checking if the moisture sensor has returned the wet signal (The signal will depend on the sensor you get) and, in the block that executes if there is a signal, a statement driving the buzzer and a delay before turning it off.

Bear in mind that you want to keep the Arduino itself away from the moisture sensor, as your Arduino probably won't survive the dog's doings.

  [1]: http://www.ebay.co.uk/itm/like/370999421770?limghlpsr=true&hlpv=2&ops=true&viphx=1&hlpht=true&lpid=108&chn=ps&device=c&adtype=pla&crdt=0&ff3=1&ff11=ICEP3.0.0-L&ff12=67&ff13=80&ff14=108


message:
Switching a dual h bridge in parallel

I'm using a dual h bridge to control two dc motors on an inverted pendulum (cart-pole system).  At the moment, I have to send two different pulse width modulated signals to the two enable pins to control the two motor speeds and four digital write commands to control the directions.

Ideally, I want to switch the two motors simultaneously in the same direction and with the same speed.  So, I'd like to be able to control both motors' speeds with only one pulse width modulation signal and control both motor directions with only two digital write commands.

Is there a way I can do with with Arduino?  Can one PWM signal from a single arduino pin be sent to two enable pins at the same time? Can the same be done for a single digital output pin?  If so, how can I accomplish this?

body: You can connect a single output to as many input loads as you like, provided the current is sufficient to hold the output voltage within the input thresholds. See the datasheet for the H bridge to find out what the input load and thresholds are, and compare them with the output from the Arduino.


message:
Shift registers. What, how and why?

I'm making a project and I'm using multiple 1 digit 7 segment displays. I haven't plugged them all on my arduino because currently I'm just testing. The problem is on the I/O ports. Obviously I need to use shift registers and since it's my first time ever using them I need to know more about them. After googling, I found that the specific model I bought outputs 8 pins and you can stack up to 8 in series. So lets do the math. `8 shift register` x `8 pins each SR` = `64 new pins` It seems cool but assuming I'm using 28 displays let's do the math again.
28 displays, each display has 8 pins (8 for segments and 2 as common cathode)
`28` x `8` = `224` required pins.
Is is possible to expand the I/O pins by 224 pins? How many shift registers can I stack together? Also which is better, the single digit display or the 4 digit display?

body:
You can chain as many shift registers as you want.

Most commonly, these displays are multiplexed. Only one digit is lit at a time, cycling though all the digits fast enough, so the eye can't tell. This is however not very good practice for 28 digits, as the brightness will become 1/28th (though you could create groups of digits, and multiplex those groups separately).

There are specialized chips that do this multiplexing for you. E.g. the Max7219. This chip can multiplex 8 digits, with 8 segments. So you'd need 4 of these to light up 28 digits.


body:
You can buy these displays on eBay for a few dollars. A bit of soldering and you are done (although also pre-assembled ones are available). They can be daisy-chained. Example:

![6 x 4-digit 7-segment display modules][1]

You only need 5 wires to the Arduino: Gnd/5V/MOSI/SCK/SCK.

![modules in operation][2]

Also, 64-dot displays for displaying arbitrary text:

![8x8 LED matrix][3]

Again, only 5 wires.

I have Arduino libraries for driving both sorts of display on [
Interfacing LED displays with the MAX7219 driver ](http://www.gammon.com.au/forum/?id=11516).

  [1]: https://i.stack.imgur.com/dEbzN.jpg
  [2]: https://i.stack.imgur.com/YhNOe.jpg
  [3]: https://i.stack.imgur.com/8Z5oV.jpg


message:
pcDuino 3B Wire library errors

I recently purchased a pcDuino 3B and I am very pleased with the Board so far. I can use the preinstalled arduino IDE to program the board from the board and run programs.

However, when I came to use I2C, it generated a load of errors with the built-in libraries when I tried to compile. I don't know why it did this, it does it when trying to compile any program using I2C. Here is the error list (Yes, I am using an Adafruit display library that works fine with exactly the same sketch on my laptop):

    In file included from /usr/share/arduino/hardware/arduino/pcduino/cores/arduino/Stream.h:26:0,
                     from /usr/share/arduino/hardware/arduino/pcduino/libraries/Wire/Wire.h:9,
                     from Stopwatch_new.ino:1:
    /usr/share/arduino/hardware/arduino/pcduino/cores/arduino/Print.h:47:23: error: ‘byte’ has not been declared
    In file included from Stopwatch_new.ino:1:0:
    /usr/share/arduino/hardware/arduino/pcduino/libraries/Wire/Wire.h:41:23: error: ‘byte’ has not been declared
    Stopwatch_new.ino:5:51: error: cannot allocate an object of abstract type ‘Adafruit_RGBLCDShield’
    /home/ubuntu/Arduino/libraries/AdafruitLCD/Adafruit_RGBLCDShield.h:68:7: note:   because the following virtual functions are pure within ‘Adafruit_RGBLCDShield’:
    /usr/share/arduino/hardware/arduino/pcduino/cores/arduino/Print.h:47:17: note:  virtual int Print::write(int)
    Stopwatch_new.ino:5:23: error: cannot declare variable ‘lcd’ to be of abstract type ‘Adafruit_RGBLCDShield’
    /home/ubuntu/Arduino/libraries/AdafruitLCD/Adafruit_RGBLCDShield.h:68:7: note:   since type ‘Adafruit_RGBLCDShield’ has pure virtual functions
    Stopwatch_new.ino: In function ‘void updateScreen()’:
    Stopwatch_new.ino:125:27: error: call of overloaded ‘String(float&, int)’ is ambiguous
    Stopwatch_new.ino:125:27: note: candidates are:
    /usr/share/arduino/hardware/arduino/pcduino/cores/arduino/WString.h:44:14: note: String::String(unsigned int, unsigned char)
    /usr/share/arduino/hardware/arduino/pcduino/cores/arduino/WString.h:43:14: note: String::String(int, unsigned char)
    /usr/share/arduino/hardware/arduino/pcduino/cores/arduino/WString.h:42:14: note: String::String(unsigned char, unsigned char)

It seems that no one else is having this issue.

Just to clarify, the issue is not with my code or the library, it compiles fine on my other computer running WINDOWS but same Arduino version (1.5.3), same sketch code and same library code.

Help much appreciated, thanks!

body: It turns out that the libraries for compiling were incomplete. Having copied the libraries for the official IDE, it worked fine.


message:
Can Ultimate GPS module use arduino micro instead of UNO?

i am doing a Ultimate GPS module like this:![enter image description here][1]

it works when i use arduino UNO board, but when I use arduino micro board it doesn't work, so could anyone tell me how to fix it?.By the way I use the example code in GPS library.

UNO: the data looks like messy code
![enter image description here][2]

Micro: didn't give me any time, date or fix
![enter image description here][3]

  [1]: https://i.stack.imgur.com/r87dZ.png
  [2]: https://i.stack.imgur.com/lXlrk.png
  [3]: https://i.stack.imgur.com/U2Xw6.png

body:
The Arduino Uno and Micro, in practice, work almost exactly the same. Just make sure that your wiring is correct (In this photo, the wires go from TX to TX and RX to RX, they should go between TX on one board and RX on the other, and vice versa.

Your code should work on a micro exactly as it does on an Uno. That is one of the best features of Arduino; the ability to port code to another board without much (if any) modification.


body:
Your photo shows the GPS connected to pins 0 and 1 (RX and TX) on the UNO.  But you don't show the sketch you are running.  Do you have it set that way in the sketch?

It turns out the micro and UNO are different in the way those pins work.  From http://arduino.cc/en/Main/arduinoBoardMicro

> Serial: 0 (RX) and 1 (TX).  Used to receive (RX) and transmit (TX) TTL
> serial data using the ATmega32U4 hardware serial capability. Note that
> on the Micro, the Serial class refers to USB (CDC) communication; for
> TTL serial on pins 0 and 1, use the Serial1 class.

This suggests to me that you'd need to change the code to read pins 0 and 1.

Easier is probably to wire it up to pins 2 and 3 and use the defaults in the sketch

    // If using software serial, keep this line enabled
    // (you can change the pin numbers to match your wiring):
    SoftwareSerial mySerial(3, 2);


message:
difference between output pin high and 5v pin

So this might be a total noob question (which admittedly I am) I have a Motor, if I connect it to GND and the 5V output it runs. Ok so far. But if I connect it to GND and a pin set to OUTPUT and HIGH nothing happens. My multimeter reads 5V for both setups, so if 5V come to the motor one way or the other why does one work and one not?

body: That's probably caused by the motor's current consumption. The 5V pin can deliver much more current than the output pin in high state. If you want to switch the motor on/off by software, you need a "hardware driver" for the motor, in the simplest case a power transistor.


message:
How to use an 8x8 LED Matrix?

I have a LED Matrix just like this one

![][1]

  [1]: https://i.stack.imgur.com/S4JeL.jpg
but couldn't find the data sheet for it (1855AS)
I asked around in my country and one guy told me to try attaching one side to 5v and the other to GND. Some LEDs worked fine and others didn't light up at all. In the end one if not more got burned.

So I'm here asking if anyone can tell me a way to figure out how it works.
I would appreciate the help!

body:
You could check from where you have bought it. Maybe they have datasheet.
I found one similar, but before you must check if everything is the same and then do testing with power. [LuckyLight][1]

  [1]: http://www.adafruit.com/datasheets/454datasheet.pdf


body:
As you are testing the correct functionality of LEDs on matrix board, which means the LEDs are multiplexed together. The fastest way to check the pinout is to use a multimeter in continuity test mode and then connect the positive or signal wire ( the red one ) to an fixed pin  (usually start with one ) and the with negative or gnd wire ( the black one ) connect it one by one to the all the remaining pins. When you have finished move the signal wire to the next pin and rescan all the pins, repeat all the steps for every pins on the matrix board.
I don't recommend you to use directly 5v because it can be dangerous and you can damage the LEDs of the matrix display as there isn't a current limiting resistor.


message:
Send \r or \n via phone serial monitor

I have a bluetooth adapter connected to uno, and using a serial monitor on phone.

In the arduino code im debugging there is this line waiting for new line signal in the serial stream:

    char c = SerialBT.read();

    if (c == '\r' || c == '\n'){

no matter what i try sending to via my phone i cant get this to evaluate as true...

if i send \n , i believe it is sending it as 2 chars \ and n , not as a single char.

is this a problem with the phone app or what ?

body: It turns out it was a problem with the android terminal program i was using, by switching to another that specifically has support and options for \n \r things it works now.


message:
Adding a steering servo

I got a Sparkfun Redbot Kit a while back. I ended up building it vanilla and it was a good introduction to the board (the board is basically Uno and a motor shield in one) and the toys that came with it. I figured if could scavenge an RC car, I'd get a more robust redbot. I found an old RC Rock Crawler, it has a basic suspension, two motors, and a steering servo.
Unfortunately, I encountered a problem. The steering servo only has two wires. I loaded the *Servo* -> *Sweep* example that is default in the Arduino IDE to see if I could make it work regardless. I tried all the different all the different wire/header combinations on the servo headers:

 1. When I attach the wires to gnd and # I get a buzzing noise.
 2. When I attach the wires to gnd and pow the servo turns left or, if I swap the wires, it turns right.
 3. When I attach the wires to pow and # nothing happens.

I currently can't take advantage of the servo headers on the board (or at least I don't know how to). I was hoping that I could that there might be a work around, I just don't know what it is.
The obvious answer is that I could run both motors off of only one of the headers and use the other to control the steering (thats how the original board from the car was wired), but I can get a faster car if each motor has its own header, and I'm all about the vroom vroom...

I'm running the whole thing off the default 6v (4 AA) battery pack. I might be able to wire in the extra 2 AA's for the extra 3v but I don't want mess with the wiring on the pack unless I know it's going to work.

I have an accelerometer connected to the A4 A5 header block and the motors connected too (I checked w/o them connected but there was no difference).

![A basic image of all the headers on the RedBot board](https://dlnmh9ip6v2uc.cloudfront.net/assets/7/6/b/4/6/520026ca757b7f2344958fd5.jpg)
*Image courtesy of https://learn.sparkfun.com/tutorials/getting-started-with-the-redbot*
More info on the redbot board https://www.sparkfun.com/products/12097

body:
If the motor you are using has only two wires, and as you described it's response to the direct connection to the power, it can't be a servo. The motor is a normal dc motor.
If you want to control the amount of the turns on your rc car you should try to play with the pwm signal, I don't know if it will work or not but at least you will have tried. And remember not to connect the motor directly on the micro's pin if there no motor pins on your red board.


message:
I have to reload Sketch every time I start my Yun

I am new to Arduino and IoT. I got my hands on a Yun and loaded a simple sketch to subscribe to a topic. I am receiving messages (I have set up a PHP script and broker on a server, which takes care of the messages) and can turn ON and OFF LED, L13. But when I disconnect the Yun from my PC and connect it again (to power it up), it stops receiving messages. I have to load the sketch again to make it work. Here is my code:

    #include <spi.h>
    #include <pubsubclient.h>
    #include <yunclient.h>

    byte server[] = { 192, 168, 1, 196 };
    int port = 1883;
    char* pubTopic = "fromYun";
    char* subTopic = "sensor/light";

    void callback(char* topic, byte* payload, unsigned int length) {
      //convert byte to char
      payload[length] = '\0';
      String strPayload = String((char*)payload);
      // handle message arrived
      if(strPayload == "ON") {
        digitalWrite(13, HIGH);
      } else if(strPayload == "OFF") {
        digitalWrite(13, LOW);
      }
    }

    YunClient yun;
    PubSubClient mqtt(server, port, callback, yun);

    void setup() {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
      Bridge.begin();
      if (mqtt.connect("arduinoClient")) {
        mqtt.publish(pubTopic,"hello world!");
        mqtt.subscribe(subTopic);
      }
    }

    void loop() {
      mqtt.loop();
    }

Am I missing something?

I referred to [this][1] post and PubSubClient -> mqtt_basic.ino for making this ketch.

I don't understand what `mqtt.connect("arduinoClient")` is. I mean, what is this string "arduinoClient"? In one sketch on GitHub I saw it as "yun"...

Any help will be appreciated. Thanks in advance!

EDIT: I am using Mosquitto MQTT.

  [1]: http://jpmens.net/2013/10/15/mqtt-on-the-arduino-yun/

body:
Please explain which messages? Serial port messages or MQTT messages?

The mqtt.connect name "arduinoClient" is the ID name. It depends on the server what the parameters should be. For some servers it can be an empty string and the second parameter should be the account name, and a third parameter for the password/key.

When you upload a sketch, the OpenWrt part is already running. Perhaps there is a problem with `Bridge.begin`. Try to wait 90 seconds before calling `Bridge.begin`. If a 90-second delay makes it work, lower it to 5 seconds, and keep it at 5 seconds.

Perhaps you can use (blinking) LEDs to indicate that the code has finished the `Bridge.begin` or to indicate an error.

When you solve this problem, there will be other problems. Have you updated to the newest firmware for the OpenWrt part? The Arduino Yún might only work with a very simple and small sketch. Don't try to add too many things that use the Bridge. The OpenWrt/linux part is reliable, you can run linux scripts there. The ATmega32U4 part is just like an Arduino Leonardo and is also reliable. It is the combination and the Bridge that causes a never ending chain of problems.

What about the Raspberry Pi? That is reliable. Have you thought about the ESP8266 or ESP32 in Arduino compatible mode? Adafruit has an MQTT server for users, and the Adafruit Feather M0 WiFi seems a very nice board. Anything but the Yún.

My best advice for you is to grab a hammer and destroy the Yún and forget about it. It will make your life so much easier.

(*I just noticed that this is a very old question, sorry, but my answer is still valid*).


message:
interrupt and/or other ressources used by Time functions micros() and delayMicroseconds()

I want to use Arduino Uno (Rev. 3) resp. Arduino Nano for time critical ignition control of a combustion engine. Software is developed under arduino rev. 1.6.2.

The only Arduino system functions i use are micros()  and delayMicroseconds(). I suppose they are implemented by a timer interrupt, which may fire within time critical port polling regions of the program.

What's the maximum runtime for the ISR i have to expect? As long it stays within the range of a few microseconds, say 10 or like, it would be tolerable.

Are there other time ressources used in the background by the arduino system i have to cope with?

body:
Here is the [The ISR code](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c#L47-L65).

Here is the obj-dump:

    000008f6 <__vector_16>:
    #if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
    ISR(TIM0_OVF_vect)
    #else
    ISR(TIMER0_OVF_vect)
    #endif
    {
     8f6: 1f 92        push r1
     8f8: 0f 92        push r0
     8fa: 0f b6        in r0, 0x3f ; 63
     8fc: 0f 92        push r0
     8fe: 11 24        eor r1, r1
     900: 2f 93        push r18
     902: 3f 93        push r19
     904: 8f 93        push r24
     906: 9f 93        push r25
     908: af 93        push r26
     90a: bf 93        push r27
     // copy these to local variables so they can be stored in registers
     // (volatile variables must be read from memory on every access)
     unsigned long m = timer0_millis;
     90c: 80 91 a0 01  lds r24, 0x01A0
     910: 90 91 a1 01  lds r25, 0x01A1
     914: a0 91 a2 01  lds r26, 0x01A2
     918: b0 91 a3 01  lds r27, 0x01A3
     unsigned char f = timer0_fract;
     91c: 30 91 9f 01  lds r19, 0x019F

     m += MILLIS_INC;
     f += FRACT_INC;
     920: 20 e3        ldi r18, 0x30 ; 48
     922: 23 0f        add r18, r19
     if (f >= FRACT_MAX) {
     924: 2d 37        cpi r18, 0x7D ; 125
     926: 20 f4        brcc .+8       ; 0x930 <__stack+0x31>
     // copy these to local variables so they can be stored in registers
     // (volatile variables must be read from memory on every access)
     unsigned long m = timer0_millis;
     unsigned char f = timer0_fract;

     m += MILLIS_INC;
     928: 40 96        adiw r24, 0x10 ; 16
     92a: a1 1d        adc r26, r1
     92c: b1 1d        adc r27, r1
     92e: 05 c0        rjmp .+10      ; 0x93a <__stack+0x3b>
     f += FRACT_INC;
     if (f >= FRACT_MAX) {
      f -= FRACT_MAX;
     930: 23 eb        ldi r18, 0xB3 ; 179
     932: 23 0f        add r18, r19
      m += 1;
     934: 41 96        adiw r24, 0x11 ; 17
     936: a1 1d        adc r26, r1
     938: b1 1d        adc r27, r1
     }

     timer0_fract = f;
     93a: 20 93 9f 01  sts 0x019F, r18
     timer0_millis = m;
     93e: 80 93 a0 01  sts 0x01A0, r24
     942: 90 93 a1 01  sts 0x01A1, r25
     946: a0 93 a2 01  sts 0x01A2, r26
     94a: b0 93 a3 01  sts 0x01A3, r27
     timer0_overflow_count++;
     94e: 80 91 a4 01  lds r24, 0x01A4
     952: 90 91 a5 01  lds r25, 0x01A5
     956: a0 91 a6 01  lds r26, 0x01A6
     95a: b0 91 a7 01  lds r27, 0x01A7
     95e: 01 96        adiw r24, 0x01 ; 1
     960: a1 1d        adc r26, r1
     962: b1 1d        adc r27, r1
     964: 80 93 a4 01  sts 0x01A4, r24
     968: 90 93 a5 01  sts 0x01A5, r25
     96c: a0 93 a6 01  sts 0x01A6, r26
     970: b0 93 a7 01  sts 0x01A7, r27
    }
     974: bf 91        pop r27
     976: af 91        pop r26
     978: 9f 91        pop r25
     97a: 8f 91        pop r24
     97c: 3f 91        pop r19
     97e: 2f 91        pop r18
     980: 0f 90        pop r0
     982: 0f be        out 0x3f, r0 ; 63
     984: 0f 90        pop r0
     986: 1f 90        pop r1
     988: 18 95        reti

I'll let you calculate how many clock cycles that is. My guess is that it's less that 160 clock cycles (i.e. 10S).

But I'm unsure if the accuracy of `micros` is good enough in your application.


message:
How to I measure the duration of touch with a soft potentiometer?

I'm having a soft pot meter here and I would like to register the duration of the touch event. I'm having a different variable, which keeps going from 1024 to 0 , which regularly takes 60 seconds, but for every second you touch the soft pot meter the count adds 50 up to 1024. Like returning the clock backward.

How would I register/code this?

![Softpot meter][1]

  [1]: https://i.stack.imgur.com/NtBgH.jpg

body:
You have to go with timer interrupts. Here is the documentation: http://playground.arduino.cc/code/timer1

Roughly, when you detect a press, an interrupt is raised and the same thing goes for releasing. Using the timer values from both these events, you can accurately measure the time that the press lasted.


message:
IR trouble with raw buffer

I am attempting to send a RAW IR code using the IRremote.h library.  The process for capturing IR pulses is easy to find on the web, but the process for sending them again is not.  After a few days, i pieced the following code together:

    #include <IRremote.h>
     IRsend irsend;

    void setup() {

    }

    void loop() {

      int IRsignal[] = {

    // ON, OFF (in 10's of microseconds)

     90, 86,

     174, 88,

     86, 88,

     86, 88,

     86, 88,

     86, 88,

     86, 88,

     86, 88,

     86, 174,

     88, 86,

     174, 88,

     86, 2340,

     88, 86,

     174, 88,

     86, 88,

     86, 88,

     86, 88,

     86, 88,

     86, 88,

     86, 88,

     86, 174,

     88, 86,

     174, 88,

     86, 0};

          irsend.sendRaw(IRsignal, 10, 38);

          delay(1000);

    }

When I run it, i get the following error:

> ir_test.ino: In function 'void loop()': ir_test.ino:65:38: error:
> invalid conversion from 'int*' to 'unsigned int*' [-fpermissive] In
> file included from ir_test.ino:3:0:
> /Applications/Arduino.app/Contents/Resources/Java/libraries/RobotIRremote/src/IRremote.h:143:8:
> error:   initializing argument 1 of 'void IRsend::sendRaw(unsigned
> int*, int, int)' [-fpermissive]    void sendRaw(unsigned int buf[],
> int len, int hz);
>         ^ Error compiling.

I am not sure what I did wrong, or how to convert the data types.  Any tips or ideas?

body:
Use `unsigned int IRsignal[]` instead.

Also, your array is 48 items long, not 10. So `irsend.sendRaw(IRsignal, 48, 38);`


message:
Problem with declaring 2D vector in Arduino

I have included the STL library in Arduino and i can run a program with 1D vector.
But i am getting error while declaring a 2D vector.

    #include <StandardCplusplus.h>
    #include <serstream>
    #include<vector>
    #include<iterator>

    using namespace std;

    vector <vector<int> > grid;
    vector<int> col(5,3);
    grid.push_back(col);

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

    void loop()
    {
      for(int i = 0; i < 5; i++)
      {
        Serial.println(grid[[0][i]);
      }
    }

And the error is

    'grid' does not name a type.
Do i need to add another header file?

body:
The error is coming from

     grid.push_back(col);

You cannot have this line at the top-most level outside a function / main. Move it inside `setup` or `loop`.


message:
Problem importing a library in .h file

I have following code:

**MyApp.ino**:

    #include "DfRobotLcdShield.h"

    void setup() {
    }

    void loop() {
    }

**DfRobotLcdShield.h**:

    #include <LiquidCrystal.h>

When I try to compile, I'm getting the error:

    In file included from MyApp.ino:1:0:
    c:\temp\build5856181074637812172.tmp\DfRobotLcdShield.h:4:27: fatal error: LiquidCrystal.h: No such file or directory
     #include <LiquidCrystal.h>
                               ^
    compilation terminated.
    Error compiling.

When I add

    #include <LiquidCrystal.h>

directly to the .ino file, it works. I'm using the latest Arduino-IDE 1.6.3.

body:
This seems to be a general problem of the Arduino IDE: It only recognizes libraries that are included in the (primary) `.ino` file.

If you look at the invocation of the compiler, the path to any given library is only added if this library's header file is included in the `.ino` file.

I tested this with the EEPROM library. If this library is included in the `.ino` file, the compiler is called with

    avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/eightanaloginputs -I/usr/share/arduino/libraries/EEPROM /tmp/build2678545434708654378.tmp/test.cpp -o/tmp/build2678545434708654378.tmp/test.cpp.o

where the important part is the `-I/usr/share/arduino/libraries/EEPROM`.

If I now remove `#include <EEPROM.h>` (but still have it in another header file which in turn is included in the `.ino` as in your case), the compiler call changes to

    avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/eightanaloginputs /tmp/build2678545434708654378.tmp/test.cpp -o/tmp/build2678545434708654378.tmp/test.cpp.o

where now the include path to the library is missing.

## TL;DR ##
If you need to use a library, just (also) add an include to the `.ino` file. It doesn't cost you anything and will solve your problem ;)

----------
### `#include <file>` vs. `#include "file"` ###
From the [gcc documentation][1]:

 - *#include <file>* is used for system header files. It searches for a file named file in a standard list of system directories. [...]
 - *#include "file"* is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>. [...]

  [1]: https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html


message:
What is the size of the buffer in serial communication with arduino uno?

as it is in the question, i need to know what is the size of the biggest string that i can send using the serial port to the arduino.
Thank you

body: That would be 64 bytes, providing the buffer is fully empty. See https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.h#L42-L43


message:
Calculating time between Serial events

I am trying to calculate time between two serial events. Using Arduino UNO R3 with 16MHz default clock source.
I am using timer 1 with pre-scale of 64 to get time per one count = 4000ns. This i am choosing at random without any specific reason.
Sending character 'o' to start the timer and character 'k' to stop it and hence calculate the time in between. The ISR routine calculates how much times the timer overflows.
The code is:

        unsigned int t;
    unsigned int c;
    char r;
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1 = 0;

      TIMSK1 = (1<<TOIE1);//enable timer overflow interrupt
      sei();
      //SREG = (1<<8);//enable global inteerupt
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(Serial.available()>0)
      {
        r=Serial.read();
      if(r=='o')
      {
        TCNT1=0;
        TCCR1B |= (1<<CS11)|(1<<CS10);//64 pre-scale & start
        Serial.println(TCNT1);
      }
      else if(r=='k')
      {
        Serial.println(TCNT1);
        TCCR1B = 0;//stop timer
        t=TCNT1+(c*65536);
        t=t*(4*10^(-9));
        Serial.print("overflows = ");
        Serial.println(c);
        Serial.print("time = ");
        Serial.println(t);
        c=0;
        t=0;
      }
      }
    }//loop

    ISR(TIMER1_OVF_vect)
    {
      c++;
    }//isr

But, on serial monitor only the block of if(Serial.read()=='o').... is executing. The flow does not enter the second else if block.

What is wrong with this code? How long does the Serial buffer hold its vale ?

**EDIT:** I got the code working for checking for 'k'. But the timer value it calculates is very less than compared to what it should be. Is anything wrong with the timer settings. Setting CS10=CS11=1 gets the pre-scaler value to 64.

  Hence, the time for 1 count should be = 1/(16MHz/64) .

Is anything wrong with this?

body:
I'd read the result of `Serial.read()` to a variable and check this variable, because otherwise the first `Serial.read()` will have already read the 'k'. I reckon you can remove the `Serial.available()` check.

    void loop() {
  int chr = Serial.read();
  if(chr=='o')
  {
   TCNT1=0;
   TCCR1B |= (1<<CS11)|(1<<CS10);//64 pre-scale & start
  }
  else if(chr=='k')
  {
   t=TCNT1;
   TCCR1B = 0;//stop timer
   t=t+(c*65536);
   c=0;
   Serial.println(t);
   t=0;
  }
    }//loop


message:
Tone inside interrupt

I am trying to play a tone with a buzzer connected on an arduino nano pin. I have also connected a reed switch with INPUT_PULLUP on INT0 and a led. The program loops continuously (it's an environmental monitor and alarm personal project) until the reed switch is set on HIGH where a function is called and the buzzer should play an one-second high pitch tone.

    void doorStateChange() {
      static unsigned long last_interrupt_time = 0;
      unsigned long interrupt_time = millis();
      if (interrupt_time - last_interrupt_time > 1000)
      {
        led_B_state   = !led_B_state;
        digitalWrite(buzzPin, HIGH);
        digitalWrite(led_A_Pin, HIGH);

        if (millis() - interrupt_time <= 1000 ){
            digitalWrite(buzzPin, LOW);
            digitalWrite(led_A_Pin, LOW);
        }

      }
      last_interrupt_time = interrupt_time;
    }

The interrupt is called, the Led lights up but I can't make the buzzer sound right. I 've tried with ```   tone(buzzPin, 5000, 1000); ``` but seems that the delay does not work - The sound is heard but after the 1000ms it continuous to work in a different tone (strange?).

The only way I could make it work is with ``` buzzPin_state = ! buzzPin_state; ``` where the buzzer beeps as long as the reed switch is HIGH.

I also need to say that ``` attachInterrupt(0, doorStateChange, CHANGE); ```.

The information I get from googling this issue is gibberish: some say that delays don't run in interrupts, others call external functions etc.

What is the proper way to achieve this ?

body:
Don't do delay() calls inside an ISR. In all probability it will hang indefinitely. If you want to play the tone for a second all you need to do in the ISR is set a flag, which you test in the main loop. Turn the buzzer on when the flag changes state. Remember when you did that. When a second is up turn the buzzer off again.

In fact in your case you probably don't need the interrupt at all. Test for the reed switch change in the main loop as well. Don't overcomplicate it.


message:
How to Communicate between arduinos wirelessly?

I am doing a project where I need to send some numbers between arduinos. But it has to be wirelessly because they will be moving. How to Communicate between arduinos wirelessly? I need to send data between them. Wifi would be preferred.

Thank You.

body:
You can use XBees. They are powerful and do provide wifi connections (the recent versions).

And you rely on well-designed devices which guarantee packet retransmission and they achieve up to 1km in an open field.

XBee still works with serial communications making them an excellent tool for your embedded project.

Just plug your Arduinos and write code to send/receive data. This [library][1] is a good start point for API mode.

If you don't mind using all the benefits from ZigBee protocol, just use AT mode where all you push in one side is sent to another via serial communication.

  [1]: https://code.google.com/p/xbee-arduino/


body:
As has been mentioned in the comments, you have at least three possible solutions:

 - Wifi using the ESP8266
 - Private protocol using the nRF24
 - Bluetooth using the HC-05

All of these will handle 20 feet of separation.  All of these have high quality libraries for Arduinos and lots of free tutorials and assistance via forums and Stack Exchanges.

Some of the primary differences are price, size of data and power consumption.

My personal weapon of choice, and not knowing anything further about your project ... is the nRF24.  This is crazy cheap and pretty easy to use.  It also benefits from no need for a Wifi access point and also has a broadcast capability so that multiple devices can receive the same message.  The down sides are that it is a private protocol that your phone and laptop can't decode natively (it isn't WiFi).

My second choice would be Bluetooth.  This would allow your phone and laptop to be transmitters and receivers as there are plenty of great Bluetooth terminal emulators available.


message:
Using Arduino Micro With 12V Buzzer

I have an interesting situation.  I wonder if anyone can help?

I have:

 - 4x Arduino Micros loaded with the basic Blink sketch
 - 5x [12 volt buzzers][1]
 - A desk full of completely fresh Duracell AA and 9v batteries

If I connect (using VIN and GND) any of the Arduino Micros to either a 9v battery, or a 12v network of 8 AA batteries, then they run the blink sketch, and the appropriate LED flashes on the Arduino as expected.

If I connect any of the buzzers to either a 9v battery, or a 12v network of 8 AA batteries, then they buzz as expected.

If I connect both a buzzer and an Arduino in parallel to either a 9v battery, or a 12v network of 8 AA batteries, then the Arduino works fine, **but the buzzer makes barely an inaudible whimper**.

If I connect only a buzzer to the Arduino and battery, it works fine.  If whilst the buzzer is buzzing I connect the Arduino, then on every ON or OFF of the blink sketch LED, the buzzer gets quieter and quieter until it can barely be heard.

These buzzers are rated to work at 25mA, so it really astounds me that they can't be run off a battery together with an Arduino.

Any help would be appreciated!

Thanks

Dave

  [1]: http://uk.rs-online.com/web/p/magnetic-buzzer-components/7243184/

body:
Attach your voltmeter across the battery, and measure the available voltage when different things are attached; or attach it in series, and measure current draws.  You probably will find that a 9V battery's voltage is under 8 volts when a mix of multiple Arduinos and buzzers is attached.  That voltage may be too low to activate the buzzer.

A powerstream.com web page called *[9V Alkaline tests](http://www.powerstream.com/9V-Alkaline-tests.htm)* shows how rapidly a 9V battery's voltage drops when heavy currents (more than a few dozen milliamps) are drawn from it, and a batteriesinaflash.com [web page](http://www.batteriesinaflash.com/lithium/9v/12x-ultralife-9v-lithium-battery-1200mah-for-alarm-home-safety) includes the following diagram that shows battery voltage quickly falling below 8.5 V in its first minutes of life when 27 mA is drawn from it. ![9v-lithium-comparison.gif][1]

For some models of Arduino, eg the [Uno R3](http://arduino.cc/en/main/arduinoBoardUno), various [posts on the web](http://forum.arduino.cc/index.php?topic=5536.0) list currents from 25 mA up to 45 mA, depending on LED and sleep settings.  Currents for the [Duemilanove](http://arduino.cc/en/Main/arduinoBoardDuemilanove) from 10 mA up are reported.  The [Arduino Micros](http://arduino.cc/en/Main/arduinoBoardMicro) in your tests probably use a little more current than [Pro Mini](http://arduino.cc/en/Main/arduinoBoardProMini) boards (which have no USB), and although it's unlikely they will use as much or more current than the buzzers, they still may drag the voltage down to a level where the buzzers won't work.

If your system needs to be battery powered, consider using separate batteries for different devices, to avoid problems like you saw.  Alternatively, use heavier-duty batteries, eg [good-sized lithium-polymer units](https://en.wikipedia.org/wiki/List_of_battery_sizes#Cylindrical_lithium-ion_rechargeable).  Also review posts about decreasing Arduino power usage via sleep, disconnecting the power LED, and using large capacitors to buffer power surges.

*Edit:* Given that voltage measurements show enough voltage being available, the suggested use of capacitors or inductors to isolate circuits may be a good idea.

When adding a capacitor, locate it physically close to the power-using board or component.  For electrolytic  capacitors, attach the capacitor's + terminal to the high side, eg to the +5, +9, or +12 side, and attach its - terminal to ground.

When adding ferrite beads, wrap the supply wire through the bead several times, if there's room.  The picture below illustrates the idea.

An electrolytic capacitor across a circuit acts as a voltage reservoir.  It also gives high-frequency signals an easy path to ground, reducing interference.  A ferrite bead or other inductor impedes high frequency signals, again reducing interference.

![enter image description here][2]

  [1]: https://i.stack.imgur.com/egLKW.gif
  [2]: https://i.stack.imgur.com/T9qkj.jpg


message:
How to prevent file overwriting in processing?

i am working on this arduino project using processing. There are some sensor values which should be logged, but unfortunately my processing code rewrites the file after each cycle so that i get the last sensor value only. How do i prevent this from happening? I am using the ordinary method by the way. PrintWriter command followed by createWriter

body:
`PrintWriter pw = new PrintWriter(new FileOutputStream(
    new File("persons.txt"),
    true /* append = true */)); `

The `true` is the append mode flag.
Also check if you're using

`pw.append(p.toString());
        pw.append("sdf");`

https://stackoverflow.com/questions/8210616/printwriter-append-method-not-appending


message:
RTC and SD work separately but not together

I am running a small project. I want to use an Arduino Mega 2560 v3, a PIR sensor, a micro SD card module, an RTC 1307 module, some LEDs, buttons and a buzzer. To enable and disable motion detection and when detection is found the time is saved to the SD card.

I wired everything together, coded and started to test. During tests, Arduino on bootup was restarting over and over. First, I was thinking that the problem is in the breadboard and connection. I checked it a few times and I didn't notice anything wrong. So I checked the code over and over. Still nothing.

So I started to test modules. And I found a problem. When I don't use in the sketch either the RTC or the SD card (physically they are still connected, because I am lazy) everything works fine. Arduino doesn't restart. I didn't use the SD module to write data, instead I used the serial port to show data. Everything works fine: I can see at what time is motion detected and Arduino prints it on the terminal.

In the second scenario, I didn’t use the RTC, only the SD module. This time again everything works fine. On the SD card I could read how many times motion was detected. This is weird because when I mix all together it doesn't work.

Here is my code:

    // *********************************************
    // INCLUDE
    // *********************************************
    #include <Wire.h>
    #include <SD.h>
    #include <SPI.h>
    #include "RTClib.h"
    // *********************************************
    // DEFINE
    // *********************************************
    #define GREENLED 39
    #define BTNON 11
    #define REDLED 41
    #define BTNOFF 9
    #define BUZZ 3
    #define PIR_PIN 10
    //SD (na mega)
    #define SD_CLK_SD 52
    #define SD_MI 50
    #define SD_MO 51
    #define SD_CS 4

    //RTC
    #define RTC_SDA 20
    #define RTC_SCL 21
    #define RTC_DS 2

    // *********************************************
    // VARIABLES
    // *********************************************
    RTC_DS1307 rtc;
    File myFile;
    char godz[8];
    char data[5];

    int btnON;
    int btnOFF;
    int pirD;
    bool stan_alarmu;

    void wlAlarmu() {
      digitalWrite(REDLED,LOW);
      digitalWrite(GREENLED, HIGH);
      stan_alarmu=true;
      gettime();
      myFile = SD.open("dane.txt", FILE_WRITE);
      if (myFile) {
        myFile.print("### Wlaczenie alarmu ### ");
        myFile.print(" ");
        myFile.print(godz);
        myFile.print(data);
        myFile.println("");
        myFile.close();
      }
    }

    void wylAlarmu(){
      digitalWrite(GREENLED, LOW);
      digitalWrite(REDLED,HIGH);
      stan_alarmu=false;
      gettime();
      myFile = SD.open("dane.txt", FILE_WRITE);
      if (myFile) {
        myFile.print("### Wylaczenie alarmu ### ");
        myFile.print(" ");
        myFile.print(godz);
        myFile.print(data);
        myFile.println("");
        myFile.close();
      }
    }

    void alarm(){
      digitalWrite(GREENLED,LOW);
      digitalWrite(REDLED,HIGH);
      digitalWrite(BUZZ,HIGH);
      delay(500);
      digitalWrite(BUZZ,LOW);

      gettime();
      myFile = SD.open("dane.txt", FILE_WRITE);
      if (myFile) {
        myFile.print("Alarm: ");
        myFile.print(" ");
        myFile.print(godz);
        myFile.print(data);
        myFile.println("");
        myFile.close();
      }
      delay(5000);
      digitalWrite(REDLED,LOW);
      digitalWrite(GREENLED,HIGH);
    }

    void blad() {
      while(1){
        digitalWrite(REDLED,HIGH);
        delay(500);
        digitalWrite(REDLED,LOW);
        delay(500);
      }
    }

    void gettime() {
      DateTime now = rtc.now();
      sprintf(godz,"d:d:d ",now.hour(),now.minute(),now.second());
      sprintf(data,"%d.%d",now.day(),now.month());
    }

    // *********************************************
    // SETUP
    // *********************************************
    void setup() {
      //RTC
      Wire.begin();
      // Shield I2C pins connect to alt I2C bus on Arduino Due
      rtc.begin();
      if (!rtc.isrunning()) {
        blad();
        // following line sets the RTC to the date & time this sketch was compiled
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
      }
      pinMode(BTNON,INPUT);
      pinMode(GREENLED, OUTPUT);
      pinMode(BTNOFF,INPUT);
      pinMode(REDLED, OUTPUT);
      pinMode(PIR_PIN,INPUT);
      pinMode(BUZZ,OUTPUT);

      //test seq
      digitalWrite(GREENLED,HIGH);
      digitalWrite(REDLED,HIGH);
      digitalWrite(BUZZ,HIGH);
      delay(100);
      digitalWrite(BUZZ,LOW);
      digitalWrite(GREENLED,LOW);
      digitalWrite(REDLED,LOW);
      delay(500);
      pinMode(SD_CS, OUTPUT);
      if (!SD.begin(SD_CS)) {
        blad();
      }
      digitalWrite(GREENLED,HIGH);
      delay(1000);
      digitalWrite(GREENLED,LOW);
      gettime();
      Serial.begin(9600);

      myFile = SD.open("dane.txt", FILE_WRITE);
      if (myFile) {
        myFile.print("####START SYSTEMU: ");
        myFile.print(godz);
        myFile.print(data);
        myFile.print(" ####");
        myFile.println("");
        myFile.close();
      }
      wylAlarmu();
    }

    void loop() {
      btnON = digitalRead(BTNON);
      btnOFF = digitalRead(BTNOFF);
      pirD = digitalRead(PIR_PIN);

      if(btnON == HIGH) {
        wlAlarmu();
        delay(2000);
      }
      if(btnOFF == HIGH) {
        wylAlarmu();
        delay(2000);
      }

      if(pirD==HIGH && stan_alarmu==true) {
        alarm();
      }
      delay(1000);
    }

body:
You should start to debug your code stepwise. I.e. insert debug output commands (print via serial) at some crucial points to find the block of code which resets your device. Then narrow it down, until you know the very command which breaks your setup.

Maybe, there will be more than one point in your software, which is responsible for the failure. Nonetheless you will be wiser after that.

Then you will probably have to dive into the guts of the libraries.

If you have identified some command or procedure call responsible for the reboot, it may be still a hardware issue. Writing SD-cards consumes considerable amount of power. If you supply your device solely via USB, I recommend buying an additional PSU and see, if the behaviour changes.

The next thing is to check the reset-signal on all of your shields and daughter-boards for unwanted connections like solder-bridges or single wire threads snipped of elswhere. Another funny thing are stacking connectors not matching the mainboard and shorting something on it.


body:
Are you using breakout boards as pictured in your links? Or Arduino shields?

Many Uno shields are almost, but not quite, compatible with Mega boards. It is possible there there is one or more pins that are not compatible between them.

If you're using breakout boards, double check all of the connections to the Mega. Could something be dragging down your power supply? Or actually grounding the reset pin? It would probably be one of the programmable I/O pins since the failure only depended on whether you used the SD library and seems not affected by the mere presence of the board.


body:
A common issue when using strings (character vectors) is that the vector size is not updated when the format is update. Check the size required for this data. Does it fit for the sprintf() statements?

    char godz[8];
    char data[5];

    void gettime()
    {
      DateTime now = rtc.now();
      sprintf(godz,"d:d:d ",now.hour(),now.minute(),now.second());
      sprintf(data,"%d.%d",now.day(),now.month());
    }

What is the worst case size required?

Cheers!


body:
I ran into the same problem lately. I have a work-around but don't have a clear explanation of this problem. As you initialize the different modules in your `setup()`, make sure to perform the SD card initialization first, then followed by the RTC's. Doing this completely sorted me out. However, I am yet to explain these results.

Though it is late, just in case anyone else runs into the same problem.


body:
When using Catalex Micro SD Card module, there is a problem with the MISO output. It is not disabled on the SPI bus because of a hardware failure. To correct the problem pin 13 on the IC must be liftet from ground connection and put together with pin 8, that have the CS signal. Now the Card Works fine with other SPI modules. Take care when soldering - it is very small pins.
Best regards OZ7LM Leif


body:
It is too late to answer but I had the same issue and spent a week to solve it. This will not be the exact solution. It worked and I think this is the easiest way to solve it.

First let me tell you my components:

- WeMos D1 R2 (ESP8266)
- MicroSD Card Adapter
- DS3231 RTC (I tried with DS1302 but it did not work).

How I solved is, on setup part, first I initialized the RTC DS3231 then I set the built in Arduino clock to DS3231 RTC values. After that I initialized SD card. In this case you are not able to get RTC data in loop but you have it in built in Arduino clock and SD card works. If your Arduino lose electricity, then it will get the RTC data in setup again.

This solution solves it in someway.

Also there is no tutorial for how to connect these cards to WeMos D1 R2 so I want to share my connections.

    SD Card    WeMos D1 R2
    -------    -----------
    SC      -> D14/SDA/D5
    SCK     -> D13/SCK
    MOSI    -> D11/MOSI
    MISO    -> D12/MISO
    VCC     -> 5V
    GND     -> GND

    RTC DS3231   WeMos
    ----------   -----
    SCL        -> SCL/D15
    SDA        -> SDA/D14
    VCC        -> 3.3V
    GND        -> GND

Also my code:

<!-- language: lang-c++ -->

    #include <Wire.h>
    #include "RTClib.h"
    #include <SD.h> //Load SD library
    #include <SPI.h>
    #include <time.h>
    #include <TimeLib.h>
    File file;
    int chipSelect = 5;
    RTC_DS3231 rtc;
    bool not1024prev;
    unsigned long timepast;
    unsigned long timecurr;
    int cnt = 0;
    int rpm;

    char daysOfTheWeek[7][12] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

    void setup()
    {

    #ifndef ESP8266
        while (!Serial)
            ; // for Leonardo/Micro/Zero
    #endif

        Serial.begin(9600);

        delay(3000); // wait for console opening

        if (!rtc.begin()) {
            Serial.println("Couldn't find RTC");
            while (1)
                ;
        }

        if (rtc.lostPower()) {
            Serial.println("RTC lost power, lets set the time!");
            // following line sets the RTC to the date & time this sketch was compiled
            //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
            // This line sets the RTC with an explicit date & time, for example to set
            // January 21, 2014 at 3am you would call:
            //rtc.adjust(DateTime(2018, 3, 11, 16, 29, 30));
        }
        DateTime now = rtc.now();
        setTime(now.hour(), now.minute(), now.second(), now.day(), now.month(), now.year());

        if (!SD.begin(chipSelect)) { // Initialize SD card
            Serial.println("Could not initialize SD card."); // if return value is false, something went wrong.
        }
    }

    void loop()
    {
        String curtime = String(year()) + "." + String(month()) + "." + String(day()) + "-" + String(hour()) + ":" + String(minute()) + ":" + String(second());

        Serial.println(curtime);
    }