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

title: How do you use SPI on an Arduino?

Answers: 2

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


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

title: Measure Vcc using 1.1V bandgap

Answers: 2

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.


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

title: Dagu Mini Driver Board Issues

Answers: 2

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.


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

title: Trying to get my MPU chip to work

Answers: 2

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


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

title: A/C doesn't detect IR codes sent from Arduino

Answers: 1

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

     }


body:
I have an Arduino Uno and I am using arduino 1.0.5 IDE. I followed he procedures for bootloading an atmega328P-PU on a breadboard using an Arduino Uno from the link:

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

I uploaded the ArduinoISP sketch first, made the connections(using the External Oscillator) and then wired it up. Then, I selected the programmer as Arduino as ISP, selected the board as Arduino duemilanove w/ Atmega328P . Then I selected the correct serial port and clicked Burn Bootloader. I got the following errors:

    avrdude.exe: stk500_program_enable(): protocol error, expect=0x14,
    resp=0x50avrdude.exe: initialization failed, rc=-1 Double check
    connections and try again, or use -F to override this
    check.avrdude.exe: stk500_disable(): protocol error, expect=0x14,
    resp=0x51

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

title: Standalone Arduino

Answers: 2

body:
See [How to make an Arduino-compatible minimal board](http://www.gammon.com.au/breadboard).

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

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

I think my method of [using a Uno as a programmer](http://www.gammon.com.au/bootloader) is easier, frankly.

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


body:
I have a rotary encoder KY-040 connected to a Digispark like this:

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

CLK go to p0 and and DT go to p2, SW is disconnected for now (it's just a button).

I did everything like the instructions here: http://henrysbench.capnfatz.com/henrys-bench/keyes-ky-040-arduino-rotary-encoder-user-manual/

    #include <DigiKeyboard.h>

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

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

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

       }
       pinALast = aVal;
     }

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

    DigiKeyboard.write("1");
    DigiKeyboard.println("1");
    DigiKeyboard.sendKeyStroke(KEY_V);

All of them didn't do anything when rotating the knob...

Any ideas?
Maybe the 10K resistors are too much?

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

title: Reading from a KY-040 rotary encoder with Digispark

Answers: 2

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

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

See [my page about rotary encoders](http://www.gammon.com.au/forum/?id=11130) for more ideas.

---

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

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

---

> Maybe the 10K resistors are too much?

No, that looks fine.

body:
Shown below is a KY-040 test program that in my tests doesn't lose any counts and is more accurate than some other software; it picks up the counts between detents as well as those at detents.  You may be able to adapt it to your DigiKeyboard ATtiny system.

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

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

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

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

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

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

      attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
      attachInterrupt(1, pinChangeISR, CHANGE);

with

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

and add the following `#include` near the beginning:

    #include <EnableInterrupt.h>

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


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

    int prPin = A0;

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

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

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

title: RGBs, photoresistors, and delays

Answers: 1

body:
Instead of the two delays of one second, have the program check if the current time is an even or odd number of seconds.

    int prPin = A0;

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

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


body:
First a little background on me and my project. Most of my programming experience is with PHP and javascript. I have just recently started looking at C and C++ for this Arduino project. My project is a weather station that feeds its data to a web based database in real time. I will be writing the code for a web site that will access this data base and present the data in realtime. I am currently working on the temperature section of my weather station. It is an RTD coupled to a constant current circuit and feeds a varying voltage to analog pin 5 on my Arduino Uno. My problem is with the code. I have a working code but I decided to make it object oriented so that I could reuse it in other projects. Here is the code that works.

    const unsigned int RTD_PIN = A5;
    const float MVOLTS_CTS = 4.882813;
    const float OHMS_DEGREE = 0.3851;
    const unsigned int SAMPLES = 10;
    const float MILLI_AMPS = 19.125;
    unsigned long currentMillis;
    unsigned long oldMillis = 0;
    unsigned long timeBetweenSamples = 1000; // milliseconds between samples
    int measurement[SAMPLES];
    int read_index = 0;
    int total = 0;
    int average_cts = 0;
    boolean initialized = false;
    float degC = 0;
    float degF = 0;

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

    void loop() {

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

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

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

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

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

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

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

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

        read_index++;
        oldMillis = currentMillis;

      }
    }

And this is the code that doesn't work.

    #include "Arduino.h"
    #include "Sensor.h"

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

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

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

      }

      int Sensor::update() {

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

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

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

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

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

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

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

       return average_cts;
         }

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

      }

It seems like the issue is with this one line of code on line 34.

    measurement[read_index] = analogRead(sensorPin);

When this line has not been remarked out the read_index only goes to 4 before it resets to 0 and it does it at the rate of program execution instead of every second like expected.

If this line is remarked out the the read_index is incremented from 0 to 9 once every second as expected.

Here is where the read_index is defined.

    #ifndef Sensor_h
    #define Sensor_h

    #include "Arduino.h"

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

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

    #endif

and this is the Arduino sketch that calls update()

    #include <Sensor.h>

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

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

    void loop() {

      rtd.update();

      Serial.println(rtd.read_index);
    }

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

title: Identical statements, different outcome

Answers: 2

body:
You have made a few fundamental errors with your class.

Firstly you have not provided a storage size (number of elements) for the `measurement` array class member variable:

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

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

Then it seems like you try to dynamically allocate the space for it in your constructor:

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

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

BUT that's *not* what you are doing.  What you are doing there is creating a *new* local variable (local to *just that one single function*) called `measurement` with an array size of `samples`.  As soon as you leave the constructor that variable is thrown away.

You haven't touched the class member variable `measurement` at all.  So, when you do:

    measurement[read_index] = analogRead(sensorPin);

you are storing the read value into an array of no size that points nowhere.  And of course that then causes a crash because you're writing to memory that you shouldn't be writing to.

If you want to be specifying the number of array elements in the constructor you need to be learning about *dynamic memory allocation* using `malloc()` and `free()` and all the pitfalls that go along with using those on a small microcontroller with very tight RAM constraints.

For an example of how it can be done you should take a look at my [Average Library](https://github.com/MajenkoLibraries/Average) which uses dynamic allocation to allocate the array memory in the constructor and free it in the destructor.

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

---

Change:

    int measurement[];

to:

    int * measurement;

and then in the constructor do:

    measurement = new int [samples];

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

---

Also, this is wrong in two ways:

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

It should be:

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

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

---

You should also have a destructor that frees the memory, ie.

    delete [] measurement;

---

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

The destructor is automatically called when an instance of the class is destroyed. This is when you do things like free memory you allocated. You don't call it directly.

An example:

    class Sensor
    {
    public:
      // constructor
      Sensor(int analogPin, int numSamplesInAverage, unsigned long mysampleRate);
      // destructor
      ~Sensor ();
      // call to update samples
      int update();

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

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

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

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

    }  // end of constructor

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

---

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

`int * measurement` creates a pointer to an int (called `measurement`). However pointers can also point to the start of an array (or indeed, to the middle of an array) of ints. So this variable will hold the start of your array of ints.

`measurement = new int [samples];` allocates the memory for this array - in this case "samples" lots of ints.

Once the memory is allocated you can treat the pointer as an array, eg.

    measurement [5] = 42;

For more detail about this see [So what is meant by the "equivalence of pointers and arrays" in C?](http://c-faq.com/aryptr/aryptrequiv.html) and also Google: `pointer vs array`.

Also Google: `new` and `delete` with reference to the C++ language.


body:
I'm trying to get [MMA8452Q](http://www.freescale.com/files/sensors/doc/data_sheet/MMA8452Q.pdf) to trigger an interrupt when motion is detected and wonder if I'm missing something very obvious here.

So I setup CTRL_REG4 to 0x0B with

    void MMA8452Q::setupISR()
    {
     writeRegister(CTRL_REG4, 0x0B);
    }

then I setup FF_MT with

    void MMA8452Q::setupFF_MT()
    {
     writeRegister(FF_MT_CFG, 0xF8);
     writeRegister(FF_MT_THS, 0x0F);
     writeRegister(FF_MT_COUNT, 0x00);
    }

and I read ISR with

    #define SRC_PULSE 2
    #define SRC_FF_MT 1

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

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

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

      Serial.print("\t");

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

      Serial.print("\t");
    }

AFAIK, that should already have FF/MT interrupt enabled. Even when I'm getting readings in `FF_MT_SRC`, I'm not picking up an interrupt in `INT_SOURCE`.

Interrupts are fired on (most) taps, but not on motion at all.

Am I missing something here?

Thanks

title: Interrupt not firing on motion

Answers: 1

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

[![interrupt enable bits][1]][1]

Rather than saying `writeRegister(CTRL_REG4, 0x0B);` in `MMA8452Q::setupISR()`, try `writeRegister(CTRL_REG4, 0xD);`.

0xB is 1011 in binary, while 0xD is 1101, which turns on INT_EN_FF_MT to enable freefall/motion interrupts.

The above should answer your question as asked.  The following expands on my earlier comment which said
>Absent other info, it looks like MMA8452Q::readISR() is not an interrupt processing routine, but instead a routine that polls an interrupt-source register to find out what source would have triggered an interrupt if correctly wired and initialized.

"Interrupt" as used in your question (and code) refers to when the MMA8452 signals (via an I1 or I2 output line) that an interrupt-worthy condition has occurred.

"Interrupt" as in the question does not refer to an interrupt from the Uno's point of view, because (per diagram) neither of I1 or I2 connects to the Uno.

If speed of response becomes important, you may wish to hook I1 or I2 to one of the Uno's Digital Pins With Interrupts, ie pin 2 or 3, as noted in the [AttachInterrupt](https://www.arduino.cc/en/Reference/AttachInterrupt) page at arduino.cc.  Then you'd replace the polling loop that now periodically reads the MMA8452's ISR (interrupt status register) to check for set bits, with an interrupt service routine which would set a flag to cause loop() to use Wire.read to get ISR data.

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


body:
I'd like to get a TCP based connection from an arduino to a node.JS server. I found an example, I've tried to run it but its throwing the errors below, would appreciate any help.

Error Messages
    Arduino: 1.6.6 Hourly Build 2015/09/24 05:43 (Windows 7), Board: "Arduino/Genuino Uno"

    WARNING: Category '' in library ArduinoJson is not valid. Setting to 'Uncategorized'
    socketio.ino: In function 'void hello(Client&, const char*)':

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

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

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

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

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

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

            ^

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

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

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

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

            ^

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

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

Arduino Code
    #include <SPI.h>
    #include <Ethernet.h>

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

    EthernetClient ethClient;
    SocketIOClient client(ethClient);

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

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

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

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

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

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

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

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

SocketIO.h

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

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

     Copyright 2014 Quentin Pigné

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

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

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

    #ifndef SocketIOClient_H
    #define SocketIOClient_H

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

    #include <ArduinoJson.h>

    #include "HashMap.h"

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

    //Max size of the HashTable
    #define HASH_SIZE 20

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

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

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

    #endif

title: Help with socketIO Example

Answers: 1

body: Make your `char *` parameters `const char *`.


body:
NOOB Question: when my Uno is connected to an external power source it will not start running the uploaded sketch. The Arduino web site says it's because the RX pin is not connected and then gets random data.

The site suggests grounding the RX pin using a resistor (granted it suggests a 10K and I used a smaller one ) or connecting it to the TX pin.

From [Why doesn't my sketch start when I power up or reset the Arduino board?][1]

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

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

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

Both failed for me.

What should I do?

  [1]: https://www.arduino.cc/en/Guide/Troubleshooting#toc19
  [2]: https://www.arduino.cc/en/Guide/Troubleshooting#toc6

title: Sketch will not start with external power source

Answers: 3

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

body:
I also had a similar problem running with an external power supply.  In my case the sketch ran but totally incorrectly .  Conected RX to ground with a 10K Ohm resistor and solved the problem.

Thanks for the info!!  Others have spent a lot more time solving this problem than I did.

body:
I will add my little drop of experience here...   So I am using a display tm1637, having CLK in 6 and DIO in 5. When connecting the Battery (12V 3s lipo 4000mA) to Vin, the arduino will freeze, even connected to the USB, will still freeze.

Short version, Moving DIO from 5 to 7 corrected the problem, now i have my device running from USB and or battery with no problem.

Long version: after 3 hours of trying different mods, including resistor to RX,TX, to GND, even removing the ch340 chip and connecting Rts and others to GND/VCC..  Nothing, so i decided to move the different devices from One nano to Other but testing after each connection. When the display was connected, the Nano will freeze while running on battery power. So... i moved DIO first to a different pin, and the device started working.  I know is a very particular case, but one more thing to try if you are like me, stock without knowing what to do.... moving some pins (maybe skipping 5?)...


body:
I bought a GPS module with GPS antenna SIM39EA online.

The manual for the GPS module is here:

http://www.vis-plus.ee/pdf/SIM39EA_Hardware_Design_V1.00.pdf

I have an Arduino board. It has 3 ground pin, one Vcc and two input/output pin.

I want to know how can I connect this module to Arduino GPS module and get GPS coordinates?

title: Connect GPS module with GPS antenna SIM39EA to Arduino Uno

Answers: 1

body:
Your data comes back via the GPS's UART port.
Use the softserial library to create a second serial port on your Arduino (means you can still use the normal serial to read the console).

Then write a program that sucks data from the GPS and squirts it out of the Arduino serial port back to your PC using printf.

I only had a quick flick through and didn't see the default serial speed, so start with 9600 and experiment.

What should come out is probably a line of comma separated values which is in NEMA format.  Google for the specification and you will be able to find out the bits of interest.

Hope that helps.


body:
Connected a generic ESP8266 to an Arduino Uno.

I can send AT commands fine and generate a normal response, but cannot upload sketches to the ESP8266. I have "Generic ESP8266 Module selected as the board. Tried everything e.g. switching Tx and Rx, connecting GPIO0 and GPIO2 to to Vcc or ground, but to no avail.

Arduino IDE spits this out -

    esptool v0.4.5 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
     setting board to ck
     setting baudrate from 115200 to 115200
     setting port from COM1 to COM3
     setting address from 0x00000000 to 0x00000000
     espcomm_upload_file
     stat C:\Users\Michael\AppData\Local\Temp\build7227402767538495982.tmp/wifi_setup.cpp.bin success
     setting serial port timeouts to 1000 ms
    opening bootloader
    resetting board
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    resetting board
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    resetting board
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2013 bytes of data
     read 0, requested 1
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    warning: espcomm_sync failed
    error: espcomm_open failed

title: Can send AT+ commands, but can't upload sketch to ESP8266 via Arduino Uno

Answers: 3

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

body:
You mention:

> connecting GPIO0 and GPIO2 to to Vcc or ground

I've had success with this sequence:

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

To do a firmware flashing, you need to hold GPIO0 to ground for the duration of the flashing process, so the sequence would be slightly different.

You can do this just prior to "build and upload" in the Arduino IDE—provided the build process doesn't take too long.  It will sometimes still fail, in which case reset the ESP8266 (RST to gnd momentarily) and restart the sequence.

I've found a little test/development harness (like this one http://www.buildcircuit.com.au/esp8266-test-board) is very handy for doing this repeatedly.

body:
You don't need an Arduino UNO to program the ESP. You just need an USB to UART adapter (CP210x or FTDI one) and the Arduino IDE. Hook the ESP rx and tx to the tx an rx of the adapter and you are ready to go.
Here is an detailed explanation [how to program ESP using arduino][1]

If you don't have an USB to UART bridge you can use the Arduino board as bridge: [check this][2]

  [1]: http://ezbitz.com/program-esp8266-using-arduino-ide/
  [2]: http://microcontrollerkits.blogspot.ro/2015/05/esp8266-firmware-update-with-arduino.html


body: I am designing a PCB in which I am using the MCU used in **`Arduino UNO`** which is **`Atmega328P`** and some other components as per my project requirements. I have almost designed the circuit but I am confused with the USB programming part. I want my MCU to be programmed using **`USB B Type`** just like we do it in **`Arduino UNO`**. My friend suggests me to purchase an **`Arduino UNO`** device and program that MCU and then put it in my circuit. But I don't want to do it like this. I have found the [**schematic design**](https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf) but its very confusing. Can anyone help me out with this.?

title: How to make an Arduino USB programming circuit?

Answers: 3

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

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

  [1]: https://www.sparkfun.com/products/9718

body: If you wanted a more permanent option on the board, you could also add a USB to FTDI chip like this: http://www.mouser.com/Search/m_ProductDetail.aspx?FTDI/FT232RL-REEL/&qs=D1/PMqvA103RC6OU6bKtoA==&gclid=CNmDjr7dvssCFYZefgod9jgPeQ


body: Im new here. Anyone that could give a code or sample that would generate I wanted to use a frequency in range of 35k-43kHz. Please help me.

title: Arduino coding of producing frequency

Answers: 3

body:
This is meant to be a comment, but I can't put (pseudo) code in a comment.

A 40 kHz square wave? Simple:

    for(;;){
       wait ( 1 / 2 * 40.000 );
       make pin high;
       wait ( 1 / 2 * 40.000 );
       make pin low;
    }

body:
use the 'tone' function:
[arduino tone function][1]

  [1]: https://www.arduino.cc/en/Reference/Tone
example:

    //tone(pinNumber, FrequencyInHertz);
    tone(6, 35000); //generate a 35kHz tone on pin 6
    delay(10);
    tone(6, 43000); //generate a 43kHz tone on pin 6

body:
The code below generates 38 kHz and modulates its duty cycle.

    // Example of modulating a 38 kHz frequency duty cycle by reading a potentiometer
    // Author: Nick Gammon
    // Date: 24 September 2012

    const byte POTENTIOMETER = A0;
    const byte LED = 10;  // Timer 1 "B" output: OC1B

    // Clock frequency divided by 38 kHz frequency desired
    const long timer1_OCR1A_Setting = F_CPU / 38000L;

    void setup()
     {
      pinMode (LED, OUTPUT);

      // set up Timer 1 - gives us 38.005 kHz
      // Fast PWM top at OCR1A
      TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
      TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
      OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
      }  // end of setup

    void loop()
      {
      // alter Timer 1 duty cycle in accordance with pot reading
      OCR1B = (((long) (analogRead (POTENTIOMETER) + 1) * timer1_OCR1A_Setting) / 1024L) - 1;

      // do other stuff here
      }