text:
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.

An overall word specification or just maybe simple pseudo code will help us see exactly how this is intended to work and help you visualise what needs doing where. You have right general ideas and millis() is gpoing to do what you want. Just needs tidying.

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.

To create a behavior of toggling between two inputs, for example, LED 1 is on and when a button is pressed LED 1 turns off and LED 2 turns on for a specified amount of time then turns off and LED 1 turns on until the button is pressed again, I could specify a second set of outputs to then be able to toggle between the two correct? I am trying to wrap my head around how the code you posted works so I can understand the structure.

My apologies, when I first breadboarded the circuit I accidentally jumpered the pushbuttons which gave me a constant "on". This sketch works well. I am going to set up "outPinsB" and toggle their state on at the point where "outPins" are turned off.

Yes, you can specify sets of other output pins for follow-on actions.  If you need more states and additional time delays, you can add if statements after the last else and detect state values like debounced, debounced+1, etc.

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.

buttonPush = 0; is bolded for unrelated reasons.

previousMillis = millis(); should be changed to previousMillis = currentMillis;

@portforwardpodcast - arguably yes - what I show is his original code. As millis() increments at 1 ms intervals, in most systems currentMillis() and millis() will be identical as the time taken from the timer read at the top of the loop to this point will take << 1 mS.(You can be unlucky and have the timer roll over in the few uS involved.) BUT in a system with user interrupts running and heavy background load millis() and currentMillis() may be different. Even then the result is that there is an extra delay in the next timeout equal to the time spent in the interrupt routine.

All of what you said in your comment points to not calling millis() a second time

@portforwardpodcast AGAIN :-) arguably yes. But also, possibly no. It looks in this case as if the decision process is uncertain enough that the differences are not part of the process. But in some cases there may be reasons to do as is done here for overall reasons. Again, I agree with you that that's probably not the case here - we have not yet even got a functionally fully designed system, but just maybe .... :-)

I am gently astounded that this received two downvotes and 0 upvotes. A downvote is meant to indicate "not useful". | The answer explicitly identified the main current problem - the test for buttonPress when buttonPress is always = 1. That seems useful :-). | The answer identifies a millis() variable related type mismatch which will cause random operation. That seems useful. | And a code line that relies on operator precedence when subtraction and comparison are mixed [ if(currentMillis - previousMillis > interval) ] - that is probably useful.  ...

... Reasons for downvoting do not have to be given. But not doing so in cases like this is unlikely to be useful to the original poster - or to encourage other people to spend the time needed to give quality answers.

I had a feeling that it was getting stuck when I toggled on the buttonPush. I am cleaning up the code to see if I can fix it. I will try to format it better as well. I agree it is a lot easier to see what is happening when it is formatted better than my first attempt.

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").

I'm surprised that my statement "When the button is first pressed you set buttonPush and then immediately test to see if it is set. As it always is the LED never gets turned off as the "else" condition is never met." is not considered clear.  | 'Getting the first one running' is good advice. However, having done so he can extend the principle with relative ease - there is no need to eg alter how clock interrupts are used etc.  ie N routines can independently test whether eg: " ( millis() - lastMillisN) > delayN )" and act accordingly. Doing multiple such comparisons with eg case() would work.

I agree, I was trying to keep it simple, I guess I was thinking that the "else { buttonPush = 0;} would reset the state after the "interval" had run out. It may be overcomplicating it? I guess I have a misunderstanding as to how the loop exits an if statement if the condition isn't met. It was an attempt to toggle the state of that button and as @RussellMcMahon had mentioned, then adding additional ones. I know it will all click in my head as to how the codes function, but the gears upstairs are a little rusty.

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.


text:
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

What happens in you increase the delay?

@Gerben, is this an required option - to make a delay after build? Will try soon

Questions, questions: [1] What happens if you do a second Serial.print(<something>);? [2] What happens if you change the data rates (in code and Serial Monitor)? [3] If you change the first letter (H), does the displayed symbol change too? [4] If it does change, could you edit your question to include a list of half a dozen examples? The character you've shown is not part of neither the standard nor the extended ASCII tables. This suggests an extra byte is being sent or the Serial Monitor is adding the preceeding byte and decoding it along with the 'H'.

I had the same problem when were I sending data from the ptython script. First byte was alway lost. As a workaround I add unnecessery ser.read() before actual communication. ser was the name of the Serial instance.

@chaaarlie2: ‘¤’ is U+00A4. It's a single byte in quite a few 8-bit character sets, including Latin-1, several other ISO-8859 variations, and Windows-1252.

@Edgar Bonet: yes, it appears in the UCS as a replacement for the original ASCII character in most fonts, but it's still not an original ASCII character. Yes, it's unlikely that the serial monitor is taking a double-byte letter, and it's probably the monitor's font representation of U00A4, but there's nothing wrong with being thorough. An answer from the OP to my fourth question in my original comment would rule out any ambiguity by mapping sent characters to received characters.

@chaaarlie2: I'm not saying it's an ASCII character. It's not. I'm not questioning the usefulness of your questions either. I'm only pointing out that in your sentence: “The character you've shown is not part of neither the standard nor the extended ASCII tables.” the part I emphasized is incorrect. At least if you use “extended ASCII tables” in its usual meaning of “ASCII-compatible 8-bit character sets”.

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.

That delay only applies to the host.  The sketch does not start until the bootloader surrenders control.

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)
   ...

The Uno resets itself when you open the terminal.

Oh, yes, of course. I'm too used to bare chips without auto-reset implemented.

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.

source: Stack Exchange

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

sort: votes


text:
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?

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.

Hallo, My speed is 9600.  I copied the program but when i tried to validate and upload i get the following error " C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:53:20: note:   no known conversion for argument 1 from 'int' to 'const uint8_t* {aka const unsigned char*}'"

I have changed the "Serial.write(myData,Dec);" to "Serial.write(myData)". Then i can upload it, but it still does not work. does it matter were the router and the co ordinator goes?

What does "still doesn't work mean"? You need to provide more info. For example are you receiving data on the other arduino? did you hook up normal serial so you can trace/debug via the pc serial window? What is the code at the other end?

I am not not receiving any data on the Adruino because nothing is being displayed in the Arduino serial monitor.  I have connected the one xbee to the XCTU program that needs to send a 1 or 2 across to the other xbee/arduino to be displayed in the Arduino serial monitor and opperate a LED.  I do not know what "hook up normal serial" means but both are connected to the laptop.  There is no code on the other end.

I see. Well one thing to do is to add a Serial.println("Hello, some serial was found") command just inside where you check for Serial.available(). I also suggest you post the code from the other Arduino that sends the 1 or 2

There is no other arduino yet.  I am doing baby steps.  The 1 and 2 is being sent directly over the xbee connected to the laptop with a UART cable. I have edited my program with "Serial.println"  and Nothing is being displayed in the serial monitor of the Arduino IDE.  So i think it does not pick up the serial port?  But it has the same baud rate and the other setting of the xbee's are correct because i can do a simple chat with them.

It would help if you were clearer about what is being sent to the arduino and the code you have posted. What are you typing into the Serial monitor?

Ok, I am typing in a "1" or a "2" into XCTU which is connected directly to the one Xbee 2B.  It must then pass the data wireless to the other Xbee 2B which is connected to the Arduino Mega 2560.  The Arduino must process the data and display it in the Arduino Serial monitor and also turn the LED "ON" or "OFF".  If it receives a "1 the LED must turn ON" and a "2 it must turn OFF".  I am using the program above.  No data is transferred across the Xbee's.  The Xbee setup is correct to my knowledge.

Saying the Xbee setup is correct is confusing because you are not using xbee you are just using xctu connected via a 2nd usb cable to Pin2 and 3 on the Arduino? You also have the upload usb cable plugged from the Arduino to the Pc? Both x-ctu and the arduino serial monitor are open and both are set to 9600? I will edit the example to show how to add better diagnostics for problem solving. Hope it helps.

What I ment by Xbee setup, I mean that the PANID's are the same, the DL and DH addresses are set And the buad rate is 9600.  Yes, I have a Uart cable connected to a xbee adapter for Xbee 1.  And the other xbee is connected to a shield (Xbee pro shield) onto the Arduino via a usb cable to the laptop. Yes, both the X CTU and Serial monitors are open at the same time and there baud rate is 9600.  I will appreciate it.  Thank you.

Have you done the loop back test in xctu?

No, I am very new with all of this. What must i do?

Use the arduino.cc or other forum to learn. This site is not geared towards long running educational threads. Just questions with answers. Or open another question. I think I have answered your initial question.

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


text:
Bridge */arduino/analog/2 returns a blank page
Had some start up difficulties. But updated the YUN and IDE to the latest version.
Using  * "/arduino/digital/13/1" works as supposed (turns on the LED) - it's just a bit slow. But I can't see why the analogs shouldn't work. I tried to connect it to 5V or GND, so it wasn't floating. But it still returns no reading.
Don't know if this is the cause. But when I connect to my router I can't the the YUN in the list of DHCP Clients...


text:
Which Timer can I use to control a servo with Arduino Uno

I would like to control 2 motors using Timer2 @ 200Hz. The frequency of the timer is printed in the main loop every second. I'm using an Arduino Uno with two interrupt used for the encoders connected to pin 2 and 3.
The problem
The timer runs at 200Hz as expected but the motors are shaking even if I ask them not to spin. The Timer2 is not required by the servo library.
How can I solve this problem? How do you handle Timer interrupts and servo routines?
CODE
#include <Servo.h>
Servo motorDx, motorSx;
[...]

void setup()
{
  // Setup Timer2 @ 200Hz
  cli(); // Stops interrupts

  TCCR2A = 0;// set entire TCCR1A register to 0
  TCCR2B = 0;// same for TCCR1B

  // set compare match register for 200 Hz increments
  OCR2A = 77;// = (16*10^6) / (200*1024) - 1 -> 200 Hz

  // turn on CTC mode
  TCCR2A |= (1 << WGM21);
  // Set CS10 and CS12 bits for 1024 prescaler
  TCCR2B |= (1 << CS20) | (1 << CS21) | (1 << CS22);
  // enable timer compare interrupt
  TIMSK2 |= (1 << OCIE2A);

  sei(); //enable global interrupts

  attachInterrupt(0, MSencVel, RISING);
  attachInterrupt(1, MDencoder, RISING);
  motorDx.attach(10, 1000, 2000);
  motorSx.attach(11, 1000, 2000);
}

void loop()
{
  if(micros()-tOld >= 50000)
  {
    tOld = micros();
    count += 1;
    if(count >= 20) // Runs @ 1 Hz
    {
      count = 0;
      serialRoutine();
      // prints number of ISR/sec
      Serial.println(contIsr)
      contIsr=0;
    }
  }
}

ISR(TIMER2_COMPA_vect)
{
  //sendValuesToMotors();
  motorDX.write(90);
  contIsr++;
}

What motors exactly are you attempting to control?

DC motors with a fully working H bridge.

Don't H-bridges just use steady state or PWM signals? servo uses its own interrupts to generate the PPM signal used by hobby servos, ESC's, and RC radios.


text:
mega include a library
This question is a little related to this one: How to compile and upload the specific (.cpp + .h) code?
I've installed 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?

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.

Regards, done compiling! What do you think about it? Why author set these values empty?

He might have had another file, that he didn't upload to github.
You do have an idea of what these values do? Because TXB8 is bit 0 from the register, so instead of using 0, you can use a define or definition, which is easier to understand.
Also, you should check the error message when it won't compile.
error: ‘TXB8’ was not declared in this scope Which mean that the compiler could't find the variable 'TXB8'. So either missing a variable, out of scope, or missing a define ;D And if you look at the code on that position, you should see what is missing there.

I asked him at github about this. In general, this library allows to connect mdb bus with PC through arduino

btw, it's still don't work on windows. I get this: C:\Users\User\Documents\Arduino\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);

You're sure you have all the RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1 UCSZ12, UCSZ11, UCSZ10, UPM11, UPM10, UMSEL11, UMSEL10 defined or initialized somewhere? And can you see on what character/position on that line the error is?

Thanks for helping, this was a typo: https://github.com/justintconroy/MdbBillValidator/pull/4

Ah I see, yea, it's hard to just see such an error in code you haven't made yourself.
But, the error usually gives a good idea of what is wrong (though it might sound a bit technical) expected ')' before numeric means that it simply didn't expect another numeric to come, thus wanted to close the function call (with a ')') before it could take another numeric. But in this case we didn't need a ')' there but a ','... But that's also why I asked for the position/character on the line.


text:
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?

Large scale manufacturing doesn't involve arduino boards, as this would be too costly. They, however, can use the same microcontroller (Atmega 328). And usually they program with ISP programmers, so it does not require a FTDI chip or any usb/serial converters. And it also doesn't require a (usb-programmer) bootloader.

This belongs back on EESE where it was originally asked - "Arduino" is effectively nothing more than an example in this generic question.

I don' t find this question that generic; it is AVR oriented since the issue is how to program series of AVR, compared with programming one AVR with Arduino.

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

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.

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.

Atmel doesn't mask-program AVRs, but will preflash an image you provide to them.

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.

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 is "old" and tested one. It really works :) AVR studio is also good one
Hardware USBasp 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.


text:
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 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.

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)
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.

Can you suggest me any camera to work with UNO?

In the answer I linked you arducam

yeah, I saw that but arducam are not low cost and are not widely available in India. Can you check this blog and tell me the possibilities of it's happening. Thank you

Can you give a link to the camera you want ot use? I need more of a photo.
Also, I have read the guide on Adafruit that you have linked, and it might work but from what I have read to take a photo it takes over two thousand milliseconds, so it isn't very fast

Camera I want to use.

Unfortunately that's analogic, I don't know how to use it.


text:
I2C or SPI to control 6 motors?
I am a hobbyist & know little about electronics.
I am making a robot arm, like this one. 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:

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.
If not possible, how do I overcome the shortage of pins, because I have already dedicated them to many sensors.

For the stepper motors, the easiest way to work with them is by using a very common A4988 board which is widely used with 3D printers. The controls are very easy and for them I send you this question 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, but it depends by your budget for what you can buy.
You could fix the pin shortage problem by adding some 74HC595 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.
Finally, if the pins that you use are inputs, use a 74HC165, which is the opposite of a 595. As always, see the Arduino website tutorial.


text:
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?

You can control a servo with just a basic 555 chip

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.

Since you need some sort of programmer in order to write the bootloader out, you're usually better off bypassing the bootloader altogether and sticking with the programmer. This will also free up any flash that may have been used by the bootloader as well.

Please, take a look at this guide 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.

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 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.


text:
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.

rain sensor.

You probably will want a moisture sensor like this one (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.


text:
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?

How precisely do you need to match the speeds? A single PWM control will likely result in (slightly) miss-matched speeds.

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.


text:
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?

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.

Is the Max7219 using an SPI pin? If yes since im using an ethernet shield how can i make it work?

http://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf
SPI, QSPI and Microwire. You should check the datasheet first and then ask.
You can make it work by using the slave-select pins, to choose one of the devices to send to. http://arduino.cc/en/Reference/SPI

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:

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

Also, 64-dot displays for displaying arbitrary text:

Again, only 5 wires.
I have Arduino libraries for driving both sorts of display on
Interfacing LED displays with the MAX7219 driver .


text:
Arduino based temperature sensing circuit
I've currently got a setup where I am using a 2 thermocouple setup using MAX31850 and the circuit looks exactly as mentioned here using the external power option. (https://learn.adafruit.com/adafruit-1-wire-thermocouple-amplifier-max31850k/wiring-and-test)
I take the data that is returned from this over serial and pass it over to a simple inverter circuit, which inverts the signal and fluctuates the voltage of a small CREE LED.
The problem that I am encountering is that the data being received from the thermocouples is incorrect when the LED is attached to the setup. And it becomes correct as soon as the LED is detached.

I have tried running my thermocouple set up over an external 5V
supply and using common ground with the Arduino, but it still does
not help.
I have tried using decoupling capacitors on the power rails
to remove any noise due to the LED, but again to no help. What else
can I try to ensure that I can read the data and modulate the LED
simultaneously?

The question doesn't include details that would allow someone to replicate the problem and find out its cause.  "A simple inverter circuit" is vague.  Complete electrical schematics and some photos indicating layouts would improve the question.   ¶ You might try using optical isolators to transmit control signals, and run the LED with a separate battery.


text:
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!

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


text:
Can Ultimate GPS module use arduino micro instead of UNO?
i am doing a Ultimate GPS module like this:
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

Micro: didn't give me any time, date or fix

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);

https://learn.adafruit.com/downloads/pdf/adafruit-ultimate-gps.pdf    actually, the first photo is from Page 7. And the second photo is the result that showed on serial Monitor after i wired it like Page 11, the last one is the result after I change the board to micro. and I use example code in ultimate GPS library

The important parts of your question should be: how is it wired up and what is the sketch doing?  The only source for the first is the photo, so if it doesn't reflect your wiring, please tell us how it's wired  The current example library uses pins 2 and 3, so I don't know if you've modified yours.  Pasting the sketch (or at least the relevant bits from the top where the pins are set) would be recommended.

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.

I am sure my wiring is correct. Actually, it should show me something on the serial Monitor after uploading the code, but it doesn't if I use Micro board.

@weiyulu That is strange. Can you get another sketch on the micro to send something on the serial monitor, to see if it is an issue with the micro or not?

https://learn.adafruit.com/downloads/pdf/adafruit-ultimate-gps.pdf   this is the ulitmate GPS guide, i just do what the guide ask me to do, and the serial monitor should show something like page 13, but in my serial monitor it doesn't show the correct data, like this:                                                                                Time: 0:0:0.0
Date: 0/0/200
Fix: 0 quality: 0

Right. I think what you are doing wrong is your wiring. For the sketch to work as on page 13, you need to connect TX on the GPS up to pin 3 of the Arduino and RX of the GPS up to pin 2 on the arduino. Then, make sure you have downloaded the library and uploaded the sample code. Then open your serial monitor and it should display as in page 13. Could you do this with both arduinos, making sure you wire up the pins not as in the photo above, but as I just said, and then tell me the results on both arduinos? The wiring as in page 11 By the way. @weiyulu

@ harry_p_6 this time i wired exact the same like page 11, but it still didn't work. I put the result photo in the question.

The micro and the uno are not always drop in replacements for each other. Serial on the Uno refers to pins 0 and 1, but on the leonardo/micro it is serial1 that is connected to 0 and 1.


text:
Will we be able to burn arduino zero pro's bootloader?
As arduino.org states, the bootloader is pre-burnt by Atmel at the factory. I'd like to know if it will be possible for us to buy "raw" ICs and burn them at home for our own boards, as we do with the Atmega328 for example.

Burning shouldn't be a problem. Though you might need a JTAG programmer.

My worry isnt that much about the hardware itself but the availability of the bootloader/firmware..

I can't seem to find it. Though my guess it that it will become available, since it's open source hardware/software. The bootloader might however depend on the onboard debug chip.

Hopefully it will be possible. Afaik with Due's its impossible because part of the firmware is burnt by Atmel at the factory..

That's interesting. I didn't know that.


text:
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?

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.

So you mean it is an Amper difference between the pins do you know what the limit for the output pins are

40mA per IO pin.

Be careful! You should't connect anything to the arduino pins, because you will burn them! It's better to use a transistor as @rolf said. Also add a resistance between the pin and the base of the transistor.

That is what I always suspected. Transistors are not anything.


text:
How to use an 8x8 LED Matrix?
I have a LED Matrix just like this one

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!

BTW I don't have an Avometer!

I think all those 8x8 matrixes are pretty much the same. Here is some datasheet. I wouldn't be surprised if the pinouts are exactly the same. See bottom of page 3, for how these displays are wired inside. Also, you definitely need to use resistors, or the leds will burn out.

That's what they told me! But I don't think this one is. Would 220ohm resistors be enough ?

220 is a very nice value.

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.

Would it be ok if I used 3.3v and/or a 220ohm resistor and check each pin ? I don't have a multimeter at the moment. And thanks for your help!

I suggest you to use 3v3 with 220ohm resistor in series.. That will be OK.

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

That might take a while, It's a bit far from where I live. And I don't think they'd be helpful.

What do you mean by that???

I mean the shop I got this matrix from is far from where I live and the people who work there won't be very helpful because everyone around here acts like they know everything which they don't. I said I asked around right? And just like that two got in a fight each one of them says he's better than the other. And thanks to them some LEDs got burned from the matrix! I'm sorry for speaking like this .. and thanks for your help ! :)

Dude... I gave you datasheet. Conect some resistors like 1k ohm and then test. You do not need to ask someone;)

With 1k resistor it will shine not so bright but you wont damage leds...

Thanks a lot :) I'm still learning so I don't understand everything in the data sheet but will try my best ! Thank you ^^


text:
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 ?

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.

If you had used third party app terminal, and in EditText field you wrote Hello World\n then yes it will send it as '' and 'n' because it reads them  as chars.


text:
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:

When I attach the wires to gnd and # I get a buzzing noise.
When I attach the wires to gnd and pow the servo turns left or, if I swap the wires, it turns right.
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).

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

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.


text:
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 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.

The "arduinoClient" part is just an arbitrary name. It's useful when you look at the log in your server. It serve to separate requests from different clients.

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).

It's dubious to call raspberry pi's reliable when they depend on a fragile SD card for their root filesystem. Waiting for the Linux side of things to fully start up does sound like a good idea, unless part of the Linux startup is commanding a reset of the ATmega. Ultimately, to get reliable communication through a bridge likely requires doing a full handshake between the software on both sides. A better system design would probably run most of the logic on the Linux side (as you observed, "you can run scripts there") and use the ATmega only as a delegate for I/O or simple realtime sequencing.


text:
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?

Here is the The ISR code.
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.


text:
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?

You'll probably want to use millis (http://arduino.cc/en/reference/millis) to see how long the user touches the sensor.. that's a starting point. Post some code you've tried and we can help you figure it out.

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.


text:
Servo Issues with Arduino
I am trying to execute the sweep program but all the servo does is go back and forth in one step. When I tried changing the delay, It behaves erratically.
Servo Specs:
Required Pulse: 3-5 Volt Peak to Peak Square Wave
Operating Voltage: 4.8-7.2 Volts
Operating Temperature Range: -10 to +60 Degree C
Operating Speed (4.8V): 0.18sec/60 degrees at no load
Operating Speed (6V): 0.16sec/60 degrees at no load
Operating Speed (7.2V): 0.14sec/60 degrees at no load
Stall Torque (4.8V): 11kg/cm
Stall Torque (6V): 13.5kg/cm
Stall Torque (7.2V): 16kg/cm
360 Modifiable: Yes
Potentiometer Drive: Indirect Drive
Bearing Type: Double Ball Bearing
Gear Type: All Metal Gears
Connector Wire Length: 12"
Dimensions: 1.6" x 0.8"x 1.4" (41 x 20 x 36mm)
Weight: 56gm

Sweep Code:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=0; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

I tried both powering up internally and externally. Internally it responds but externally, arduino's L LED is high all the time and servo does not respond. May I know what is actually going wrong here.

Without code or a schematic it is difficult to help you.

@geometrikal I've included the sweep code from the Arduino IDE

What are you referring to when you say powering internally and externally? Driving a servo requires a variable duty cycle of about [1, 2.5]% or so. The fact that it actually responds to your commands informs us that your signals are changing, albeit not in the correct manner. Make sure you are supplying power and signal to the correct pin on the servo connector - otherwise you may be supplying 100% duty cycle to the signal line and PWM to the power which will not do you any favors. Also, avoid powering the server from the Arduino; the servo current will cause voltage issues.

Well, its doing what it is programmed to do. You havent included any delay between forward motion and backward motion, so it will go in one direction till 180 deg and then turn back instantly. If you want some delay between forward and backward motion, then add it. (You cant observe 15 ms delay..can you ?)

Plus consider what will happen in the for loop. In first loop, you have written pos <= 180. When pos is 180, it will still increment it to 181, write it to servo. But servo function only takes upto 180. Similarly in 2nd loop, it will run even when pos is 0 and still decrement it making it -1 (minus 1). I dont know what will happen to servo, but it maybe a cause of error. So better correct that as well.

Do you have a common ground when you're powering it externally?

@Comintern & sherrellbc By externally I meant, voltage being supplied from a different source and yes, the grounds were tied.


text:
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?

Most IR protocols start with a long signal at the beginning. Yours has a 2340 right in the middle.

Use unsigned int IRsignal[] instead.
Also, your array is 48 items long, not 10. So irsend.sendRaw(IRsignal, 48, 38);

Now the code compiles and appears to work... no response from the remote device though.... guess the number are a little off

If you have a second arduino, you could try to capture the signal being send by the first arduino.


text:
CO2 pressure regulator for keg
Is there anything like the link below that I can read/set with an arduino/raspberry pi?
I'd like to be able to control this completely from a computer in my kegerator setup.
Any search terms that might help me find something would be useful too.
Thanks
http://www.amazon.com/Taprite-Product-Pressure-Kegerator-Regulator/dp/B0060NOX40/ref=lh_ni_t?ie=UTF8&psc=1&smid=AEUC6GAA8XY7Y

A good search term is pressure transducer.

I also need to be able to adjust the delivery pressure to the kegs though - not just measure the pressure

If it's to be cheaper, I'd be surprised if you ended up with something that costs less than some mechanical stuff. If it's for automation, you're going to have a struggle finding a pneumatic regulator that works with Arduino... you might have to use a motor to turn a dial...

For adjusting pressure, search for a solenoid valve. Just make sure that whatever you get is food grade and can handle enough gas pressure (same goes for the transducer).


text:
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?

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.


text:
How should I make a UI for my arduino project?
It's easy enough to attach a display for displaying sensor data, but I'm wondering what the proper way is to have the user change variables using an user interface on the attached 2x16 display.
The only library I found for this purpose:
https://liudr.wordpress.com/libraries/phi_prompt/
Takes a lot of code just to set up. I'm wondering if there's perhaps an easier option. All thoughts appreciated!

The key question is: what do you want to do? Sometimes developing an own library with exactly this functionality you need might be a good alternative to using a large all-in-one library from another party, especially for the Arduino boards with their limited resouces. In that case you also might learn a lot.

I'm just trying to change a few variables, call some functions, give the user the output of functions, etc. Of course I could reinvent the wheel but maybe there's some library I missed.

Well, in this case, reinventing the wheel would not be rocket science. I'd start simple.


text:
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.

It sounds like you're outgrowing the limitations of the Arduino IDE. I'm not offering this as an answer because changing IDEs is not a quick fix, but consider upgrading to more capable tools in the not-too-distant future.

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:

#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>. [...]

Try #include "LiquidCrystal.h"
Or where is the library located?
Be sure the include specifies the location.
You might have to add the library location to your environment variables.

LiquidCrystal.h is a system library and hence, according to my limited C knowledge, has to be included with < >.

Did you add it through "sketch -> include library -> LiquidCrystal.h"?

I've tried that, too, without any difference.

Can you verify that this file is in your libraries folder? You could try to put it in your project folder, so that the linker doesn't have to look that far

Yes, it is there - please read my 2nd last sentence in the question.


text:
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

You may check the sources shipped with the Arduino IDE.

The size of the buffer and the size of the biggest string you can send are not necessarily related (if they are, that's really lazy programming on someone's part)

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


text:
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?

You can get more accurate timing by connecting a GPIO to the RX line. Then use a pin change interrupt to capture the start bit of both serial characters. I don't have any code example, sorry

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

Yes. thank you. Just found that Serial.read() clears the Serial receive buffer. Thats why it will never enter the else if block. I will try with a separate variable as you said.


text:
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 ?

Can you give a more detailed description about what you expect and what is happening with this code? You just want to pull the buzzer pin to high on a rising edge (when the input pin goes from low to high)?

I want to pull the buzzer pin to high on CHANGE for one second.

But you don't need tone() then, correct? (Rising/change/falling are really irrelevant in this case)

I wanted to hear a high pitch tone rather than the default buzzer (beep) one.

But that's not only the point. I can't make it to delay the tone for one second. Only way it works is if the state changes inside the interrupt function which means the sound lasts as much as the reed switch pin is high.

You might need to enable interrupts inside the function. Try placing sei();  at the beginning of the function.

The tone() function initializes the PWM at the frequency and determines the number of toggles that equate to your desired length. Along with initializing a the Output Capture interrupt to coincide with each PWM toggle. Where the PWM's ISR decrements that counter.Hence being inside another ISR will prevent the OCI(or PWM) ISR. Gerben's suggestion of SEI() will help. But you should really write ISR() or functions called by AttachInterrupt() not to be LONG or blocking. ISR's should be quick in and out.

@mpflaga ok got it, but I am starting to think that the whole design of this function is wrong.

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.


text:
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.

nRf24l01+ is one simple option, what size of data, at what speed and distance?

There is also the ESP8266 which provides easy access to WLAN and can be used to setup an access point.

The speed at most will be around 2-5 mph. Distance will be about 20ish feet

Wifi would require an active wifi access point around.
I would go by either RF which is fast, long range (they use this in the radio-controlled cars) or go with bluetooth, which makes it fun to optionally control them by phone/bluetooth. But it has a little smaller range and I have no idea how to connect two of these together

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 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.

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.

Yes - and there's really no reason to pay the 2x-3x premium for wifi or bluetooth when both ends are ATmega-based Arduinos.  If one end were a PC or a phone or other gadget already having one of those radios then using something that it already supports would make sense - but when you get to define both ends, pick something simple.