text:
Why can't I connect more than one Arduino Uno + Ethernet Shield to my network?
I'm using 3 Arduino Uno boards with Ethernet shields. Each is connected to my home Internet switch with an Ethernet cable.  I assigned a different local IP address to each Arduino and gave each board a different MAC Address.
Each Uno is collecting temperature/humidity for a bedroom in my house.  The data is sent to a MySQL Database using PHP/HTML.
They work fine for a while (5 minutes) and then they conflict each other.  If I use one Arduino at a time it works fine, but I can't get them to work together.
Any idea how to solve the problem?

post the ethernet set-up code. And perhaps an Admin should migrate this to the Arduino stack exchange

How do you know where the conflict is? Are you assigning IP address in the DHCP range? If so, it might be conflicting with other devices on your network.

Well I create 3 sketches and put different IP Addresses to each one 192.168.0.177; 192.168.0.178 and 192.168.0.179. They work fine for a while without conflicts but after lets say 5 minutes the website become unavailable and it timed out. Its hard to explain and frustrating.

One Arduino has the MAC address printed in the sticker and the rest of the Arduinos I set it manually (different MAC address of course)...

It would be most helpful to see the code you're using and to know more about the configuration of your network and the symptoms of the conflict – for example where is the web site running?
Some things to try:

Simplify your network. Eliminate everything but the Arduinos and the web server. See if that changes anything.
Run the command arp -a (assuming you've got a machine running something UNIXish). It will show you the MAC and IP addresses of hosts on your network. Look to see if the Arudinos are still there and if there are any devices that conflict with them.
Try to ping the Arudinos. Do they respond?
Use WireShark or tcpdump to monitor traffic on the network. Look for traffic to or from the Arudinos (by IP addresses and by MAC addresses).
Add some debug code to the Arduino sketch so that you can watch what they are doing (send it out the serial monitor). See if what goes on the wire matches what you expect (monitoring with tcpdump).


text:
Can Bus Shield Not Receiving Data
I am trying to connect my Arduino Uno board with SeeedStudio Can Bus Shield to my 2006 325i BMW. After compiling and uploading the example program by SeeedStudio, the serial monitor returns "Can Bus Shield Init ok!"
// demo: CAN-BUS Shield, receive data with check mode
// send data coming to fast, such as less than 10ms, you can use this way
// loovee, 2014-6-13

#include <SPI.h>
#include "mcp_can.h"

// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 9;

MCP_CAN CAN(SPI_CS_PIN); // Set CS pin

void setup() {
  Serial.begin(115200);
START_INIT:
  if(CAN_OK == CAN.begin(CAN_500KBPS)) {
  // init can bus : baudrate = 500k
    Serial.println("CAN BUS Shield init ok!");
  } else {
    Serial.println("CAN BUS Shield init fail");
    Serial.println("Init CAN BUS Shield again");
    delay(100);
    goto START_INIT;
  }
}

void loop(){
  unsigned char len = 0;
  unsigned char buf[8];
  if(CAN_MSGAVAIL == CAN.checkReceive()) {
    // check if data coming
    CAN.readMsgBuf(&len, buf);
    // read data,  len: data length, buf: data buf
    unsigned char canId = CAN.getCanId();
    Serial.println("-----------------------------");
    Serial.println("get data from ID: ");
    Serial.println(canId);
    for(int i = 0; i<len; i++) {
      // print the data
      Serial.print(buf[i]);
      Serial.print("\t");
    }
    Serial.println();
  }
}

So I get the initialize statement returned but I'm not receiving any data. It seems like the if(CAN_MSGAVAIL == CAN.checkReceive()) statement isn't executed. I found my vehicle's Can high and Can low wires and inserted them into my Can Bus Shield. So I'm not sure if it's a code problem or if the wires aren't transmitting the data to the shield. Any help would be great.

No :/ only the power light

How are you connecting to the can bus shield. I stripped two wires and stuck them into can high and can low

Not yet. Im going to order a different canbus shield from spark and see if that works :/

Yes. Connected Can-Bus Shield to Arduino and also connected to Can High and Can Low. Then turned car on

@DailenSpencer - Does the module return "CAN BUS Shield init ok!" without being connected to the car? Mine is saying "CAN BUS Shield init fail" but I'm not sure if it's my connection to the module or the module's connection to the car. Thanks.

@Bort Yes. When connected to can wires, Arduino output returns "Can BUS Shield init ok!"

@DailenSpencer - I'm sorry, but "Yes" doesn't match the rest of your answer. So, it DOESN'T say "init ok" UNLESS you connect to the car? If I get any further, I'll post how I get it to work!

Any progress guys? I am facing the same problem. Mine says "Init OK" even when not connected to the car. (I am using a clone http://www.elecfreaks.com/estore/can-bus-shield.html)
I only connect CAN-H and CAN-L. You mentioned also GND... Should I wire that too?

UPDATE: So yes, for me it was the GND. Also when connecting to an in-car bus make sure to break the P1 trace, or at least consider it and read-up about it why you might need to do it.

It may be a dumb question, but are you sure your car CAN bus is 500kbps?
Have a look at this:
pdfLink
Maybe try different speeds? 100kbps maybe?
Also, look at the schematics of your shield? Is the bus termination resistor soldered on the board?

Make sure to cut the P1 trace (see the link below) and also to connect GND from the OBD-2 to the shield/Arduino. There are two ground pins on the OBD-2 port, Signal and Chassis Ground. I went with Signal GND, but allegedly they are linked anyways.
This guide helped me a lot.

source: Stack Exchange

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

sort: votes


text:
Scroll LCD display connected to an Arduino Uno
I want to make some characters scroll left without affecting the first positions in each row of my LCD 16x2 screen. I have this code inside the loop so far:
lcd .clear();
lcd.setCursor(17, 0);
for (int i = 15; i > 0; i--) {
  lcd.print("x");
  lcd.scrollDisplayLeft();
  if (digitalRead(switchPin) == HIGH) {
    lcd.setCursor(0, 0);
    lcd.write(5);
  } else {
    lcd.setCursor(0, 1);
    lcd.write(5);
  };
  lcd.setCursor(17, 0);
  delay(500);
}
lcd.noAutoscroll();

I think it should work, but the character x just moves left by one position, whereas the character in the first position, either in the first or second row doesn't appear at all.

There is an example that does just this shipped with the arduino IDE and the LCD library. Check it out

I would do the following (beware - not tested):
lcd.clear();
lcd.setCursor(15, 0);
lcd.print("x");
for (int i = 0; i < 15; i++) {
    lcd.setCursor(0, digitalRead(switchPin) == LOW);
    lcd.print("5");
    delay(500);
    lcd.scrollDisplayLeft();
}

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

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


text:
Why can't the OCR1A register be set to 1 to get a 8MHz PWM?
The max PWM frequency that can be achieved with an Arduino is by using the PWM fast mode with the pre-scaler set at 1 and the TOP counter value at 3, getting 4MHz
f_OC = 16000000/(1(1 + 3)) = 4000000
Why can't be the TOP value set at 1?

Because then you only have 1-bit PWM. And there aren't an awful lot of applications for 1-bit PWM.

Yeah, I understand isn't quite useful, but there is some kind of physical limitation? if I set the TOP =1, what will happen?

There's no physical limitation, there's just no point. The DC of the signal will be either 0% or 100%, which means you've emulated a normal GPIO except that you're consuming the power to run the clock as well.

You're right I was thinking on three values.

And what about TOP =2 ?


text:
how to change increase pwm frequency by changing resolution?
As told in this post:
http://forum.arduino.cc/index.php/topic,16612.0.html#
The arduino can achive up to 62.5khz with 8 bits resolution
adding this line in the setup:
TCCR0B = TCCR0B & 0b11111000 | 0x01

sets the divisor of the timer to 1
int output = 5;
void setup() {
  // put your setup code here, to run once:
  TCCR0B = TCCR0B & 0b11111000 | 0x01;

}

void loop() {
  analogWrite(output,127);

}

But I need a frequency of 100khz or as close as possible, the 8 bits resolution is not necessary of my porpouse, it will work just fine with 6 or 7 bits.

For 100kHz, you need to use a fast PWM mode, with a TOP specified by OCRxA,

http://arduino.stackexchange.com/a/19553/6628 has an exellent answer.  You do need the smaller /1 prescaler though.

Here's code for timer 1 on a atmega32u tested in a Teensy 2.0:
void setup() {
  // put your setup code here, to run once:

   // Timer 1 Fast PWM mode *toggling* OC1A at 50kHz with *two* OCR1A counts
   // And 7.32 bits 0-159 PWM on OC1B at 100kHz
   // Output on OC1B
   // Set at TOP, Clear at OCR1B
   // WGM =15 0b1111

   DDRB |= bit(DDB5) | bit(DDB6);  // atmega32u OC1A and OC1B outputs
  // DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;
}

void loop() {
  // put your main code here, to run repeatedly:
  OCR1B = 160/4 -1 ; // 25% duty cycle.
}

The trick here is using OCRxA to set the TOP value/resolution/frequency of the timer, and then using OCRxB as the PWM-controlled output.  The popular examples aim for a specific frequency with toggling, but often don't go into showing the PWM with the non-TOP OCRxx registers.
If you check the registers for your chip, this should also adapt to the other timers.  Here, I used timer1 to avoid confusing delay() and millis().

This will correspond to the pin 10 of the arduino uno rigth? https://www.arduino.cc/en/Hacking/PinMapping168. I have no try the code and get no output

Yes, per that diagram digital Pin 10 is OC1B, but since on the atmega168, it is PB2, so the DataDirectionRegister needs to enable bit 2.  I added it in a comment in the above code, but I'm not able to test it.

Tested, it works just fine.


text:
Why is integer-to-string not working in this sketch?
I am using a Pro Mini to read analog values and to send them via serial.
Goal of the sketch is to stream these values to Serial as fast as possible, to obtain a steady stream of at least 1000 readings per second. For this reason I reduced the ADC prescaler and I increased serial speed.
I tested sending binary values with Serial.write and it works (it's the fastest), I tested Serial.print (it's the slowest), and I tested an optimised conversion integer-to-string (found on StackOverflow) in association with Serial.write.
This optimised conversion is faster than Serial.print (it would allow me to send the full strings within the given timeframe), but it gives me wrong values. I cannot understand why it happens, the code looks fine to my not-so-expert eye.
A correct stream as sent by Serial.print would be (spaces added for clarity):
3075 \t 2800 \t 4132 \n

"Wrong values" means that the last value gets repeated for all the three columns:
4132 \t 4132 \t 4132 \n

What is the issue in my code regarding the int2str conversion?
Since I cannot get one measurement taken and sent every 500 us, I would like to use the optimised routine to get plaintext readings at 1000 us intervals.
The source code follows. I cut out the function slimADC because it was tested as working, while I left all the 3 methods for sending data via serial: binary, optimised, Serial.print.
#include <digitalWriteFast.h>

volatile unsigned long previousMicros, currentMicros;

#define SAMPLES 8
volatile unsigned int valuesX;
volatile unsigned int valuesY;
volatile unsigned int valuesZ;

char* x;
char* y;
char* z;

void setup() {
// set pins, ADC prescaler and initialise ADC
  pinModeFast(A0, INPUT);
  pinModeFast(A1, INPUT);
  pinModeFast(A2, INPUT);
  ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear bits
  ADCSRA |= bit (ADPS0) | bit (ADPS2);  // 32: 32 us per ADC
  slimADC(0);
  slimADC(0);

// initialise Serial
  Serial.begin(250000);
  Serial.write("\n");
  Serial.write("\n");
  previousMicros = 0;
}

void loop() {
  currentMicros = micros();
  if ((currentMicros - previousMicros) < 1000) { return; }
  previousMicros = currentMicros;

// ADC readings, repeated SAMPLES times
  valuesX = 0;
  valuesY = 0;
  valuesZ = 0;
  for (uint8_t i = 1; i < SAMPLES; i++) {  // 8*3*32=768 us
    valuesX += slimADC(0);
    valuesY += slimADC(1);
    valuesZ += slimADC(2);
  }

// SERIAL TRANSMISSION

// fastest
//  Serial.write(valuesX / 256);
//  Serial.write(valuesX % 256);
//  Serial.write("\t");
//  Serial.write(valuesY / 256);
//  Serial.write(valuesY % 256);
//  Serial.write("\t");
//  Serial.write(valuesZ / 256);
//  Serial.write(valuesZ % 256);
//  Serial.write("\n");

// good
  x = int2str( valuesX );
  y = int2str( valuesY );
  z = int2str( valuesZ );
  Serial.write(x);
  Serial.write("\t");
  Serial.write(y);
  Serial.write("\t");
  Serial.write(z);
  Serial.write("\n");

// slowest
//  Serial.print(valuesX);
//  Serial.print("\t");
//  Serial.print(valuesY);
//  Serial.print("\t");
//  Serial.print(valuesZ);
//  Serial.print("\n");
}

static int slimADC(uint8_t pin) { ... }

char _int2str[7];
char* int2str( register int i ) {
  register unsigned char L = 1;
  register char c;
  register boolean m = false;
  register char b;  // lower-byte of i
  // negative
  if ( i < 0 ) {
    _int2str[ 0 ] = '-';
    i = -i;
  }
  else L = 0;
  // ten-thousands
  if( i > 9999 ) {
    c = i < 20000 ? 1
      : i < 30000 ? 2
      : 3;
    _int2str[ L++ ] = c + 48;
    i -= c * 10000;
    m = true;
  }
  // thousands
  if( i > 999 ) {
    c = i < 5000
      ? ( i < 3000
          ? ( i < 2000 ? 1 : 2 )
          :   i < 4000 ? 3 : 4
        )
      : i < 8000
        ? ( i < 6000
            ? 5
            : i < 7000 ? 6 : 7
          )
        : i < 9000 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    i -= c * 1000;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // hundreds
  if( i > 99 ) {
    c = i < 500
      ? ( i < 300
          ? ( i < 200 ? 1 : 2 )
          :   i < 400 ? 3 : 4
        )
      : i < 800
        ? ( i < 600
            ? 5
            : i < 700 ? 6 : 7
          )
        : i < 900 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    i -= c * 100;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // decades (check on lower byte to optimize code)
  b = char( i );
  if( b > 9 ) {
    c = b < 50
      ? ( b < 30
          ? ( b < 20 ? 1 : 2 )
          :   b < 40 ? 3 : 4
        )
      : b < 80
        ? ( i < 60
            ? 5
            : i < 70 ? 6 : 7
          )
        : i < 90 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    b -= c * 10;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // last digit
  _int2str[ L++ ] = b + 48;
  // null terminator
  _int2str[ L ] = 0;
  return _int2str;
}

Appendix
The bare ADC conversions take about 768 us.
With binary data I am sending via serial 3x uint16_t plus one end of line and two tabs, meaning 9 characters per reading. At 250 kbps 8N1 the minimum time required is 324 us. Using RealTerm (for Win) I can see that I get a stram of 9k chars/s, as expected.
With Serial.print I am sending 4x string[4] (readings are always between 1000 and 9999), plus tabs and newline, meaning 15 bytes per reading. RealTerm however gives me an incoming stream of 11-12k chars/s, therefore Serial.print is too slow.
The optimised int-to-string function (even without modifying it to avoid checking for negative and for >9999, not needed in my case) still sends 15 bytes per reading, and RealTerm also shows me an actual stream of 15k chars/s, as expected.

Here is a benchmark that you might find interesting; https://github.com/mikaelpatel/Cosa/blob/master/examples/Benchmarks/CosaBenchmarkDataLogger/CosaBenchmarkDataLogger.ino It tries to answer the question if 4K ADC samples (and number conversions) per second is possible.

Well I already have 24 samples (768 us) and 3 number conversions (not sure how long they take) per millisecond. Not that different. I could probably double the conversions if I reduce the number of samples (I'm taking 8 per channel), but first I want to get the rest right :) But thanks for sharing, I starred that project for future reference. I will study it if possible.

@MikaelPatel yep, with 4 samples per acquisition and using a binary stream I get 18k chars received on the PC side for a 500 us period. It's 24 ADC conversions (3234=384 us) and 18 chars sent (9*10/250000=360 us) per millisecond!

Unfortunately with such fast serial I cannot afford to use ADC noise reduction (it would stop the IO clock used by USART), but it's not important right now.

3 number conversions (not sure how long they take). approximately 300 - 320 ticks per conversion. or 20us @ 16MIPS.

It's 24 ADC conversions (3234=384 us). try to run the adc in free-running model. you can enable the adc interrupt so the data is automatically saved in a buffer for you.

@dannyf In this specific case the time budget I have (500 us) seems to be enough for my requirements, so no need to spend more time on optimization. I will use the free running ADC for the final project (this is an intermediate step).

it took me a while and i'm still not 100% sure if I got you right. I think you have two questions:

1) how to speed up the entire execution?

the serial routines will be your biggest bottleneck. I would suggest that a) you speed up the baud rate; and b) you try to use a tx interrupt here.

2) why isn't the int2str() routine working?

because int2str() stores the converted string in a buffer (_int2str[]), which is subsequently destroyed by conversions. so for it to work, you should do something like this:
  serial.write(int2str(x)); serial.write("\t");
  serial.write(int2str(y)); serial.write("\t");
  serial.write(int2str(z)); serial.write("\n");

BTW, int2str() can be written a lot better than it is now.
edit: to add an alternate int2str() implementaton.
//positive and negative numbers
//int is 16-bit type
char *int2str2(int i) {
    static char _int2str[7];
    unsigned char tmp, str_len=0;       //converted string starts at _int2str[0]

    //process the sign
    if (i&0x8000/*<0*/) {
      _int2str[str_len++]='-';          //insert leading '-'
      i=-i;                             //make the number positive
    };

    //convert the next position (10,000)
    tmp = 0;                            //reset tmp
    while (i >= 10000) {
      i-=10000;                         //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the next position (1,000)
    tmp = 0;                            //reset tmp
    while (i >= 1000) {
      i-=1000;                          //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the next position (100)
    tmp = 0;                            //reset tmp
    while (i >= 100) {
      i-=100;                           //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the next position (10)
    tmp = 0;                            //reset tmp
    while (i >= 10) {
      i-=10;                            //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the lsb
    //tmp = 0;                          //reset tmp
    //while (i >= 100000ul) {
    //  i-=100000ul;                        //decrement i
    //  tmp+=1;                         //increment counter
    //}
    tmp = i;
    _int2str[str_len++] = tmp + '0';    //form the msb

    return _int2str;
}

here is what I would use. I benchmark against yours, converting numbers from 0 to 32767. total cycle count for yours is 10.5 million and 7.0 million for mine. Now, the actual performance will depend on a lot of factors, like your chips, compilers (I used IAR AVR), and optimization settings, to name a few.
Note: the routine was written as a generic one. if you are only converting 10-bit numbers (from a 10-bit adc for example), it can be greatly simplified, and execution time greatly shortened: <160K cumulative cycles converting numbers from 0 to 1023.

Part 2) was my actual question and your explanation is clear, I corrected my code and accepted your answer. Part 1) was more side information I put there to let the reader understand what I'm doing, I didn't expect any answer or significant improvements there. But thanks for letting me know about TX interrupts. Isn't Arduino using hardware UART (and interrupts) already? see https://www.arduino.cc/en/Reference/softwareSerial Concerning int2str: it's using basically the bisection method, I thought it was already quite efficient. Do you have a link for a better version? I'm quite beginner.

the arduino uses the hardware uart module in the avr. but uses polling in its transmission -> they want for the prior transmission to end before sending the next. the usr of isr would have allowed the mcu to do other things which uart is transmitting.

I understand how your conversion routine works, but I'm not sure why it is faster. On average you have 5 comparisons, 11 sums, 11 value assignments per decade, while the old one has 3 comparison, 2 sums, 1 multiplication (hardware in ATmegas) and 3 assignments. On my atmega328p I measured (0 to 32767) 311072 us for the old one and 325656 us for yours. avr-gcc 4.9.2 and following options: -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328. I guess that on ATtiny yours would be faster, since hardware multiplication is missing.


text:
Multiple buttons on single interrupt, how to debounce?
Buttons on separate interrupt pins work fine (triggered on FALLING), bouncing is handling by forcing a 80ms lockout period during which further presses are ignored. I like that solution for being lightweight.
My goal is to have 1 interrupt handle all events (buttons and other digital inputs). I don't want to depend on loop(), I wish to be free to use delay often rather than timer interrupts.
Most buttons execute an action when pressed, some, while pressed.
What I have now (just 2 buttons for now):

simulate this circuit – Schematic created using CircuitLab
void setup() {
  pinMode(17, INPUT_PULLUP);
  pinMode(16, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(3), wotHappnd, CHANGE);
}

boolean isDebouncing(){
  unsigned int now = millis();
  if(now - time_lastPressed > time_debounceLockout){
    time_lastPressed = now;
    return false;
  }
  return true;
}

void wotHappnd(){
  boolean interruptFalling = digitalRead(3) == LOW;
  if(interruptFalling && isDebouncing()) return;
  // digitalRead the pins; do stuff
}

Internal pullups on all used pins.
My problem is that often (~4%), on interrupt, the interrupt pin is LOW all button pins are HIGH ("not pressed" - likely bouncing just as I read it). How to fix that?
Can't use delay during an interrupt; delayMicroseconds to wait for stable readout still feels inappropriate; a cap-based delay on the interrupt pin induces a period of floating.
Prefer solutions in software or with no more than 1 extra component per input.
[edit] here's a claim that pin interrupts do some filtering already, which, if true, may make some solutions unreliable.

Can't you catch the button being pressed on the next bounce? Since the button bounces a few times, there should be one where it's LOW for long enough to catch. So in the code, you'll have to check if one of the buttons is pressed, before calling the isDebouncing function.

@Gerben It's a common debounce for all buttons. Sufficient for me. So, you're suggesting I do digitalRead in a loop until I get a LOW somewhere?

No. Do two digital reads for the two buttons in the ISR. If both are high, do nothing. Otherwise execute the code you now have in the ISR.

Oh. Still, is it certain that a bouncing button will trigger effloads of interrupts? I'm asking because I read somewhere (Electrical Engineering StackExchange?) that there is already some signal stability assurance done on interrupts in some microcontrollers, to prevent exactly that. Plus, I have no idea what impact the diodes or other connected pins may have here, if any.

I think you will find that in the end, thee best software debounced is none- a capacitor plus a resistor (or a terrible switch) will do wonders here.

Any reason you don't attachInterrupt(..., FALLING)? 2) There is no filtering done by the MCU on external interrupts.

@EdgarBonet I forgot the terms for it, so I wrote: "Most buttons execute an action when pressed, some, while pressed." For the latter, I have to know when they're released.

In the Isr, read the two pins and maintain their current status (UN debounced), and reset a counter.
In the main loop, increment that counter. If it is more than a certain number, it means that the current state of the key has been stable for a while - bounce no more.
Or Google Kuhn debounced. I wrote a blog page about that. If you want, I can post it later. The basic idea is the same.

Thanks of reminding me of Kuhn debounce. Too bad it needs polling in main loop, which I don't want to do. Polling without delay won't produce the same result... maybe polling on a timer interrupt? Hmm...

The approach I suggested is essentially the Kuhn debounced, without polling the buttons. Instead, you increment a counter as a way to detect stabilized buttons.

Sorry, I misunderstood before. Still, what puts me off is dependence on the main loop being free of long delays. Also, any idea about what's in the 4th comment under the question? Won't there be fewer CHANGE interrupts than changes on the (non-interrupt) button pin?

There is no requirement for the main loop to have any delays, long Orr short

Any solution using loop() needs loop() to NOT have long delays. Kuhn repeats 10 times per second. Arduino is a prototyping platform - perfection is reserved for later, and in the meantime I tune my signal generation using delay.

Accepting this as it seems no method as convenient as the lockout exists for my scenario, leaving loop and hardware solutions. Thank you.

As ever I am the voice of dissent: never write software to solve a hardware problem.
For a double-throw switch the classic solution is an SR latch.
Single throw is actually harder. On the face of it, debounce is a trivial matter done with a capacitor and a pull-down (or pull-up) resistor. This will certainly stop floating and false positives from induced current from spikes. However, microprocessors switch pretty fast and will recognise the edges of microsecond oscillations around the switching voltage as changes of switch state. To prevent this you need the hysteresis of a Schmitt Trigger such as an LM7414 (TTL) or LM7417 (suitable for 3V3).
Here is the debounce circuit suggested in Understanding Schmitt Triggers. Unfortunately, it doesn't behave correctly under all conditions, for reasons explained on the Ganssle page referenced later.

You can fix the problem with a diode. For TTL, R1 = 82kΩ, R2 = 18kΩ, C = 1µF

Larger values of C will absorb slower bounces. One of my projects has a relay that bounces for so long I needed 470µF.
Here's what I regard as the last word on the subject — the Ganssle page. There's even a solution for multiple buttons on a single input. This is not quite the same as multiple buttons on a single interrupt but I think the approach may be applicable.
Note that on the Ganssle page a software solution is touted as cheaper than hardware. That's irrelevant for a one-off, true for mid sized runs and potentially false for mass produced items. Debugging software has its own costs and so does product recall. Make your decision in context. Arduino projects are usually one-off.
One objection to a hardware solution is cost, in assembly time, component count and board size. For hobby work that's a personal choice, and for commercial work it's a trade-off between simplicity and reliability. Reliability of software hinges on deterministic behaviour and the management of complexity. The Atmel chip doesn't have a lot of DRAM or program space, and moving this problem out of the software will make it smaller, simpler and more predictable.
That's not to say there aren't other ways to deal with the problem.
If you really want to do it in software you need to measure the pulse width and compare it to a threshold. Since you need both falling and rising edges for this, bind to CHANGE and test for state. The primary difference between this and the Kuhn method mentioned by others is it uses the clock instead of a counter allowing you to specify millisecond duration rather than iterations.
In the excerpt below, the listen flag is a simple alternative to noInterrupt() or unbinding the handler. My loop code evaluates a state machine transition function for current state and inputs, and not all states want input.
void isr_change()
{
    if (listen)
    {
        unsigned long now = millis();
        int d2 = digitalRead(2);
        if (d2 == LOW || fall_time == 0)
        { // FALLING
            fall_time = now;
        }
        if (d2 == HIGH)
        { // RISING
            command_pending = now - fall_time > MIN_PULSE_MS;
        }
    }
}

The state machine doesn't look at digital inputs, it looks at the command_pending flag, which is reset after the transition function finishes.
This is one of those things that looks simple, isn't, but does have a stock solution. It beats me why there isn't a mass produced debouncer component the way you can get op-amps.
Thank you to kaay in comments for referring me to the MC14490 which is a DIP16 or SOIC16 with six diode protected debouncers. Kaay thinks it's expensive but consider the cost of the time to code and debug debounce of six inputs. What about the cost when the program doesn't quite fit and you have to rewrite it to shrink it? And then regression test everything. Would you pay someone $5 for an instant guaranteed result that doesn't complicate or bloat your software? The economics change with production scale of course, but in very small runs I think it's well worthwhile.
I found the MC14490 DIP16 for 5USD and the SOIC for 9AUD online. Local shops didn't carry it.

One up and one down. Pity the down-voter couldn't be bothered to say why he thinks this is a poor answer.

I am not the downvoter, but I can see that hardware is more expensive than software in terms of parts, board real state, assembly time...

@EdgarBonet I should hope you can see it, I discussed in explicitly in the penultimate paragraph.

@EdgarBonet no longer the second last para but it was when you read it. I have added some material to help people with tunnel vision.

+1 for effort. This answer gathers some nice ideas, and even if it's not a good match to the requirements in the question, it is useful. Although, gotta disagree with "(cost is) irrelevant for a one-off" - for most, slapping on a Shmitt&TheRest will cost from 20 minutes (in the unlikely case they have everything at hand) PLUS testing, to several hours. And that is ESPECIALLY hurtful if all you get is one unit. Debouncer ICs - I've had the exact same thought! As far as I'm concerned, at that price, MC14490 does not exist.

@kaay perhaps, in many ways it's a values question. I suspect most Arduino projects are labours of love, where one of the deliverables is the satisfaction of both do it yourself and design it yourself. Given the negative reactions, I may be wrong about that. The reason I think a hardware debounce may be cheaper than software for a very small run is the cost of quality control for software and the cost of pushing firmware updates.


text:
Arduino Ethernet intermittently connects to server
Here is my code:
#include <SPI.h>
#include <OneWire.h>
#include <EthernetV2_0.h>
#include <EthernetClientV2_0.h>
#include <EthernetServerV2_0.h>
#include <EthernetUdpV2_0.h>
#include <math.h>
#include <Client.h>
#include <WString.h>
     #include <stdlib.h>
#include <OneWire.h>
#include <stdio.h>
#include <DhcpV2_0.h>
#include <DnsV2_0.h>

int whiteLevel;
int colorLevel;
int blueLevel;
int standardLightingPattern[3] = { 200, 160, 250 };
int twilightLightingPattern[3] = { 20, 50, 100 };
int nightTimeLightingPattern[3] = { 0, 10, 40 };
int morningLightingPattern[3] = { 50, 50, 100 };
int deepNightLightingPattern[3] = { 0, 20, 80 };
int feedingLightingPattern[3] = { 20, 20, 50 };
int i;
int j;
char *buildUrlParameter(float ph, float temp1, float temp2);

// Pin Delcarations
int temperaturePins[2] = { 30,31 };
int outletPins[] = { 22, 23, 24, 25, 26, 27 };
const int whiteLedString = 44;    // connected to LDD-700HW on white strand
const int colorLedString = 45;    // connected to LDD-1000HW on color strand
const int blueLedString = 46;     // connected to LDD-1000HW on royal blue     strand

// Sensor Variables
float temps[2];
String sensorstring = "";
boolean sensor_string_complete = false;
float pH;

// Variables for URL char buffer
char outBuf[100];
char charBuf[6];
char cnctPh[6];
char cnctTemp1[7];
char cnctTemp2[7];
char urlParameter[34];
char dest1[34];

//char serverIP[] = "74,125,224,80";
//char serverIP[] = "192.168.1.107";
//char serverIP[] = "www.arduino.cc";

// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(192,168,1,199);

// fill in your Domain Name Server address here:
IPAddress myDns(8,8,8,8);

// initialize the library instance:
EthernetClient client;

char server[] = "192.168.1.107";

unsigned long lastConnectionTime = 0;          // last time you connected to the server, in milliseconds
boolean lastConnected = false;                 // state of the connection last time through the main loop
const unsigned long postingInterval = 10*1000;  // delay between updates, in milliseconds
#define W5200_CS  10
#define SDCARD_CS 4
void setup() {
   // start serial port:
 Serial.begin(38400);
 Serial3.begin(38400);
 pinMode(SDCARD_CS,OUTPUT);
  digitalWrite(SDCARD_CS,HIGH);//Deselect the SD card
  // give the ethernet module time to boot up:
   delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns);
  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  char c;
  dimLights(standardLightingPattern);
  dimLights(nightTimeLightingPattern);

  // if there's no net connection, but there was one last time
  // through the loop, then stop the client:
  if (!client.connected() && lastConnected) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }
  // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if(!client.connected() && (millis() - lastConnectionTime >    postingInterval)) {
    getPh();
    getTemperature();
    httpRequest();
  }
  // store the state of the connection for next time through
  // the loop:
  lastConnected = client.connected();
}

void getPh() {
  Serial3.print("r<CR>");
  if (sensor_string_complete == true) {
   //Serial.println(sensorstring);
   if (isdigit(sensorstring[0])) {
      pH = sensorstring.toFloat();
    }
  }

 sensorstring = "";
 sensor_string_complete = false;
}

void dimLights(int lightingBrightnessArray[]) {
  analogWrite(whiteLedString, lightingBrightnessArray[0]);
  analogWrite(colorLedString, lightingBrightnessArray[1]);
  analogWrite(blueLedString, lightingBrightnessArray[2]);

}

float getTemp(int pin) {
  OneWire ds(pin);
  byte k;
  byte present = 0;
  byte type_s = 0;
  byte data[12];
  byte addr[8];
  float celsius;
  float fahrenheit;

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

  ds.reset();
  ds.select(addr);

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

  // maybe 750ms is enough, maybe not
  delay(1000);

  present = ds.reset();
  ds.select(addr);

  // Read Scratchpad
  ds.write(0xBE);

  // we need 9 bytes
  for (k = 0; k < 9; k++) {
    data[k] = ds.read();
  }

  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {

   // 9 bit resolution default
   raw = raw << 3;

   if (data[7] == 0x10) {
     // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
    } else {
      byte cfg = (data[4] & 0x60);
      // at lower res, the low bits are undefined, so let's zero them
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms

     // default is 12 bit resolution, 750 ms conversion time
    }

    celsius = (float)raw / 16.0;
    fahrenheit = celsius * 1.8 + 32.0;
    return fahrenheit;
}

void getTemperature() {

 //get temperature 1 from display
  temps[0] = getTemp(temperaturePins[0]);
  delay(1000);

  //get temperature 2 from sump
  temps[1] = getTemp(temperaturePins[1]);
  delay(1000);

  //used for building parameters for GET request for passing DB values
  Serial.println("");
  float temp1 = temps[0];
  float temp2 = temps[1];
  //converts pH sensor char buffer to float val
  //float pH = atof(stamp_data);

  //used for debugging
  Serial.println("Returned Temp 1: ");
  Serial.println(temp1);
  Serial.println("Returned Temp 2: ");
  Serial.println(temp2);
  Serial.println("ph val:");
  Serial.println(pH);

  //build url for GET request using above parameters
  *buildUrlParameter(pH, temp1, temp2);
  Serial.println(dest1);
  //make HTTP request
   httpRequest();
}

char *buildUrlParameter(float pH, float temp1, float temp2) {
  //builds char buffer from three float values passed from
  //sensors and apends proper sensor monikers
  dtostrf(pH, 4, 2, cnctPh);
  dtostrf(temp1, 5, 2, cnctTemp1);
  dtostrf(temp2, 5, 2, cnctTemp2);
  strcpy(dest1, "ph=");
  strcat(dest1, cnctPh);
  strcat(dest1, "&T1=");
  strcat(dest1, cnctTemp1);
  strcat(dest1, "&T2=");
  strcat(dest1, cnctTemp2);

  return dest1;
}

 // this method makes a HTTP connection to the server:
   void httpRequest() {

   sprintf(outBuf, "GET http://192.168.1.107/ReefController/trunk/app/php/reef_controller_loadVals_all.php?%s HTTP/1.0", dest1);
   Serial.println(outBuf);
//Serial.println("connecting...");
 delay(1000);
  //client.connect(server, 80);

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    client.println(outBuf);
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.println("Host: localhost");
    client.println("User-Agent: arduino-ethernet");
    client.println("Content Type: application/json");
    client.println("Connection: close");
    client.println();

    Serial.println("Successfully recorded to database");
    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
    Serial.println("disconnecting.");
    client.stop();
  }
}`

What is happening is when my program hits httpRequest the client.connect is successful maybe 2-3 times out of 5.  The PHP server is up and running fine.  It will just fall into the last else and give me connection failed / disconnecting when it isn't working.... when it does work I get a response back 500 internal server error yet the PHP script runs and records my posted values to the database.  Any thoughts?

If i put client.stop:
     // if you're not connected, and ten seconds have passed since        // your last connection, then connect again and send data:        if(!client.connected() && (millis() - lastConnectionTime >         postingInterval)) {         getPh();         getTemperature();         httpRequest();       }
I seem to have better results but I am not sure why I would need to stop the client after an httpRequest.

You need to stop the socket connection when you are done, in order for the server to successfully close the connection and also to free file handles, i think. In your GET request, get rid of the IP address; start with /ReefCont...also get rid of the other header fields in your GET request, and try again

@brianrho good point, I had not even seen the part where he adds the other headers. With HTTP1.0 you can get away with nothing more than just the GET line. If you want to keep the other headers do not forget to add \r\n after each line.

@brianrho do I not need the ip in my get because I'm already connected to that server?

Exactly. You are already connected.

@brianrho do you think this may fix the connection problem and the error 500 or just the error?

You will have to try it and see. Dont forget to remove the other header fields.

This is why I think the server returns a HTTP500:
Usually in HTTP requests you do not include the ip address, so:
GET http://192.168.1.107/<really long part>?%s HTTP/1.0
would become:
GET /<really long part>?%s HTTP/1.0
Also HTTP requests should use carriage return AND line feed to indicate the end of a line.
And an HTTP request should ALWAYS end in a full blank line.
You are using the HTTP1.0 protocol, so your request can be done in one line, so you can just end it with: \r\n\r\n. If your request would be multiple lines, every line should also end with \r\n.
So the result would be:
GET /<really long part>?%s HTTP/1.0\r\n\r\n
One CRLF (the \r\n part) to begin a new line and one more for the blank line.
As for the connection problem, I think this has to do with the fact that you need to open AND close the connection for each HTTP request. You are using the HTTP1.0 protocol which does not support multiple HTTP requests in one connection. You can send multiple HTTP requests when using HTTP1.1, but then you also have to think about the TCP keepalive and it makes your request more complicated.
Try changing your HTTP request as mentioned above and call  client.connect() and a client.stop() for every HTTP request. And don't forget to tell us the results!

Great thanks @larzz11.    I am going to try this when I eat home from work tonight.  It's 730am in my time zone right now. I'll update once I try it.


text:
Error uploading Arduino Micro Sketch using Kubuntu
I have an arduino micro which I want to program from my Kubuntu 15.10 system. I installed the arduino software using apt-get, but when I try to upload the program (for test purpose I use the Basics\BareMinimum sketch) I get the following error:
Found programmer: Id = "0.00 V1"; type =
    Software Version = 0..; Hardware Version = 0.0
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?

The proper device "Arduino Micro" is selected and also the proper port "/tty/ACM0". I found people on the internet which have the same error and could solve it by using another USB port or cable. But I tried it with two different cables and different ports and didn't manage to get it working. I even tried it on my Laptop running an older version of Kubuntu which produced the same error.
Therefore I tried the newest version of the Arduino software from the arduino homepage. With this I get a different error:
avrdude: ser_open(): can't open device "/dev/ttyACM0": Device or resource busy
avrdude: ser_send(): write error: Bad file descriptor

My user is added to the dialout group, so I should have access to the port. It is also the right port as the port disappears from the arduino menu when I unplug the board.
The arduino itself shouldn't be the problem, as I can upload the sketch from another windows laptop without problems.
EDIT: when I plug in the arduino, the following is added to the dmesg output:
[ 8390.293960] usb 1-2: new full-speed USB device number 6 using xhci_hcd
[ 8390.424861] usb 1-2: New USB device found, idVendor=2341, idProduct=8037
[ 8390.424863] usb 1-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 8390.424864] usb 1-2: Product: Arduino Micro
[ 8390.424865] usb 1-2: Manufacturer: Arduino LLC
[ 8390.425283] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
[ 8390.426815] input: Arduino LLC Arduino Micro as /devices/pci0000:00/0000:00:14.0/usb1/1-2/1-2:1.2/0003:2341:8037.0007/input/input21
[ 8390.482163] hid-generic 0003:2341:8037.0007: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC Arduino Micro] on usb-0000:00:14.0-2/input2

Try hitting reset before upload.

Hitting the reset button also doesn't solve the problem. Not I get an "upload completed", but the arduino still has the previous program loaded.

Which version of the IDE are you using?

I tried the one from the ubuntu package repository and one directly from the arduino.cc page. I have to look the version numbers up.

The package version I am using is 1:1.0.5+dfsg2-2, the other I tried was 2:1.0.5+dfsg2-4.

Are you in the dialout group?

Yes I am, as stated in the text of the question.

I know this is a long shot and I'm expecting the answer to be no, but just confirming, you don't have any other serial monitors running that is monitoring the port do you?

and/or you have rebooted somewhere along the lines and that no other copy of the Arduino IDE is running and has control of the port? (sorry for the silly questions, just trying to help you rule everything out)

No I don't have any serial monitor running I know of. Maybe Kubuntu ships something I don't know of. And yes, as I am trying for quite a while, I have shutdown and rebooted the system a couple of times.

I now tried to install a fresh Linux on my Laptop. I used now Ubuntu 15.10., downloaded the newest stable Arduino software and added my user to the dialout group. The same error occurs again. So doesn't Arduino Micro work with Ubuntu? Because it now doesn't seem to depend on my settings and the Arduino and Cable works with another Windows Laptop, so it should also be ok. Anyone an idea?

Do you have a Uno to test with? The Micro/Leonardo devices are harder to upload to, if they have code loaded on them. The Uno (or similar) are somewhat more reliable.

No I only have an Arduino Micro.

Therefore I tried the newest version of the Arduino software from the arduino homepage.
The package version I am using is 1:1.0.5+dfsg2-2, the other I tried was 2:1.0.5+dfsg2-4.

That is not the newest version.
I think the more recent versions of the IDE are more robust - after all they have fixed reported bugs. Try 1.6.5 or 1.6.7. The version 1.0.5 is pretty old.

I too have had "upload completed" on my Leonardo (virtually the same as the Micro) when it did no such thing.
I am using Ubuntu 14.04 and don't have any problems programming my Micro with IDE 1.6.7.

When programming you should see the Tx/Rx and yellow LEDs flicker. If not, press Reset when it starts to upload and try again.

Have you followed the instructions here? Arduino Troubleshooting.

I installed the arduino software using apt-get ...

Personally I download the IDE from this page: https://www.arduino.cc/en/Main/Software

Update
I just compiled and uploaded "Blink" with IDE 1.6.7 to my Micro on Ubuntu 14.04. This is what I saw:
Forcing reset using 1200bps open/close on port /dev/ttyACM1
PORTS {/dev/ttyACM0, /dev/ttyACM1, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, /dev/ttyACM1, } => {/dev/ttyACM1, }
Found upload port: /dev/ttyACM1
/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avrdude -C/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM1 -b57600 -D -Uflash:w:/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/nick/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM1
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587
avrdude: reading input file "/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex"
avrdude: writing flash (4456 bytes):

Writing | ################################################## | 100% 0.33s

avrdude: 4456 bytes of flash written
avrdude: verifying flash memory against /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: load data flash data from input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex contains 4456 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.03s

avrdude: verifying ...
avrdude: 4456 bytes of flash verified

avrdude done.  Thank you.

Can you please compare to what you get? Or post exactly what you see?

What do you see in your Port menu? This is what I see:

Installing Arduino on a fresh Ubuntu system
I did the following steps to get Arduino up on Ubuntu 14.04, on a PC where it was not previously installed.
Download and install

Downloaded Linux IDE 1.6.7 (64 bit) from https://www.arduino.cc/en/Main/Software
Un-archive downloaded file into ~/development folder
Executed from terminal:  ./arduino

Compile "blink"

Selected Uno device type
Loaded "Blink" from examples
Uploaded (checked Uno showed in menu as shown above)
Got error:
Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device

Check permissions, join dialout and tty groups
See owner of /dev/ttyACM*
$ ls -l /dev/ttyACM*
crw-rw---- 1 root dialout 166, 0 Feb  1 07:32 /dev/ttyACM0

Am I in that group? (No)
getent group dialout
dialout:x:20:

Add to group dialout:
$ sudo usermod -a -G dialout nick

Am I in that group? (Yes)
$ getent group dialout
dialout:x:20:nick

Try again:
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Add to group tty:
$ sudo usermod -a -G tty nick

Check groups I am in:
$ groups nick
nick : nick adm tty dialout cdrom sudo dip plugdev lpadmin sambashare

Try again (same error).
Log out and log back in
After logging out and back in, it uploaded OK! Changed to Micro board (very similar to Leonardo) - still uploaded OK (after changing board type in IDE).
Check USB for Micro
After reset:
$ lsusb | grep Arduino
Bus 002 Device 014: ID 2341:0036 Arduino SA

After about 3 seconds:
$ lsusb | grep Arduino
Bus 002 Device 015: ID 2341:8037 Arduino SA

Did my suggestion (of using the latest IDE) help? You have a bounty on the question, but we aren't getting much feedback on the suggested solutions.

I already had the newest version. Maybe I did read the version number wrong. I downloaded the newesest version 1.6.7 again and also tried the nightly build 1.6.8 (just downloaded). But I still get avrdude: ser_open(): can't open device "/dev/ttyACM0": Device or resource busy and avrdude: ser_send(): write error: Bad file descriptor as error messages in two subsequent lines.

In the arduino IDE (Version 1.6.7, on Kubuntu 15.10) I get: http://pastebin.com/a77ctPEn
With avrdude in the terminal I get: http://pastebin.com/N7AZAhjW

See screenshot of Port menu in my answer.

http://www.renderclonks.de/files/ScreenShotArduino.png  I see nothing special or suspicious

I don't see it detecting the device type, like in my screenshot.

Ah hmm. What could be the problem? Do I need a driver for the Arduino Micro? But https://www.arduino.cc/en/Guide/ArduinoLeonardoMicro says There is no need to install drivers for Ubuntu 10.0.4

See http://playground.arduino.cc/Linux/All - can you please do ls -l /dev/ttyACM* on the terminal, and paste the results into your question.

The result is just crw-rw---- 1 root dialout 166, 0 Jan 28 21:41 /dev/ttyACM0

Are you in group "dialout"? Please do: getent group dialout

dialout:x:20:richard (richard is my username)

Let us continue this discussion in chat.

Do you have any suggestions left what I could try? As mentioned above I tried to use a fresh Ubuntu 15.10 installation and it didn't work neither.

See updated answer where I got it to work on a Ubuntu 14.04 system which did not previously have Arduino IDE installed.

I will look through it and test it this evening. As the bounty period is already over and you had the most effort, I will assign the bounty to you.

You might consider removing the detour through the tty group, since that isn't relevant and the fact that it wouldn't be relevant was already evident from the ownership of the device node.  Without that, it will be clearer to future readers what the effective steps are.

I have been meaning to try the Arduino IDE on Ubuntu. (I'm on Ubuntu 14.10 LTS and using an original Arduino UNO).
From the top, I installed using:
sudo apt-get update && sudo apt-get install arduino arduino-core

(from: http://playground.arduino.cc/Linux/Ubuntu)
It's the older version 1.0.5 and loaded up the basic sketch. It worked straight off the bat.
Just some quick thoughts:
Keyboard and mouse emulation
I noticed the hid-generic and was reminded of the caution on:
https://www.arduino.cc/ re codig practices for keyboard and mouse emulation
regarding coding practices for keyboard and mouse emulation. Does your old sketch utilise the keyboard/mouse libraries at all? It might come down to REALLY timing the reset perfectly.
The reset problem
Given that you're getting a communication error based on the virtual USB device in the Leonardo/Micro (single chip as opposed to the previous versions), and you're seeing it in the IDE but not via the avrdude software, have you followed the reset instructions from the above link? So back to timing the reset (emphasis mine):

In general, you upload code to the Leonardo or Micro as you would with the Uno or other Arduino boards. Click the upload button in the Arduino IDE and your sketch will be automatically uploaded onto the board and then started. This works more or less the same way as with the Uno: the Arduino software initiates a reset of the board, launching the bootloader - which is responsible for receiving, storing, and starting the new sketch.
However, because the serial port is virtual, it disappears when the board resets, the Arduino software uses a different strategy for timing the upload than with the Uno and other boards. In particular, after initiating the auto-reset of the Leonardo or Micro (using the serial port selected in the Tools > Serial Port menu), the Arduino software waits for a new virtual (CDC) serial / COM port to appear - one that it assumes represents the bootloader. It then performs the upload on this newly-appeared port.
These differences affect the way you use the physical reset button to perform an upload if the auto-reset isn't working. Press and hold the reset button on the Leonardo or Micro, then hit the upload button in the Arduino software. Only release the reset button AFTER you see the message "Uploading..." appear in the software's status bar. When you do so, the bootloader will start, creating a new virtual (CDC) serial port on the computer. The software will see that port appear and perform the upload using it. Again, this is only necessary if the normal upload process (i.e. just pressing the uploading button) doesn't work. (Note that the auto-reset is initiated when the computer opens the serial port at 1200 baud and then closes it; this won't work if something interferes with the board's USB communication - e.g. disabling interrupts.)

avrdude command line
Next, share your avrdude command line and we can see if something is odd there. As an example with my UNO I see this:
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build1362089533882735765.tmp/Blink.cpp.hex:i

avrdude: Version 6.0.1, compiled on Oct 21 2013 at 15:55:32
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/madivad/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: Send: 0 [30]   [20]
.... and so on ....

USB 3 vs USB 2
I probably could have put this closer to the top, but are you using a USB 2 or USB 3 port? If USB 3 are the correct drivers loaded? Have you tried a USB 2 port (if available)
Good luck

Thank you for your comment.
I tired different USB ports, also USB 2 ports. I don't use any mouse or keyboard functions in the arduino, so this souldn't apply. I uploaded the bare minimum sketch before (using a windows laptop) to rule out problems from the previous sketch. Holding down the reset button now results in the arduino IDE pretending to upload correctly, but the sketch doesn't work (the LED doesn't blink, and it does if I upload from windows. The avrdude gives an output with "programmer is not responding": http://pastebin.com/iPwFK7yK

You may find that there is a process on Ubuntu that is grabbing the newly created CDC/ACM port as soon as it enters programming mode.
With the Leonardo and Micro you have a CDC/ACM port while it's running, and when the board resets to enter programming mode that CDC/ACM port is destroyed and an entirely new one (hopefully under the same name) is created.  The process modem-manager can grab that newly created CDC/ACM device thinking it's a modem and try to configure it as such, thus locking you out of the port.  A similar process in Debian is brltty which tries to configure the CDC/ACM port as a braille TTY interface.
You can check to see what process has the CDC/ACM device node open if any with the lsof command:
sudo lsof /dev/ttyACM0

If you find that you do have modem-manager running on your system (I'm not sure if it's still default or not, it's been a while since I used Ubuntu, preferring the purity of Debian) it's best to completely remove it:
sudo apt-get remove modemmanager

sudo lsof /dev/ttyACM0 gives an empty output.

Then nothing is locking the file at that moment then.  Still, check to see if modem-manager is running: ps ax | grep -i modem

  787 ?        Ssl    0:00 /usr/sbin/ModemManager  4497 pts/1    S+     0:00 grep --color=auto -i modem
so it appears to be running I think. I will try to remove it.

I uninstalled it as well as brltty, but it didn't change anything.

Make sure that the processes have actually gone - they may still be lingering even after uninstall.

The command ps ax | grep -i modem now doesn't display any processes. I also did a reboot of the laptop and plug out and in again of the arduino to be on the save side. The same holds for brltty

Ok, I think we have exhausted my ideas for the moment. I will keep thinking it over and see if I can come up with anything else.

This is all the symptoms of not having the correct board selected in the IDE.
The fact that the LEDs are flashing during uploading means it's probably not a comms issue.
I understand you wrote that you have selected the correct board already, but please double/triple-check.
I work with both UNOs and Nanos, this is a classic mistake I make all the time.

No, I chose the right board: http://www.renderclonks.de/files/ScreenShotArduino.png

sudo chmod 666 /dev/ttyACM{for your arduino board}
mine happens to be "/dev/ttyACM1" so i did
sudo chmod 666 /dev/ttyACM1

There are two problems here: first, the error is not one of permissions, but that the device is busy, so this won't help.  The other is that this solution is not lasting - if there were an actual permission issue, you'd have to do this each time the Arduino enumerated.  The correct way is to add one's user to the group which owns serial devices, which the asker seems to have already attempted to do.  It's worth noting also that the question is a year and a half old.


text:
RC drag strip finish line with mph calculation (using 1" spaced lasers)
My question is: how do I read multiple inputs at the same time without using interrupts on an UNO.  I'm building an RC drag strip with tree and finish line that will calculate run time as well as calculate each run in mph.  I'm using lasers and non modulated laser detectors for the beams and I'm using a 1" beam gap(between 1st beam and 2nd beam) at the finish line(for mph calculation). My concern comes in when two cars come close enough at the finish line for one to break the first beam at set the win flag but the car in the other lane is close enough to cross the 1st beam before the 1st car actually crosses the 2nd beam then the detection loop is going to miss one of them. (just a note: a few of these cars can top 100 mph when crossing the line)

100mph 5280ft/mi12in/ft/(3600s/h)=1760in/s, so your system needs to measure on the order of 1in/1760in/s = 568 microseconds, broken down tighter for ties.  How many multiples?  Just two? Why not use interrupts?  From http://arduino.stackexchange.com/a/12958/6628 you could approach 0.01" resolution.

then the detection loop is going to miss one of them - how long are the cars? Isn't the bigger issue that the first beam will still be broken, and that the second car won't register at all, regardless of how you program it?

With the beams crossing both/all lanes, overlapping cars will always be an issue.  Whether for determining how fast the first car is or who is second with more than two lanes.  You will need to use separate detectors per lane if you want to avoid this.

@nick, your code in http://arduino.stackexchange.com/a/12958/6628 detected and switched in 1.52us. One could maybe save (PIND_last ^PIND)  and a timer/counter in a table of events with each pin change, and then leave the arming and interpretation to the loop().  You could store timing information at the resolution of the counter, and differentiate ties at the resolution of the interrupt servicing routine.  Maybe I'll copy your code and try that as an answer.

Yes, I was going to try a timing test once we cleared up the issue of the overlapping readings. But I agree it looks like you can get pretty good results.

ONE:
What you can do is use a while loop waiting for the first pulse and then wait until the last pulse, for an idea look at this code from Gadjet, he made a chronograph with a similar operation, you would just need to adapt the design, this might not be as accurate for an 1". Also it will be the issue of having ties between cars. This is short as I don't like this option.
TWO:
Another option, although using what you don't want to use, would be using the interrupts on the Arduino. I am basing the following on the fact that you are using two cars.
What you can do is have a finish line for both vehicles and detect a break with a interrupt, one interrupt pin per lane(UNO has to interrupts).
The trick here is that you place both the outputs from one lane onto a single interrupt pin with a edge detector type of circuit1 to generate a pulse while the vehicle crosses a point, especially important as it will be in the inch area for a while. The code handles the double pulse on one pin. I know this works as I used this on a ballistic chronograph which works in microseconds detecting shots >2000fps over a 0.406 foot distance.
1 This is an example of the circuit you would use at the output of each sensor before the OR gates:

The hardware would just become a duplicate for each lane, and to combine the input on one pin you can use an OR gate IC or you can use diode OR gate:

Interrupts are actually easy to use with Arduinos, and there are a lot of examples out there.
Have a look at the below flow chart to get an idea of operation in the code:

A small thing would be that the code ignores a interrupt once the cars have passed so it doesn't calculate a second time.

Building upon Nick Gammon's excellent answer at How many interrupt pins can an Uno handle? here's some untested code:
 const int events = 256; // events to store
 unsigned volatile int index;
 byte pinStates[events];
 unsigned int times[events];

 ISR (PCINT1_vect) //  Watch for pin changes on the C port (Uno pins A0-A5)
 {
   if (index == 0) { // start clock
    TCCR1B = bit(CS12) | bit (CS10) ;    // clock/1024 for <4.19s x 64us
    //TCCR1B = bit(CS12);                // clock/256  for <1.05s x 16us
    //TCCR1B = bit(CS11) | bit (CS10) ;  // clock/64   for <0.25s x 4us
    //TCCR1B = bit(CS11) ;               // clock/8    for <0.03s x 0.5us
    //TCCR1B = bit(CS10) ;               // clock/1    for <0.004s x 62ns
   }
   times[index] = TCNT1;
   pinStates[index] = PORTC;
   index = (index+1) & 0xff; // increment and protect from overflow

 }  // end of PCINT1_vect

void setup ()
  {
  // activate pin change interrupts on port C / pins A0-A5

  PCICR   =  bit (PCIE1);    // enable PCINT[14:8] pin triggers
  PCMSK1 |=  bit (PCINT8) |
             bit (PCINT9) |
             bit (PCINT10) |
             bit (PCINT11) |
             bit (PCINT12) |
             bit (PCINT13);     // enable individual pins

  // stop and clear 16 bit timer  CS1[0-2]=0; TCNT1 = 0;
  TCCR1A = 0;  // no comparisons, normal WGM mode, stop the counting
  TCCR1B = 0;
  TCNT1  = 0;  // Clear the counter

  pinMode (A0, INPUT_PULLUP);
  pinMode (A1, INPUT_PULLUP);
  pinMode (A2, INPUT_PULLUP);
  pinMode (A3, INPUT_PULLUP);
  pinMode (A4, INPUT_PULLUP);
  pinMode (A5, INPUT_PULLUP);

  index = 0 ; // nothing happened yet

  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {

   // check index, parse and report times, check for arming, etc...

  }

The point is to use the pin change interrupt to record state changes on the pins and the times.   The clock/1024 prescaler would give a 1/16MhZ*1024*65536= 4.19s window at 64us resolution timing counts, but you could go to higher resolution with a tighter window by using a smaller prescaler.
Also, if you wanted longer timing windows, you could cascade timer1 into timer0 (messing up millis(), etc.,) and get 24 bits of range before overflow, but a better way than cascading timers might be to add another interrupt to increment a variable.  For much longer timing windows add another quick interrupt to handle for timer1 overflow.
...
volatile unsigned long int t1Cycles,times[events];
...

ISR(TIMER1_OVF_vect){t1Cycles++;}

void setup(){
    ...
    TIMSK1 = bit(TOIE1);
    t1Cycles = 0;
    ...
}

ISR (PCINT1_vect)
{
    ...
    times[index] = t1Cycles << 16 | TCNT1; // store 32 bit count of clocks
    ...
}

This is still untested, but it looks like it could be capable of 268 seconds worth of 62ns resolution multichannel timing.  With the longer period, you could move the conditional clock-starting code out of the pin-change ISR.

I think I would use a much lower prescaler. Since you have kept the timer stopped until the first pulse, it won't take 4 seconds for the car to cross to the second laser.

One certainly could use a lower prescaler.  I chose the slower speed because my kids just did a pinewood derby race, and wanted to allow plenty of time to measure the slow cars to cross the line.

Are you trying to catch all entries? In that case 4s might be too little. You could catch overflows ... wait you just edited that in. Excellent. Tip: make t1Cycles volatile. Also I think you want to shift t1Cycles left 16, as Timer 1 is a 16-bit timer.

Yes, catching all entries was what I was aiming at.  Thanks for the tips.

I made more edits and it seems to compile for an Uno.  To test it on the AT90usb1286 hardware I've got, I'd need to switch things over to port B.

I chose the slower speed because my kids just did a pinewood derby race - so, not quite 100mph?

One option, if you want very-real-time processing, for a task like this that break neatly into chunks: Have one Arduino per vehicle.
Arduinos are cheap. If they are too expensive, use AtTiny's - they can be had for about a dollar a piece (depending on your currency). You can share a clock/power between a large number of them.
You can either have a "master" Arduino talk to each individual one, to collect the information, or have daisy-chained bus - each one can pass it's data to the next one in the chain (once is has the data, and the next one in the chain indicates it's ready for it).

I think my objection to this would be synchronizing them. Especially if they are each doing different lanes. If they didn't agree exactly on what the time was, they might report the runner-up as the winner.


text:
Code compilation errors for 101 - no errors with Uno
I asked this question before a few days ago about undefined references errors to custom library functions. By accident I found that the code compiled fine when the board target was set to an Uno, not the Intel Curie 101 that I was indending to use (and what is was set to when the errors appear) Can anyone explain why you would get undefined reference errors that are board specific?
Disclaimer - I haven't got access to the hardware I need to test at the moment so I don't know for certain that the code works on an Uno.
Edit:
I have tested the compilation for a few board targets as below

Uno - no errors
Mega / Mega 2560 - no errors
Leonardo - no errors
Due - no errors
101 - undefined reference as detailed in linked question

Additionally, moving the libaries into the sketch folder rather then having them in the Arduino libaries folder stops compilation errors. Is there a difference in how the 101 links to included files?

why did you create a new question instead of updating the original question with this new information?

I made a new question as in my mind this is a different issue to the previous question. The original post was more asking for code advice as that's what I believed the issue was - where as this is now more about the behaviour of Arduino in general. For someone who has the same problems that I have encountered about baord specific compilation errors then this would be a more helpful question would it not?

if the other question gets deleted, then this one becomes broken .... your question should stand on its own

it is unclear what your question actually is .... the Uno and the Curie use different microcontrollers, therefore the libraries are different

@jsotola: The OP's question is about their own library.

error.h is not a good name for a library. Some cores or compilers (the Curie one included) have an "error.h" file within them.

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


text:
MAX6675 gives a climbing reading
I am using a MAX6675 board and a k-type thermal couple to measure temp. The problem is even when running the example the temp value keeps climbing.
MAX6675 test
27.25
C = 27.25
F = 130.10
109.00
C = 218.00
F = 816.80
872.00
C = 1744.00
F = 2624.00
832.00
C = nan
F = nan
512.75
C = nan
F = nan

I am using the max6675.h library. Is there a way to fix this?
#include "max6675.h"

int thermoDO = 4;
int thermoCS = 5;
int thermoCLK = 6;

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
int vccPin = 3;
int gndPin = 2;

void setup() {
  Serial.begin(9600);
  // use Arduino pins
  pinMode(vccPin, OUTPUT); digitalWrite(vccPin, HIGH);
  pinMode(gndPin, OUTPUT); digitalWrite(gndPin, LOW);

  Serial.println("MAX6675 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp

   Serial.print("C = ");
   Serial.println(thermocouple.readCelsius());
   Serial.print("F = ");
   Serial.println(thermocouple.readFahrenheit());

   delay(1000);
}

edit: Added code (https://github.com/adafruit/MAX6675-library/blob/master/examples/serialthermocouple/serialthermocouple.pde)

Code? Wiring? ...?

I think your house is on fire. Or maybe your code is incorrect, but it's impossible to say when you haven't provided it to us.

The output does not look like it came from this sketch, quite apart from the values it prints. Your loop() function is coded to sample and print 2 lines every second: "C = .... \n" "F = .... \n", yet the output you showed has another line preceding each pair. Are you saying the sketch (or the library) is producing 3 lines where only 2 are coded?

I added a line that was just C= thermocouple.readCelsius() Serial.print (C)

Please provide a picture of your wiring, or at the very least confirm that the pins GND, VCC, DO, CS and CLK do indeed go to data pins 2, 3, 4, 5 and 6 respectively - as declared in your code. I assume this is AdaFruit's version of the library? If this all checks out, then it's almost certainly hardware: the thermocouple, the MAX6675, or the Arduino itself.

Check the sensor wiring. The return value NAN indicates that "no thermocouple attached". https://github.com/adafruit/MAX6675-library/blob/master/max6675.cpp#L38

I can confirm that the pins do match and I am using the AdaFruit library ( most current one I could download from using library manager)

After test some other K-type thermal couples on this I am now thinking I just got a bad board. Thanks for all the help

After test some other K-type thermal couples on this I am now thinking I just got a bad board. I was able to order a new one and it worked without issue


text:
Using HC-05 to play a sound on an app
I connected a HC-SR04 Ultrasonic Sensor to Arduino Uno and built the circuit as shown in the link below. I also used the code below the link. Together, this code and the circuit detect any motion that occurs in front of the ultrasonic sensor. When the sensor detects motion, the console in the Arduino IDE prints that it detects motion and how far away the moving object is. Otherwise, nothing is printed.
I created an app using MIT App Inventor. Every time the Arduino detects motion, I want a sound to be played on the phone of the person with the app. In order to do this, I plan on using a HC-05 Bluetooth Module.
Does anyone have any suggestions for how I should build the circuit and what code I should use?
arduinobasics.blogspot.de/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html
#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
 Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

int prevdist = 0;

void loop() {
/* The following trigPin/echoPin cycle is used to determine the
 distance of the nearest object by bouncing soundwaves off of it. */
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);

 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);

 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);

 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;

 if (distance >= maximumRange || distance <= minimumRange){
 //Print "Out of range when there is no object within the range of the ultrasonic sensor.
 Serial.println("Out of range.");
 digitalWrite(LEDPin, HIGH);

 }
 else {

 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */

   if((prevdist - distance) > 10 || (prevdist - distance) < -10)
   {
     prevdist = distance;
     Serial.println("[OBJECT MOVED]");
     Serial.print("Detecting object ");
     Serial.print(distance);
     Serial.println(" cm away");
     Serial.println();
     digitalWrite(LEDPin, LOW);
   }
 }

 //Delay 1 millisecond before next reading.
 delay(1);
}

Every time the Arduino detects motion, I want a sound to be played on the phone of the person with the app. In order to do this, I plan on using a HC-05 Bluetooth Module.
Does anyone have any suggestions for how I should build the circuit and what code I should use?

The Arduino sketch above is a good start.
The first step is to connect the Bluetooth module so that the Serial output can be sent. The circuit is simply connecting the Bluetooth module to RX/TX on the Arduino. I am assuming that you have written an app that can read from Bluetooth on the phone and write to the screen.
The second step is to parse the output and play the sound. That is also part of the app and not the code on the Arduino. To make this easier the sketch output statements can be changed to something easier to parse (detect).
All and all the work is mainly app programming.
Cheers!


text:
Weird stepper motor behaviour on RAMPS in arduino
Following this tutorial:
http://www.instructables.com/id/Complete-newbie-step-by-step-3D-printer-with-all-p/?ALLSTEPS
I connected DVD stepper motor to RAMPS 1.4 on arduino with Marlin software with this settings:
 //#define DEFAULT_AXIS_STEPS_PER_UNIT   {80,80,4000,500}  // default steps per unit for Ultimaker

 #define DEFAULT_AXIS_STEPS_PER_UNIT {215.12,215.12,8034.69,196.52}

 // #define DEFAULT_MAX_FEEDRATE          {300, 300, 5, 25}    // (mm/sec)

 #define DEFAULT_MAX_FEEDRATE {100, 100, 2, 25}

 // #define DEFAULT_MAX_ACCELERATION      {3000,3000,100,10000}    // X, Y, Z, E maximum start speed for accelerated moves. E default values are good for Skeinforge 40+, for older versions raise them a lot.

 #define DEFAULT_MAX_ACCELERATION {200,200,50,5000}

 #define DEFAULT_ACCELERATION          100    // X, Y, Z and E acceleration in mm/s^2 for printing moves

 #define DEFAULT_RETRACT_ACCELERATION  100    // E acceleration in mm/s^2 for retracts

 #define DEFAULT_TRAVEL_ACCELERATION   100    // X, Y, Z acceleration in mm/s^2 for travel (non printing) moves

I put a video at vid.me (hopefully with sound) showing stepper behaviour when I press +1mm,-1mm,-1mm,-1mm,-1mm,-1mm,-1mm,+1mm,+1mm,+1mm,+1mm  on Pronterface software.

What did you expect/want to happen, and how is that different from what actually happened? Do know know how to detect which 4 wires from RAMPS go to which 4 wires on the stepper motor? What happens when you use a slower acceleration?

The video you show shows movement of far more than 1mm.  This indicates that the steps per unit is far different than you are configuring the Marlin software for.  With a +/-1mm and 212 steps per mm, there should have been 212 steps sent to your stepper.
Recalculate your steps/mm values and slow down the feed rate to get something reliable.
For experimenting, in Pronterface, set the feedrate of 10mm/sec (600mm/min) or 1mm/sec (60mm/min) to slow things down so you can hear or count the steps with your ear, then choose smaller steps, like +0.1mm and see if you get the planned displacement.  If, at a really slow speed, you don't get the corresponding movement, then your steps/mm need adjustment to match your system.
Eyeballing it, I'd say the called-for 1mm or 212 steps is moving the stage about 10mm, so you would need numbers more like this for the x and y axes:
#define DEFAULT_AXIS_STEPS_PER_UNIT {21 ,21 ,8034.69,196.52}


text:
Arduino DC motor causes disturbance. What can cause it?
I tried to fix this problem the whole weekend but, after no success I decided to post it here. I would really appreciate any help.
The problem
The Wi-Fi module activates the DC motor and lets it run for 3 seconds, but when the DC motor stops after that 3 seconds, the Wi-Fi module and display don't respond anymore.  It only works once.  (After I push the reset button the same thing happens.)
Question
What causes this disturbance? Any advice on my circuit? (I included a Fritzing Diagram because I am bad at drawing schematics)

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
SoftwareSerial ESP8266(9, 8); // RX = 8 en TX = 9

#define DEBUG true

boolean FAIL_8266 = false;
int LED = 13; // led op 13

int secondeAan = 3000;

String my_AP_SSID = "myID";
String my_AP_Pass = "myPass";

void setup()
{
  // -- stel led in --
  pinMode(LED, OUTPUT);

  // -- lcd scherm --
  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(0, 1);

  do {
    ESP8266.begin(115200); // start communicatie met esp8266

    //Wait Serial Monitor to start
    while (!Serial);

    lcd.clear();
    lcd.print("--- Start ---");

    ESP8266.print("AT\r\n");
    delay(500);

    if (ESP8266.find("OK"))
    {
      FAIL_8266 = false;
      sendData("AT+RST\r\n", 4000, DEBUG);
      sendData("AT+CWMODE=3\r\n", 2000, DEBUG);
      sendData("AT+CWJAP=\"" + my_AP_SSID + "\",\"" + my_AP_Pass + "\",9,4\r\n", 2000, DEBUG);
      sendData("AT+CIFSR\r\n", 2000, DEBUG);
      sendData("AT+CIPMUX=1\r\n", 2000, DEBUG);
      sendData("AT+CIPSERVER=1,80\r\n", 2000, DEBUG);

    } else {
      lcd.clear();
      lcd.setCursor(0, 1);
      lcd.print("Module have no response.");
      delay(500);
      FAIL_8266 = true;
    }
  } while (FAIL_8266);
}

void loop()
{
  // Get the number of bytes (characters) available for reading from the serial port
  if (ESP8266.find("+IPD,"))
  {
    lcd.clear();
    lcd.print("Nieuwe connectie");
    // -- sluit connectie --
    motorToggle();
    sendData("AT+CIPCLOSE=0\r\n", 100, DEBUG);
    sendData("AT+CIPCLOSE=1\r\n", 100, DEBUG);
    sendData("AT+CIPCLOSE=2\r\n", 100, DEBUG);
  }
}

void motorToggle () {
  digitalWrite(LED, HIGH);
  lcd.clear();
  lcd.print("eten gegeven");
  delay(secondeAan);
  digitalWrite(LED, LOW);
  delay(200);
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";

  ESP8266.print(command); // send the read character to the esp8266

  long int time = millis();

  while ( (time + timeout) > millis())
  {
    while (ESP8266.available())
    {
      char c = ESP8266.read();
      response += c;
    }
  }

  if (debug)
  { lcd.clear();
    lcd.print(response);
  }

  return response;
}

Can the Uno provide 3.3V power for the esp8266? Should have a 3.3V regulator from 5V instead. And a few very large capacitors. This reference might help: http://iot-playground.com/2-uncategorised/17-esp8266-wifi-module-and-5v-arduino-connection. Cheers!

@MikaelPatel  Thanks for the comment! Do you think this causes the disturbance? The esp8266 works fine without the dc motor running

Exceeding the 3.3v regulator capability is possibly an issue, yes.  You might also put a small ceramic disc capacitor across the motor terminals or one between each terminal and the can.  That used to be considered necessary to suppress interference to lower frequency analog RC gear, it may be less so at 2.4 GHz but still isn't a bad idea.

Are you sure this is a hardware issue and not a software issue? Can you post some example code? Based on the information provided, it is impossible to know if it is infact the motor that causes the issue.

Since the motor runs open loop, simply disconnexting the motor while running software that assumes it is still there should clarify if it is a hardware or software issue.

@ChrisStratton MattClark   My guess it is a hardware issue because, when I disconnect the battery that supplies the dc motor everything works fine. I shall add the arduino code to my post

The battery wiring looks odd in the diagram, is it correct? Replace the motor with an open circuit or dummy resistor to eliminate it as a cause.  Is your FET and resistor working as expected? Can you check it out with a DMM?  A 2k2 resistor should limit the draw on the UNO to ~2mA.

Thanks for the help everyone. I fixed it by using Capacitors. They suppress the noise that the dc motor produces. I found my information  here

There are a couple of things that could be causing your problems:

The current draw of the motor, especially at start up. The motor may be drawing enough power to pull down the voltage at the processor causing it to crash, or
You may be seeing transients as the motor starts and/or stops that are causing the processor to crash.

One way you could detect problems like this is to use the on-board LED as a heart beat or run indicator. You could either blink it in loop() or do something like turn it off just before starting or stopping the motor and then back on afterwards. If the blink stops or if the LED goes out then you know that the processor has stopped running.
As a general rule, except with the tiniest of motors, I'd suggest using the Arduino to control a transistor that controls the motor from its own power supply line (it could be the same supply as the one the feeds the Arduino, just don't run the motor power through the Arduino). That and the suggestions in the comments will go a long way towards isolating the Arduino from the motor and power disturbances it will cause.

Note that the poster is already "using a transistor that controls the motor from its own power supply"

Ack, missed that…


text:
ESP8266 as wifi Card?
I am very new to arduino and electronics in general. Can i use the NodeMcu Esp8266 as one of those usb wifi dongles? I want to use it as a monitor mode capable wifi card, for my linux laptop.

No, you can't. All you have is a UART interface through a USB to UART adaptor. It can only ever be a UART.
The best you could get would be to write a program to run on the NodeMCU that did the monitoring for you (assuming you can get it into a suitable promiscuous mode) and report information back to you through the UART.


text:
Fluctuating readings of LM35 temperature sensor (+- 5°C) with Arduino UNO
I am trying to read a LM35 temperature sensor with Arduino UNO which I got as a gift.
The issue is the fact, that my readings of sensor are, well, suspicious at least - they jump with each reading some 5 °C up or down.
I had used several posts how to wire  the thing to Arduino board and for and program the reading (1, 2, 3) and produced the code posted below. The sensor reading fluctuates really a lot - it jumps by some 3 to 7 °C after  each reading regardless of reading frequency (tested with reading each 0.5 s, 1.0 s or 2.5 s). (Unfortunately I do not own a multi-meter to check actual values.) To mitigate the issue I implemented an averager, but underlying problem stays. Expected values are something like 23 or 24 °C as measured by digital weather station and bimetallic thermometer respectively.
Have you met this before ? Do you have any ideas what might be source of this ? I am beginner to electronics as well as to Arduino, trying to learn and mainly understand it.
The complete code:
#include <WString.h>

//Stores read analog values
int readLM35;
const int sensorAnalogPin = 0;
const float voltsToTemperature = 1.1 / 1023 * 100; // (1.1V supply / 10bit resolution) * (10 mV/°C = 1 V / 100 °C)
//Stores the temperature in °C
float temp;
//Averager
float temps[8];
byte position = 0;
float averageTemp;

void setup() {
    Serial.begin(9600);
    pinMode(LED_BUILTIN, OUTPUT);

    //For setting internal analog reference voltage to 1.1V
    analogReference(INTERNAL);
}

void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(50);
    digitalWrite(LED_BUILTIN, LOW);

    //Measure temperature
    readLM35 = analogRead(sensorAnalogPin);
    temp = readLM35  * voltsToTemperature;

    //Save it
    temps[position] = temp;
    if (position == 7) {
        position = 0;
    } else {
        position++;
    }

    //Get average
    averageTemp = 0;
    for (byte i = 0; i < 8; i++) {
        averageTemp += temps[i] / 8;
    }

    //Write
    Serial.println(String(readLM35) + " => " + String(temp, 1) + " deg. C, avg. " + String(averageTemp, 1));
    delay(2500);
}

Example of output (note the first numbers - actual reading):
211 => 22.7 deg. C, avg. 22.5
186 => 20.0 deg. C, avg. 21.9
234 => 25.2 deg. C, avg. 22.7
173 => 18.6 deg. C, avg. 21.9
237 => 25.5 deg. C, avg. 22.6
185 => 19.9 deg. C, avg. 21.9
231 => 24.8 deg. C, avg. 22.4
193 => 20.8 deg. C, avg. 22.2
223 => 24.0 deg. C, avg. 22.3
206 => 22.2 deg. C, avg. 22.6
197 => 21.2 deg. C, avg. 22.1
225 => 24.2 deg. C, avg. 22.8
183 => 19.7 deg. C, avg. 22.1
240 => 25.8 deg. C, avg. 22.8

I don't see any decoupling capacitors (100 nF typically) at the LM35. Check the datasheet for recommendations.

+1 more for same.  Very good question.  I would give another +1 for the averaging code if I could.  You're on the right track.  I always use .1 uF caps on my analog inputs like this.  Non-electrolytic.  I avoid ceramic but tantalum and mica are fine.  It can be larger in value but won't help much.  A little will help.  But perhaps a tad more than the aluminum foil & Saran Wrap.  ;-)    (By the way, @analogsystemsrf, you remind me of doing something similar with newspapers on the coffee table.  Feeding audio into the primary on a hi-V transformer then the secondary to the foil makes a speaker)

@SDsolar ... can you explain why you avoid ceramic (and non-electrolytic)?

The cause is the low sinking capabilities of LM35 output. This makes the output sensitive to EMI. Yes, the output output impedance is stated as 0.5 ohms but only for sourcing current. The sinking current is limited to 1uA which is easily achieved by the environment noise.

You need to add a low impedance load between LM35 output and ground, can be 200 ohm as the data sheet recommends for heavy capacitive loads but I wouldn't go that far, might be 1k or 2k to avoid self heating errors.
No software only solution can solve this error.

I guess when 0 = 0 and 5V = 1023, then you should divide by 1023.
Looking at the question, I notice that you use AnalogPin = 0. Myself, I would stick to AnalogPin = A0.
A0 is defined as:
define PIN_A0   (14)
so it is not equivalent to 0.
Are you sure you're reading the right pin? Also try another pin like A3.

Using 0, A0 or 14 will read from the same analog pin.

Why have you done 1.1/1023. Your saying that the supply is 1.1v but your supplying it 5v. I use (readLM35/1024)*500 to get temperature value in °C and it is on par with a thermometer I have bought. If this doesn't work try with another lm35. You might just have a faulty one.
Also the LM35 is factory calibrated for voltage. So you have to calibrate it according to the Arduino you use.
I would recommend the ds18b20 as it's calibrated for temperature. Using the Dallas temperature library makes it easier to use as well

If issue with readings persist, put an RC circuit for measuring the voltage as it is similar to averaging done in software. Another thing that you can try is replacing the LM35 with a new one as sometimes it could be faulty or you might have damaged it(has happened with me). However u can easily check this by measuring the voltage at the sensing pin whether it corresponds to what you are getting. If you are working with electronics please invest in a multi-meter as it will help you in all your projects

this is a known issue for all Arduino sensors (fluctuations and drift), I also had this problem with humidity sensor and water level sensor with LM393 comparator, what I tried to do to make the fluctuations less was trying to calculate average readings instead of single reading:
for (int i = 0; i < 100; i++)
{
levelSensorValue = levelSensorValue + analogRead(levelSensorPin);
moistureSensorValue = moistureSensorValue + analogRead(moistureSensorPin);
}
levelSensorValue = levelSensorValue / 100;
moistureSensorValue = moistureSensorValue / 100;

generally speaking, all sensors have a linear range witch cannot be reliable beyond it, and also calibration for them is necessary.

many answers, stick to the code or the LM35 itself rather than the main part, the ADC.
when you are reading a [approximately] right temperature, well, then the code, vRef and pin config is right.
I had problem with ADCs as I had to measure many voice signals for my thesis. here are some problems which may occur :

double check if the board itself, has proper AVCC/AREF decoupling caps. many clone boards doesn't pay attention to production failures. decoupling caps usually connect between ground (GND) and a positive supply line(like VCC) to filter out noise.
if you have access to the AVCC/AREF pin, connect 2 or 3 paralleled 100nf caps between them and ground. the values are not critical. anything in the 10nF up to 10uF range is fine. you can use different values for each cap.
check your input power supply noise. computer USB port is the most trusted power supply. other power supplies (wall adapters, cheap power banks etc.) have some unimaginable noise.
use caps (decoupling caps. the caps which are connected between + and - pins) on every single component or sensor. like LCDs, LM35 sensor... .
try to use the exact code and sensor on other analog pins and if you got any, another Arduino. if the problem insists, then you can check for another LM35, or the code like the others said. but if the problem didn't exist, then the board has a problem. any faulty component in supply line can cause this. from regulators to a bad joint or PCB via.

While I agree that a computer's USB port power is a lot cleaner than a Chinese power brick, it is not the cleanest. There are various DC-DC modules that will provide a very clean output, and if you want perfectly smooth power you can't beat a chemical battery. I never design for these but I do use them for troubleshooting.