body:
I2C is truly a powerful option of Arduino, for too many reasons; yet the amount of tutorials available are not that many and unfortunately are too complicated for the average person.

After working on this for 2 days, I think I have a way to transfer pretty much anything between master and slaves and viceversa. Note that I2C does not transfer floats or even integers larger than 255, there are several ways to go about this and here is a good tutorial
http://www.gammon.com.au/i2c
and even a library: http://forum.arduino.cc/index.php?topic=171682.0

The solution I found was simpler. Basically we convert any value, string, number, text, float, you name it, and turn into a variable char, which can be transferred via I2C. Once transferred, you can convert back to a number although in my case below, I just wanted to display the data from the slave.

Here is the code. I provide comments on different parts for clarity. I hope this helps. it worked for me.

    //master
    #include <Wire.h>

    char t[10]={};//empty array where to put the numbers comming from the slave
    volatile int Val; // varaible used by the master to sent data to the slave

    void setup() {
      Wire.begin();        // join i2c bus (address optional for master)
      Serial.begin(9600);  // start serial for output
    }

    void loop() {
      Wire.requestFrom(8, 3);    // request 3 bytes from slave device #8

    //gathers data comming from slave
    int i=0; //counter for each bite as it arrives
      while (Wire.available()) {
        t[i] = Wire.read(); // every character that arrives it put in order in the empty array "t"
        i=i+1;
      }

    Serial.println(t);   //shows the data in the array t
    delay(500); //give some time to relax

    // send data to slave. here I am just sending the number 2
      Val=2;
      Wire.beginTransmission (8);
      Wire.write (Val);
      Wire.endTransmission ();
    }

here the other part
    //slave

    #include <Wire.h>

    char t[10]; //empty array where to put the numbers going to the master
    volatile int Val; // variable used by the master to sent data to the slave

    void setup() {
      Wire.begin(8);                // Slave id #8
      Wire.onRequest(requestEvent); // fucntion to run when asking for data
      Wire.onReceive(receiveEvent); // what to do when receiving data
      Serial.begin(9600);  // serial for displaying data on your screen
    }

    void loop() {
      int aRead = analogRead(A0); //plug a potentiometer or a resistor to pin A0, so you can see data being transfer
      float x = aRead/1024.0*5.0; //generate a float number, with this method you can use any time of data pretty much

      dtostrf(x, 3, 2, t); //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
      Serial.println(Val);         // print the character
     delay(500);
    }

    // function: what to do when asked for data
    void requestEvent() {
    Wire.write(t);
    }

    // what to do when receiving data from master
    void receiveEvent(int howMany)
    {Val = Wire.read();}


sender: user

message:
Sending and receiving different types of data via I2C in Arduino

I have found a few good tutorials on how to send and receive data via I2C in connected arduinos. My limitation is now how to transmit different types of data like for instance, long, float, etc. Right now the communication via I2C using the wire library only allows transmission of numbers between 0 and 255. How can one transmit different types of numbers?.

In my code a master receives three types of data from the slave, and it send data of a fourth variable to the slave.

here is the code for the master

    #include <Wire.h>

    const int SLAVE_ADDRESS = 8; //Slave arduino ID
    int table[]={0,0,0}; //the data will be transmited via table as to allow different data to be transfer.
    void setup ()
    {
    Wire.begin ();
    Serial.begin (9600);  // start serial for output
    }  // end of setup
    void loop()
    {
    Wire.requestFrom(SLAVE_ADDRESS, 3);// request 3 bytes from slave device #8

    for(int i=0;i<3;i++)//organizes the data from the slave in the table
    {
    int c = Wire.read(); // receive a byte as character
    table[i]=c;
    }
    //displays the data
     Serial.print('\n');
       Serial.print(table[0]);
        Serial.print('\t');
       Serial.print(table[1]);
        Serial.print('\t');
       Serial.print(table[2]);
       Serial.print('\n');

    delay (500);

    // transmit just this variable to the slave
    int Work=1;
    Wire.beginTransmission (8);
    Wire.write (Work);
    Wire.endTransmission ();
    }

here is the code for the slave

    #include <Wire.h>
    int table[]={0,0,0};
    int Work=0;

    void setup() {
    Wire.begin(8);                // join i2c bus with address #8
    Wire.onRequest(requestEvent); // register event
    Wire.onReceive(receiveEvent); // register event
    }

    void loop() {
    int x=120;
    int y=1200;// gets converted to an strange # because is larger than 255
    int z=3;
      table[0]=x;
      table[1]=y;
      table[2]=z;
    }

    void requestEvent()
    {
      uint8_t Buffer[3];
      Buffer[0]=table[0];
      Buffer[1]=table[1];
      Buffer[2]=table[2];
      Wire.write(Buffer,3);
    }

    void receiveEvent(int howMany)
    {Work = Wire.read();}

sender: assistant

body:
Use the 'I2C_Anything' library, available [here][1]. I use it in all my I2C projects.  It is extremely simple and works great. Here's the entire .h file

    // Written by Nick Gammon
    // May 2012

    #include <Arduino.h>
    #include <Wire.h>

    template <typename T> unsigned int I2C_writeAnything (const T& value)
      {
      Wire.write((byte *) &value, sizeof (value));
      return sizeof (value);
      }  // end of I2C_writeAnything

    template <typename T> unsigned int I2C_readAnything(T& value)
      {
        byte * p = (byte*) &value;
        unsigned int i;
        for (i = 0; i < sizeof value; i++)
              *p++ = Wire.read();
        return i;
      }  // end of I2C_readAnything

  [1]: https://github.com/nickgammon/I2C_Anything


message:
Using an Arduino as a electrical mains switch

How do I make an electrical switch using Arduino, that when it receives signal (wirelessly or through a LAN port) to switch off it disconnects the switch and then again told to turn on turns the switch on?

The main problem I am facing is that I need to give a 5V output to turn off the transmission between two wires having voltage rating of 230V.

body: As pointed out in the comments, I would need to use something known as a relay with my Arduino.


body:
You need to use [Relays][1].  There all kind of relays.

Regular and Solid state ... for controlling a Regular Relay using Arduino you will need a transistor (so you will able to provide the right current to the relay to close a circle)

There are a lot of guides for Arduino and Relays (for [example][2])

  [1]: https://en.wikipedia.org/wiki/Relay
  [2]: http://www.instructables.com/id/Arduino-Controlled-Relay-Box/


message:
Write to EEPROM during power down

I am making a counting device, and I would like to be ensure that the count is not lost if the power is lost.
As I need to count to many millions I cannot use EEPROM writes as I will trash the nvm after ripping through the 100,000 max write cycles. I also need to ensure the count is accurate, so can't update 'every-so-often' either.

I want to write to EEPROM when the Arduino detects power down. I am reading on an Analogue input pin and am then planning on using a capacitor to hold the power on to complete the write. I have this set up but am having issues testing as I have found that when Ground is connected to GND pins and then when 5v is supplied to any I/O pin the device powers up. I have now tested a Nano and Uno and have found the same thing on both.

I have looked through the arduino site and tried looking for forums where this has been discussed, but to no avail.

Is this damaging to the Arduino if powered in this way? Does this pass the sanity check as a way of achieving my main objective of not loosing the count on power down?

thanks in advance :)

body:
The arduino chips have clamping diodes on all the GPIO pins. So if the voltage on one of the pins is above Vcc (which is 0v is there is no power applied to the chip), the internal diode will 'redirect' this voltage to the Vcc line. This will damage the chip, is too much current is going through the clamping diodes.

Instead, connect the 5v signal via a large resistor (e.g. 100k) to the input pin.

Using a capacitor (plus diode to prevent backfeeding) will work. You just have to be careful if you have connected anything to an output pin that uses current. An led running at 20mA will drain a charged capacitor pretty quickly.

What I've done in the past is use the entire EEPROM space to store a single value. Just write every next value to a higher address. On powerup read the entire EEPROM till you find two adjacent address that don't contain successive numbers. Then you know where the last written value was, and you can read this last value, and continue writing the the address right after that one.


body:
I would suggest powering it from the 12V input and monitor the 12V with a power supply monitoring chip or circuit which will send an interrupt to your system when the voltage drops to whatever voltage you design it for. This can be accomplished with a few resistors and a comparator.

Your hold up time will be controlled by the amount of capacitance on the 12V side.  When the interrupt is tripped write the value to EEPROM and then shut down.

The analog input is a good sounding idea but there is a lot of latency between the time the voltage starts to fail and is detected.  The hardware interrupt will be much faster giving you more time to save your counter and the additional capacitance on the 12V side will give you a lot more time then back feeding through the GPIO pins..


body:
A typical method of increasing the number of writes to EEPROM is to use a vector of counters instead of a single value. The counter value is written to the EEPROM vector in a cyclic fashion.

On startup the vector is searched for current counter value, i.e. the highest counter in the vector. The write index is restored by locating the lowest counter value.

The number of writes is increased with the length of the vector.

Please read more about this method [here][1].

  [1]: http://www.atmel.com/images/doc2526.pdf


body:
A more sophisticated version of @MikaelPatel's techique is not to store the individual counts, but to store a derivative:

1. Reserve a block of storage with (say) 8 counters. Each counter has as many bits as necessary to store the largest value - but see below for what "largest" means.
2. Each time the count goes up, write into the next counter along (modulo the number of counters).
3. But don't write the value of the counter, write the value divided by the number of counters - `counter/8`.
4. Here's the trick: while that looks like you're losing precision, you're not - because the counter location is information too! In fact you're _gaining_ size.

It's best shown with an example. For ease, I'll assume an 8-bit counter, and only 8 counters:

    0000: 03 03 03 03 03 02 02 02

Assuming that everything started at `00`, that means that it took 8 counts for them all to get to `01`, a further 8 counts for them all to get to `02`, and only 5 counts to get the first 5 to `03`. That's a total of `8+8+5` or `21`.

At boot time, look for where the number sequence goes down. That's your current buffer position for future updates, plus the information for the current value:

    CurrentCount = [Smaller number] * [Number counters] + [Number of larger];

Once you've worked it out, keep the current value for incrementing, and the buffer pointer for where to store the next count.

### Advantages:

A. You write as often as you would storing a counter - but in different locations, spreading the load.
B. Each location (8, 16 or 32 bits) can store a certain maximum - but the total maximum is a factor of `Number of Counters` larger than that!

Odometer manufacturers use this exact technique to store the current mileage in digital dashboards - they have a legal requirement to maintain the correct number. They only use 16-bit counters (which would overflow after 65,535 miles), but then they use 16 counters, for a total mileage maximum of over a million. Each location only gets written every 16 miles, and they don't need to use 32-bit locations.


message:
USB 1.1 Low Speed project for Arduino UNO/ATmega328P to learn USB protocol

[Arduino UNO][1] is 5V, 16 MHz.

USB 1.1 Low Speed spec operate:

 * at 5V level - so we avoid to maintain voltage level
 * at 1.5 Mb/s - so we have 16/1.5 ~= 10 instructions per elementary protocol signal

Is it possible to make Arduino as slave USB device from UART lines connected to USB D+/D- interface with careful timing and assembler programming?

I doesn't familiar with ATmega328P pin I/O capabilities, may be them can't operate at 1.5 MHz so project isn't possible?

**UPDATE** I found [V-USB][2] library that:

    implementation of a low-speed USB device for Atmel’s AVR® microcontrollers,
    making it possible to build USB hardware with almost any AVR® microcontroller,
    not requiring any additional chip.

Still dig into docs to realize possibilities.

  [1]: https://www.arduino.cc/en/Main/arduinoBoardUno
  [2]: https://www.obdev.at/products/vusb/index.html

body:
Not exactly the answer to your question, but have you tried the [typical][1] way to emulate slave devices with Arduino UNO?

It uses the 2nd ATMega present onboard (this applies only to UNO, afaik) and lets you use the main ATMega for other tasks, delegating the USB protocol to the smaller ATMega16.

Do you have any specific reason why you would use the serial lines?

  [1]: http://smartinteractionlab.com/lufa-example-turning-your-arduino-into-a-keyboard/


message:
Linking Arduino With Twitter

My project is having Arduino with my WiFi shield connect to Twitter and look for any messages that other users have tweeted at me that contain a certain color, (I.E. @myTwitterHandle I want red) and then changes an RGB LED to become that color.

I have been searching online for different methods, and found a few different solutions which I could use as a starting point. However, these apparently call to an old Twitter API that is not supported anymore (support stopped mid 2013).

One solution I came across was to use node-red as well as MQTT.  I am not too familiar with these programs.

Does anyone know how to have Arduino parse a twitter account for mentions containing certain strings and have it print to LED? Any help with be appreciated

body:
The new Twitter 1.1 API requires OAuth authorization over SSL, for which Arduino is under-powered.

You will need to write a proxy application, which would parse the tweets and then send a RGB color value to your Arduino.

You should split your project into three parts.

1. Retrieving tweets with the [Twitter API](https://dev.twitter.com/overview/documentation).
You can get some library to do it for you.

2. Communicating with your Arduino.
Just try to send an arbitrary color to your Arduino over internet.

3. And finally joining first two pieces of code together.

And if you get stuck somewhere, you can always ask for help here on StackExchenge.


message:
Querying streaming sensor data on the Arduino board

I am new to Arduino and this forum, so please forgive me if I am asking something really trivial and stupid.

I have an Arduino board which collects sensor readings from an MPU6050 sensor (acceleration+gyroscope). The next step for me would be to process these data directly on the board. I want to somehow store N last sensor values and then query this set (collection, vector, array, whatever you call it) to fetch certain values. This set will be constantly updated with new values, whereas older values will be pushed out, so that only the most up-to-date values are stored in the set. For example, I want to know if the acceleration exceeded 10 m/s in the last minute.

In the literature this kind of set with most recent values is sometimes called *window* - this approach allows limiting an unbounded sequence of constantly generated tuples to a bounded bag and then apply traditional SQL-like query operators. For example, Oracle has come with [CQL][1] - an engine and a query language for handling streaming data.

Before I start implementing this, I am wondering if there is a similar (and, of course, much simpler) library for Arduino? If not, which data structure should I use to implement such functionality?

Also, my intention is to query not just individual values, but certain patterns and sequences - e.g., I want to know if the acceleration first decreased and then increased again (something similar to the WHERE condition of an SQL query). Does it look realistic to implement with Arduino?

  [1]: http://docs.oracle.com/cd/E16764_01/doc.1111/e12048/intro.htm "CQL"

body:
It sounds like you are after my Average library:

* https://github.com/MajenkoLibraries/Average

It allows you to store a rolling set of data where you get to "push" values into it and the oldest one drops off the end. (It's implemented internally using a circular buffer).

You can then do various forms of analysis on the data - get the *mean* average, the *mode* average, calculate the standard deviation, find the maximum and minimum values of the set, and even access individual entries within the set.

It's a fully templated library, so you can use it with any numerical data type (float, double, int, long, etc).


message:
Serial.readString() - how does it work exactly?

Someone posted a solution for a problem I had which used Serial.read() .Why doesn't readString() seem to work though? From the docs it seems it reads the data as a String object which would make things a bit cleaner.

But here's my Python code:

    import serial

    arduinoSerialData = serial.Serial('com7', 9600, timeout=0)

    while True:
     arduinoSerialData.write('ALIVE\r\n')

And Arduino code:

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

      pinMode(13, OUTPUT);

    }

    void loop() {
        if (Serial.readString() == "ALIVE") {
            digitalWrite(13, HIGH);
        } else {
            digitalWrite(13, LOW);
        }
    }

If this was right, the green LED on the Arduino would light up when the Python program would run, but it doesn't. What is Serial.readString() expecting that it doesn't get?
I even tried `if (Serial.readString().startsWith("ALIVE"))` instead, as well as `arduinoSerialData.flush()` before `arduinoSerialData.write()`

body:
`readString()` will read characters from the serial (or other Stream) device until a timeout occurs.  That timeout is, by default, 1 second.  It is only appropriate to use `readString()` if your data is arriving in chunks with a minimum time between each chunk.

It is more appropriate to use `readStringUntil()` which will read characters from the serial device until *either* it times out, *or* it receives a certain character.  It is most common to use either the line feed (`\n`) or carriage return (`\r`) characters as the end of string marker.  You must, of course, ensure that your sending program sends the string terminated in the right way.

However, that all said, you really should avoid using String objects when possible, since the constant creation and destruction of temporary objects all over the place can make a real mess of your heap.

It is far better to learn to use character arrays and fill them using `Serial.read()`.  A tutorial I wrote for that is here:

* http://hacking.majenko.co.uk/reading-serial-on-the-arduino


message:
Is the Serial buffer going from Arduino to PC and from PC to Arduino different?

I'm both sending and receiving strings to Arduino from my Python program on the PC and the opposite. I don't check by code if one is finished before doing the other. Are they seprate buffers, or is it just pure luck my program has been running fine until now and each program has been reading the right string ?

body:
There shall be separate buffers for Tx and Rx (in Arduino Serial library). The actual buffer size may vary, but shall be around 8-16 bytes and there is also hardware buffer in MCU. Please try to increase serial baudrate, if possible.

**UPD:** In HardwareSerial.h:

    #if (RAMEND < 1000)
    #define SERIAL_TX_BUFFER_SIZE 16
    #else
    #define SERIAL_TX_BUFFER_SIZE 64
    #endif

    ....

    unsigned char _rx_buffer[SERIAL_RX_BUFFER_SIZE];
    unsigned char _tx_buffer[SERIAL_TX_BUFFER_SIZE];

It seems for Atmega328 the buffers are 16 bytes each

**UPD:** As Nick pointed, for Atmega328:

    #define RAMEND       0x8FF     /* Last On-Chip SRAM Location */

So the buffers are 64 byte each.


message:
Is it difficult to do high voltage parallel programming using Nick Gammon library?

I have bricked a few AT328P by invalid fuse settings.

Has anybody used the above sketches and the associated circuitry to perform high voltage programming?

body:
I have not tried with those instructions, as I have an AVRDragon, but it's a good exercise for precision, since you have to wire lots of pins.

20+ iirc

My guess is that if anything fails, it's likely to be because of a mistake in the wiring.

If you are planning to do it often, you might consider soldering the wires and the ZIF socket to a prototype board, to preserve your mental sanity.


message:
Arduino circuit diagram help

I'm new to the arduino and to EE in general. I've built the basic examples and a, now trying to get a deeper understanding of what the physics is doing. As such, I'd like some help in understanding the diagram here:

https://www.arduino.cc/en/Tutorial/Blink

**Question 1:**

Specifically,it seems that the flow is going from Pin 13 to Ground. Is the diagram using the conventional flow or the electron flow approach.

Specifically, is it the *electrons* flowing from Pin 13 to ground or does the diagram show protons flowing? It seems that its showing the electron flow as the diagram has the anode attached to the resistor so the electrons flow from the pin to the resistor to the positive end (anode) of the LED.

**Question 2:**
This is about bread boards, like one shown here:

https://www.google.com/search?q=arduino+breadboard&biw=1696&bih=988&tbm=isch&tbo=u&source=univ&sa=X&ved=0CFEQsARqFQoTCIjsw5WhkMgCFdWYiAodttcKIw#tbm=isch&q=breadboard&imgrc=KwnTrtjnYJdB1M:

1) Would I connect Pin 13 (or say the 5V pin) to the + (the red line). Then I would connect the blue line (the -) to the ground on the arduino? Do I need to connect the blue line?

2) Also, is it again the electron flow notation so that from Pin 13, the electrons flow to the + (red), then to one of the lettered columns and then to whatever component I have?

Thank you for your help! I realize these are basic questions but I want to go a little beyond building the examples and start trying things out myself. As such I want to make sure I'm getting the theory behind it right!

body:
It doesn't matter whether you use conventional current or electron current to describe a circuit; in the end they give the same results.

Protons are not a charge carrier in 99.99999% of circuits; positive charge carriers are the quasiparticles known as **holes**, but they only flow in semiconductors.

The power rails on a breadboard should be used for power only, never signals. It is possible to use them for other things, and it is possible to not use them at all, but when they are used they should only be used for supply in order to cause the least confusion.


body:
Protons don't flow. They are part of the atom nucleus. If they flowed the copper wire would be flowing. Electrons are what flow, particularly if there are some free ones hanging around, like teenagers hanging around a mall.

You don't need to worry about that however. Most people think of current as flowing from positive to negative (ie. pin 13 to ground) even if in fact the electrons are flowing from ground to pin 13.

See [Conventional Versus Electron Flow](http://www.allaboutcircuits.com/textbook/direct-current/chpt-1/conventional-versus-electron-flow/). I quote:

>  When Benjamin Franklin made his conjecture regarding the direction of charge flow (from the smooth wax to the rough wool), he set a precedent for electrical notation that exists to this day, despite the fact that we know electrons are the constituent units of charge, and that they are displaced from the wool to the wax—not from the wax to the wool—when those two substances are rubbed together. This is why electrons are said to have a negative charge: because Franklin assumed electric charge moved in the opposite direction that it actually does, and so objects he called “negative” (representing a deficiency of charge) actually have a surplus of electrons.
>
> By the time the true direction of electron flow was discovered, the nomenclature of “positive” and “negative” had already been so well established in the scientific community that no effort was made to change it, although calling electrons “positive” would make more sense in referring to “excess” charge. You see, the terms “positive” and “negative” are human inventions, and as such have no absolute meaning beyond our own conventions of language and scientific description. Franklin could have just as easily referred to a surplus of charge as “black” and a deficiency as “white,” in which case scientists would speak of electrons having a “white” charge (assuming the same incorrect conjecture of charge position between wax and wool).

Quote courtesy of Design Science under [this license](https://www.gnu.org/licenses/dsl.html).

---

>  Would I connect Pin 13 (or say the 5V pin) to the + (the red line). Then I would connect the blue line (the -) to the ground on the arduino? Do I need to connect the blue line?

When using a breadboard I connect the 5V pin to the red line, the Gnd pin to the blue line, and other things (signals) to the internal (numbered) holes. The internal ones are connected cross-ways, so that is useful, for example, to put a series resistor for the LED there.

I trust you are using a resistor for the LED, if not you might damage both the LED and the Arduino. See [The care and feeding of LEDs](http://www.thebox.myzen.co.uk/Tutorial/LEDs.html).


body:
The thing to remember about electrons is they are a negative charge.  That means that the direction of current flow (positive charge) is opposite to the direction of flow of the actual electrons (negative charge). Picture it like those "compression jams" you get on the motorway (freeway) where cars that are travelling too close together have to slam their breaks on to avoid running into each other.  The one at the front slams its breaks on briefly then carries on. The one behind has to do the same, and so on and so forth.  You then get a wave effect travelling in the opposite direction to the direction of travel of cars as they slam their breaks on in turn.  The cars are moving forwards, but the compression jam is moving backwards.  Similar in a circuit - the electrons are moving forward, but the charge is moving backwards.

Another way to visualize it is as a bubble in a pipe of stationary water.  The bubble moves in one direction, but in order for it to do that the water has to flow past the bubble in the opposite direction.*

So the current flows out of pin 13 through the LED and to ground, but the electrons themselves are actually flowing from ground through the LED and in to pin 13 (where they eventually return back to ground through the power supply).

For how the IO pin works it's best to picture it as a pair of switches - one connected to Vcc and one connected to GND.  For instance, this is the LED wired up with the IO pin set to HIGH:

[![enter image description here][1]][1]

You can see that S1, being on, forms a circuit between the battery and the LED to allow the current to flow.

When the IO pin is set to LOW the circuit looks a bit like this:

[![enter image description here][2]][2]

You see that S1 is now turned off, and S2 is turned on.  the connection from that battery is now broken, and current can't flow.

But, you ask, what is the point of S2 here? It doesn't actually do anything.  No, not in that circuit it doesn't. But consider if you re-arrange the circuit to be like this:

[![enter image description here][3]][3]

Now it's S2 that is controlling the connection to the battery.  S1 is now the redundant switch.

This leads to some terminology.

When S1 is closed the IO pin is said to *source* current since it is pretty much connected directly to the positive power source.

When S2 is closed instead the IO pin is said to *sink* current since it is connected to ground, so current can "sink" down to ground through it.

As far as breadboards are concerned - they are just collections of metal strips that are used to join wires and component leads together in whatever way you need to.  There is no one part of it that is any different to any other, and there is nothing that says you must use this bit in a certain way, or that bit in another way.

Your typical breadboard has sprung metal clips that are arranged in this pattern:

[![enter image description here][4]][4]

You can use any collection of holes for any purpose you choose.

That said, normally the blue (or black) marked line of holes down each side is used for ground, and the red line of holes is used for power.  As both sides of the board are separate it is possible to use different voltages on each side, or the same voltage on both sides, etc.  That can be especially useful when you're working on a circuit that has, say, +3.3V and +5V in it.  Another common split usage is for a positive voltage on one side and a negative voltage on the other - common when working with op-amps.  Just remember which is which.

----
* This is a complete lie, but it's as close as you need to know at this point in your education. https://en.wikipedia.org/wiki/Lie-to-children

  [1]: https://i.stack.imgur.com/gWOUn.png
  [2]: https://i.stack.imgur.com/Atfxx.png
  [3]: https://i.stack.imgur.com/uaV1O.png
  [4]: https://i.stack.imgur.com/u220p.png


message:
atmega16 in Arduino Board

I had a very common question. Why a additional MEGA used in most of the Arduino Boards. Arduino board Mega2560 also have a MEGA16U2 controller on board which i think is used for programming via USB. Is there any other specific usage of atmega16 on arduino board.

Thanks

body: It's an ATmegaU2, which has USB hardware and handles the USB communication. It passes the hex file on to the bootloader in the main microcontroller. That is its only job.


message:
I2C Master send reset command to the slave counter

My name is Gianni, I live in Olbia Sardinia Italy and I have some experience in electronics.

For several years I have been passionate about Arduino.

They are now engaged in a project to counter with hall sensors.

The slave sends data to the master via I2C, for my project. I'm using the [sketch of Gammon](http://www.gammon.com.au/i2c) which uses a structure enum to send a request to the slave.

I have the need to send a reset command from master to slave.

I edited the sketch and I can see the command on the slave but will not let me use it to reset the counter.

---

## Master code section

       void RstCounter()
      {

      Serial.println ("funzione azzera attivata");
       Serial.println (sensor);
      char key = keypad.getKey();
      if (key !='A')
      {

       char cmdrst = 'a';
       //set=key;

         if (sensor==11)
        {
        sendCommand (CMD_WRITE_D2, 1);

        Wire.beginTransmission(SLAVE_ADDRESS); // testiamo questa istruzione
        Wire.write(cmdrst);
        Wire.endTransmission();

        delay(100);
        Serial.println (cmdrst);
        }

       else
      {
      m=0;
      }

       azzera =true;
      }
       else if (key=='A')
        {
       Serial.println("");
       Serial.println("AZZERA close");
       azzera = false;
       }
         delay(100);
        }

---

## SLAVE code section

    #include <Wire.h>

    const byte MY_ADDRESS = 42; // address in valore esadecimale

    /************  VARIABILI SENSORI **********************/

    #define Sensor11 2
    int lastValueSensor11 =0;
    int ValueSensor11=0;
    int contatore11=0;
    int counter11;

    // various commands we might get
    /************  VARIABILI ENUMERATORE **********************/
    enum {
        CMD_ID = 1,
        CMD_READ_D2  = 2,
        CMD_READ_D3 = 3,
        CMD_READ_D4 = 4,
        CMD_WRITE_D2 = 5
        };

    char command;
    int sensor;
    char cmdrst;

    /************  SETUP **********************/
    void setup()
      {
      command = 0;

      pinMode (Sensor11, INPUT);
      digitalWrite (Sensor11, HIGH);  // enable pull-up

      Serial.begin(9600);
      Wire.begin (MY_ADDRESS);
      Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
      Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

      }  // end of setup

    /************  LOOP **********************/
    void loop()
      {
            /************************ CONTATORE SENSOR 1 ***********************/
       ValueSensor11  = digitalRead(Sensor11);

                if ( ValueSensor11 != lastValueSensor11)
                   { if ( ValueSensor11 == LOW)
                        {
                          contatore11 = contatore11 + 1;

                            }
                         }
       lastValueSensor11 = ValueSensor11;

    /************  I2C RECEIVE **********************/
    void receiveEvent (int howMany)
      {

      command = Wire.read ();  // remember command for when we get request
      //Serial.println(command);
      switch (command)
         {
         case CMD_WRITE_D2:
         Serial.println("comando 5 ricevuto");
         char cmdrst=Wire.read();
         delay(100);
         Serial.println (cmdrst);
         break;
        }
    } // end of receiveEvent

    void sendSensor1 (const byte which)
      {
      int val11 = contatore11;
      Serial.println(contatore11);
      byte buf11 [2];

        buf11 [0] = val11 >> 8;
        buf11 [1] = val11 & 0xFF;
        Wire.write (buf11, 2);
      }  // end of sendSensor

    void requestEvent ()
      {
      switch (command)
         {
         case CMD_ID:
         Wire.write (0x55);
         break;   // send our ID

         case CMD_READ_D2:
         sendSensor1 (2);
         break;  // send A0 value

         case CMD_READ_D3:
         sendSensor2 (3);
         break;    // send D8 value

         case CMD_READ_D4:
         sendSensor3 (4);
         break;

         }  // end of switch

      }  // end of requestEvent

body:
    void receiveEvent (int howMany)
      {

      command = Wire.read ();  // remember command for when we get request
      //Serial.println(command);
      switch (command)
         {
         case CMD_WRITE_D2:
         Serial.println("comando 5 ricevuto");
         char cmdrst=Wire.read();
         delay(100);
         Serial.println (cmdrst);
         break;
        }
    } // end of receiveEvent

* Don't do serial prints inside an interrupt service routine (ISR). That is, not here.

* Don't do `delay` inside an ISR.

---

      if (key !='A')
      {

I would be checking for NO_KEY first, otherwise you will assume that no key press is not 'A' and be doing that transmission to the slave **a lot**.


message:
Hardware to measure velocity via string/wire attatchment? beginner

This is a broad question but I want advice on what type of hardware I should look for to make a device that could measure the velocity of an object attached via a string/wire to some sort of rotary wheel.

The purpose of this is to attach it to a barbell and measure mean-velocity for weightlifting atheletes.

I'm a software engineer by trade but know nothing about hardware. I will obviously need to start with simple projects to learn, but I would like to know which hardware I should lean towards buying, so I don't have to re-buy anything?

body:
[This][1] is an example of the optical encoder.
You want to use interrupt detection, rather than polling.
Or maybe even an HW counter.
That's all you really need.

I am using 4 of them for a car.

I am in the process of refactoring the code, but you could already have a look at the driver & example I wrote for ChibiOS, [here][2].

  [1]: http://www.ebay.com/itm/photoelectric-speed-sensor-encoder-coded-disc-code-wheel-for-freescale-smart-/231699340055?hash=item35f25b5b17
  [2]: https://github.com/ChibiOS/ChibiOS/pull/10


body:
You can use a dog lead (or replace it with a fishing line). I made one my self. I used a rotary encoder and a dog lead, an Arduino board Paralax, and Excel.

It will use interrupts. Once the wire is triggered, the Arduino will send to Excel time and distance traveled. Once the weight goes down distance and time will be printed too, however distance will run in a minus direction. Later just press one button in Excel and each set of lifts will appear on the desktop. I can see my lift speed, power generated, distance travelled and so on.

[![Excel example][1]][1]

  [1]: https://i.stack.imgur.com/8lhAU.png


message:
help with 7- segment display

I'm playing with a 7 segment display.

The following works on my breadboard:

    5V -> 330 Ohm Resistor (same row, row 9)
    330 Ohm Resistor -> Com Port (row 9 to row 15)
    h led (the dot/row 17) -> ground rail

I get the dot to light up.

However, the following does not light up:

    5V -> h led (the dot/row 17)
    Com Port -> 330 Ohm Resistor (Row 15 -> row 38).
    330 Ohm Resistor to negative rail (row 38 -> negative rail)

I realize that the row numbers are meaningless -- things just need to be on the same row. I've included them to make it easier to visualize.

So basically, if the circuit goes:

5V -> Resistor -> Com, then I can use the ground wire to light up any part I want.

If the circuit goes Com -> Resistor to Ground, I can't use the 5V to light up any part.

I'm not sure why given that all the stuff is in serial?

body: Because you have a common-anode display and you're trying to use it as a common-cathode display. LEDs, like all diodes, only conduct freely in one direction.


message:
Just sanity-checking a concept... poor man's self-monitored alarm system

If I wanted to throw together a simple burglar-alarm system that had wireless sensors talking to an Arduino (which would then send me an SMS message via cellular shield as a silent alarm telling me which alarm sensor had changed state_)... what technology would you recommend for the sensor-to-arduino signalling?

It needs to be something that draws little or no power until the alarm is triggered, resistant to radio interference, and as always cheap is a huge plus.... but I haven't gotten much beyond that.

(Of course if anyone's already implemented something like this and there are descriptions/sketches I can adopt and adapt, feel free to point me in the right direction.)

EDIT: To provide more info,this is a wood-framed house, 2 storey plus basement, brick chimney possibly in the way. No straight-line distances greater than 60 feet. Wifi, wireless phone, usual electronics and a wood shop I'm still putting together. Shouldn't be difficult, I just want a robust solution in case a friend asks me to replicate it... and for purely aesthetic reasons.

body:
NRF24L01+ for communication. Extreme low power if not sending. Detects packet loss, and automatically resend the packet.

You would however need a small arduino board at the sensor, to read the sensor, and signal to NRF24L01 to send a message.

You'll have to put the arduino in to low power sleep mode to get some good battery life. Either have the sensor wake the arduino up with an interrupt, of poll the sensor like every half second, and immediately go back to sleep.


message:
How do I connect Arduino directly to MySQL server using the URL?

I started a project with my Arduino Mega 2560 that gets some values from sensors. I'm using MySQL Connector, https://launchpad.net/mysql-arduino, and this library allows me to connect to a server using the IP address, and it worked on localhost.

This is the code:

    /* Setup for all libraries */
    #include <SPI.h>
    #include <Ethernet.h>
    #include <sha1.h>
    #include <mysql.h>
    #include <OneWire.h>

    /* Setup for Ethernet Library */
    byte mac_addr[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xB3, 0x05 }; // MAC address must be unique; this is the Ethernet shield address
    IPAddress server_addr( 177, 156, 122, 113 ); // Server addr

    /* Setup for all others variables */
    int DS18S20_Pin = 2; // Temperature sensor
    float temperature;
    float placasTensao;
    float placasCorrente;
    float geradorEolicoTensao;
    float geradorEolicoCorrente;
    float bateriaTensao;
    float bateriaTemp;
    float correnteSaidaControlador;
    float correnteSaidaConsumo;

    OneWire ds(DS18S20_Pin);  // On digital pin 2

    /* Setup for the Connector/Arduino */
    Connector my_conn; // The Connector/Arduino reference

    /* Setup for connection and all variables of the database */
    char user[] = "";
    char password[] = "";
    char INSERT_SQL[1000];
    char temperature_convt[10], placasTensao_convt[10], placasCorrente_convt[10], geradorEolicoTensao_convt[10],
         geradorEolicoCorrente_convt[10], bateriaTensao_convt[10], bateriaTemp_convt[10], correnteSaidaControlador_convt[10],
         correnteSaidaConsumo_convt[10];

    void setup(){
      Ethernet.begin(mac_addr);
      Serial.begin(9600);
      delay(1000);
    }

    void loop(){
      temperature = getTemp();
      convert(temperature, temperature_convt);
      snprintf(INSERT_SQL, "INSERT INTO data.data VALUES (%s, 1, 1, 1, 1, 1, 1, 1, NULL)", temperature_convt);
      sendData();
      delay(20000);
    }

    // Convert a float variable to string
    void convert(float data, char *value){
      dtostrf(data, 7, 3, value);
    }

    // Saves all data on database
    void sendData(){
      Serial.println("Connecting...");
      if (my_conn.mysql_connect(server_addr, 3306, user, password)){
        delay(500);
        Serial.println("Starting SQL!");
        Serial.println(INSERT_SQL);
        my_conn.cmd_query(INSERT_SQL);
        Serial.println("Query Success!");
        my_conn.disconnect();
        Serial.println("\n");
      } else {
        Serial.println("Connection failed!");
        Serial.println("Make sure all cables are properly connected!\nIf they are, restart the Arduino!\n");
      }
    }

    // Returns the temperature from one DS18S20 in degree Celsius
    float getTemp(){
      byte data[12];
      byte addr[8];
      if (!ds.search(addr)) {
          // No more sensors on chain, reset search
          ds.reset_search();
          return -1000;
      }

      if ( OneWire::crc8( addr, 7) != addr[7]) {
          Serial.println("CRC is not valid!");
          return -1000;
      }

      if ( addr[0] != 0x10 && addr[0] != 0x28) {
          Serial.print("Device is not recognized");
          return -1000;
      }
      ds.reset();
      ds.select(addr);
      ds.write(0x44,1);
      // Start conversion, with parasite power on at the end
      byte present = ds.reset();
      ds.select(addr);
      ds.write(0xBE); // Read Scratchpad
      for (int i = 0; i < 9; i++) { // We need 9 bytes
        data[i] = ds.read();
      }
      ds.reset_search();
      byte MSB = data[1];
      byte LSB = data[0];
      float tempRead = ((MSB << 8) | LSB); // Using two's complement
      float TemperatureSum = tempRead / 16;
      return TemperatureSum;
    }

Now, how can I connect to a server using the URL? Is there a library like MySQL Connector that allows me to use the URL instead of the IP address?

All I want is to do exactly the same thing that I'm doing with MySQL Connector, but using the URL of the server instead of the IP address.

body:
You are using DHCP, so this step might be optional.
Specify your network addresses (actually we want to specify DNS only but have to specify IP in 2nd argument, so likely have to specify gateway and subnet too):

    IPAddress dns_addr( 8, 8, 8, 8); // GOOGLE DNS server, could be any DNS
    IPAddress gateway_addr( , , , );   // put your gateway addr
    IPAddress ip_addr( , , , );   // put your IP addr
    IPAddress subnet( , , , );   // put your subnet mask

    void setup(){
                      Ethernet.begin(mac_addr, ip_addr, dns_addr, gateway_addr, subnet);...

Now you could modify **Connector::mysql_connect** method (or create new method) as follows (only function declaration is changed, body is not):

    boolean Connector::mysql_connect(/*IPAddress server*/const char *server, int port, char *user, char *password)
    {
      int connected = 0;
      int i = -1;

      // Retry up to MAX_CONNECT_ATTEMPTS times 1 second apart.
      do {
        delay(1000);
        connected = client.connect(server, port);
        i++;
      } while (i < MAX_CONNECT_ATTEMPTS && !connected);

      if (connected) {
        read_packet();
        parse_handshake_packet();
        send_authentication_packet(user, password);
        read_packet();
        if (check_ok_packet() != 0) {
          parse_error_packet();
          return false;
        }
        print_message(CONNECTED);
        Serial.println(server_version);
        free(server_version); // don't need it anymore
        return true;
      }
      return false;
    }

Modify the header file also:

    boolean mysql_connect(/*IPAddress server*/const char *server, int port,
                                     char *user, char *password)
Now you can supply URL:

    if (my_conn.mysql_connect("http:\\www.mysqlserver.com", 3306, user, password))...


body:
The easiest, just git 'er done, way would be to do an nslookup on the domain, get the IP address and just hard code that into your source. It's not the most robust solution, as it's possible for the IP address to change over time. However, it's highly likely the IP address won't change frequently.

    > nslookup google.ca
    Server:  64.59.144.93
    Address: 64.59.144.93#53

    Non-authoritative answer:
    Name: google.ca
    Address: 216.58.193.67

If you need it to be more robust, you would need the Arduino to perform the dns lookup to resolve the IP address. This looks like it would do the job:

https://github.com/esp8266/Arduino/blob/master/libraries/Ethernet/src/Dns.h


message:
How do you use SPI on an Arduino?

With reference to the Arduino Uno, Mega2560, Leonardo and similar boards:

* How does SPI work?
* How fast is SPI?
* How do I connect between a master and a slave?
* How do I make an SPI slave?

---

*Please note: This is intended as a reference question.*

body:
## Introduction to SPI

<!-- language-all: lang-C++ -->

The [Serial Peripheral Interface Bus](https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus) (SPI) interface is used for communication between multiple devices over short distances, and at high speed.

Typically there is a single "master" device, which initiates communications and supplies the clock which controls the data transfer rate. There can be one or more slaves. For more than one slave, each one has its own "slave select" signal, described later.

---

## SPI signals

In a full-blown SPI system you will have four signal lines:

* Master Out, Slave In (**MOSI**) - which is the data going from the master to the slave
* Master In, Slave Out (**MISO**) - which is the data going from the slave to the master
* Serial Clock (**SCK**) - when this toggles both the master and the slave sample the next bit
* Slave Select (**SS**) - this tells a particular slave to go "active"

When multiple slaves are connected to the MISO signal they are expected to tri-state (keep at high impedance) that MISO line until they are selected by Slave Select being asserted. Normally Slave Select (SS) goes low to assert it. That is, it is active low. Once a particular slave is selected it should configure the MISO line as an output so it can send data to the master.

This image shows the way that data is exchanged as one byte is sent:

[![SPI protocol showing 4 signals][1]][1]

Note that three signals are outputs from the master (MOSI, SCK, SS) and one is an input (MISO).

---

## Timing

The sequence of events is:

* `SS` goes low to assert it and activate the slave
* The `SCK` line toggles to indicate when the data lines should be sampled
* The data is sampled by both master and slave on the **leading** edge of `SCK` (using the default clock phase)
* Both master and slave prepare for the next bit on the **trailing** edge of `SCK` (using the default clock phase), by changing `MISO` / `MOSI` if necessary
* Once the transmission is over (possibly after multiple bytes have been sent) then `SS` goes high to de-assert it

Note that:

* The most significant bit is sent first (by default)
* Data is sent and received at the same instant (full duplex)

Because data is sent and received on the same clock pulse it is not possible for the slave to respond to the master immediately. SPI protocols usually expect the master to request data on one transmission, and get a response on a subsequent one.

Using the SPI library on the Arduino, doing a single transfer looks like this in code:

     byte outgoing = 0xAB;
     byte incoming = SPI.transfer (outgoing);

---

## Sample code

Example of sending only (ignoring any incoming data):

    #include <SPI.h>

    void setup (void)
      {
      digitalWrite(SS, HIGH);  // ensure SS stays high
      SPI.begin ();
      } // end of setup

    void loop (void)
      {
      byte c;

      // enable Slave Select
      digitalWrite(SS, LOW);    // SS is pin 10

      // send test string
      for (const char * p = "Fab" ; c = *p; p++)
        SPI.transfer (c);

      // disable Slave Select
      digitalWrite(SS, HIGH);

      delay (100);
      } // end of loop

---

## Wiring for output-only SPI

The above code (which sends only) might be used to drive an output serial shift register. These are output-only devices, so we don't need to worry about any incoming data. In their case the SS pin might be called the "store" or "latch" pin.

[![SPI protocol showing 3 signals][2]][2]

Examples of this are the 74HC595 serial shift register, and various LED strips, just to mention a couple. For example, this 64 pixel LED display driven by a MAX7219 chip:

[![64 pixel LED display][3]][3]

In this case you can see that the board maker has used slightly different signal names:

* DIN (Data In) is MOSI (Master Out, Slave In)
* CS (Chip Select) is SS (Slave Select)
* CLK (Clock) is SCK (Serial Clock)

Most boards will follow a similar pattern. Sometimes DIN is just DI (Data In).

Here is another example, this time a 7-segment LED display board (also based on the MAX7219 chip):

[![7-segment LED display][4]][4]

This uses exactly the same signal names as the other board. In both of these cases you can see that the board only needs 5 wires to it, the three for SPI, plus power and ground.

---

## Clock phase and polarity

There are four way you can sample the SPI clock.

The SPI protocol allows for variations on the polarity of the clock pulses. CPOL is clock polarity, and CPHA is clock phase.

* Mode 0 (the default) - clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0)
* Mode 1 - clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1)
* Mode 2 - clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0)
* Mode 3 - clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1)

These are illustrated in this graphic:

[![SPI clock phase and polarity][5]][5]

You should refer to the datasheet for your device to get the phase and polarity correct. There will usually be a diagram which shows how to sample the clock. For example, from the datasheet for the 74HC595 chip:

[![74HC595 clock][6]][6]

As you can see the clock is normally low (CPOL = 0) and it is sampled on the leading edge (CPHA = 0) so this therefore is SPI mode 0.

You can change the clock polarity and phase in code like this (choose one only, of course):

    SPI.setDataMode (SPI_MODE0);
    SPI.setDataMode (SPI_MODE1);
    SPI.setDataMode (SPI_MODE2);
    SPI.setDataMode (SPI_MODE3);

This method is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the clock mode in the `SPI.beginTransaction` call, like this:

    SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));  // 2 MHz clock, MSB first, mode 0

---

## Data order

The default is most-significant bit first, however you can tell the hardware to process the least significant bit first like this:

    SPI.setBitOrder (LSBFIRST);   // least significant bit first
    SPI.setBitOrder (MSBFIRST);   // most significant bit first

Again, this is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the bit order in the `SPI.beginTransaction` call, like this:

    SPI.beginTransaction (SPISettings (1000000, LSBFIRST, SPI_MODE2));  // 1 MHz clock, LSB first, mode 2

---

## Speed

The default setting for SPI is to use the system clock speed divided by four, that is, one SPI clock pulse every 250 ns, assuming a 16 MHz CPU clock. You can change the clock divider by using `setClockDivider` like this:

    SPI.setClockDivider (divider);

Where "divider" is one of:

*  SPI_CLOCK_DIV2
*  SPI_CLOCK_DIV4
*  SPI_CLOCK_DIV8
*  SPI_CLOCK_DIV16
*  SPI_CLOCK_DIV32
*  SPI_CLOCK_DIV64
*  SPI_CLOCK_DIV128

The fastest rate is "divide by 2" or one SPI clock pulse every 125 ns, assuming a 16 MHz CPU clock. This would therefore take 8 * 125 ns or 1 µs to transmit one byte.

This method is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the transfer speed in the `SPI.beginTransaction` call, like this:

    SPI.beginTransaction (SPISettings (4000000, MSBFIRST, SPI_MODE0));  // 4 MHz clock, MSB first, mode 0

However empirical testing shows that it is necessary to have two clock pulses between bytes, so the maximum rate at which bytes can be clocked out is 1.125 µs each (with a clock divider of 2).

To summarize, each byte can be sent at a maximum rate of one per 1.125 µs (with a 16 MHz clock) giving a theoretical maximum transfer rate of 1/1.125 µs, or 888,888 bytes per second (excluding overhead like setting SS low and so on).

---

## Connecting to Arduino

### Arduino Uno

Connecting via digital pins 10 to 13:

[![Arduino Uno SPI pins][7]][7]

Connecting via the ICSP header:

[![ICSP pinouts - Uno][8]][8]

[![ICSP header][9]][9]

### Arduino Atmega2560

Connecting via digital pins 50 to 52:

[![Arduino Mega2560 SPI pins][10]][10]

You can also use the ICSP header, similar to the Uno above.

### Arduino Leonardo

The Leonardo and Micro do not expose the SPI pins on the digital pins, unlike the Uno and Mega. Your only option is to use the ICSP header pins, as illustrated above for the Uno. However the Leonardo and ProMicro don't expose the SS pin and thus cannot be used as an SPI slave.

---

## Multiple slaves

A master can communicate with multiple slaves (however only one at a time). It does this by asserting SS for one slave and de-asserting it for all the others. The slave which has SS asserted (usually this means LOW) configures its MISO pin as an output so that slave, and that slave alone, can respond to the master. The other slaves ignore any incoming clock pulses if SS is not asserted. Thus you need one additional signal for each slave, like this:

[![Multiple SPI slaves][11]][11]

In this graphic you can see that MISO, MOSI, SCK are shared between both slaves, however each slave has its own SS (slave select) signal.

---

## Protocols

The SPI spec does not specify protocols as such, so it is up to individual master/slave pairings to agree on what the data means. Whilst you can send and receive bytes simultaneously, the received byte cannot be a direct response to the sent byte (as they are being assembled simultaneously).

So it would be more logical for one end to send a request (eg. 4 might mean "list the disk directory") and then do transfers (perhaps just sending zeros outwards) until it receives a complete response. The response might terminate with a newline, or 0x00 character.

Read the datasheet for your slave device to see what protocol sequences it expects.

---

## How to make an SPI slave

The earlier example shows the Arduino as the master, sending data to a slave device. This example shows how the Arduino can be a slave.

### Hardware setup

Connect two Arduino Unos together with the following pins connected to each other:

* 10 (SS)
* 11 (MOSI)
* 12 (MISO)
* 13 (SCK)

* +5v (if required)
* GND (for signal return)

On the Arduino Mega, the pins are 50 (MISO), 51 (MOSI), 52 (SCK), and 53 (SS).

In any case, MOSI at one end is connected to MOSI at the other, you **don't** swap them around (that is you **do not have** MOSI <-> MISO). The software configures one end of MOSI (master end) as an output, and the other end (slave end) as an input.

On some boards (like Leonardo, ProMicro — see above) the SS pin isn't exposed (rather it is connected to RX_LED). It is not possible to remap SS to another pin to be able to use those boards as an SPI slave as the AVR uses fixed SPI pins according to the datasheets (PB0-PB3 on 32U4).

### Master example

    #include <SPI.h>

    void setup (void)
    {

      digitalWrite(SS, HIGH);  // ensure SS stays high for now

      // Put SCK, MOSI, SS pins into output mode
      // also put SCK, MOSI into LOW state, and SS into HIGH state.
      // Then put SPI hardware into Master mode and turn SPI on
      SPI.begin ();

      // Slow down the master a bit
      SPI.setClockDivider(SPI_CLOCK_DIV8);

    }  // end of setup

    void loop (void)
    {

      char c;

      // enable Slave Select
      digitalWrite(SS, LOW);    // SS is pin 10

      // send test string
      for (const char * p = "Hello, world!\n" ; c = *p; p++)
        SPI.transfer (c);

      // disable Slave Select
      digitalWrite(SS, HIGH);

      delay (1000);  // 1 seconds delay
    }  // end of loop

### Slave example

    #include <SPI.h>

    char buf [100];
    volatile byte pos;
    volatile bool process_it;

    void setup (void)
    {
      Serial.begin (115200);   // debugging

      // turn on SPI in slave mode
      SPCR |= bit (SPE);

      // have to send on master in, *slave out*
      pinMode (MISO, OUTPUT);

      // get ready for an interrupt
      pos = 0;   // buffer empty
      process_it = false;

      // now turn on interrupts
      SPI.attachInterrupt();

    }  // end of setup

    // SPI interrupt routine
    ISR (SPI_STC_vect)
    {
    byte c = SPDR;  // grab byte from SPI Data Register

      // add to buffer if room
      if (pos < sizeof buf)
        {
        buf [pos++] = c;

        // example: newline means time to process buffer
        if (c == '\n')
          process_it = true;

        }  // end of room available
    }  // end of interrupt routine SPI_STC_vect

    // main loop - wait for flag set in interrupt routine
    void loop (void)
    {
      if (process_it)
        {
        buf [pos] = 0;
        Serial.println (buf);
        pos = 0;
        process_it = false;
        }  // end of flag set

    }  // end of loop

The slave is entirely interrupt-driven, thus it can doing other stuff. The incoming SPI data is collected in a buffer, and a flag set when a "significant byte" (in this case a newline) arrives. This tells the slave to get on and start processing the data.

###  Example of connecting master to slave using SPI

[![Arduino SPI master and slave][12]][12]

---

## How to get a response from a slave

Following on from the code above which sends data from an SPI master to a slave, the example below shows sending data to a slave, having it do something with it, and return a response.

The master is similar to the example above. However an important point is that we need to add a slight delay (something like 20 microseconds). Otherwise the slave doesn't have a chance to react to the incoming data and do something with it.

The example shows sending a "command". In this case "a" (add something) or "s" (subtract something). This is to show that the slave is actually doing something with the data.

After asserting slave-select (SS) to initiate the transaction, the master sends the command, followed by any number of bytes, and then raises SS to terminate the transaction.

A very important point is that the slave cannot respond to an incoming byte at the same moment. The response has to be in the next byte. This is because the bits which are being sent, and the bits which are being received, are being sent simultaneously. Thus to add something to four numbers we need five transfers, like this:

    transferAndWait ('a');  // add command
    transferAndWait (10);
    a = transferAndWait (17);
    b = transferAndWait (33);
    c = transferAndWait (42);
    d = transferAndWait (0);

First we request action on number 10. But we don't get a response until the next transfer (the one for 17). However "a" will be set to the reply to 10. Finally we end up sending a "dummy" number 0, to get the reply for 42.

### Master (example)

      #include <SPI.h>

      void setup (void)
        {
        Serial.begin (115200);
        Serial.println ();

        digitalWrite(SS, HIGH);  // ensure SS stays high for now
        SPI.begin ();

        // Slow down the master a bit
        SPI.setClockDivider(SPI_CLOCK_DIV8);
        }  // end of setup

      byte transferAndWait (const byte what)
        {
        byte a = SPI.transfer (what);
        delayMicroseconds (20);
        return a;
        } // end of transferAndWait

      void loop (void)
        {

        byte a, b, c, d;

        // enable Slave Select
        digitalWrite(SS, LOW);

        transferAndWait ('a');  // add command
        transferAndWait (10);
        a = transferAndWait (17);
        b = transferAndWait (33);
        c = transferAndWait (42);
        d = transferAndWait (0);

        // disable Slave Select
        digitalWrite(SS, HIGH);

        Serial.println ("Adding results:");
        Serial.println (a, DEC);
        Serial.println (b, DEC);
        Serial.println (c, DEC);
        Serial.println (d, DEC);

        // enable Slave Select
        digitalWrite(SS, LOW);

        transferAndWait ('s');  // subtract command
        transferAndWait (10);
        a = transferAndWait (17);
        b = transferAndWait (33);
        c = transferAndWait (42);
        d = transferAndWait (0);

        // disable Slave Select
        digitalWrite(SS, HIGH);

        Serial.println ("Subtracting results:");
        Serial.println (a, DEC);
        Serial.println (b, DEC);
        Serial.println (c, DEC);
        Serial.println (d, DEC);

        delay (1000);  // 1 second delay
        }  // end of loop

The code for the slave basically does almost everything in the interrupt routine (called when incoming SPI data arrives). It takes the incoming byte, and adds or subtracts as per the remembered "command byte". Note that the response will be "collected" next time through the loop. This is why the master has to send one final "dummy" transfer to get the final reply.

In my example I am using the main loop to simply detect when SS goes high, and clear the saved command. That way, when SS is pulled low again for the next transaction, the first byte is considered the command byte.

More reliably, this would be done with an interrupt. That is, you would physically connect SS to one of the interrupt inputs (eg, on the Uno, connect pin 10 (SS) to pin 2 (an interrupt input), or use a pin-change interrupt on pin 10.

Then the interrupt could be used to notice when SS is being pulled low or high.

### Slave (example)

    // what to do with incoming data
    volatile byte command = 0;

    void setup (void)
      {

      // have to send on master in, *slave out*
      pinMode(MISO, OUTPUT);

      // turn on SPI in slave mode
      SPCR |= _BV(SPE);

      // turn on interrupts
      SPCR |= _BV(SPIE);

      }  // end of setup

    // SPI interrupt routine
    ISR (SPI_STC_vect)
      {
      byte c = SPDR;

      switch (command)
        {
        // no command? then this is the command
        case 0:
          command = c;
          SPDR = 0;
          break;

        // add to incoming byte, return result
        case 'a':
          SPDR = c + 15;  // add 15
          break;

        // subtract from incoming byte, return result
        case 's':
          SPDR = c - 8;  // subtract 8
          break;

        } // end of switch

      }  // end of interrupt service routine (ISR) SPI_STC_vect

    void loop (void)
      {

      // if SPI not active, clear current command
      if (digitalRead (SS) == HIGH)
        command = 0;
      }  // end of loop

### Example output

<!-- language-all: lang-none -->

    Adding results:
    25
    32
    48
    57
    Subtracting results:
    2
    9
    25
    34
    Adding results:
    25
    32
    48
    57
    Subtracting results:
    2
    9
    25
    34

### Logic analyzer output

This shows the timing between sending and receiving in the above code:

[![SPI master and slave timing][13]][13]

---

## New functionality in IDE 1.6.0 onwards

Version 1.6.0 of the IDE has changed the way SPI works, to an extent. You **still need to do** `SPI.begin()` before using SPI. That sets up the SPI hardware. However now, when you are about to start communicating with a slave you **also** do `SPI.beginTransaction()` to set up SPI (for this slave) with the correct:

* Clock speed
* Bit order
* Clock phase and polarity

When you are done communicating with the slave, you call `SPI.endTransaction()`. For example:

<!-- language-all: lang-C++ -->

    SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));
    digitalWrite (SS, LOW);        // assert Slave Select
    byte foo = SPI.transfer (42);  // do a transfer
    digitalWrite (SS, HIGH);       // de-assert Slave Select
    SPI.endTransaction ();         // transaction over

---

## Why use SPI?

> I would add one preliminary question: when/why would you use SPI? A need for multi-master configuration or a very large number of slaves would tilt the scale toward I2C.

This is an excellent question. My answers are:

* Some devices (quite a few) only support the SPI transfer method. For example the 74HC595 output shift register, the 74HC165 input shift register, the MAX7219 LED driver, and quite a few LED strips that I have seen. So, you might use it because the target device only supports it.
* SPI is really the fastest method available on the Atmega328 (and similar) chips. The fastest rate quoted above is 888,888 bytes per second. Using I<sup>2</sup>C you can only get around 40,000 bytes per second. The overhead of the I<sup>2</sup>C is quite substantial, and if you are trying to interface really quickly, SPI is the preferred choice. Quite a few chip families (eg. MCP23017 and MCP23S17) actually support both I<sup>2</sup>C and SPI so you often can choose between speed, and the ability to have multiple devices on a single bus.
* The SPI and I<sup>2</sup>C devices are both supported in hardware on the Atmega328 so you could conceivably be doing a transfer via SPI simultaneously with I<sup>2</sup>C which would give you a speed boost.

Both methods have their place. I<sup>2</sup>C lets you connect many devices to a single bus (two wires, plus ground) so it would be the preferred choice if you needed to interrogate a substantial number of devices, perhaps fairly infrequently. However the speed of SPI could be more relevant for situations where you need to output rapidly (eg. a LED strip) or input rapidly (eg. an ADC converter).

---

## References

* [My page about SPI](http://www.gammon.com.au/spi) - also has details about bit-banged SPI, and using the USART to gain a second hardware SPI on the Atmega328 chip.

* [Serial Peripheral Interface Bus - Wikipedia](https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus)

* [Arduino SPI library reference pages](http://arduino.cc/en/Reference/SPI)

* [SPI documentation at PJRC](http://www.pjrc.com/teensy/td_libs_SPI.html)

* [SPI protocol - Sparkfun](https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi)

  [1]: https://i.stack.imgur.com/6cTce.png
  [2]: https://i.stack.imgur.com/bbmei.png
  [3]: https://i.stack.imgur.com/OeBsB.png
  [4]: https://i.stack.imgur.com/CvhRc.jpg
  [5]: https://i.stack.imgur.com/MHkRd.png
  [6]: https://i.stack.imgur.com/IdlVA.png
  [7]: https://i.stack.imgur.com/QJx5X.jpg
  [8]: https://i.stack.imgur.com/0c2a8.jpg
  [9]: https://i.stack.imgur.com/NH4o9.png
  [10]: https://i.stack.imgur.com/zEhcv.jpg
  [11]: https://i.stack.imgur.com/x4uKM.png
  [12]: https://i.stack.imgur.com/PB7Ob.jpg
  [13]: https://i.stack.imgur.com/3qtCV.png


body:
Thank you for the information.

Mr. Nick Gammon said

> However the Leonardo and ProMicro don't expose the SS pin and thus cannot be used as an SPI slave.

but I could use ProMicro and Leonardo as SPI slave devides by wiring SS signal.

Reference: https://asukiaaa.blogspot.com/2023/05/atmega32u4-as-spi-slave.html

[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][4]][4]
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/3Gds3m.jpg
  [2]: https://i.stack.imgur.com/dgLeJm.jpg
  [3]: https://i.stack.imgur.com/PIwCZm.jpg
  [4]: https://i.stack.imgur.com/mHf3sm.jpg


message:
Measure Vcc using 1.1V bandgap

For an battery driven application I want to measure the Vcc (using an Atmega 32u4). That is my code:

    int readBandGap() {
      ADMUX = (B01 << REFS0)    // VCC
            | (0 << ADLAR)      // right-adjusted result
            | (B011110 << MUX0) // 1.1V
            ;
      // switch off any ADC conversion
      ADCSRA &= ~(1 << ADEN);
      // enable ADC
      ADCSRA |= 1 << ADEN;
      // start ADC
      ADCSRA |= 1 << ADSC;
      // wait until finished
      while (bit_is_set(ADCSRA, ADSC));
      // first read low, then high!
      uint8_t low = ADCL;
      uint8_t high = ADCH;
      // switch off any ADC conversion
      ADCSRA &= ~(1 << ADEN);
      return (high << 8) | low;
    }

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

    void loop() {
      int value = readBandGap();
      float vcc = 1.1 * 1023 / value;
      Serial.print(value);
      Serial.print("  ");
      Serial.println(vcc);

      delay(1000);
    }
My Olimexino 32u4 board has the ability to switch the voltage between 5V and 3.3V. There are two strange things:

 1. the first measurement is always significantly different than the later measurements

 2. with 5V I'm getting 450, followed by ~367; with 3.3V I'm getting 422, followed by ~395. I would have expected a higher Vcc resulting in a lower measured value (bandgap should be measured compared to Vcc).

Any ideas what is wrong with my approach?

body:
After tweaking a lot, I've now have found following code to work quite good.

    float readVcc() {
      ADMUX = (B01 << REFS0)    // VCC
            | (0 << ADLAR)      // right-adjusted result
            | (B011110 << MUX0) // 1.1V
            ;
      // enable ADC
      ADCSRA |= (1 << ADEN);
      // seems necessary
      delay(2);
      // start ADC
      ADCSRA |= 1 << ADSC;
      // wait until finished
      while (bit_is_set(ADCSRA, ADSC));
      // first read low, then high!
      long value = ADCL;
      value |= ADCH << 8;
      return 1.1 / value * 1023;
    }


body:
The bandgap voltage reference needs some time to stabilize, after you enable it. See http://jeelabs.org/2012/05/12/improved-vcc-measurement/

Doing 3 dummy measurements, gives it enough time to do that.


message:
Dagu Mini Driver Board Issues

I have the Dagu Mini Driver board which is based on the atmega8 and I uploaded the code [here][1]. It uploaded perfectly and I wired 4x AA pack to the battery terminals making sure to observe polarity.

I then attached two DC motors to the ML and MR pins just like it said in the picture. I turned the board on, making sure the switch was set to on also.

The red light lighted up and the blue light flickered for a second. The motors did not move. I tried different motors. To check if it was a corrupt bootloader I tried to upload the hello world blink sketch. That worked perfectly.

I got my multi-meter out and tested the wires I was using...all good! Tested the battery...6.31v! That's within specs. I have the jumpers correctly inserted on the D7 - 10 pins. Here's my setup:
[![http://blog.dawnrobotics.co.uk/wp-content/uploads/2013/11/circuit_diagram.png][2]][2]

What in the world could be wrong? The code is supposed to make it turn in a rough square. I checked it over and over and it looks right. Any ideas?

  [1]: http://blog.dawnrobotics.co.uk/2013/11/getting-started-with-the-dagu-arduino-mini-driver-board/
  [2]: https://i.stack.imgur.com/Q5tGn.png

body:
This is a generic debugging advice, but maybe it can still be of help:
have you tried driving the led from the loop, to check that it doesn't get stuck for some reason?

Other thing you could do is to get the datasheet of the motor driver, find out the inputs from the ATMega and see how they look like.
At least that would allow you to bisect the problem answering the question:
"Does the ATMega generate the expected signal?"


body: Switching the selector did not help. I received a new one which worked perfectly following the steps from before. Apparently the issue was hardware related, possibly a cold solder joint preventing the motor driver section to work while still letting everything else continue normally.


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

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


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


message:
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](https://github.com/z3t0/Arduino-IRremote)

The question is, what could explain this behavior?
A few possibilities I had in mind:

 1. IR frequency. Could it be that the detection circuit worked with the default settings but transmitting wouldn't?
 2. IR wavelength. Any chance the A/C side doesn't detect my IR pulses at all?
 3. 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.

body:
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);
              }

     }