text:
Trying to get my MPU chip to work
I'm new to Arduino and I'm trying to get my MPU 6050  chip to work. The simple code runs fine but when I use the downloaded example I get the following:
Arduino: 1.6.5 (Windows 7), Board: "Arduino/Genuino Uno"
Build options changed, rebuilding all
....

g.cpp.o

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-gcc -w -Os -Wl,--gc-sections -mmcu=atmega328p -o C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp/MPU6050_DMP6.cpp.elf C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050_DMP6.cpp.o C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\Wire\Wire.cpp.o C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\Wire\utility\twi.c.o C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp/core.a -LC:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp -lm

C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setRate(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:133: undefined reference to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setExternalFrameSync(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:175: undefined reference to `I2Cdev::writeBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setDLPFMode(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:218: undefined reference to `I2Cdev::writeBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setFullScaleGyroRange(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:253: undefined reference to `I2Cdev::writeBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setFullScaleAccelRange(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:387: undefined reference to `I2Cdev::writeBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setMotionDetectionThreshold(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:531: undefined reference to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setMotionDetectionDuration(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:561: undefined reference to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setZeroMotionDetectionThreshold(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:601: undefined reference to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setZeroMotionDetectionDuration(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:632: undefined reference to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setSlaveAddress(unsigned char, unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:972: undefined reference to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o:C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:1558: more undefined references to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)' follow
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::getIntStatus()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:1687: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:1687: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:1687: undefined reference to `I2Cdev::readByte(unsigned char, unsigned char, unsigned char*, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setFIFOEnabled(bool)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2351: undefined reference to `I2Cdev::writeBit(unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setI2CMasterModeEnabled(bool)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2375: undefined reference to `I2Cdev::writeBit(unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::resetFIFO()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2391: undefined reference to `I2Cdev::writeBit(unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::resetI2CMaster()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2400: undefined reference to `I2Cdev::writeBit(unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::reset()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2426: undefined reference to `I2Cdev::writeBit(unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o:C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2450: more undefined references to `I2Cdev::writeBit(unsigned char, unsigned char, unsigned char, unsigned char)' follow
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setClockSource(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2543: undefined reference to `I2Cdev::writeBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::getFIFOCount()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2708: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2708: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2708: undefined reference to `I2Cdev::readBytes(unsigned char, unsigned char, unsigned char, unsigned char*, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::getFIFOBytes(unsigned char*, unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2744: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2744: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2744: undefined reference to `I2Cdev::readBytes(unsigned char, unsigned char, unsigned char, unsigned char*, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::getDeviceID()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2764: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2764: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2764: undefined reference to `I2Cdev::readBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char*, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::getOTPBankValid()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2785: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2785: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2785: undefined reference to `I2Cdev::readBit(unsigned char, unsigned char, unsigned char, unsigned char*, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setOTPBankValid(bool)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2789: undefined reference to `I2Cdev::writeBit(unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::getXGyroOffsetTC()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2792: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2792: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2792: undefined reference to `I2Cdev::readBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char*, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setXGyroOffsetTC(signed char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2796: undefined reference to `I2Cdev::writeBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::getYGyroOffsetTC()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2802: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2802: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2802: undefined reference to `I2Cdev::readBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char*, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setYGyroOffsetTC(signed char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2806: undefined reference to `I2Cdev::writeBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::getZGyroOffsetTC()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2812: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2812: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2812: undefined reference to `I2Cdev::readBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char*, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setZGyroOffsetTC(signed char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2816: undefined reference to `I2Cdev::writeBits(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setZAccelOffset(int)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2876: undefined reference to `I2Cdev::writeWord(unsigned char, unsigned char, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setXGyroOffset(int)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2886: undefined reference to `I2Cdev::writeWord(unsigned char, unsigned char, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setYGyroOffset(int)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2896: undefined reference to `I2Cdev::writeWord(unsigned char, unsigned char, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setZGyroOffset(int)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2906: undefined reference to `I2Cdev::writeWord(unsigned char, unsigned char, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setDMPEnabled(bool)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2971: undefined reference to `I2Cdev::writeBit(unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::resetDMP()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2974: undefined reference to `I2Cdev::writeBit(unsigned char, unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setMemoryBank(unsigned char, bool, bool)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2983: undefined reference to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setMemoryStartAddress(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2989: undefined reference to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::readMemoryByte()':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2995: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2995: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:2995: undefined reference to `I2Cdev::readByte(unsigned char, unsigned char, unsigned char*, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::readMemoryBlock(unsigned char*, unsigned int, unsigned char, unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:3016: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:3016: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:3016: undefined reference to `I2Cdev::readBytes(unsigned char, unsigned char, unsigned char, unsigned char*, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::writeMemoryBlock(unsigned char const*, unsigned int, unsigned char, unsigned char, bool, bool)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:3060: undefined reference to `I2Cdev::writeBytes(unsigned char, unsigned char, unsigned char, unsigned char*)'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:3066: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:3066: undefined reference to `I2Cdev::readTimeout'
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:3066: undefined reference to `I2Cdev::readBytes(unsigned char, unsigned char, unsigned char, unsigned char*, unsigned int)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::writeDMPConfigurationSet(unsigned char const*, unsigned int, bool)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:3170: undefined reference to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setDMPConfig1(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:3198: undefined reference to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)'
C:\Users\Emma\AppData\Local\Temp\build2536911660206936106.tmp\MPU6050\MPU6050.cpp.o: In function `MPU6050::setDMPConfig2(unsigned char)':
C:\Users\Emma\Documents\Arduino\libraries\MPU6050/MPU6050.cpp:3208: undefined reference to `I2Cdev::writeByte(unsigned char, unsigned char, unsigned char)'
collect2.exe: error: ld returned 1 exit status
Error compiling.

Help would be most appreciated
Thanks!

Do you have the i2cdev library installed?

when I use the downloaded example - I don't see any code in your post, nor any reference to what you are talking about.

What URL did you download the example from?

You seem to be missing the I2C header.
If you are using the Arduino IDE, beware that it has its own whacky idea of where headers should be. Try adding the #include to the .ino file.

Get i2cdevlib from this linkhttp://github.com/jrowberg/i2cdevlib or just  git clone if your linux user.
then go to i2cdevlib--> arduino folder.There have a folder name with I2Cdev ,just copy that folder in to your library folder in your workspace and then restart the IDE .It will compile now


text:
A/C doesn't detect IR codes sent from Arduino
I have an IR receiver and an IR LED I got from a kit (I don't have the datasheets for them).
I uploaded an Arduino sketch to record my A/Cs IR codes. Those were NEC encoded 32bit integers.
After recording the codes, I tried retransmitting them. The A/C unit failed to detect the signals.
Troubleshooting a bit, I sent the code from the Arduino the receiver sketch from the previous step - it received them successfully.
All the above steps used the IRRemote Arduino library
The question is, what could explain this behavior?
A few possibilities I had in mind:

IR frequency. Could it be that the detection circuit worked with the default settings but transmitting wouldn't?
IR wavelength. Any chance the A/C side doesn't detect my IR pulses at all?
Decoding/Encoding of the NEC protocol in IRRemote. If there is no standard for the NEC protocol, the Arduino and A/C implementation might be a little different.

Is it an NEC air conditioner? I think the IR library has a "raw" mode - you could try that, which more exactly replicates exactly what it received. I think your solutions (1) and (2) are a little unlikely, but feasible.

You could try a different library: http://tech.cyborg5.com/irlib/

range. The ir led you use could be far weaker than the one in the remote. Try placing the arduino right next to the AC unit.

@NickGammon It's not a NEC air conditioner. It just uses the NEC IR protocol. As for your RAW mode suggestion, I tried it, but the raw receiver generates both negative and positive values. I'll try to give it another try and try the other library as well. Thanks!

HI I have put my answer on the link below. https://stackoverflow.com/questions/44528781/clone-remote-using-arduino-with-the-irremote-library/45955124#45955124 Please let me know if it works for you. Let me know if you need help.

Simple brightness is also an issue. Have you tried various positions of the LED with respect to the sensor? Lowering the current-limiting resistor value?

Hi i have done the same thing. I was using this to get the AC codes for the GREE AC. I find it with two weeks struggle and a forum called AnalysIR. If you find any issue in this code below or method let me know.
AC codes are usually long and those doesn't come right with the code which you used above so i am giving you the sample code to run in the Arduino sketch so that you can test.
   #define LEDPIN 13
  //you may increase this value on Arduinos with greater than 2k SRAM
  #define maxLen 800

       volatile  unsigned int irBuffer[maxLen];
       //stores timings - volatile because changed by ISR
       volatile unsigned int x = 0;
       //Pointer thru irBuffer - volatile because changed by ISR

     void setup() {
     Serial.begin(115200); //change BAUD rate as required
     attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);
    //set up ISR for receiving IR signal
     }

 void loop() {
   // put your main code here, to run repeatedly:

   Serial.println(F("Press the button on the remote now - once only"));
    delay(5000); // pause 5 secs
  if (x) { //if a signal is captured
digitalWrite(LEDPIN, HIGH);//visual indicator that signal received
Serial.println();
Serial.print(F("Raw: (")); //dump raw header format - for library
Serial.print((x - 1));
Serial.print(F(") "));
detachInterrupt(0);//stop interrupts & capture until finshed here

for (int i = 1; i < x; i++) { //now dump the times
  if (!(i & 0x1)) Serial.print(F("-"));
  Serial.print(irBuffer[i] - irBuffer[i - 1]);
  Serial.print(F(", "));
                     }

   x = 0;
   Serial.println();
   Serial.println();
   digitalWrite(LEDPIN, LOW);//end of visual indicator, for this time
   attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//re-enable ISR for            receiving IR signal
        }

      }

  void rxIR_Interrupt_Handler() {
    if (x > maxLen) return; //ignore if irBuffer is already full
     irBuffer[x++] = micros(); //just continually record the time-stamp of signal transitions

    }

Once this is done you will get the right code to send it to the AC.
A little Tricky part
once you will receive the codes of raw values you will have to little modify it for example i got the raw values and i converted it into the array.
What i received for example
Raw (16): -27750, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628
To Convert the above raw values into array remove first value which is -27750 and put 3800 instead of that. Below is the array sample.**
unsigned int data[] = {3800, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628,
};
Now sending these values to the IR transmitter use this code below.
      #include<IRremote.h>
       IRsend irsend;
       int KHz = 38;                    // default frequency

      unsigned int data[] = {3800, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628,
        };

    void setup()
   {
     Serial.begin(9600);
     irsend.enableIROut(38);
   }

    void loop()
   {

    for (int i=0; i<1 ; i++){
    irsend.sendRaw(data, sizeof(data) / sizeof(int),38 );
    delay(40);
          }

 }

source: Stack Exchange

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

sort: votes


text:
Standalone Arduino
I have an Arduino Uno and I am using arduino 1.0.5 IDE. I followed he procedures for bootloading an atmega328P-PU on a breadboard using an Arduino Uno from the link:
https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard
I uploaded the ArduinoISP sketch first, made the connections(using the External Oscillator) and then wired it up. Then, I selected the programmer as Arduino as ISP, selected the board as Arduino duemilanove w/ Atmega328P . Then I selected the correct serial port and clicked Burn Bootloader. I got the following errors:
avrdude.exe: stk500_program_enable(): protocol error, expect=0x14,
resp=0x50avrdude.exe: initialization failed, rc=-1 Double check
connections and try again, or use -F to override this
check.avrdude.exe: stk500_disable(): protocol error, expect=0x14,
resp=0x51

How to solve this issue? Also, can I upload the bootloader directly by using it on the Uno in place of the original chip. If so, how?

On the Arduino Uno, you'll need to connect a 10 uF capacitor between reset and ground (after uploading the ArduinoISP sketch) source (PS <rant>I'm getting very annoyed by the inaccuracies on the arduino website. New users continue to have to figure out why things don't work, while the problem has been known for years.</rant>)

See How to make an Arduino-compatible minimal board.

Also, can I upload the bootloader directly by using it on the Uno in place of the original chip.

No, a blank chip cannot install its own bootloader. You use a second chip. My page above describes how to do that. An alternative is a stand-alone ICSP programmer, which can be purchased for around $20. The tutorial page you linked uses your Uno as a stand-alone programmer.
I think my method of using a Uno as a programmer is easier, frankly.

Hey, I followed your procedure for making Arduino Compatible minimal breadboard. I had to use an external oscillator. But when I run the code my output is not what it should be. I get the following output
"MD5 sum of bootloader = 0x6A 0xE5 0x9E 0x64 0x85 0x03 0x77 0xEE 0x54 0x70 0xC8 0x54 0x76 0x15 0x51 0xEA
No bootloader (all 0xFF)"
What should i do now?

Please edit your question, and post the exact output (copy and paste) from the bootloader uploading program. Turn it into "code format" by selecting all of the output and hitting Ctrl+K.

I had the same problem; I never figured it out. I eventually threw down some cash for am ICSP (I got the FreeTronics USBASP), and have never looked back. In fact, with an ICSP, you don't even need a bootloader. It's also real easy to solder a 6-pin header onto your custom soldered board; then you will realize you don't need an Arduino at all, just an Atmel chip.

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


text:
Reading from a KY-040 rotary encoder with Digispark
I have a rotary encoder KY-040 connected to a Digispark like this:

CLK go to p0 and and DT go to p2, SW is disconnected for now (it's just a button).
I did everything like the instructions here: http://henrysbench.capnfatz.com/henrys-bench/keyes-ky-040-arduino-rotary-encoder-user-manual/
#include <DigiKeyboard.h>

 int pinA = 0;  // Connected to CLK on KY-040
 int pinB = 2;  // Connected to DT on KY-040
 int encoderPosCount = 0;
 int pinALast;
 int aVal;
 boolean bCW;

 void setup() {
   pinMode (pinA,INPUT);
   pinMode (pinB,INPUT);
   /* Read Pin A
   Whatever state it's in will reflect the last position
   */
   pinALast = digitalRead(pinA);
   Serial.begin (9600);
 }

 void loop() {
   aVal = digitalRead(pinA);
   if (aVal != pinALast){ // Means the knob is rotating
     // if the knob is rotating, we need to determine direction
     // We do that by reading pin B.
     if (digitalRead(pinB) != aVal) {  // Means pin A Changed first - We're Rotating Clockwise
       encoderPosCount ++;
       bCW = true;
     } else {// Otherwise B changed first and we're moving CCW
       bCW = false;
       encoderPosCount--;
     }
     Serial.println("Rotated: ");
     if (bCW){
       //Serial.println ("clockwise");
       DigiKeyboard.sendKeyStroke(KEY_V); //or DigiKeyboard.write("1");
     }else{
       //Serial.println("counterclockwise");
        DigiKeyboard.println("cc");
     }
     Serial.print("Encoder Position: ");
     Serial.println(encoderPosCount);

   }
   pinALast = aVal;
 }

I only changed the pin numbers in the code and the Serial.println (... to any of the following:
DigiKeyboard.write("1");
DigiKeyboard.println("1");
DigiKeyboard.sendKeyStroke(KEY_V);

All of them didn't do anything when rotating the knob...
Any ideas?
Maybe the 10K resistors are too much?

This might help: https://github.com/Bluebie/volume_knob/blob/master/volume_knob.ino

Shown below is a KY-040 test program that in my tests doesn't lose any counts and is more accurate than some other software; it picks up the counts between detents as well as those at detents.  You may be able to adapt it to your DigiKeyboard ATtiny system.
/*  roto_jw4.ino -- JW, 29 September 2015 --
 *  A 4-state state-machine implementation of rotary
 *  encoding for KY-040 rotary knobs.  The state-machine picture at
 *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
 *  in a Feb 4, 2014 7:40 PM post by Anthony Seely shows counts
 *  increasing on transitions 10 -> 11 -> 01 -> 00 -> 10 and
 *  decreasing on transitions the other way.  Transitions between 00
 *  and 11 or 10 and 01 are invalid.  This code detects valid
 *  transitions by (abOld xor abNew) equaling 1 or 2.  It detects
 *  up-count events by the tri-bit value ABA' (where A' is the new
 *  reading on pin A) being equal to 1, 2, 5, or 6 (a bit mask of
 *  0x66), and down-count events by ABA' being equal to 0, 3, 4, or 7
 *  (a bit mask of 0x99).
 *
 *  On a KY-040 unit I tested, there are 30 detent positions per turn.
 *  With this unit the code generates 60 counts per turn, which can be
 *  seen individually as one turns the rotor slowly.  Odd counts
 *  appear between detents, even counts at detents.
 *
 *  Set quadrature-signal pin numbers, via PinA and PinB constants.
 *  Set IPINMODE to INPUT_PULLUP if there are no external pull-ups
 *  on encoder AB pins, else set IPINMODE to INPUT
 */
enum { PinA=2, PinB=3, IPINMODE=INPUT };

static  byte abOld;     // Initialize state
volatile int count;     // current rotary count
         int old_count;     // old rotary count

void setup() {
  pinMode(PinA, IPINMODE);
  pinMode(PinB, IPINMODE);
  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);
  abOld = count = old_count = 0;
  Serial.begin(115200);
  Serial.println("Starting Rotary Encoder Test");
}

// On interrupt, read input pins, compute new state, and adjust count
void pinChangeISR() {
  enum { upMask = 0x66, downMask = 0x99 };
  byte abNew = (digitalRead(PinA) << 1) | digitalRead(PinB);
  byte criterion = abNew^abOld;
  if (criterion==1 || criterion==2) {
    if (upMask & (1 << (2*abOld + abNew/2)))
      count++;
    else count--;       // upMask = ~downMask
  }
  abOld = abNew;        // Save new state
}

void loop() {
  if (old_count != count) {
    Serial.print(millis());
    Serial.print("  ");
    Serial.println(count);
    old_count = count;
  }
}

Since some ATtiny's only have one external-interrupt pin, it may be necessary to use two pin-change interrupts instead of two external-interrupt pins.
(Six of the pins on an ATtiny45, for example, support pin-change interrupts, and only one is an external-interrupt pin.) Change PinA and PinB to appropriate pin numbers, and replace
  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);

with
  enableInterrupt(PinA, pinChangeISR, CHANGE); // Set up pin-change interrupts
  enableInterrupt(PinB, pinChangeISR, CHANGE);

and add the following #include near the beginning:
#include <EnableInterrupt.h>

To install the .h file for use via the Arduino IDE, unpack an EnableInterrupt zip file (for example, enableinterrupt-0.8.2.zip from bintray.com/greygnome) in the directory ~/sketchbook/libraries.  I think the package works with ATtiny's as well as more-standard Arduinos.

This is the only code so far worked for me. All the others caused erratic outputs at some encoder ticks. How to adjust this code so to have only one count output for each tick. I mean your code outputs two consecutive numbers for each tick like this for example for 5 ticks I get: 12 34 56 78 910 But I want to get 1 2 3  4 5. How can I do that? Thanks in advance.

@user16307, There are several ways; which is best depends on intended use.   You can:  • Divide count by 2 before using it  • Use the count only if (count&1), or !(count&1), ie, only when odd (or even) • In ISR, instead of count++ say icount++, where icount is a static internal counter, and then say, count += icount&1, or count += 1-(icount&1) to increment  count only when icount is odd (or even); and similarly for the count-- case.  Please let me know if you find bugs in any of these approaches if you try them.  Thanks!

@JamesWaldby-jwpat7, your answer is so great! It helped me with proper values from the encoder. Please, could you explain pinChangeISR function? I am new to cpp and I would like to understand it. I understand that there are bit operations and shifts, but explanation would be great. thank you

@Dawe, I will edit the answer next week to add some detail re pinChangeISR.  For the moment, refer to the comments in the first paragraph of code and to the referenced state machine diagram

 int pinA = 0;  // Connected to CLK on KY-040
 ...
   Serial.begin (9600);

Hardware Serial uses pins 0 and 1. I would try other pins. (Oh, it's an ATtiny - well I'm not sure about HardwareSerial on that, but it looks suspicious).
See my page about rotary encoders for more ideas.

I only changed the pin numbers in the code and the Serial.println (... to any of the following:

Maybe post the code you actually used, that would be helpful. Not some code you didn't use.

Maybe the 10K resistors are too much?

No, that looks fine.

This is the code I used, the only difference was with changing the Serial.println (... to other things as I mentioned.
On the digispark p3,p4 are used for usb communication, p5 is the reset and p1 is connected to the led so I'd have to add a resistor, so p0 and p2 are only really free ones to use.

So you left the Serial.begin in? I can't help you without seeing your code, maybe someone else can.

Yes, I edited the question.

... the only difference was with changing the Serial.println (... to other things as I mentioned. - not really: Serial.println(encoderPosCount);

That was in the original code too.

The Serial.println stuff doesn't do anything since the digispark doesn't have a serial com port nor serial to usb converter.

I would not personally be calling a function that cannot do anything useful, as you acknowledge. For all you know it is doing something to one of the ports which stops it doing what you want.

Nick, while your page about rotary encoders is interesting and informative, both of the programs there tend to lose a lot of counts, eg 2 or 3 out of 30 per turn for the single-interrupt-line version, and 1 or 2 per couple of turns for the two -interrupt-line version.  Also, both of them only see half of the countable transitions.  I'll post a version below that doesn't lose counts, is twice as accurate, and about the same amount of code.


text:
RGBs, photoresistors, and delays
I am having a little trouble with a program of mine. My circuit consists of (mainly) an arduino UNO, two RGB LEDs, and a photoresistor. My current code(programmed in c#) operates the hardware as so: When the lights in the room are on, the two LEDs alternate blue/off once per second in a loop. When the lights are off, or the photoresistor is not sensing any light, both LEDs turn on, and stay on, red.
My code:
int prPin = A0;

void setup()
{
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(prPin,INPUT);
  Serial.begin(9600);
}

void loop()
{
  int prVal = analogRead(prPin);
  Serial.write(prVal);
    if(prVal>450)
    {
      digitalWrite(5,HIGH);
      digitalWrite(6,HIGH);
      digitalWrite(7,HIGH);
      digitalWrite(8,LOW);
      digitalWrite(9,HIGH);
      digitalWrite(10,HIGH);
      delay(1000);
      digitalWrite(5,LOW);
      digitalWrite(6,HIGH);
      digitalWrite(7,HIGH);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
      digitalWrite(10,HIGH);
      delay(1000);
    }
    else
    {
      digitalWrite(5,HIGH);
      digitalWrite(6,HIGH);
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
      digitalWrite(10,LOW);
      delay(10);
    }
}

The problem I am having is when the lights turn off, the LEDs will not operate according to the "else" statement/loop until it finishes going through the "if" statement/loop.
Any suggestions or answers are appreciated. I'm an open book, so I'll take anything you guys give me.

Stop delaying. Use a state machine.

How to do multiple things at once. Also State machines.

Instead of the two delays of one second, have the program check if the current time is an even or odd number of seconds.
int prPin = A0;

void setup()
{
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(prPin,INPUT);
  Serial.begin(9600);
}

void loop()
{
    int prVal = analogRead(prPin);
    Serial.write(prVal);
    if(prVal>450)
    {
      if( (millis()/1000)%2 == 0 ) // check if even or odd number of seconds have passes since the program started
      {
        digitalWrite(5,HIGH);
        digitalWrite(6,HIGH);
        digitalWrite(7,HIGH);
        digitalWrite(8,LOW);
        digitalWrite(9,HIGH);
        digitalWrite(10,HIGH);
      }
      else
      {
        digitalWrite(5,LOW);
        digitalWrite(6,HIGH);
        digitalWrite(7,HIGH);
        digitalWrite(8,HIGH);
        digitalWrite(9,HIGH);
        digitalWrite(10,HIGH);
      }
    }
    else
    {
      digitalWrite(5,HIGH);
      digitalWrite(6,HIGH);
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
      digitalWrite(10,LOW);
      delay(10);
    }
}


text:
Identical statements, different outcome
First a little background on me and my project. Most of my programming experience is with PHP and javascript. I have just recently started looking at C and C++ for this Arduino project. My project is a weather station that feeds its data to a web based database in real time. I will be writing the code for a web site that will access this data base and present the data in realtime. I am currently working on the temperature section of my weather station. It is an RTD coupled to a constant current circuit and feeds a varying voltage to analog pin 5 on my Arduino Uno. My problem is with the code. I have a working code but I decided to make it object oriented so that I could reuse it in other projects. Here is the code that works.
const unsigned int RTD_PIN = A5;
const float MVOLTS_CTS = 4.882813;
const float OHMS_DEGREE = 0.3851;
const unsigned int SAMPLES = 10;
const float MILLI_AMPS = 19.125;
unsigned long currentMillis;
unsigned long oldMillis = 0;
unsigned long timeBetweenSamples = 1000; // milliseconds between samples
int measurement[SAMPLES];
int read_index = 0;
int total = 0;
int average_cts = 0;
boolean initialized = false;
float degC = 0;
float degF = 0;

void setup() {
  Serial.begin(9600);
  for (int i = 0; i < SAMPLES; i++) {
    measurement[i] = 0;
  }
}

void loop() {

  // Reset the counter when we go over the
  // set number of samples
  if (read_index >= SAMPLES) {
    read_index = 0;
    initialized = true;
  }

  // only take a measurement if one second has passed
  currentMillis = millis();

  if (currentMillis - oldMillis >= timeBetweenSamples) {
    // subtract one element from the total
    total = total - measurement[read_index];

    // take a measurement
    measurement[read_index] = analogRead(RTD_PIN);

    // add the new measurement back into the total
    total = total + measurement[read_index];

    // take an average of the readings
    average_cts = total / SAMPLES;

    // calculate degrees
    degC = (average_cts * MVOLTS_CTS / MILLI_AMPS -100) / OHMS_DEGREE;
    degF = degC * 1.8 + 32;

    // print results only if all elements of measurement[] are filled
    if (initialized) {
      Serial.print(degC);
      Serial.print(" degrees C ");
      Serial.print(degF);
      Serial.print(" degrees F ");
      Serial.println(average_cts);
    }

    read_index++;
    oldMillis = currentMillis;

  }
}

And this is the code that doesn't work.
#include "Arduino.h"
#include "Sensor.h"

    Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long sampleRate) {

     sensorPin = analogPin;
     samples = numSamplesInAverage;
    _sampleRate = sampleRate;
     int measurement[samples];

     // initialize the measurement array
     for (int i = 0; i >= samples; i++) {
       measurement[i] = 0;
     }

  }

  int Sensor::update() {

    if (read_index >= samples) {
       read_index = 0;
     }

     // only take a measurement if sample rate has been exceeded
     // and return a rolling average
     currentMillis = millis();

     if (currentMillis - oldMillis >= _sampleRate) {
       //subtract one element from the total
       total = total - measurement[read_index];

       // take a measurement
     measurement[read_index] = analogRead(sensorPin);

       // add the new measurement into the total
       total = total + measurement[read_index];

       // take an average of the readings
       average_cts = total / samples;

       // increment the read_index
       read_index++;
       oldMillis = currentMillis;

      return average_cts;
     }

     // return false if the sample rate has not expired
     return false;

  }

It seems like the issue is with this one line of code on line 34.
measurement[read_index] = analogRead(sensorPin);

When this line has not been remarked out the read_index only goes to 4 before it resets to 0 and it does it at the rate of program execution instead of every second like expected.
If this line is remarked out the the read_index is incremented from 0 to 9 once every second as expected.
Here is where the read_index is defined.
#ifndef Sensor_h
#define Sensor_h

#include "Arduino.h"

class Sensor
{
   public:
     Sensor(int analogPin, int numSamplesInAverage, unsigned long sampleRate);
     int update();

   private:
     unsigned int sensorPin;
     unsigned long currentMillis;
     unsigned long oldMillis;
     unsigned long sampleRate; // milliseconds between samples
     int read_index = 0;
     int total = 0;
     int average_cts = 0;
     int samples;
     unsigned long _sampleRate;
     int measurement[];
};

#endif

and this is the Arduino sketch that calls update()
#include <Sensor.h>

Sensor rtd(4, 10, 1000);  // instantiate a Sensor object
int cts;

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

void loop() {

  rtd.update();

  Serial.println(rtd.read_index);
}

can anyone tell me why this works in my procedural code but not the objected oriented code?

Where is read_index defined? Please post all your code.

Where is "update" called? Please post all your code. You have posted a complete sketch that works, and snippets that don't work.

Sorry @Nick Gammon it is late.

How big is measurement in the class version...?

You have made a few fundamental errors with your class.
Firstly you have not provided a storage size (number of elements) for the measurement array class member variable:
class Sensor
{
   public:
     Sensor(int analogPin, int numSamplesInAverage, unsigned long sampleRate);
     int update();

   private:
     // ... cut ...
     int measurement[];           // <<-- How big is this?!
};

Then it seems like you try to dynamically allocate the space for it in your constructor:
Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long sampleRate) {

    sensorPin = analogPin;
    samples = numSamplesInAverage;
    _sampleRate = sampleRate;
    int measurement[samples];    // <<-- Here
    // ... cut ...
}

BUT that's not what you are doing.  What you are doing there is creating a new local variable (local to just that one single function) called measurement with an array size of samples.  As soon as you leave the constructor that variable is thrown away.
You haven't touched the class member variable measurement at all.  So, when you do:
measurement[read_index] = analogRead(sensorPin);

you are storing the read value into an array of no size that points nowhere.  And of course that then causes a crash because you're writing to memory that you shouldn't be writing to.
If you want to be specifying the number of array elements in the constructor you need to be learning about dynamic memory allocation using malloc() and free() and all the pitfalls that go along with using those on a small microcontroller with very tight RAM constraints.
For an example of how it can be done you should take a look at my Average Library which uses dynamic allocation to allocate the array memory in the constructor and free it in the destructor.

Thank you for taking the time to answer this for me. I will have a look into it when time allows.

Well spotted. I elaborated on how to do that in my reply, because what I wanted to say was too long for a comment.

I was going to add to Majenko's excellent answer, but what I want to say is too long. :)

Change:
int measurement[];

to:
int * measurement;

and then in the constructor do:
measurement = new int [samples];

And check that measurement is not NULL, in case there is not enough memory.

Also, this is wrong in two ways:
// initialize the measurement array
for (int i = 0; i >= samples; i++) {
  measurement[i] = 0;

It should be:
// initialize the measurement array
for (int i = 0; i < samples; i++) {
  measurement[i] = 0;

You need to test less than, and you don't test equals (that would initialize one too many).

You should also have a destructor that frees the memory, ie.
delete [] measurement;

When would this destructor come into play? How and when should I call it?

The destructor is automatically called when an instance of the class is destroyed. This is when you do things like free memory you allocated. You don't call it directly.
An example:
class Sensor
{
public:
  // constructor
  Sensor(int analogPin, int numSamplesInAverage, unsigned long mysampleRate);
  // destructor
  ~Sensor ();
  // call to update samples
  int update();

private:
  unsigned int sensorPin;
  unsigned long currentMillis;
  unsigned long oldMillis;
  unsigned long sampleRate; // milliseconds between samples
  int read_index;
  int total;
  int average_cts;
  int samples;
  int * measurement;
};

Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long mysampleRate)
  {
  sensorPin = analogPin;
  samples = numSamplesInAverage;
  sampleRate = mysampleRate;
  read_index = 0;
  total = 0;
  average_cts = 0;
  measurement = new int [samples];

  if (measurement == NULL)
    exit (1);  // can't continue

  // initialize the measurement array
  for (int i = 0; i < samples; i++) {
    measurement[i] = 0;
  }

}  // end of constructor

// destructor
Sensor::~Sensor ()
  {
  delete [] measurement;
  }  // end of destructor

Can you please explain how these two line of code work int * measurement and measurement = new int [samples];

int * measurement creates a pointer to an int (called measurement). However pointers can also point to the start of an array (or indeed, to the middle of an array) of ints. So this variable will hold the start of your array of ints.
measurement = new int [samples]; allocates the memory for this array - in this case "samples" lots of ints.
Once the memory is allocated you can treat the pointer as an array, eg.
measurement [5] = 42;

For more detail about this see So what is meant by the "equivalence of pointers and arrays" in C? and also Google: pointer vs array.
Also Google: new and delete with reference to the C++ language.

When would this destructor come into play? How and when should I call it?

See amended answer.

If the Arduino is constantly calling the update() function it doesnt seem to me that the instance would ever be destroyed. So is a destructor even necessary?

In your case, with the object at global scope, no it will never be destroyed, so the destructor is not necessary. If you were to put the object instantiation into a function, then it would be necessary. It is a good idea to have a destructor if you allocate memory, otherwise one day you (or someone else) will use your class in a place where it will be needed.

Thank you. I will give this a try later and let you know how it turns out.

This has worked great i voted Majenko's answer as the correct answer only because he had a more thorough answer that will probably help more people but  in the end your suggestions are worked for me. One more question though. Can you please explain how these two line of code work int * measurement and measurement = new int [samples];

That's fine - he spotted the problem, I just elaborated on his solution. See amended answer. You can vote for mine as well if you like it (you can vote for both of them).


text:
Interrupt not firing on motion
I'm trying to get MMA8452Q to trigger an interrupt when motion is detected and wonder if I'm missing something very obvious here.
So I setup CTRL_REG4 to 0x0B with
void MMA8452Q::setupISR()
{
    writeRegister(CTRL_REG4, 0x0B);
}

then I setup FF_MT with
void MMA8452Q::setupFF_MT()
{
    writeRegister(FF_MT_CFG, 0xF8);
    writeRegister(FF_MT_THS, 0x0F);
    writeRegister(FF_MT_COUNT, 0x00);
}

and I read ISR with
#define SRC_PULSE 2
#define SRC_FF_MT 1

byte MMA8452Q::readISR()
{
    byte intStat = readRegister(INT_SOURCE);

    if (intStat & 0x0B)
    {
        readRegister(FF_MT_SRC);
        return intStat & 0x0B;
    }
    else
        return 0;
}

void printISR()
{
  byte isr = (accel.readISR() >> 2);
  if (isr & SRC_PULSE)
    Serial.print("(ISR) Tap");
  else
    Serial.print("(ISR) No Tap");

  Serial.print("\t");

  if (isr & SRC_FF_MT)
    Serial.print("(ISR) Motion");
  else
    Serial.print("(ISR) No Motion");

  Serial.print("\t");
}

AFAIK, that should already have FF/MT interrupt enabled. Even when I'm getting readings in FF_MT_SRC, I'm not picking up an interrupt in INT_SOURCE.
Interrupts are fired on (most) taps, but not on motion at all.
Am I missing something here?
Thanks

Please post all your code. Do not do serial prints inside an ISR. Read: Interrupts

@NickGammon I've updated my post with the full code now. Re. serial prints, am I doing serial prints inside an ISR? I read the ISR first and then print. The ISR would have finished processing - right?

Kar, I may have missed something, but in what you've posted I don't see any setup() or loop() routines as often found in Arduino sketches.  Without that code it isn't clear what routines are being called when.  Also, you haven't shown how the MMA8452Q is connected to your Uno.  Is an interrupt wire from the 8452 connected to the Uno?  Absent other info, it looks like MMA8452Q::readISR() is not an interrupt processing routine, but instead a routine that polls an interrupt-source register to find out what source would have triggered an interrupt if correctly wired and initialized

Kar, re setup() & loop(),  I'd overlooked a block of code.

Here's an extract from page 39 of MMA8452Q-rev8.1.pdf, the MMA8452 spec sheet:

Rather than saying writeRegister(CTRL_REG4, 0x0B); in MMA8452Q::setupISR(), try writeRegister(CTRL_REG4, 0xD);.
0xB is 1011 in binary, while 0xD is 1101, which turns on INT_EN_FF_MT to enable freefall/motion interrupts.
The above should answer your question as asked.  The following expands on my earlier comment which said

Absent other info, it looks like MMA8452Q::readISR() is not an interrupt processing routine, but instead a routine that polls an interrupt-source register to find out what source would have triggered an interrupt if correctly wired and initialized.

"Interrupt" as used in your question (and code) refers to when the MMA8452 signals (via an I1 or I2 output line) that an interrupt-worthy condition has occurred.
"Interrupt" as in the question does not refer to an interrupt from the Uno's point of view, because (per diagram) neither of I1 or I2 connects to the Uno.
If speed of response becomes important, you may wish to hook I1 or I2 to one of the Uno's Digital Pins With Interrupts, ie pin 2 or 3, as noted in the AttachInterrupt page at arduino.cc.  Then you'd replace the polling loop that now periodically reads the MMA8452's ISR (interrupt status register) to check for set bits, with an interrupt service routine which would set a flag to cause loop() to use Wire.read to get ISR data.

Ah yes, I was about to say something to this effect. Your code does not actually use interrupts, so I am not surprised it is missing things. Your terminology of "reading the ISR" was confusing. The chip appears to actually generate interrupts, which you should connect to a pin as jwpat7 suggested.

Kar -- note that if your Uno's V+ is 5V, use a Logic Level Converter between it and the MMA8452.  Sparkfun's BOB-12009 is bidirectional if the i/o's it connects are implemented with  open-collector/open drain.


text:
Help with socketIO Example
I'd like to get a TCP based connection from an arduino to a node.JS server. I found an example, I've tried to run it but its throwing the errors below, would appreciate any help.
Error Messages
    Arduino: 1.6.6 Hourly Build 2015/09/24 05:43 (Windows 7), Board: "Arduino/Genuino Uno"
WARNING: Category '' in library ArduinoJson is not valid. Setting to 'Uncategorized'
socketio.ino: In function 'void hello(Client&, const char*)':

socketio:19: error: expected unqualified-id before '.' token

socketio.ino: In function 'void setup()':

socketio:38: error: invalid conversion from 'void (*)(Client&, const char*)' to 'void (*)(Client&, ArduinoJson::JsonArray&)' [-fpermissive]

In file included from socketio.ino:6:0:

C:\arduino_1.6.6\libraries\socket.io-arduino-client.2/SocketIOClient.h:56:8: error:   initializing argument 2 of 'void SocketIOClient::setEventHandler(const char*, void (*)(Client&, ArduinoJson::JsonArray&))' [-fpermissive]

   void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));

        ^

socketio:39: error: invalid conversion from 'void (*)(Client&, const char*)' to 'void (*)(Client&, ArduinoJson::JsonArray&)' [-fpermissive]

In file included from socketio.ino:6:0:

C:\arduino_1.6.6\libraries\socket.io-arduino-client.2/SocketIOClient.h:56:8: error:   initializing argument 2 of 'void SocketIOClient::setEventHandler(const char*, void (*)(Client&, ArduinoJson::JsonArray&))' [-fpermissive]

   void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));

        ^

exit status 1
expected unqualified-id before '.' token

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

Arduino Code
    #include
    #include
#include <ArduinoJson.h>
#include <SocketIOClient.h>

EthernetClient ethClient;
SocketIOClient client(ethClient);

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char hostname[] = "192.168.100.40";
int port = 3000;

// Socket.io "hello" EVENT handler
void hello(Client& client, char const * data) {
    Serial.print("[hello] event happening: ");
    Serial.println(data);
    Client.emit("goodbye", "Arduino here, goodbye!");
}

// Socket.io "goodbye" EVENT handler
void goodbye(Client& client, char const * data) {
    Serial.print("[goodbye] event happening: ");
    Serial.println(data);
    Serial.println("That is all.");
}

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

    if(!client.connect(hostname, port)) {
        Serial.println(F("Not connected."));
    }

    //Event hanlders
    client.setEventHandler("hello", hello);
    client.setEventHandler("goodbye", goodbye);

    //Say hello to the server
    client.emit("hello", "Arduino here, hello!");
}

void loop() {
    client.monitor();
}

SocketIO.h
/*
    socket.io-arduino-client: a Socket.IO client for the Arduino

    Based on Bill Roy's Arduino Socket.IO Client (which is based on
    Kevin Rohling's Arduino WebSocket Client) with event handling by
    @dantaex

    Copyright 2014 Quentin Pigné

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef SocketIOClient_H
#define SocketIOClient_H

#include <Arduino.h>
#include <Client.h>
#include <SPI.h>

#include <ArduinoJson.h>

#include "HashMap.h"

//Length of static data buffers
#define DATA_BUFFER_LEN 200
#define SID_LEN 24

//Max size of the HashTable
#define HASH_SIZE 20

class SocketIOClient {
    public:
        SocketIOClient(Client& client);
        //Public connection methods
        bool connect(const char* hostname, int port = 80, const char* resource = "socket.io", const char* nsp = "/");
        //Public event handling methods
        void setEventHandler(const char* eventName, void (*handler)(Client& client, JsonArray& data));
        //Public data emitting methods
        void emit(const char* event, const char* data);
        //Monitoring for incoming data
        void monitor();

    private:
        //Connection attributes
        Client& client;
        char* hostname;
        int port;
        char* resource;
        char* nsp;
        char sid[SID_LEN];
        //Incoming data reading attributes
        char databuffer[DATA_BUFFER_LEN];
        char* dataptr;
        //Event handling attributes
        int nbEvent;
        static HashType<const char*, void(*)(Client& client, JsonArray& data)> hashRawArray[HASH_SIZE];
        static HashMap<const char*, void(*)(Client& client, JsonArray& data)> eventHandlers;

        //Private incoming data reading methods
        bool waitForInput();
        void eatHeader();
        void readInput();
};

#endif

Where is your code?

Hi @NickGammon, ive added the code.

bump    anyone?

Make your char * parameters const char *.

Did his suggestion fix it? If so, please mark the answer as the correct solution.

Hi @NickGammon, no I'm still having issues, updated the errors in my original post.


text:
Sketch will not start with external power source
NOOB Question: when my Uno is connected to an external power source it will not start running the uploaded sketch. The Arduino web site says it's because the RX pin is not connected and then gets random data.
The site suggests grounding the RX pin using a resistor (granted it suggests a 10K and I used a smaller one ) or connecting it to the TX pin.
From Why doesn't my sketch start when I power up or reset the Arduino board?

Most likely because you are sending serial data to the board when it
  firsts turns on. During the first few seconds, the bootloader (a
  program pre-burned onto the chip on the board) listens for the
  computer to send it a new sketch to be uploaded to the board. After a
  few seconds without communication, the bootloader will time out and
  start the sketch that's already on the board. If you continue to send
  data to the bootloader, it will never time out and your sketch will
  never start. You'll either need to find a way to stop serial data from
  arriving for the first few seconds when the board powers (e.g. by
  enabling the chip that sends the data from within your setup()
  function) or burn your sketch onto the board with an external
  programmer, replacing the bootloader.

From Why doesn't my sketch start when I'm powering the board with an external power supply? (Arduino Diecimila or earlier)

Because the RX pin is unconnected, the bootloader on the board may be
  seeing garbage data coming in, meaning that it never times out and
  starts your sketch. Try tying the RX pin to ground with a 10K resistor
  (or connecting RX directly to the TX pin).

Both failed for me.
What should I do?

To upload your sketch, you have to connect your uno to your system using usb cable. After that you can use any ext. supply

I uploaded the sketch using the USB port connected to my computer. The sketch runs immediately after I upload it (the motor runs). Then I disconnected the USB port and connect a 9V batery to the barrel connector. The "power on light" on the UNO is on, but the sketch does not start.

Try uploading some other sketch like blinking led connected to 13 pin then connect your uno to 9v battery and check if led is blinking or not.!

Motors use large amount of current. A 9v battery can't provide that much current, so the motors won't run.

Gerben is right. The problem was the battery. Everything runs fine on a 9V power source connected to the outlet. So, my question is, what batery should I use? The projet is a small robot with 2 "yellow dc motors"

My BOEbot robot used 5 x AA batteries, and that worked. You need to be looking at substantially larger power. A LiPo battery might do for you, they come in a range of sizes.

Try to give power through ardino with ardino adapter..try

A 9V battery as a power supply it is not. I would venture to guess your 9V is dropping to below 6 volts. If you must use batteries use several single cell batteries in series such as AA as previously suggested. If you have a wall wart try that.

The problem was, as Gerben said, the battery was too weak to run the engine.

I also had a similar problem running with an external power supply.  In my case the sketch ran but totally incorrectly .  Conected RX to ground with a 10K Ohm resistor and solved the problem.
Thanks for the info!!  Others have spent a lot more time solving this problem than I did.

I will add my little drop of experience here...   So I am using a display tm1637, having CLK in 6 and DIO in 5. When connecting the Battery (12V 3s lipo 4000mA) to Vin, the arduino will freeze, even connected to the USB, will still freeze.
Short version, Moving DIO from 5 to 7 corrected the problem, now i have my device running from USB and or battery with no problem.
Long version: after 3 hours of trying different mods, including resistor to RX,TX, to GND, even removing the ch340 chip and connecting Rts and others to GND/VCC..  Nothing, so i decided to move the different devices from One nano to Other but testing after each connection. When the display was connected, the Nano will freeze while running on battery power. So... i moved DIO first to a different pin, and the device started working.  I know is a very particular case, but one more thing to try if you are like me, stock without knowing what to do.... moving some pins (maybe skipping 5?)...

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


text:
Connect GPS module with GPS antenna SIM39EA to Arduino Uno
I bought a GPS module with GPS antenna SIM39EA online.
The manual for the GPS module is here:
http://www.vis-plus.ee/pdf/SIM39EA_Hardware_Design_V1.00.pdf
I have an Arduino board. It has 3 ground pin, one Vcc and two input/output pin.
I want to know how can I connect this module to Arduino GPS module and get GPS coordinates?

Please post a link to the board datasheet, or at least some information about it. Which Arduino do you have?

here it is the manual of gps module please use this link to download manual   www.vis-plus.ee/pdf/SIM39EA_Hardware_Design_V1.00.pdf     I am trying to connect it  with Arduino UNO R3 board with DIP ATmega328P

Your data comes back via the GPS's UART port.
Use the softserial library to create a second serial port on your Arduino (means you can still use the normal serial to read the console).
Then write a program that sucks data from the GPS and squirts it out of the Arduino serial port back to your PC using printf.
I only had a quick flick through and didn't see the default serial speed, so start with 9600 and experiment.
What should come out is probably a line of comma separated values which is in NEMA format.  Google for the specification and you will be able to find out the bits of interest.
Hope that helps.


text:
Can send AT+ commands, but can't upload sketch to ESP8266 via Arduino Uno
Connected a generic ESP8266 to an Arduino Uno.
I can send AT commands fine and generate a normal response, but cannot upload sketches to the ESP8266. I have "Generic ESP8266 Module selected as the board. Tried everything e.g. switching Tx and Rx, connecting GPIO0 and GPIO2 to to Vcc or ground, but to no avail.
Arduino IDE spits this out -
esptool v0.4.5 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    stat C:\Users\Michael\AppData\Local\Temp\build7227402767538495982.tmp/wifi_setup.cpp.bin success
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed

Not sure, but I think you need to flash the NodeMCU firmware first.

You are going to have to provide a bit more detail on your setup. How do you have the ESP8266 connected to the Arduino? What are you using to program the ESP 8266?  This?

Hi @user2277005 ! did you manage to solve this problem? All the solutions here don't work

You mention:

connecting GPIO0 and GPIO2 to to Vcc or ground

I've had success with this sequence:

GPIO0 to gnd (and hold momentarily)
RST to gnd (then let go, while holding GPIO0 to gnd)
let go of GPIO0 from gnd (e.g. let it float again)

To do a firmware flashing, you need to hold GPIO0 to ground for the duration of the flashing process, so the sequence would be slightly different.
You can do this just prior to "build and upload" in the Arduino IDE—provided the build process doesn't take too long.  It will sometimes still fail, in which case reset the ESP8266 (RST to gnd momentarily) and restart the sequence.
I've found a little test/development harness (like this one http://www.buildcircuit.com.au/esp8266-test-board) is very handy for doing this repeatedly.

Your solution worked for me, when I have this error.   Thanks!

I have been hooking the ESP8266 straight up to my PC and programming it in NodeLua.  Of course it depends on what you want to do, but consider dropping the Arduino and just using the ESP8266.

Alright will give that a go.

You don't need an Arduino UNO to program the ESP. You just need an USB to UART adapter (CP210x or FTDI one) and the Arduino IDE. Hook the ESP rx and tx to the tx an rx of the adapter and you are ready to go.
Here is an detailed explanation how to program ESP using arduino
If you don't have an USB to UART bridge you can use the Arduino board as bridge: check this


text:
How to make an Arduino USB programming circuit?
I am designing a PCB in which I am using the MCU used in Arduino UNO which is Atmega328P and some other components as per my project requirements. I have almost designed the circuit but I am confused with the USB programming part. I want my MCU to be programmed using USB B Type just like we do it in Arduino UNO. My friend suggests me to purchase an Arduino UNO device and program that MCU and then put it in my circuit. But I don't want to do it like this. I have found the schematic design but its very confusing. Can anyone help me out with this.?

Eh. Save yourself the pain and just use ISP.

Can you explain more.?

You can use an Arduino to program a bootloader into an ATmega328.  There's even an official tutorial for that.

I fail to see why you think this is so confusing. If you want the functionality of an Arduino UNO then just duplicate the schematic into your project. Fully. You will end up with two MCUs in your project just like the UNO. BTW these MCUs are quite inexpensive.

The "core" part of the arduino uno board is the Atmega328P, with the 16MHz oscillator (can be removed if you want to use the internal 8MHz clock - search for optiboot) bypass capacitor(s) (C6, but I suggest you to put another one close to the other pair of power pins), reset circuit (RN1D and, I suggest you, also the button), ICSP connector and, suggested, capacitor C4. You will need an ISP programmer to put at least the bootloader on board. If you want to program through serial, just add a usb-serial converter (suggested: FTDI). If it has also the DTR pin, you can enable auto-reset

To enable it, just add the capacitor C5 between the reset node and the DTR pin. And that's all. If you want everything on-board, you can use a FT232RL (and its VCP drivers), which does not require you to flash the firmware (like the Atmega16U2 used by the real arduino boards). Otherwise you can use any USB-UART module (and if it has the DTR pin, well, better). I suggest you the FT232RL because I recently got a prolific 2303 cable and.. There are no more drivers for Win8+, while FTDI goes on supporting their products

It is quite a lot simpler to obtain an FTDI USB - TTL Serial cable. (The link goes to the American supplier, Sparkfun, but such cables are available from many online suppliers.) They are typically made with a 6-pin female header instead of a USB B connector; you may have to make up that part yourself, if it is important to you. If you only need USB functionality for programming, one cable can serve any number of boards (one at a time, of course), no need to build it into each board.

Not 100% exact. In fact this requires you to have a Atmega328P with bootloader; commonly sold atmega, however, do not have it, so you will also need the ICSP port to program the bootloader the first time

It takes only one chip with a bootloader to make an arduino work-alike which can then flash the bootloader into bare chips. A borrowed work-alike can flash that first chip. The OP seems familiar with Arduino and there was no constraint that no Arduino should ever be used

Totally agree, but... If there is no ICSP connector on the PCB then you will not be able to program it once soldered. Hence, the "not 100% exact", since you can fix it by pre-programming the bootloader, but 1) it's more useful to put an ICSP connector on the PCB (if the bootloader gets corrupted you can flash it again later), and 2) better saying it before the OP solders the IC on the board (and then finds out he can't upload with just a USB-TTL cable)

Looking at the schematic design, you need atmega8 to make a usb programming connection. Design your circuit exactly like in the schematic.You will also need bootloader for it, so use any programmer like usbasp, connect its pins to mosi, miso sck, rst,vcc,gnd and click on burn boot loader in arduino ide

If you wanted a more permanent option on the board, you could also add a USB to FTDI chip like this: http://www.mouser.com/Search/m_ProductDetail.aspx?FTDI%2fFT232RL-REEL%2f&qs=D1%2fPMqvA103RC6OU6bKtoA%3d%3d&gclid=CNmDjr7dvssCFYZefgod9jgPeQ

Again, this requires you to already have a Atmega328P with bootloader


text:
Programming a motor with an RGB
Please see the comments section if confused.
I am trying to turn a motor on and off once per second, and when the motor is on, the RGB turns green. When the motor is off, the RGB is red. Everything is connected to an arduino UNO.I have the motor connected to pins 0 and 1, and to the 5V and GND. The RGB is connected to pins 4, 5, and 6, and the 5V.
I have two codes; one with a bunch of screwing around with a bunch of different loops and everything else I've tried, and one with the simple motor on/off code.
void setup ()
{
  pinMode(0,OUTPUT); //IB1
  pinMode(1,OUTPUT); //IA1
////  pinMode(2,OUTPUT); //IB2
////  pinMode(3,OUTPUT); //IA2
//  pinMode(4,OUTPUT); //RGB
//  pinMode(5,OUTPUT); //RGB
//  pinMode(6,OUTPUT); //RGB
//  pinMode(A0,INPUT); //lMotor
////  pinMode(A1,INPUT); //rMotor
//  Serial.begin(9600);
}

void loop ()
{
  digitalWrite(0,HIGH);
  delay(1000);
  digitalWrite(0,LOW);
  delay(1000);

//  int lMotor = analogRead(A0);
//  Serial.write(lMotor);
////  int lMotor = analogRead(A1);
////  Serial.write(lMotor);
//
//  if (lMotor>10)
//  {
//    digitalWrite(4,HIGH);
//    digitalWrite(5,HIGH);
//    digitalWrite(6,LOW);
//  }
//  else
//  {
//    digitalWrite(4,HIGH);
//    digitalWrite(5,LOW);
//    digitalWrite(6,HIGH);
//  }
}

And here's this:
void setup ()
{
  pinMode(0,OUTPUT);
  pinMode(1,OUTPUT);
}

void loop ()
{
  digitalWrite(0,HIGH);
  delay(1000);
  digitalWrite(0,LOW);
  delay(1000);
}

What do I need to do? Should I use a "while" loop? If so, how?
Is my circuit put together properly? I'm using a motor relay switch to turn the motor on/off, but I'm pretty sure it's hooked up right.
Any help is appreciated, even if it doesn't answer all of my questions.
Thank you.

You'll have to investigate what "component video" signals should look like. It is too simple to assume you can just drive a pin high and expect the screen to color accordingly.

@jippie I am not changing anything on screen, I am turning an RGB LED on. (Everything is connected to the arduino via a breadboard.)

You haven't actually told us what's not working. Is the motor not turning? At the top you say you have the motor connected to pins 0 and 1 and 5 V and ground! How? What's the relay doing? Can you hear the relay clicking? We'll need a schematic or a photo of a sketch. Note that the Arduino pins can't provide enough current to drive a typical little DC motor.

@transistor The motor turns with the simple code (the second one in my post); my problem is basically I don't know what to do to make the RGB turn on and change colors based on the current state of the motor (on or off). Everything works properly until I add something to the code (because someone, or some site, suggested that's what I should do); by "not working properly" I mean the entire circuit does nothing. Absolutely nothing.

If my response below doesn't answer the question can you edit the question to clearly show the code that works and the code that doesn't and explain what works - e.g., the motor works but the LEDs don't.

I forgot to say, the way you've set up the first code example you turn the motor on for a second, then turn in off for a second and then updated the LEDs. The LEDs are only updated when the motor is off so they'll never change.

Try this:
void setup ()
{
  pinMode(0,OUTPUT); //IB1
  pinMode(1,OUTPUT); //IA1
//  pinMode(2,OUTPUT); //IB2
//  pinMode(3,OUTPUT); //IA2
  pinMode(4,OUTPUT); //RGB red
  pinMode(5,OUTPUT); //RGB green
  pinMode(6,OUTPUT); //RGB blue
  boolean motorOn = false;
}

void loop ()
{
  digitalWrite(0,motorOn);
  if(motorOn) {
    digitalWrite(4,HIGH);  // red on
    digitalWrite(5,LOW);   // green off
    digitalWrite(6,LOW);   // blue off
  }
    digitalWrite(4,LOW);   // red off
    digitalWrite(5,HIGH);  // green on
    digitalWrite(6,LOW);   // blue off
  }
  delay(1000);             // wait
  motorOn = !motorOn;      // toggle the status of the motor.
}

The code above has the disadvantage that the on-time is the same as the off-time. We can make the code more flexible and a little more like your original by doing the LED related code in a subroutine:
void setup ()
{
  pinMode(0,OUTPUT);   //IB1
  pinMode(1,OUTPUT);   //IA1
//  pinMode(2,OUTPUT); //IB2
//  pinMode(3,OUTPUT); //IA2
  pinMode(4,OUTPUT);   //RGB red
  pinMode(5,OUTPUT);   //RGB green
  pinMode(6,OUTPUT);   //RGB blue
  boolean motorOn = false;
}

void loop ()
{
  motorOn = false;
  digitalWrite(0,motorOn);
  updateLEDs();            // update the LED status
  delay(1000);             // wait
  motorOn = true;          // toggle the status of the motor.
  digitalWrite(0,motorOn);
  updateLEDs();            // update the LED status
  delay(750);              // wait a different time
}

void updateLEDs(){
  // This routine updates the LEDs based on status of motorOn.
  if(motorOn) {
    digitalWrite(4,HIGH);  // red on
    digitalWrite(5,LOW);   // green off
    digitalWrite(6,LOW);   // blue off
  }
    digitalWrite(4,LOW);   // red off
    digitalWrite(5,HIGH);  // green on
    digitalWrite(6,LOW);   // blue off
  }
}


text:
Cost-effective storage for prototyping
In my project I need to add some storage space and I don't want to use an SD card, because in the "final product" the user shouldn't be able to access the data on their own.
So I was considering the options here http://playground.arduino.cc/Main/InterfacingWithHardware#Storage but many of the technologies are either outdated, for example as reads here ADESTO is discontinuing production of dataflash, or they give too little memory, like the I2C EEPROM (which is 128KByte per chip and I would rather not go through the hassle of multiplexing lots of memory chips since I'd like to have 1MByte of storage at least), or are extremely overpriced and cannot be found on retail: some sites require you to buy 2000$ worth of chips or charge you 30$ for delivery, which kind of kills the fun of prototyping something.
I know I am being picky not wanting to use an SD for the prototype, but I would like to know if you ever faced this problem and how you solved it, or if you know some alternative solution which gives a good amount of memory (~1 or 2 MBytes at least) within reasonable costs.

Don't provide a slot in the casing to remove the SD card?  Once you use a standard memory technology in a discrete package, it is readable by someone who bothers to open the casing, though I suppose a soldered surface mount SPI flash less readily so than a socketed micro SD card.  Ultimately, you should think carefully about the wisdom of trying to prevent access, and if it is truly necessary your only real choice is to encrypt the data stored.

Yes, I guess that there will always be someone smart enough to be able to pry the device open and read/edit the memory content by himself if I don't encrypt the data. I'm slowly thinking that I might as well go for an SD and if I ever manage to build the final product I'll think of a way to deal with that.

Provided you only need a few megabytes you should be able to switch from a micro SD card in mmc mode on your prototype to a smaller, cheaper, more reliable soldered SPI flash by slighty changing your board and replacing the mmc SPI operation code with the far simpler steps needed to access an SPI flash.

You may not want to hear this, but the cheapest option would be an SD card, or a micro-SD card. You could solder it into place, thus making it quite hard for the end user to take it out and plug it into a reader.
Imagine you had this micro-SD card glued onto your board (making it hard to remove in the first place):

It isn't particularly obvious what it is, unless you recognize the shape. You could cover it with a blob of plastic to hide that. Then with the SPI wires soldered to the contacts, removing would be even harder.
That gives you gigabytes of storage, a file system, the works. And all for a few dollars.
A technically sophisticated user could probably prise it loose and get at the data (although if you used strong glue this could be quite hard) but they could also get at the contents of another storage chip too.

Well actually I didn't think that one could do that, so I guess this could become an option again, and yes, having the file system is definitely a big advantage! I'll consider it again, thank you!

Reflow Solder Your Micro SD to Ensure it Doesnt Go Anywhere

There are plenty of serial flash products available.  They are generally SPI chips (8 pin) and range in sizes up to about 64MBit (8MByte).  And they're cost effective.
Here's a selection: http://www.microchip.com/pagehandler/en-us/products/memory/flashmemory/sfhome.html
There are plenty of other manufacturers as well.  Your best bet is to hit your favourite online electronics store (mouser, digikey, etc) and shop around.

Thank you, I'll have a good look at these and try to find them in some store that does not charge me too much for the shipping (I live in Italy and mouser and digikey charge a lot so as I said in the post the shipping charges make the spi chips an expensive option)


text:
Programming an ATMEGA2560 using FTDI
I want to know how exactly do I program (upload arduino sketches) an ATMEGA2560 which is boot loaded with an Arduino Bootloader using a FTDI programmer and an Arduino IDE, is there any capacitors/resistors required?

There is no such thing as a 'FTDI Programmer' what you most likely mean is programming the ATMEGA2560 over the a serial protocol like RS232.

Yeah, sorry for my terminology. I have a FTDI breakout board link which I want to use to upload arduino sketches to the atmega2560.

If you have a bootloader, you just need to connect up four wires from the FTDI cable:

Pin 1 (black) -> Ground
Pin 2 (CTS)   -> not connected
Pin 3 (Vcc)   -> 5V
Pin 4 (TxD)   -> Rx (Mega pin D0)
Pin 5 (RxD) -> Tx (Mega pin D1)
Pin 6 (green) -> not connected

This will not auto-reset, so you will have to press (and release) the Reset button on the board at the moment that the sketch starts to upload.

How to make it auto reset?

What you should be able to do is connect RTS to Reset on the board, using a 0.1 µF capacitor (in series). I found in practice that this did not bring Reset low enough to trigger it - I'm not sure why, except maybe the board has a stronger pull-up resistor on /RESET than expected. That technique works for me on breadboard Arduinos.
Since it didn't work for me, I did not put it in my original answer. You could try that, and if it works, well and good.

I don't want to do that? How to make it auto reset?

See amended reply. Is there any reason why you don't just use the USB interface? That usually works.

I've fabricated a custom PCB with ATMEGA2560 mounted on it, I added your bootloader sketch and I'm trying to upload sketches to it using the arduino IDE, so that is why I'm using the FTDI chip to do this.


text:
how to create a specific buffer when there is no buffer message in the data packet?
So I'm trying to understand a read method. In this method,
// Read data from buffer
int SoftwareSerial::read()
{
if (!isListening())
  return -1;

// Empty buffer?
if (_receive_buffer_head == _receive_buffer_tail)
  return -1;

// Read from "head"
uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
_receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
return d;
}

it looks it receives buffer head. But in the write only a 1 or 0 is being sent as the data packet's header. Nothing else. So how does the arduino know how big of an buffer to create?
also, there is no stop bit being transmitted, so how does it look at a buffer tail? Or is this all created regardless of the transmitter? and then, all the values just get read into the buffer, and then read again from there? Also I don't see a delay in this read method. Wouldn't that cause errors in the data flow? How is that being handled?

That read method just retrieves bytes that have already been received from an internal buffer.
The buffer is pre-allocated to a specific size (64 bytes) and that is how many bytes can be received before you start to lose data as it gets overwritten.  You have to be sure to read your data from the buffer before it overflows.
The function that actually receives each UART bit from the IO port, builds them into bytes, and stores them in the internal buffer, is this one:
void SoftwareSerial::recv()
{

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
  asm volatile(
    "push r18 \n\t"
    "push r19 \n\t"
    "push r20 \n\t"
    "push r21 \n\t"
    "push r22 \n\t"
    "push r23 \n\t"
    "push r26 \n\t"
    "push r27 \n\t"
    ::);
#endif

  uint8_t d = 0;

  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  {
    // Wait approximately 1/2 of a bit width to "center" the sample
    tunedDelay(_rx_delay_centering);
    DebugPulse(_DEBUG_PIN2, 1);

    // Read each of the 8 bits
    for (uint8_t i=0x1; i; i <<= 1)
    {
      tunedDelay(_rx_delay_intrabit);
      DebugPulse(_DEBUG_PIN2, 1);
      uint8_t noti = ~i;
      if (rx_pin_read())
        d |= i;
      else // else clause added to ensure function timing is ~balanced
        d &= noti;
    }

    // skip the stop bit
    tunedDelay(_rx_delay_stopbit);
    DebugPulse(_DEBUG_PIN2, 1);

    if (_inverse_logic)
      d = ~d;

    // if buffer full, set the overflow flag and return
    if ((_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF != _receive_buffer_head)
    {
      // save new data in buffer: tail points to where byte goes
      _receive_buffer[_receive_buffer_tail] = d; // save new byte
      _receive_buffer_tail = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
    }
    else
    {
#if _DEBUG // for scope: pulse pin as overflow indictator
      DebugPulse(_DEBUG_PIN1, 1);
#endif
      _buffer_overflow = true;
    }
  }

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Restore the registers that the compiler misses
  asm volatile(
    "pop r27 \n\t"
    "pop r26 \n\t"
    "pop r23 \n\t"
    "pop r22 \n\t"
    "pop r21 \n\t"
    "pop r20 \n\t"
    "pop r19 \n\t"
    "pop r18 \n\t"
    ::);
#endif
}

To show you how the timing of the routine works, here is a little diagram:

Hello, i had a couple questions about that above code. So, when it says, " If RX line is high, then we don't see any start bit, so interrupt is probably not for us" in the comments, does that mean that if there is no startbit being detected, interrupts are turned off and if there is a startbit, then it is turned on? Also, what does 1/2 of a bit width refer to? Is that a time reference?

I know this is a old post, but can you clarify here?

The recv() function is triggered by the change interrupt (PCI) detecting the RX line has changed state - that is gone HIGH to LOW, or LOW to HIGH.  It responds to both changes, and also to other pins as well as the RX pin (if others are configured for PCI). So it checks to see if the RX pin is LOW (or HIGH with inverse logic) so it knows if it's an active start bit or not. If it is then it goes on to receive the entire byte, which it does by the use of tuned delay times.

Each bit has a specific time of 10/baud seconds (9600 baud is 10/9600 = 1.042ms) and that is how long each bit takes to transmit or receive. By waiting for half that time first the delay of 1.042ms falls in the middle of a received bit so it can reliably detect the level of that bit. If it didn't do that it would be reading the state on the border between two bits and it would be anyone's guess what the value would be that it would read,

Genius.... That's pretty clever. Thank you.

I have added a diagram to my answer to make it even clearer.