body:
Goal: I would like to be able to transfer some information to an Arduino Uno board via an NFC shield/antenna. The situation requires that the NFC tag may potentially hit anywhere within a circular area about a 12 inches in diameter.

Is it possible to increase the size of an NFC antenna? Possibly creating a loop antenna whereby the tag could be read from anywhere inside the loop.

I was thinking maybe if that isn't possible, it might be better to create an antenna array spanning the size of the area needed. Though I may have problems with overlap or double reads this way.

Has anyone attempted this before?

Note: I am not worried about increasing the z distance from the plane, just the x/y range. In fact, I still want the z distance to be very short as to not interfere with other antennas nearby.

title: Larger NFC antenna?

Answers: 1

body:
In general the size and geometry of the antenna is directly related to the carrier frequency. The antenna is tuned to the output signal of the transmitter/receiver. If you change an optimized antenna, it is no longer optimized and its performance will drop. So you can't keep extending an antenna, trying to improve its range.

The important question to be asked is if the existing antenna is already optimally sized for the transmitter/receiver. With these small things transmitter/receiver and antenna are usually closely matched. Even if the antenna is smaller than expected by math, the transmitter/receiver connected to it may be compensated for that.

With a receiver or a **low*** power transmitter, there is no harm in testing another antenna, but you'll probably won't improve performance much.

---

*) Notice that a high power transmitter can blow its output stage when connected to an unmatched load/antenna, but that is unlikely with NFC.


body:
This may be a better question for [the Physics StackExchange][1] so tell me if I should move the question.

I have a pretty simple script that I'm using to control the RPM of my stepper motor:

    void loop(){
      digitalWrite(PIN, HIGH);
      delayMicroseconds(wait);
      digitalWrite(PIN, LOW);
    }

as you can see it's just producing a pretty standard pulse, I have my Arduino connected to a driver that manages the motor. The `wait` variable comes from a second order equation I derived from measuring the RPM with a Tachometer and tweaking the value.

    // From data RPM = 31729/x + 17.327 thus x = 31729/(RPM-17.527)
    wait = M/(RPM-C);

It works pretty well, I get readings consistently within only 1 - 2 rotations off. But the slope and intercept seem completely arbitrary to me. Is there a chance it has to do with the clock speed of the Arduino? I'm using an Uno and from playing around with the numbers I can't seem to find a relationship. From what I can tell, the driver looks hardwired so I don't think it has much to do with the equation.

Any idea what these values, the slope/intercept mean?

Equation: `RPM=31729/wait + 17.327` M:`31729` and C:`17.327`

  [1]: https://physics.stackexchange.com/

title: Understanding the relationship of Pulse and Stepper RPM

Answers: 2

body:
The real answer to this question requires understanding exactly what hardware you have. The formula, assuming one step per pulse, is that the delay should be:

wait = (MicroSecondsPerMinute)*(1/RPM)*(1/PulsesPerRevolution) - overhead

where overhead is the extra time it takes to run digitalWrite twice and loop. It is small, but if it were zero your code would not work because the amount of time your signal is LOW would be zero as well.

Your numbers suggest Pulses Per Revolution is around 1891. This will be the product of how many steps per revolution the motor is wired for and how many bits of microstepping the driver is doing. A 225 step motor with 3 bit microstepping (8 fractional steps per "true" step) would have PPR of 1800 for example. Your number does not precisely match any common setups, but is exactly in the range expected, with 1600 and 2000 being normal for small steppers.

Because of the "overhead" term, RPM as a function of wait should not be linear. Your constant value should be a function of RPM; in fact, when RPM gets much larger than the number of Microseconds per minute it should converge to being equal to RPM. In this case your RPM is so low that approximating it to 17 is probably valid and all error too small to notice. It could be causing some of the oddness of your PPR value though.

body:
one pulse equals one step of stepper and rpm is how many rotation stepper makes in one minute.
Try to understand the stepper.h library and Accelstepper library


body:
I want to make a drone project, and to that I will use arduino as the platform. My plane is to use a Play Station controller to control the Drone in the air. In addition to that I want to connect a GPS-module. My question goes, is it possible to transmit the longitude and latitude from the GPS via the RF 433MHz to the receiver? When received the longitude and latitude how can I transmit them further to the Smartphone and display the data on google maps? I suggest it could be possible through the Xbee, but I am not sure.

I would like if someone can confirm my idea, if not bring me a better way to do that.

In the image below, you can see the diagram of my design.

![Image][1]

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

title: Is it possible to transmit Longitude and Latitude via RF433MHz?

Answers: 2

body: If you are using Xbee modules in your project, why add 433MHz RF, just for the sole purpose of transmitting the location?  With the 433Mhz, you will have to implement error-correction yourself.

body:
Your design suffers several redundancies that should be fixed. First of all, you have an Xbee (only one, not a pair) *and* a a 433 MHz transmitter/receiver combo. **Why not just add another Xbee to the drone and remove the RF combo?** That would save a little battery life for the receiver end, and a lot of your time. You'll also get two way communication with error checking. Although an Xbee would increase your project size a *little*, if you manually wired the Xbee instead of a shield (3.3V), it would save a lot of space.

As some people point out, Bluetooth is a viable option that's fairly small and low cost. However, it would suffer shorter ranges and it would need a special configuration on the host side for a BT stack.


body:
I'm having some conflicts between the core `HardwareSerial.cpp` and an external DMX library.

For DMX I'm using the [Four Universes DMX 512 Library](http://www.deskontrol.net/blog/arduino-four-universes-dmx-512-library/). Using the library standalone, it all works perfectly. But when combining it with other libraries, I'm getting the error:

    core.a(HardwareSerial.cpp.o): In function '__vector_36':
    C:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino/HardwareSerial.cpp:147: multiple definition of '__vector_36'
    Dmx\lib_dmx.cpp.o:C:\Program Files (x86)\Arduino\libraries\Dmx/lib_dmx.cpp:206: first defined here

The DMX library uses the UART hardware to generate the DMX signals. It supports four universes on the Arduino Mega since that has four UART hardware parts. Now, I'd like to only use the second hardware part, so the UART1. In the DMX library this is easily adjusted in the .h-file, by commenting out the non-used serial ports.

The line from `lib_dmx.cpp` that is conflicting is this line:

    #if defined(USE_UART1)
    ISR (SIG_USART1_RECV)
    {
      ArduinoDmx1.Process_ISR_RX(1);
    }
    #endif

The line from `hardwareSerial.cpp` that is conflicting is in the ISR here:

    #if defined(USART1_RX_vect)
      void serialEvent1() __attribute__((weak));
      void serialEvent1() {}
      #define serialEvent1_implemented
      ISR(USART1_RX_vect)
      {
        if (bit_is_clear(UCSR1A, UPE1)) {
          unsigned char c = UDR1;
          store_char(c, &rx_buffer1);
        } else {
          unsigned char c = UDR1;
        };
      }
    #endif

I have been having issues with this for a very long time and don't have a solution at hand yet. It's also a but unclear to me how the interrupts on Arduinos are arranged. I've also included the .ino I'm using currently. I'm also using another Ethernet Library than the default, one that includes multicast UDP (found [here][1]).

**lib_dmx.h**

    > /***************************************************************************
    > *
    > * Title          : Arduino DMX512 library. 4 input/output universes.
    > * Version        : v 0.3 beta
    > * Last updated   : 07.07.2012
    > * Target         : Arduino mega 2560, Arduino mega 1280, Arduino nano (1 universe)
    > * Author         : Toni Merino - merino.toni at gmail.com
    > * Web            : www.deskontrol.net/blog
    > *
    > * Based on ATmega8515 Dmx library written by Hendrik Hoelscher, www.hoelscher-hi.de
    >
    > ;***************************************************************************/
    > #ifndef __INC_DMX_H
    > #define __INC_DMX_H
    >
    > #include <avr/io.h>
    > #include <stdint.h>
    > #include <avr/interrupt.h>
    > #include <util/delay.h>
    > #if ARDUINO >= 100   #include "Arduino.h"
    > #else    #include "WProgram.h"
    > #endif
    >
    > //#define        USE_INTERBYTE_DELAY     // rare cases of equipment
    > non full DMX-512 compliant, need this
    >
    > // *** comment UARTs not used *** //#define        USE_UART0
    > #define        USE_UART1 //#define        USE_UART2 //#define        USE_UART3
    >
    > // New DMX modes *** EXPERIMENTAL ***
    > #define        DMX512            (0)    // DMX-512 (250 kbaud - 512 channels) Standard USITT DMX-512
    > #define        DMX1024           (1)    // DMX-1024 (500 kbaud - 1024 channels) Completely non standard - TESTED ok
    > #define        DMX2048           (2)    // DMX-2048 (1000 kbaud - 2048 channels) called by manufacturers DMX1000K, DMX 4x or DMX 1M ???
    >
    > // DMX-512  (250 kbaud - 512 channels) Standard USITT DMX-512
    > #define        IBG_512           (10)                      // interbyte gap [us]
    > #define        DMX_512           ((F_CPU/(250000*8))-1)    // 250 kbaud
    > #define        BREAK_512         ( F_CPU/(100000*8))       // 90.9 kbaud
    >
    > // DMX-1024 (500 kbaud - 1024 channels) Completely non standard
    > #define        IBG_1024          (5)                       // interbyte gap [us]
    > #define        DMX_1024          ((F_CPU/(500000*8))-1)    // 500 kbaud
    > #define        BREAK_1024        ( F_CPU/(200000*8))       // 181.8 kbaud
    >
    > // DMX-2048 (1000 kbaud - 2048 channels) Non standard, but used by
    > manufacturers as DMX1000K or DMX-4x or DMX 1M ???
    > #define        IBG_2048          (2)                       // interbyte gap [us] + nop's to reach 2.5 uS
    > #define        DMX_2048          ((F_CPU/(1000000*8))-1)   // 1000 kbaud
    > #define        BREAK_2048        ( F_CPU/(400000*8))       // 363.6 kbaud
    >
    > // Inline assembly: do nothing for one clock cycle.
    > #define        nop()             __asm__ __volatile__("nop")
    >
    > #ifdef __cplusplus extern "C" {
    > #endif   #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    >     #if defined(USE_UART0)
    >       void SIG_USART0_RECV  (void) __attribute__((__always_inline__));
    >       void SIG_USART0_TRANS (void) __attribute__((__always_inline__));
    >     #endif
    >     #if defined(USE_UART1)
    >       void SIG_USART1_RECV  (void) __attribute__((__always_inline__));
    >       void SIG_USART1_TRANS (void) __attribute__((__always_inline__));
    >     #endif
    >     #if defined(USE_UART2)
    >       void SIG_USART2_RECV  (void) __attribute__((__always_inline__));
    >       void SIG_USART2_TRANS (void) __attribute__((__always_inline__));
    >     #endif
    >     #if defined(USE_UART3)
    >       void SIG_USART3_RECV  (void) __attribute__((__always_inline__));
    >       void SIG_USART3_TRANS (void) __attribute__((__always_inline__));
    >     #endif   #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
    >     #if defined(USE_UART0)
    >       void USART_RX_vect    (void) __attribute__((__always_inline__));
    >       void USART_TX_vect    (void) __attribute__((__always_inline__));
    >     #endif   #endif
    > #ifdef __cplusplus };
    > #endif
    >
    > class CArduinoDmx  {    #if defined(__AVR_ATmega1280__) ||
    > defined(__AVR_ATmega2560__)
    >     #if defined(USE_UART0)
    >       friend void SIG_USART0_RECV  (void);
    >       friend void SIG_USART0_TRANS (void);
    >     #endif
    >     #if defined(USE_UART1)
    >       friend void SIG_USART1_RECV  (void);
    >       friend void SIG_USART1_TRANS (void);
    >     #endif
    >     #if defined(USE_UART2)
    >       friend void SIG_USART2_RECV  (void);
    >       friend void SIG_USART2_TRANS (void);
    >     #endif
    >     #if defined(USE_UART3)
    >       friend void SIG_USART3_RECV  (void);
    >       friend void SIG_USART3_TRANS (void);
    >     #endif   #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
    >     #if defined(USE_UART0)
    >       friend void USART_RX_vect    (void);
    >       friend void USART_TX_vect    (void);
    >     #endif   #endif    public:    enum {IDLE, BREAK, STARTB, STARTADR};     // RX DMX states    enum {TXBREAK, TXSTARTB, TXDATA};
    > // TX DMX states
    >       volatile uint8_t    *RxBuffer;            // array of RX DMX values    volatile uint8_t    *TxBuffer;            // array of TX DMX
    > values
    >
    > private:    uint8_t     gRxState;    uint8_t    *gRxPnt;    uint8_t
    > IndicatorCount;    uint8_t     USARTstate;      uint8_t     RxByte;
    > uint8_t     RxState;    uint8_t     mUART;    uint8_t     gTxState;
    > uint16_t    RxCount;    uint16_t    gCurTxCh;      uint16_t
    > rx_channels;                  // rx channels number    uint16_t
    > tx_channels;                  // tx channels number    uint16_t
    > rx_address;                   // rx start address    uint16_t
    > tx_address;                   // tx start address    int8_t
    > rx_led;                       // rx indicator led pin    int8_t
    > tx_led;                       // tx indicator led pin    int8_t
    > control_pin;                  // max485 input/output selection pin
    > uint8_t     dmx_mode;                     // Standard USITT DMX512 =
    > 0, non standard DMX1024 = 1, non standard DMX2048 (DMX1000K) = 2
    > uint8_t     speed_dmx;    uint8_t     speed_break;    uint16_t
    > CurTxCh;    uint8_t     TxState;    uint8_t    *RxPnt;
    >
    > #if defined(USE_INTERBYTE_DELAY)       void        delay_gap          ();
    > #endif
    >
    > public:    void        stop_dmx           ();    void        set_speed
    > (uint8_t mode);    void        set_control_pin    (int8_t  pin)
    > { control_pin     = pin;      }    void        init_rx
    > (uint8_t mode);  // Standard USITT DMX512 = 0, non standard DMX1024 =
    > 1, non standard DMX2048 (DMX1000K) = 2    void        set_rx_address
    > (uint16_t address)   { rx_address      = address;  }    void
    > set_rx_channels    (uint16_t channels)  { rx_channels     = channels;
    > }    void        init_tx            (uint8_t mode);  // Standard USITT
    > DMX512 = 0, non standard DMX1024 = 1, non standard DMX2048 (DMX1000K)
    > = 2    void        set_tx_address     (uint16_t address)   { tx_address      = address;  }    void        set_tx_channels
    > (uint16_t channels)  { tx_channels     = channels; }
    >
    >    void        attachTXInterrupt  (void (*isr)(uint8_t uart))      {
    > TXisrCallback   = isr; }   // register the user TX callback    void
    > attachRXInterrupt  (void (*isr)(uint8_t uart))      { RXisrCallback
    > = isr; }   // register the user RX callback
    >        //void   Process_ISR_RX(uint8_t rx_isr_number);
    >
    >    void        (*TXisrCallback)   (uint8_t uart);    void
    > (*RXisrCallback)   (uint8_t uart);
    >
    >    inline void Process_ISR_RX     (uint8_t  rx_isr_number);    inline
    > void Process_ISR_TX     (uint8_t  tx_isr_number);    public:
    > CArduinoDmx                    (uint8_t uart)       { rx_address
    > = 1;
    >                                                          rx_channels     = 8;
    >                                                          tx_address      = 1;
    >                                                          tx_channels     = 8;
    >                                                          mUART           = uart; }   };
    >
    > #if defined(USE_UART0)   extern CArduinoDmx ArduinoDmx0;
    > #endif
    > #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)   #if defined(USE_UART1)
    >     extern CArduinoDmx ArduinoDmx1;   #endif   #if defined(USE_UART2)
    >     extern CArduinoDmx ArduinoDmx2;   #endif   #if defined(USE_UART3)
    >     extern CArduinoDmx ArduinoDmx3;   #endif
    > #endif
    >
    > #endif

**lib_dmx.cpp**

    /***************************************************************************
    *
    * Title          : Arduino DMX512 library. 4 input/output universes.
    * Version        : v 0.3 beta
    * Last updated   : 07.07.2012
    * Target         : Arduino mega 2560, Arduino mega 1280, Arduino nano (1 universe)
    * Author         : Toni Merino - merino.toni at gmail.com
    * Web            : www.deskontrol.net/blog
    *
    * Based on ATmega8515 Dmx library written by Hendrik Hoelscher, www.hoelscher-hi.de

    ;***************************************************************************/
    #include "lib_dmx.h"
    #include <SPI.h>

    #if defined(USE_UART0)
      CArduinoDmx ArduinoDmx0(0);
    #endif
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      #if defined(USE_UART1)
        CArduinoDmx ArduinoDmx1(1);
      #endif
      #if defined(USE_UART2)
        CArduinoDmx ArduinoDmx2(2);
      #endif
      #if defined(USE_UART3)
        CArduinoDmx ArduinoDmx3(3);
      #endif
    #endif

    // *************** DMX Transmision Initialisation ****************
    void CArduinoDmx::init_tx(uint8_t mode)
    {
      cli();          //disable interrupts
      stop_dmx();                         //stop uart
      dmx_mode = mode;
      set_speed(dmx_mode);

      if(control_pin != -1)
      {
        pinMode(control_pin,OUTPUT);        // max485 I/O control
        digitalWrite(control_pin, HIGH);    // set 485 as output
      }

      if(mUART == 0)
      {
        pinMode(1, OUTPUT);
        UBRR0H   = 0;
        UBRR0L   = speed_dmx;
        UCSR0A  |= (1<<U2X0);
        UCSR0C  |= (3<<UCSZ00)|(1<<USBS0);
        UCSR0B  |= (1<<TXEN0) |(1<<TXCIE0);
        UDR0     = 0;                 //start USART 0
      }
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      else if(mUART == 1)
      {
        pinMode(18, OUTPUT);
        UBRR1H   = 0;
        UBRR1L   = speed_dmx;
        UCSR1A  |= (1<<U2X1);
        UCSR1C  |= (3<<UCSZ10)|(1<<USBS1);
        UCSR1B  |= (1<<TXEN1) |(1<<TXCIE1);
        UDR1     = 0;                 //start USART 1
      }
      else if(mUART == 2)
      {
        pinMode(16, OUTPUT);
        UBRR2H   = 0;
        UBRR2L   = speed_dmx;
        UCSR2A  |= (1<<U2X2);
        UCSR2C  |= (3<<UCSZ20)|(1<<USBS2);
        UCSR2B  |= (1<<TXEN2) |(1<<TXCIE2);
        UDR2     = 0;                 //start USART 2
      }
      else if(mUART == 3)
      {
        pinMode(14, OUTPUT);
        UBRR3H   = 0;
        UBRR3L   = speed_dmx;
        UCSR3A  |= (1<<U2X3);
        UCSR3C  |= (3<<UCSZ30)|(1<<USBS3);
        UCSR3B  |= (1<<TXEN3) |(1<<TXCIE3);
        UDR3     = 0;                 //start USART 3
      }
    #endif

      gTxState = BREAK;                         // start with break
      TxBuffer = (uint8_t*)malloc(tx_channels);     // allocate mem for buffer
      memset((uint8_t*)TxBuffer, 0, tx_channels);   // fill buffer with 0's
      sei();          //enable interrupts
    }

    // ************************ DMX Stop ***************************
    void CArduinoDmx::stop_dmx()
    {
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      if(mUART == 0)
      {
        UCSR0B &= ~((1<<RXCIE0) | (1<<TXCIE0) | (1<<RXEN0) | (1<<TXEN0));
      }
      else if(mUART == 1)
      {
        UCSR1B &= ~((1<<RXCIE1) | (1<<TXCIE1) | (1<<RXEN1) | (1<<TXEN1));
      }
      else if(mUART == 2)
      {
        UCSR2B &= ~((1<<RXCIE2) | (1<<TXCIE2) | (1<<RXEN2) | (1<<TXEN2));
      }
      else if(mUART == 3)
      {
        UCSR3B &= ~((1<<RXCIE3) | (1<<TXCIE3) | (1<<RXEN3) | (1<<TXEN3));
      }
    #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
      if(mUART == 0)
      {
        UCSR0B &= ~((1<<RXCIE0) | (1<<TXCIE0) | (1<<RXEN0) | (1<<TXEN0));
      }
    #endif
    }

    // *************** DMX Reception Initialisation ****************
    void CArduinoDmx::init_rx(uint8_t mode)
    {
      cli();          //disable interrupts
      stop_dmx();
      dmx_mode = mode;
      set_speed(dmx_mode);

      if(control_pin != -1)
      {
        pinMode(control_pin,OUTPUT);        //max485 I/O control
        digitalWrite(control_pin, LOW);     //set 485 as input
      }

      if(mUART == 0)
      {
        pinMode(0, INPUT);
        UBRR0H   = 0;
        UBRR0L   = speed_dmx;
        UCSR0A  |= (1<<U2X0);
        UCSR0C  |= (3<<UCSZ00)|(1<<USBS0);
        UCSR0B  |= (1<<RXEN0) |(1<<RXCIE0);
      }
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      else if(mUART == 1)
      {
        pinMode(19, INPUT);
        UBRR1H   = 0;
        UBRR1L   = speed_dmx;
        UCSR1A  |= (1<<U2X1);
        UCSR1C  |= (3<<UCSZ10)|(1<<USBS1);
        UCSR1B  |= (1<<RXEN1) |(1<<RXCIE1);
      }
      else if(mUART == 2)
      {
        pinMode(17, INPUT);
        UBRR2H   = 0;
        UBRR2L   = speed_dmx;
        UCSR2A  |= (1<<U2X2);
        UCSR2C  |= (3<<UCSZ20)|(1<<USBS2);
        UCSR2B  |= (1<<RXEN2) |(1<<RXCIE2);
      }
      else if(mUART == 3)
      {
        pinMode(15, INPUT);
        UBRR3H   = 0;
        UBRR3L   = speed_dmx;
        UCSR3A  |= (1<<U2X3);
        UCSR3C  |= (3<<UCSZ30)|(1<<USBS3);
        UCSR3B  |= (1<<RXEN3) |(1<<RXCIE3);
      }
    #endif

      gRxState = IDLE;
      RxBuffer = (uint8_t*)malloc(rx_channels);   // allocate mem for buffer
      memset((uint8_t*)RxBuffer, 0, rx_channels); // fill buffer with 0's
      sei();          //enable interrupts
    }

    // *************** DMX Reception ISR ****************
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      #if defined(USE_UART0)
        ISR (SIG_USART0_RECV)
        {
          ArduinoDmx0.Process_ISR_RX(0);
        }
      #endif
      #if defined(USE_UART1)
        ISR (SIG_USART1_RECV)
        {
          ArduinoDmx1.Process_ISR_RX(1);
        }
      #endif
      #if defined(USE_UART2)
        ISR (SIG_USART2_RECV)
        {
          ArduinoDmx2.Process_ISR_RX(2);
        }
      #endif
      #if defined(USE_UART3)
        ISR (SIG_USART3_RECV)
        {
          ArduinoDmx3.Process_ISR_RX(3);
        }
      #endif
    #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
      #if defined(USE_UART0)
        ISR (USART_RX_vect)
        {
      ArduinoDmx0.Process_ISR_RX(0);
     }
      #endif
    #endif

    void CArduinoDmx::Process_ISR_RX(uint8_t rx_isr_number)
    {
      if(rx_isr_number == 0)
      {
        USARTstate = UCSR0A;            //get state
        RxByte     = UDR0;                //get data
        RxState    = gRxState;       //just get once from SRAM!!!
        if (USARTstate &(1<<FE0))         //check for break
        {
          UCSR0A  &= ~(1<<FE0);        //reset flag
          RxCount  = rx_address;      //reset frame counter
          gRxState = BREAK;
        }
      }
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)

      else if(rx_isr_number == 1)
      {
        USARTstate = UCSR1A;            //get state
        RxByte     = UDR1;                //get data
        RxState    = gRxState;       //just get once from SRAM!!!
        if (USARTstate &(1<<FE1))         //check for break
        {
          UCSR1A  &= ~(1<<FE1);        //reset flag
          RxCount  = rx_address;      //reset frame counter
          gRxState = BREAK;
        }
      }
      else if(rx_isr_number == 2)
      {
        USARTstate = UCSR2A;            //get state
        RxByte     = UDR2;                //get data
        RxState    = gRxState;       //just get once from SRAM!!!
        if (USARTstate &(1<<FE2))         //check for break
        {
          UCSR2A  &= ~(1<<FE2);        //reset flag
          RxCount  = rx_address;      //reset frame counter
          gRxState = BREAK;
        }
      }
      else if(rx_isr_number == 3)
      {
        USARTstate = UCSR3A;            //get state
        RxByte     = UDR3;                //get data
        RxState    = gRxState;       //just get once from SRAM!!!
        if (USARTstate &(1<<FE3))         //check for break
        {
          UCSR3A  &= ~(1<<FE3);        //reset flag
          RxCount  = rx_address;      //reset frame counter
          gRxState = BREAK;
        }
      }
    #endif

      if (RxState == BREAK)
      {
        if (RxByte == 0)
        {
          gRxState = STARTB;        //normal start code detected
          gRxPnt   = ((uint8_t*)RxBuffer + 1);
        }
        else
          gRxState = IDLE;
      }
      else if (RxState == STARTB)
      {
        if (--RxCount == 0)          //start address reached?
        {
          gRxState   = STARTADR;
          RxBuffer[0]= RxByte;
        }
      }
      else if (RxState == STARTADR)
      {
        RxPnt  = gRxPnt;
        *RxPnt = RxByte;
        if (++RxPnt >= (RxBuffer + rx_channels))  //all ch received?
        {
          gRxState= IDLE;
          if (*RXisrCallback) RXisrCallback(mUART);   // fire callback for read data
        }
        else
        {
          gRxPnt = RxPnt;
        }
      }
    }

    // *************** DMX Transmision ISR ****************
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      #if defined(USE_UART0)
        ISR(SIG_USART0_TRANS)
        {
          ArduinoDmx0.Process_ISR_TX(0);
        }
      #endif
      #if defined(USE_UART1)
        ISR(SIG_USART1_TRANS)
        {
          ArduinoDmx1.Process_ISR_TX(1);
        }
      #endif
      #if defined(USE_UART2)
        ISR(SIG_USART2_TRANS)
        {
          ArduinoDmx2.Process_ISR_TX(2);
        }
      #endif
      #if defined(USE_UART3)
        ISR(SIG_USART3_TRANS)
        {
          ArduinoDmx3.Process_ISR_TX(3);
        }
      #endif
    #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
      #if defined(USE_UART0)
        ISR(USART_TX_vect)
        {
          ArduinoDmx0.Process_ISR_TX(0);
        }
      #endif
    #endif

    void CArduinoDmx::Process_ISR_TX(uint8_t tx_isr_number)
    {
      TxState = gTxState;

      if(tx_isr_number == 0)
      {
        if (TxState == TXBREAK) //BREAK + MAB
        {
          UBRR0H   = 0;
          UBRR0L   = speed_break;
          UDR0     = 0;            //send break
          gTxState = TXSTARTB;
        }
        else if (TxState == TXSTARTB)
        {
          UBRR0H   = 0;
          UBRR0L   = speed_dmx;
          UDR0     = 0;            //send start byte
          gTxState = TXDATA;
          gCurTxCh = 0;
        }
        else
        {
          #if defined(USE_INTERBYTE_DELAY)
            delay_gap();
          #endif
          CurTxCh = gCurTxCh;
          UDR0 = TxBuffer[CurTxCh++];    //send data
          if (CurTxCh == tx_channels)
          {
            if (*TXisrCallback) TXisrCallback(0); // fire callback for update data
            gTxState = TXBREAK;   // new break if all ch sent
          }
          else
          {
            gCurTxCh = CurTxCh;
          }
        }
      }
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)

      else if(tx_isr_number == 1)
      {
        if (TxState == TXBREAK)
        {
          UBRR1H   = 0;
          UBRR1L   = speed_break;
          UDR1     = 0;            //send break
          gTxState = TXSTARTB;
        }
        else if (TxState == TXSTARTB)
        {
          UBRR1H   = 0;
          UBRR1L   = speed_dmx;
          UDR1     = 0;            //send start byte
          gTxState = TXDATA;
          gCurTxCh = 0;
        }
        else
        {
          #if defined(USE_INTERBYTE_DELAY)
            delay_gap();
          #endif
          CurTxCh = gCurTxCh;
          UDR1 = TxBuffer[CurTxCh++];    //send data
          if (CurTxCh == tx_channels)
          {
            if (*TXisrCallback) TXisrCallback(1); // fire callback for update data
            gTxState = TXBREAK;   // new break if all ch sent
          }
          else
          {
            gCurTxCh = CurTxCh;
          }
        }
      }
      else if(tx_isr_number == 2)
      {
        if (TxState == TXBREAK)
        {
          UBRR2H   = 0;
          UBRR2L   = speed_break;
          UDR2     = 0;            //send break
          gTxState = TXSTARTB;
        }
        else if (TxState == TXSTARTB)
        {
          UBRR2H   = 0;
          UBRR2L   = speed_dmx;
          UDR2     = 0;            //send start byte
          gTxState = TXDATA;
          gCurTxCh = 0;
        }
        else
        {
          #if defined(USE_INTERBYTE_DELAY)
            delay_gap();
          #endif
          CurTxCh = gCurTxCh;
          UDR2 = TxBuffer[CurTxCh++];    //send data
          if (CurTxCh == tx_channels)
          {
            if (*TXisrCallback) TXisrCallback(2); // fire callback for update data
            gTxState = TXBREAK;   // new break if all ch sent
          }
          else
          {
            gCurTxCh = CurTxCh;
          }
        }
      }
      else if(tx_isr_number == 3)
      {
        if (TxState == TXBREAK)
        {
          UBRR3H   = 0;
          UBRR3L   = speed_break;
          UDR3     = 0;            //send break
          gTxState = TXSTARTB;
        }
        else if (TxState == TXSTARTB)
        {
          UBRR3H   = 0;
          UBRR3L   = speed_dmx;
          UDR3     = 0;            //send start byte
          gTxState = TXDATA;
          gCurTxCh = 0;
        }
        else
        {
          #if defined(USE_INTERBYTE_DELAY)
            delay_gap();
          #endif
          CurTxCh = gCurTxCh;
          UDR3 = TxBuffer[CurTxCh++];    //send data
          if (CurTxCh == tx_channels)
          {
            if (*TXisrCallback) TXisrCallback(3); // fire callback for update data
            gTxState = TXBREAK;   // new break if all ch sent
          }
          else
          {
            gCurTxCh = CurTxCh;
          }
        }
      }
    #endif
    }

    void CArduinoDmx::set_speed(uint8_t mode)
    {
      if(mode == 0)
      {
        speed_dmx   = DMX_512;    // DMX-512  (250 kbaud - 512 channels) Standard USITT DMX-512
        speed_break = BREAK_512;
      }
      else if(mode == 1)
      {
        speed_dmx   = DMX_1024;   // DMX-1024 (500 kbaud - 1024 channels) Completely non standard, but usefull ;)
        speed_break = BREAK_1024;
      }
      else if(mode == 2)
      {
        speed_dmx   = DMX_2048;   // DMX-2048 (1000 kbaud - 2048 channels) Used by manufacturers as DMX1000K, DMX-4x or DMX-1M ???
        speed_break = BREAK_2048;
      }
    }

    #if defined(USE_INTERBYTE_DELAY)

    void CArduinoDmx::delay_gap() // rare cases of equipment non full DMX-512 compliant, need this
    {
      if(dmx_mode == 0)
      {
        _delay_us(IBG_512);
      }
      else if(dmx_mode == 1)
      {
        _delay_us(IBG_1024);
      }
      else if(dmx_mode == 2)
      {
        _delay_us(IBG_2048);
      }
    }
    #endif

**myFile.ino**

    /*-----------------------------------------------------------------------------
      include files
    ------------------------------------------------------------------------------*/
    #include <SPI.h>
    #include <Ethernet.h>
    #include <EthernetUdp.h>
    #include <lib_dmx.h>

    #define DMX512  (0)

    byte mac[] = { 0xDD, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(10,0,0,2); // TODO: assign ip address from DHCP
    unsigned int multicastPort = 8888;
    IPAddress multicastIp(239,0,0,57);

    char packetBuffer[UDP_TX_PACKET_MAX_SIZE];

    EthernetUDP Udp;

    int sensorValue = 0;
    int ledState = 0;
    int DMXPin = 0;

    void setup() {

      // DMX
      ArduinoDmx1.set_control_pin(DMXPin);
      ArduinoDmx1.set_rx_channels(1);
      ArduinoDmx1.set_tx_channels(5);
      ArduinoDmx1.init_tx(DMX512);

      Ethernet.begin(mac,ip);
      Udp.beginMulti( multicastIp, multicastPort );
      Serial.begin(9600);

    }

    void loop() {
      int packetSize = Udp.parsePacket();
      if(packetSize){
        Serial.print("Received packet of size ");
        Serial.println(packetSize);
        Serial.print("From ");
        IPAddress remote = Udp.remoteIP();
        for (int i =0; i < 4; i++){
          Serial.print(remote[i], DEC);
          if (i < 3){
            Serial.print(".");
          }
        }
        Serial.print(", port ");
        Serial.println(Udp.remotePort());

        Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
        Serial.println("Contents:");
        Serial.println(packetBuffer[0]);

        ArduinoDmx1.TxBuffer[0] = (int)packetBuffer;
      }
    }

  [1]: https://github.com/aallan/Arduino

title: Multiple definition of '__vector_36' (intterupts)

Answers: 2

body:
It seems that, from the discussion on the page you link to, the author of the DMX Library himself is not sure how to get this to run.

The easiest solution, it seems to me, is to modify HardwareSerial.cpp in your Arduino core to no longer use that interrupt vector.

body:
You use the Serial.begin(9600) and other Serial functions in your sketch. Therefore the HardwareSerial library is included. Just avoid the Serial stuff in your sketch, it won't work anyway, because the DMX uses the same serial port.

Have a look to
"Don't use the Arduino Serial implementation"
in
http://www.mathertel.de/Arduino/DMXSerial.aspx
The Four Universes DMX 512 Library works the same way as the DMXSerial library.


body:
According to [this][1]:

> The Servo library supports up to 12 motors on most Arduino boards and
> 48 on the Arduino Mega. On boards other than the Mega, use of the
> library disables analogWrite() (PWM) functionality on pins 9 and 10,
> whether or not there is a Servo on those pins. On the Mega, up to 12
> servos can be used without interfering with PWM functionality; use of
> 12 to 23 motors will disable PWM on pins 11 and 12.

However, according to [this][2]:

> Digital I/O Pins 14 (of which 6 provide PWM output)

So how can the Uno control more than 6 servos if it only has 6 digital I/O pins that can provide PWM output?

  [1]: http://arduino.cc/en/reference/servo
  [2]: http://arduino.cc/en/Main/ArduinoBoardUno

title: How can the Arduino Uno support up to 12 servos if it only has 6 digital PWM pins?

Answers: 1

body:
Although I haven't looked at the source myself, in these types of situations they usually use [interrupt timer 1](http://playground.arduino.cc/Code/Timer1), which in PWM mode would have been associated with pins 9 and 10. This would explain why you can't use pulse width modulation on those pins. In fact, you can use any of the three timers for PWM [on any digital pin, although it's not as good as the built in PWM options](http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM).

>[![][1]][1]
<sub>(source: [bansky.net](http://bansky.net/blog_stuff/images/servo_pulse_width.png))</sub>

*([Source](http://forum.arduino.cc/index.php/topic,14146.0.html))*

The above image accurately describes how the signals are sent to the servo motor. Such a waveform is similar to a standard PWM. The servo library can translate a degree to a waveform that the servo's IC will be able to use to adjust the motor's position with it's motor and potentiometer.

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


body:
My Arduino UNO board is part of a [small robot][1] that works when connected to the laptop by USB but it does not when plugged to the batteries. The baterries plug seems okay, it outputs 7.8 V. My UNO is connected to an ArduMoto board that manages the robot motors as well as a bluetooth chip. I have little experience with Arduino or electronics in general so I am stuck on the best course of action.

1) Can I find out what is wrong with the power supply without completely isolating UNO from the robot?

2) If I separate UNO, how can I find out with certainty if my UNO power supply is damaged or not? Is there something in particular that I could measure with my multimeter?

UPDATE

After fully charging my batteries I observed that the LEDs attached to the motor outputs are blinking fast. They blink for about one minute then nothing happens anymore. On USB everything works as expected. Those LEDs show that signal is going towards the motors, but why is it so different to USB? On USB power, the LEDs blink only when I command the robot to move through the BT board while under baterries they blink furiously for a minute and that is all that happens.

I also don't know what happened to the batteries, they seem to be fully drained in just one minute, but I don't know how to test that, they appear to still have high voltage.

I use two LC 18650 4800 mAh 3.7 V UltraFire baterries. The motor shield is Ardumoto Keyes_L298P, very similar to [Sparkfun's Ardumoto shield][2].

I do not have the actual code that is on my Arduino. It must be similar to the code on [this page][3], since I am using their Android app for BT communication with my robot, and it works on USB power supply.

  [1]: http://www.hobbyking.com/hobbyking/store/__37893__Arduino_Tracked_Cellphone_Bluetooth_Robot_Kit.html
  [2]: https://www.sparkfun.com/products/9815
  [3]: http://www.mobot.es/MobotBTCar.html

title: Arduino Uno + Ardumoto + BT robot works from USB but not from baterries

Answers: 1

body: Are you powering the motors with a separate supply, and not direct from the Arduino? Motors should be powered separately and the power only switched by the Arduino. Otherwise, their current draw could be pulling down your battery voltage. And even with USB power, they could be drawing more current than spec'd for either the USB power source or the Arduino's regulator or output pins. The chip itself is spec'd for a maximum current of 40mA per pin and 200mA total.


body:
I'm having a problem. I want to clear the screen on the connected console. And after the clear, I want to rerun my code. But I can't seem to figure out how to do it. Below is some part of the code:

    #include <motorStyring.h>
    #include <Bridge.h>
    #include <YunServer.h>
    #include <YunClient.h>
    #define PORT 6666
    motorStyring mt;
    int cm;

      YunServer server(PORT);
      const int pingPin = 9;
      int led = 13;
        void setup() {

        Serial.begin(115200);
        Bridge.begin();
        server.noListenOnLocalhost();
        server.begin();
     }
        void loop() {
        long duration, inches, cm;
        pinMode(pingPin,OUTPUT);
        digitalWrite(pingPin,LOW);
        delayMicroseconds(2);
        digitalWrite(pingPin, HIGH);
        delayMicroseconds(5);
        digitalWrite(pingPin,LOW);
        pinMode(pingPin, INPUT);
        duration = pulseIn(pingPin,HIGH);
        cm = microsecondsToCentimeters(duration);
        h();
       }
        void h()
       {
        YunClient client = server.accept();
         if (client.connected()) {
          String question = "What would you like to drink?\nyou have 4    choises:\n1)Juice\n2)Vodca\n3)Soda\n4)Mix\n";
    client.write((uint8_t*)&question[0], question.length());
    String response;
    while (client.connected()) {
      if (client.available()) {
        char cmd = client.read();
        if (cmd == '\n') {
          break;
        } else {
          response += String(cmd);
        }
      }
    }
    if (response == "juice") {
      juice();

    } else if (response == "vodka") {
      vodka();

    } else if (response == "soda") {
      soda();

    } else if (response == "mix") {
      mix();

    } else {

      String error = "you didn't select anything that corrospond to an option. \n try agin";
      client.write((uint8_t*)&error[0], error.length());
     }
       String awnser = "Here is your " + response;
       client.write((uint8_t*)&awnser[0], awnser.length());
     }
     delay(1000);
    }

**...**

Is there a way to clear the screen on the console, so that all of the text from the previous code is not disturbing the user?

title: Arduino Yún console clear

Answers: 1

body:
Perhaps you could count the number of lines in the console and the print out enough carriage returns (`"\n"`) to fill it with empty whitespace.

For example, with a console with 100 lines:

    for(int iter = 0; iter < 100; iter++) {
       client.write('\n');
    }


body:
I have two XBee's connected to two Arduino Uno boards (one for each XBee). I connected each XBee to the X-CTU software, and have set the following:

_XBee 1_

`Pan ID = 4270
DL = 10
MY = 20`

_XBee 2_

`Pan ID = 4270
DL = 20
MY = 10`

_Both_

`DD = 10000
IC = FF
IR = 32`

Therefore, they should be on the same network and see each other as the 'other person' each is talking to. I'm using the TX and RX pins of the arduino and the XBee to communicate over the serial port.

When testing if each can hear the other, I loaded one arduino with this code:

    #include <SPI.h>

    void setup() {
    // put your setup code here, to run once:
      Serial.begin(9600);
    }
    void loop() {
    // put your main code here, to run repeatedly:
      Serial.print('x');
      delay(1000);
    }

Then another with this:

    #include <SPI.h>

    void setup() {
    // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(7,OUTPUT);
      digitalWrite(7,LOW);
    }
    void loop() {
    // put your main code here, to run repeatedly:
      if(Serial.available())
      {
        char getData = Serial.read();
        if(getData == 'x')
        {
          digitalWrite(7,HIGH);
          delay(500);
          digitalWrite(7,LOW);
          delay(500);
        }
      Serial.print(getData);
      getData = ' ';
      }
    }

This works perfectly. One LED will light up on the correct arduino in half second intervals. However, when I try to make them both communicate at the same time to each other, nothing happens. Neither LED will light up. The code for both arduino's is:

    #include <SPI.h>

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(7,OUTPUT);
      digitalWrite(7,LOW);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.print('x');
      delay(1000);
      if(Serial.available())
      {
          char getData = Serial.read();
          if(getData == 'y')
          {
            digitalWrite(7,HIGH);
            delay(500);
            digitalWrite(7,LOW);
            delay(500);
          }
          Serial.print(getData);
          getData = ' ';
        }
    }

But for one arduino I change the code to `Serial.print('y')` and `if(getData == 'x')` to listen for the other one. I also have tried delaying one arduino in the setup by one second to offset the sending and recieving, but that also doesn't help.

I need them to be able to listen and talk to each other, maybe even at the same time like this example. I'm trying to create a proximity sensor in, lets say the 'back', area communicate with the 'front' area, and an accelerometer and two switches from the 'front' communicate with the 'back'.

Is there any settings I can change in X-CTU, such as the baud rate or the amount of packets re-sent, to overcome this problem? Or is this merely a code issue?

I do have the power connected to the 3.3V pin of the arduino, and I'm using 470/220 Ohm resistors as voltage dividers for the output pins from the arduino to the XBee, so I don't think voltage is an issue here.

Also, I have disconnected the arduino from the computer. I'm powering it via the USB-A to USB-B cord -> 13000 mAh 5V DC rechargeable battery, so there should be no interference with the serial data lines. Pin 2 (RX) of the XBee is connected to pin D0 (RX) of the arduino, and pin 3 (TX) of the XBee is connected to pin D1 (TX) of the arduino.

Thanks for your help.

title: Communication with two XBee's and Arduinos over serial

Answers: 1

body:
Did you set one of your modules into coordinator mode?
Every xBee network needs a coordinator. Therefore, you need to put one of your Xbee modules into coordinator mode using the "Function Set" dropdown box in X-CTU. The coordinator has the fixed address 0, so you need to set DL and HL address parts of the other module to 0. On your coordinator, you can set DL to FFFF and HL to 0, which is the broadcast address.

Softserial won't help you. It's just a way to use some of the pins as an additional serial port. Don't use that if you can use a hardware serial port.


body:
I'm trying to communicate with the Arduino through the serial port to fade the LED.
There's the code running on my Arduino:

    #include <aJSON.h>
    aJsonStream serial_stream(&Serial);

    const int localID = 1;
    int intensity = 100;        // fadeTo value(0% - 100%)
    int currentIntensity = 0;   // how bright the LED actually is (0-100%)
    int time = 0;               // milliseconds
    int color[] = {0, 255, 0};

    int pinRed = 11;
    int pinGreen = 10;
    int pinBlue = 9;
    int pinPower = 8;

    void fadeTo() {
      if(intensity != currentIntensity) {
        if(intensity > currentIntensity)
          currentIntensity+=1;
        else
          currentIntensity-=1;

        analogWrite(pinRed,255-currentIntensity);
        analogWrite(pinGreen,255-currentIntensity);
        analogWrite(pinBlue,255-currentIntensity);
      }
    }

    aJsonObject *createMsg()
    {
        aJsonObject *orbData, *colorData;

        orbData = aJson.createObject();
        aJson.addNumberToObject(orbData, "id", (int)localID);

        aJson.addNumberToObject(orbData, "currentIntensity", (int)currentIntensity);

        //aJson.addNumberToObject(orbData, "time", (int)time);

        colorData = aJson.createIntArray(color, 3);
        aJson.addItemToObject(orbData, "color", colorData);

        return orbData;
    }

    // echo {\"id\":1, \"intensity\":150, \"time\":10} >> /dev/ttyACM0 in terminal
    // {"id":1, "intensity":150, "time":10} in Serial Monitor
    void processMsg(aJsonObject *msg)
    {
        //Serial.println("Data succefully received.");
        Serial.println("received message: ");
        aJson.print(msg, &serial_stream);

        aJsonObject *idData = aJson.getObjectItem(msg, "id");
        if(idData != NULL)
        {
            Serial.println("ID data succefully received.");
            if(localID == (idData->valueint)) {

                aJsonObject *intensityData = aJson.getObjectItem(msg, "intensity");
                if(intensityData != NULL) {
                    if(intensityData->type != aJson_Int) {
                        Serial.println("Invalid data type for Intensity");
                        return;
                    }

                    if(intensityData->valueint == currentIntensity) {
                        Serial.println("The received intensity value is already the current LED intensity");
                        return;
                    }

                    else {
                        Serial.println("Intensity data succefully received");
                        intensity = intensityData->valueint;
                    }
                }
                else {
                    Serial.println("No intensity value received.");
                    return;
                }

                aJsonObject *timeData = aJson.getObjectItem(msg, "time");
                if(timeData != NULL) {
                    if(timeData->type != aJson_Int) {
                        Serial.println("Invalid data type for time");
                        return;
                    }
                    else {
                        Serial.println("Time data succefully received");
                        time = (timeData->valueint);
                    }
                }
            }

            else {
              Serial.println("The received ID is not mine.");
              return;
            }
        }

        else {
          Serial.println("No ID data received.");
          return;
        }

        Serial.println("received message: ");
        aJson.print(msg, &serial_stream);
    }

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

        pinMode(pinRed,OUTPUT);
        pinMode(pinGreen,OUTPUT);
        pinMode(pinBlue,OUTPUT);
        pinMode(pinPower,OUTPUT);

        digitalWrite(pinPower,HIGH);
        digitalWrite(pinRed,HIGH);
        digitalWrite(pinGreen,HIGH);
        digitalWrite(pinBlue,HIGH);
    }

    void loop()
    {
        aJsonObject *orbData = createMsg();

        Serial.println("current status: ");
        aJson.print(orbData, &serial_stream);

        Serial.println();

        aJson.deleteItem(orbData);
        delay(100);

        fadeTo();

    }

    void serialEvent()
    {
        if(serial_stream.available())
        {
            // first, skip any accidental whitespace like newlines
            serial_stream.skip();
        }

        if(serial_stream.available())
        {
            aJsonObject *msg = aJson.parse(&serial_stream);

            processMsg(msg);

            aJson.deleteItem(msg);
        }
    }

The problem is, I can open my Serial Monitor in the Arduino IDE and send json data to the Arduino and I see live the changes through the output and the LED on the board. I can also send data through terminal to /dev/ttyACM0 while running Serial Monitor in the IDE and it works fine too. But as soon as I close the Serial Monitor and send data to the device through terminal, it breaks down. I can then open Serial Monitor and every time I get the ERROR from json parser --> ("No ID data received.").

Has anyone any idea why this is happening?

title: Arduino Serial Communication

Answers: 1

body:
I had a similar problem trying to use the commands such as :

> echo 1 > /dev/ttyACM0

and found that I needed privileges to perform serial communication in this way like:

> sudo echo 1 > /dev/ttyACM0

You could also try setting the baud rate you are communicating at :

> sudo echo 1 > /dev/ttyACM0 9600

GOOD LUCK!


body:
Can a Arduino MEGA 2560 R3 provide enough current out of its pin to activate the [Songle srd-24vdc-sl-c relay][1]? Will powering the Arduino with an external power supply help?

![enter image description here][2]

  [1]: http://www.hebertech.com/view/3778-songle-srd-24vdc.pdf
  [2]: https://i.stack.imgur.com/8zapx.png

title: Can Arduino Mega2560 Use this 24VDC Relay?

Answers: 1

body:
This relay cannot be **directly** commanded by any Arduino because its coil require **24V voltage** to be able to switch the contact; Arduino Mega pins output voltage is **5V**.

Regarding **current**, the **relay coil needs 15mA** ("high sensitivity" model) **or 18.7mA** (standard model), that would be OK for an Arduino Mega pin (**max current = 40mA**).

Anyway, you would have to add some circuit to adapt voltage between the Arduino pin and the relay. For this, first of all **you will need to get a second power supply** (in addition to the Arduino 5V supply used for Arduino) that can supply 24V.

Then you could use a [MOSFET][1] transistor between the Arduino pin and the relay. A MOSFET is often used in so-called **Solid State Relay** ([SSR][2]) because it can almost do the same as a coil relay but is 100% electronic-based (no moving parts); however, contrarily to a coil relay, it does not provide galvanic isolation between the input and the output circuits.

You can check out [this question][3] to find out further information on MOSFET.

Personnally, I would rather replace that relay with a 5V relay model, as that would make the circuit simpler, and would remove the need for a second power supply.

  [1]: http://en.wikipedia.org/wiki/MOSFET
  [2]: http://en.wikipedia.org/wiki/Solid-state_relay
  [3]: https://arduino.stackexchange.com/questions/403/how-can-higher-current-devices-motors-solenoids-lights-etc-be-controlled-b


body:
I have the [GSM shield][1] and is there any ways to get the stored contacts on the SIM card? It seems that [the GSM library][2] does not support writing data onto/ reading data from the SIM card?

My aim is to store the SIM card's phone number and some variables onto the SIM card itself, such, I would not need to change the program from time to time.

All I need to do is enter all the variables in the SIM card via any mobile phone (perhaps by storing the variables as contacts, as phone book function should be very common on phones).

  [1]: http://arduino.cc/en/Main/ArduinoGSMShield
  [2]: http://arduino.cc/en/Reference/GSM

title: Getting the contacts/ storing contacts to SIM card

Answers: 2

body:
What have you researched so far? Following the link you have given for the shield, about the third line of the description is a reference to the [AT Command Set][1] used by the chip.

I just did a couple of quick searches through it and found:

>`2.2.4  ATD><n>` Originate phone call to number in memory
>
>`3.2.26 AT+CPBF` Find phone book entries
>
>`3.2.27 AT+CPBR` Read current phone book entries
>
>`3.2.28 AT+CPBS` Select phone book memory storage

probably a good place to start.

  [1]: http://arduino.cc/en/uploads/Main/Quectel_M10_AT_commands.pdf

body:
Thanks to @Madivad for the AT command inspiration. I am not very familiar with GSM and Arduino. But anyway, the below worked for me.

Credits to @Madivad and [people from the arduino forum.][1]

    #include <GSM.h>
    GSM gsmAccess(true);
    int sizer = 200;
    char myNumber[200];
    int timeout = 5000; // in milli seconds

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

      boolean notConnected = true;

      Serial.println("Connecting to the GSM network");

      while(notConnected){
        if(gsmAccess.begin() == GSM_READY) // Note: I do not require PIN #
          notConnected = false;
        else {
          Serial.println("Not connected, trying again");
          delay(1000);
        }
      }

      Serial.println("Connected");

      theGSM3ShieldV1ModemCore.println("AT+CPBS=\"SM\"");
      int start1 = millis();
      while((millis() - start1) < timeout){
        Serial.print(theGSM3ShieldV1ModemCore.theBuffer().read());
      }
      Serial.print("Set to look at SIM card storage");

      // search for contact name "test"
      theGSM3ShieldV1ModemCore.println("AT+CPBF=\"test\"");
      start1 = 0;
      start1 = millis();
      while((millis() - start1) < timeout && !theGSM3ShieldV1ModemCore.theBuffer().extractSubstring(",\"", "\",", myNumber, sizer)){
        Serial.print(theGSM3ShieldV1ModemCore.theBuffer().read());
      }
      Serial.print("Got contact number");

     // print out the phone of "test"
     Serial.println(myNumber);

    }

    void loop()
    {

    }

  [1]: http://forum.arduino.cc/index.php?topic=163155.0


body:
I am doing a project on Arduino controlled light dimmer circuit...

I have a separate circuit for zero crossing detector and IR receiver but when I am combining both of them in arduino then my IR receiver stops working and zero crossing interrupt is not detected...

Here is my code:

    #include <IRremote.h>
    int RECEIVE_PIN = 8;
    int AC_LOAD = 3;
    int dimming;

    IRrecv irrecv(RECEIVE_PIN);
    decode_results results;

    void setup()
    {
        Serial.begin(9600);
        irrecv.enableIRIn();
        pinMode(AC_LOAD, OUTPUT);
        attachInterrupt(0, zero_crosss_int, RISING);
    }

    void zero_crosss_int()
    {
        int dimtime = 75*dimming;
        delayMicroseconds(dimtime);    // Off cycle
        digitalWrite(AC_LOAD, HIGH);   // triac firing
        delayMicroseconds(10);         // triac On propogation delay
        digitalWrite(AC_LOAD, LOW);    // triac Off
    }

    void loop()
    {
        if (irrecv.decode(&results))
        {
            Serial.print("0x");
            Serial.println(
            results.value, HEX);
            delay(50);

            if(results.value==0xE13DDA28)
                dimming = 120;

            if(results.value==0xAD586662)
                dimming = 80;

            if(results.value==0x273009C4)
                dimming = 20;

            irrecv.resume();
        }
    }

Can anyone help me with this????

title: IR controlled light dimmer

Answers: 3

body:
What you've described (without source code and/or a circuit diagram) sounds like you'll probably be using interrupts at least for the zero crossing detection. And probably the IR receiver too. The IR receiver is going to be your problem since the zero crossing is a very quick flag set and you're out of the interrupt.

On the other hand, the IR detection is going to take time, and if you're doing THAT in an interrupt you're going to be missing dozens of crossings.

To mix the two you can leave the zero crossing in it's own interrupt, but you're probably better off handling the IR in the loop via a state machine.

Since you say that neither are working, I'm going to hazard a guess and you're using the same interrupt or badly implemented them (possibly a timer and interrupt clash) and until you post some code people here aren't going to be able to help you any more than that.

body:
One important problem in your code is concurrent access to `dimming` variable. That may not be the only problem you have though.

Indeed, `deeming` is accessed for writing in your `loop()`, but it can be simultaneously read by `zero_crosss_int()` function which is executed in interruption mode because it was registered as such with `attachInterrupt()`.

Since `deeeming` is an `int` (2 bytes on AVR MCU), it cannot be read or written in just one clock-cycle (AVR is an 8-bit technology). Hence it is perfectly possible that `loop()` gets interrupted by `zero_crosss_int()` just in the middle of writing `dimming`, eg in:

    dimming = 120;

Note that, in theory, concurrent acces in your case should not be an issue as long as `dimming` is never greater than 255.

## How do you protect access to `dimming` variable?
You can do the following:

    int dimming() {
        cli();
        int temp = dimming;
        sei();
    }

    void dimming(int value) {
        cli();
        dimming = value;
        sei();
    }

And replace any direct access to the `dimming` variable in your code with a call to one of these functions above.

## Will that fix your problem?
Maybe not unfortunately, as it is probable that mixing IRremote.h with your code brings other conflicts.

But at least, this will solve a dormant bug in your code, a complex bug that may catch you some day.

body:
It seems that the jaydeep might have been building my circuit and  used the provided code: http://www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit/step4/Arduino-controlled-light-dimmer-The-software/
so obviously this problem has my interest.
With regard to the 'dimming' variable, that will not go beyond 128 so I might as well have used 'byte'  to define it.
The IR remote library is I presume that of Ken Shirrif and that one uses the Timer2 interrupt. In principle, combining those two interrupts shouldnt necessarily cause a problem as I have done so as well (in using the timer interrupt rather than 'delay to trigger the TRIAC).
But in that case the entire timer interrupt was handled within the period of  the mains wavelength (100 or 83 ms depending on frequency).

I don’t think the access to the 'dimming' variable -as jfpoilpret mentions- is the problem (though he makes some sound remarks), as that will just remain as is for a specific  light level.

The problem -as  is also suggested above- might well be in the fact that the IR receive takes too long.

So... disregarding interrupt priority for a moment, if the code is hanging around in the timer interrupt routine and there is a zerocrossing, that won't be detected, or, if the code is just doing a zero crossing detection, the timer is  screwed up.

In comes interrupt priority: The external interrupt has the highest priority (other than reset). So.. when  the IR receive routine is busy in the Timer service routine and a zerocrossing arrives, it will be taken out of that routine, zerocrossing will be handled and ideally, it should continue with the timer routine again.
However, your remote has no idea what is going on in the Arduino and some of the code sent will be missed.

all of this shouldn’t need to be a problem if the external interrupt was fast, but as most of the waiting is actually done within this interrupt, it could take up to almost 10mS/8.3mS (when 'dimming' approaches 128).

Solution?
Well, I can't say much about the Timer2 interrupts in Ken's library, But on 'my side' of the software, what could be done is to shorten the external interrupt by removing the delays and use (yet another) timer interrupt.
Ken uses Timer2, so this would have to be timer1.
So, whenever there is a zerocross, there is no waiting in a delay, but it will be handled by timer1
An example is given in [Step 6 of my instructable][1]. There is no guarantee this will work but there is a good chance

Let me just point out that the basic  program I supplied was just given as an example, It uses much computer time in waiting and therefore isn’t the best to combine with other actions of the processor.

  [1]: http://www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit/step6/Arduino-controlled-light-dimmer-The-software-III/


body:
I'd like to write my sketches so that I can either build/upload them using the Arduino IDE, or optionally using GCC and a makefile.

I know about including the function declarations at the top, but is there anything else to do in order for my sketch to be considered valid C++ by my compiler?

### Update 1

Understanding what the Arduino IDE does to .ino and .pde files is fine, but extraneous to my question, so this is not a duplicate. What I want to know is "how do I write a program such that it is considered valid both by the Arduino IDE **and** g++.

The official(?) makefile [available here](http://playground.arduino.cc/Learning/CommandLine) explains what to do if using the makefile *instead* of the IDE:

    # The Arduino environment does preliminary processing on a sketch before
    # compiling it.  If you're using this makefile instead, you'll need to do
    # a few things differently:
    #
    #   - Give your program's file a .cpp extension (e.g. foo.cpp).
    #
    #   - Put this line at top of your code: #include <WProgram.h>
    #
    #   - Write prototypes for all your functions (or define them before you
    #     call them).  A prototype declares the types of parameters a
    #     function will take and what type of value it will return.  This
    #     means that you can have a call to a function before the definition
    #     of the function.  A function prototype looks like the first line of
    #     the function, with a semi-colon at the end.  For example:
    #     int digitalRead(int pin);

...but this doesn't explain how use *both* the IDE and a makefile.

### Update 2
I recently found [PlatformIO](platformio.org) which doesn't answer this question directly, but does automate a lot of the process (generates Scons files for you) and so far I prefer the workflow over both the Arduino IDE and the source+makefile approach.  Good support from the authors as well.

title: How to write makefile-compatible sketches?

Answers: 3

body:
By gcc/g++ I think you're referring specifically to avr-gcc/avr-g++.  Your arduino code probably won't be considered valid C/C++ code because gcc will try to compile with your PC as the target system. Many of the Macros in "WProgram.h" will refer to inaccessible memory on your target system.

Providing you include the header file "WProgram.h" and you build your code with the Arduino Makefile above (which uses avr-g++ not g++), your cpp files should compile and link correctly.  Likewise, you will be able to open your Arduino code within the IDE and Verify your code there.  The IDE puts in the "WProgram.h" file for you, so technically it would be included twice.  However, the include guards will prevent any duplicate code from being compiled.

body:
Generally you'll need to state the `setup()` and `loop()` functions, they are just wrappers of the IDE:

    void setup() {}
    void loop() {}

    int main() {
      setup();
      while (1)
        loop();

      return 0; // never reached
    }

This works both in the IDE and on the command line.
As you specify the Board and SerialPort in the IDE,
you'll need also to specify both in the Makefile.
So you'll end up with two configurations.

Many people leave the IDE because they prefer use different
editors or have more configuration options by setting
the compiler and linker switches.

To make it really easy, you can use [Arduino Makefile][1]. Today
starred with 347.

Here an example Makefile:

    # try: make help
    #
    include /usr/share/arduino/Arduino.mk
    ARDUINO_DIR = /usr/share/arduino
    # list boards with: make show_boards
    BOARD_TAG = promicro16
    ARDUINO_LIBS = EEPROM
    # MONITOR_CMD = picocom -b 9600
    MONITOR_CMD = moni -config ACM0-9600.cfg
    ARDUINO_PORT = /dev/serial/by-id/usb-Arduino_LLC_Arduino_Leonardo-if00
    # ARDUINO_PORT = /dev/ttyACM0
    # ARDUINO_PORT = /dev/ttyUSB0
    OPTIMIZATION_FLAGS = -Os -fexpensive-optimizations -fstrength-reduce
    #

The '*.ino' files don't need to be changed and the `Makefile` file is to be placed in the same directory.

Meanwhile I prefer the `Makefile` way, but I still use the IDE for small projects.

[1]: https://github.com/sudar/Arduino-Makefile

body:
> What I want to know is "how do I write a program such that it is considered valid both by the Arduino IDE and g++.

See: [How to avoid the quirks of the IDE sketch file pre-preprocessing](http://www.gammon.com.au/forum/?id=12625).

Disregarding for the moment what the Makefile will look like, the simple answer to your question, as discussed in the above link, is to put everything into .cpp and .h tabs in the IDE, and leave the main "sketch" (.ino file) blank. That will still compile under the IDE, and will also therefore be normal C++.

Make sure you start your .cpp files with:

    #include <Arduino.h>

If you use libraries (eg, SPI) you must include them in the main sketch file, which triggers the IDE to copy them into the temporary project build file. The Makefile won't care about that, as you will make sure your Makefile includes all the necessary library files.

Also see my answer here: https://arduino.stackexchange.com/questions/13178/classes-and-objects-how-many-and-which-file-types-i-actually-need-to-use-them/13182#13182


body:
I recently bought an Arduino Micro to see what all the fuss was about and I figured I'd use it with Ubuntu on an older Dell Latitude. I was able to install all of the files using some tutorials but I have this problem uploading sketches. After plugging in the board, the green top LED is consistently flashing so it seems to be working, but when I try to upload a sketch I get the following error

    Connecting to programmer: .avrdude: Send: . [1b]
    avrdude: Send: S [53]
    avrdude: ser_recv(): programmer is not responding
    avrdude: butterfly_recv(): programmer is not responding

Any ideas how to fix this? I tried pressing reset during the send as some forums have suggested but it doesnt seem to be working.

title: Sketches not uploading to Micro from Ubuntu 14.04

Answers: 2

body:
The only way I have been able to fix this is revert back to Ubuntu 12.04.

There is something about 14.04 that does not play nice with the Micro.

I've tried running avrdude on the command line as well with no luck. The Arduino IDE code jumps through some hoops to detect the proper USB port, so timing is probably critical. I don't know the secret sauce for 14.04 though. The micro is tricky since USB is disconnected and reconnected during programming.

If anybody has better luck with this please update.

body:
I have a Micro and Ubuntu 14.04. I have successfully uploaded sketches to the Micro using IDE 1.0.6. Thus that combination should work.

I suggest you get the sketch compiling OK. Then hold down the Reset button on the Micro, start an upload with your other hand, and release Reset when it says "Uploading".

---

Try typing

```lsusb | grep Arduino
```

I found with a sketch uploaded which opens the Serial port:

```Bus 003 Device 087: ID 2341:8037 Arduino SA ```

If you hit Reset and wait a second, then do the lsusb again you see a different device:

```Bus 003 Device 086: ID 2341:0036 Arduino SA ```

That one (the 0036 one) is the one it will upload to. You might get 0037 rather than 0036 because I reflashed the bootloader to be the Leonardo one, but the concept is the same.


body:
I can't figure out why the next script is not working. I have attached the Arduino to one USB port of the raspberry pi, in which I've installed pyserial. I just want to turn off/on a led depending of the number I write on the Raspi console (1-> on, 2-> off).

        int led=13;

    void setup(){
      Serial.begin(115200);
      pinMode(led,OUTPUT);
    }
    void loop(){
      if(Serial.available()){
         mode(Serial.read() - '0');
      }
    }
    void  mode(int n){

        if (n== 1){
             digitalWrite(led,HIGH);
        }
        if (n== 2){
            digitalWrite(led,LOW);
        }
      }

PS: I double checked and the baudrate is configured also at 115200 at the raspi side.
In addition, if I place digitalWrite(led,HIGH) just before  the line  "mode(Serial.read() - '0');" the led turn on when I send some information from the raspi shell (so, works well).

title: Simple Script controlled by Raspberry not working

Answers: 1

body: Finally I've found the error, it was the serial communication baud rate: 115200. It seems that at higher speeds it not works properly, lowering it to 9600 do the trick.


body:
I have a stepper motor connected to my Arduino like this using the ULN2003A Darlington Array:

![Circuit Diagram][1]
![Image][2]
(Ignore the potentiometer)

And I have programmed it with the following code:

    #include <Stepper.h>

    int in1Pin = 22;
    int in2Pin = 23;
    int in3Pin = 24;
    int in4Pin = 25;

    Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin);

    void setup()
    {
        pinMode(in1Pin, OUTPUT);
        pinMode(in2Pin, OUTPUT);
        pinMode(in3Pin, OUTPUT);
        pinMode(in4Pin, OUTPUT);

        motor.setSpeed(25);
    }

    void loop()
    {
        int steps = 360;

        motor.step(steps);
        delay(500);
    }

At the moment the motor rotates clockwise, how could I have it so it rotates in the opposite direction?

My code was copied and edited from [here](http://learn.adafruit.com/adafruit-arduino-lesson-16-stepper-motors/arduino-code).

----------------

The problem was that I had the two middle wires the wrong way round as said here: http://forum.arduino.cc/index.php?PHPSESSID=kvi8dt2b5en5hhk02dlmjrotl5&topic=143276.msg

[1]: https://arduino.cc/en/uploads/Reference/unipolar_stepper_four_pins.jpg
[2]: https://static.flickr.com/32/54357295_756c131217.jpg

title: Reverse turning of Stepper motor

Answers: 1

body:
The answer is simple. Just pass a negative number of steps as an argument to `motor.step();`.

Another note: You forgot a semicolon on your second to last line. IIRC this doesn't matter in C, but **it's just bad practice to do this.** If you add a line of code below that, then it won't work.

Example code:

    #include <Stepper.h>

    int in1Pin = 22;
    int in2Pin = 23;
    int in3Pin = 24;
    int in4Pin = 25;

    Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin);

    void setup()
    {
        pinMode(in1Pin, OUTPUT);
        pinMode(in2Pin, OUTPUT);
        pinMode(in3Pin, OUTPUT);
        pinMode(in4Pin, OUTPUT);

        motor.setSpeed(25);
    }

    void loop()
    {
        int steps = 360;
        motor.step(steps);
        delay(100);

        steps = -360;
        motor.step(steps);
        delay(500); //Semicolon added
    }


body:
I'm using an Arduino Due with a logic level converter to interface with two different 5v sensors via I2C. Being of poor quality, these sensors have no data sheet.

When either one of these sensors is plugged in, I am able to read from it without issue. The moment I plug the other one in as well, the I2C stops working, and I just get 0. I know that it's not an address collision issue, because they have different addresses.

I tried adding an additional set of pull-up resistors (such that they are in parallel with the built-in ones) in order to counteract potentially increased bus capacitance, but no dice.

What could be causing this issue? I apologise for asking such a noob question.

title: Adding devices makes I2C read 0

Answers: 1

body:
Your problem is probably from the level converter. Which one did you use?
Most level converters are uni-directional, and don't work for I2C.
See the App note and device from NXP:
http://www.adafruit.com/datasheets/an97055.pdf


body: I wanted to take the audio from a device such as the PC, insert it through different ADC in arduino, processing them with DSP and DAC REnter all through to the other speakers, reading here and there on the internet but some people were put in difficulty because Arduino has a data bus to 10 bits. What problems can cause this? I can not send the same 10 bits at a time, until you arrive at 32?

title: Arduino 1 can somehow support 32-bit audio?

Answers: 1

body:
First of all,*what is the point of this?* [I'm afraid this is a XY question](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You won't get that good of quality with Arduino. If you're hoping to create some sort of an amp, learn electronics and do that directly. Maybe you should just send data via serial.

Anyway, that aside, here's a chart I drew:

![][1]
(Excuse my poor image alignment, PowerPoint was being a little mean today)

The bottom is all the "channels" the PC can send. The top is all the "channels" the Arduino can recieve. As you can see, there's a *huge* degradation in quality. Not to mention, I made this that 1 bit = 1 "channel," yet it's very much more than that.

A standard Arduino (Uno, Leonardo, etc.) has a 10 bit ADC that can read values 0-1023. The computer can output 0-4294967295! (It' exponentially grows due to permutations). You can see why I very much simplified my chart! :P

DSP won't really work well, unless you are trying to do some weird alien sounding modifications or a cheesy echo to. You probably will want to add an external 32 bit ADC. I would recommend, additionally, adding a Due or Galileo that can process 32 bit integers without emulating a bigger chip, thus greatly reducing performance and giving you a low framerate.

tl;dr: It'll work fine, but it'll have horrible sound quality. You can't send the same 10 bits until 32, since the computer changes that 32 bits into a voltage (sent to Arduino), and the Arduino translates that voltage into 10 bits.

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


body:
How to make an input from computer using processing (like a password form) and trigger pin in arduino?
If you let some link to read more that would be very helpful.

title: Processing Input

Answers: 2

body:
You need to have a look at the Serial commands: http://arduino.cc/en/Serial/read

http://arduino.cc/en/Tutorial/ReadASCIIString

body:
On the processing side you need to communicate with the arduino using the Serial class. To set up use something like the following. It is a bit of guess work
to find which of the serial ports to use

    Serial myPort;
    void setup() {
      // List all the available serial ports:
      println(Serial.list());

      // Open the port you are using at the rate you want:
      myPort = new Serial(this, Serial.list()[6], 9600);
      myPort.buffer(2); // sets the size of the buffer, I send two bytes at a time
    }

You can read a write using the Serial.read() and Serial.write() see https://processing.org/reference/libraries/serial/index.html for the processing serial references.


body:
I'm using the [Pololu DRV8825 Stepper Motor Driver](http://www.pololu.com/product/2132) to control a [NEMA 17 Steppermotor](http://www.ebay.co.uk/itm/Nema-17-1-7A-2-55V-Motor-ACT-17HS4417-Rep-rap-Nema17-Bipolar-/281122696759) with an Arduino Uno.  According to the Pololu website, the circuit should be wired as follows:

![enter image description here][1]

I did, however, deviate from this exact sketch a little bit:

 1. The Arduino (microcontroller) is powered by a USB cable connected to the computer
 2. I connected the 5V pin on the arduino to the + rail on a breadboard.  I then connected two wires on this rail to the **RESET** and **SLEEP** pins on the driver.
 3. I'm using a 9V battery to power the motor.
 4. I've connected the **DIR** and **STEP** pins to Arduino Uno pins 12 & 13, respectively.

Consequently, I coded and uploaded the following sketch:

    int stp = 13;  //connect pin 13 to step
    int dir = 12;  // connect pin 12 to dir
    int a = 0;     //  gen counter

    void setup()
    {
      pinMode(stp, OUTPUT);
      pinMode(dir, OUTPUT);
    }

    void loop()
    {
      if (a <  200)  //sweep 200 step in dir 1
       {
        a++;
        digitalWrite(stp, HIGH);
        delay(10);
        digitalWrite(stp, LOW);
        delay(10);
       }
      else
       {
        digitalWrite(dir, HIGH);
        a++;
        digitalWrite(stp, HIGH);
        delay(10);
        digitalWrite(stp, LOW);
        delay(10);

        if (a>400)    //sweep 200 in dir 2
         {
          a = 0;
          digitalWrite(dir, LOW);
         }
        }
    }

**RESULT**
The stepper motor does not turn.  Instead, it just hisses at a high pitch.  After a short while, the driver gets very hot.

**THINGS I'VE TRIED**

 1. I double checked to make sure that connected stepper wires pairs are properly connected to the "A" pins and "B" pins on the driver.
 2. I tried reversing the A1-A2 pair and B1-B2 pair in all possible combinations.  All combinations produce the same result as above.
 3. I tried increasing the motor power supply to 12V (8 alkaline AA batteries).  The same result occurs.
 4. I double checked to make sure the 100microF radial electrolytic capacitor is connected with the long end to the positive motor supply and short end to the negative motor supply (on a different breadboard rail than the logic power supply, of course).
 5. I tried using the 3.3V pin instead of the 5V pin to connect to SLEEP and RESET on the driver.  Again, the same result occurs.

I'm not really sure what to try next to debug my circuit.

**My Hunch:**

I do, however, have one suspicion based on a little warning box on the pololu website which reads:

> **Caution:** Installing the header pins so that the silkscreen side is up
> and the components are down can limit the range of motion of the
> trimpot used to set the current limit. If you plan on installing the
> header pins in this orientation, please set the current limit before
> soldering in the pins.

The way I soldered the headers onto the driver looks like the bottom left corner of the picture below:

![enter image description here][2]

**My Question:**
Given that my stepper motor requires 1.7A current, is there anything I can do to improve this circuit to make it work?  Did I make any mistakes?  Is there anything else I should try or check?  Did I solder the header in the wrong way?

  [1]: https://i.stack.imgur.com/x76EK.png
  [2]: https://i.stack.imgur.com/I4p4R.jpg

title: Debugging my Stepper Motor Driver circuit

Answers: 4

body:
**A couple things I noticed first:** This is one of the best formatted questions I've ever seen... :) Anyway, your circuit looks fine to me except for a few things:

> **Warning:** This carrier board uses low-ESR ceramic capacitors, which makes it susceptible to destructive LC voltage spikes, especially when using power leads longer than a few inches. Under the right conditions, these spikes can exceed the 45 V maximum voltage rating for the DRV8825 and permanently damage the board, even when the motor supply voltage is as low as 12 V. One way to protect the driver from such spikes is to put a large **(at least 47 µF) *electrolytic* capacitor across motor power (VMOT) and ground** somewhere close to the board.

*(Added some italic/bold myself, quote from product page.)*

Capacitors are cheap ($1.50 on eBay from US), and although new drivers are too, it's generally a good idea to build it right. There's nothing more annoying than waiting for shipping on something you shouldn't have had to fix.

Additionally, battery power (especially AAs) can be bulky if not done right, and may not provide enough current. Note that in a series configuration that **it will provide the voltage of 8 AAs, but only the current of one.** You can't run a 1.7 A motor off of a single AA's current. Stab in the dark guess: you'll need ~80-100 AAs to provide enough current and voltage. I'm too lazy to measure the internal resistance and actually calculate it.

**Suggested solution:** There are a million things that could go wrong. Without being there, I'm betting that your delay function is too short. What this will do is not provide enough time for the motor to move, thus it staying still. This would still use a lot of current (50% of the time it's full current to motor coils), therefore it would make the driver hot. (**Note on heat:** *...to supply more than approximately 1.5 A per coil, a heat sink or other cooling method is required...* -Product page: you'll need a heatsink to cool your chip down.) Also note that some heat is normal; a general rule of thumb is if it's too hot to hold your thumb on it for a few seconds, you need more cooling. Remember that the more it's used, the hotter it'll get, so keep this in mind when deciding if you want to add a heatsink.

**tl;dr:** You need to increase the delay time and provide more current than you have currently.

body:
I don't think your batteries were too low in current capacity, your delay time is not too short, at 10 +10 ms per clock pulse, you are only talking about 50 steps per second, that's not all that fast. I've written programs where I have had to go to microseconds to get enough rpm out of my stepper.

First, take everything out of your loop except the digitalwrite high, delay digitalwrite low and delay lines. Then the program "should" just spin the motor continuously in one direction. That way you are sure you don't have a logic issue.
Second, did you check to see if you didn't hook up pin 12 and 13 backwards, such that you are telling the driver to change direction every 10 ms instead of stepping? The sound it makes would be more like a buzz or vibration, usually a soft, staticy hiss is when the motor is enabled, but not getting a step pulse.

Finally, this post is about 18 months old, it is considerate and helpful to others to explain how you solved the problem (assuming you figured it out).

body:
The one thing that helped me was NOT to connect GND to stepper board from microcontroller (bottom black line from schematic posted in first post).

If it was connected, driver would draw 12V@3A immediately and gets freaky hot. Also motor didn´t turn at all.

body:
I had this same issue when setting up this circuit with this code and driver on an Arduino Uno. All else was fine, but the current for the motor was set WAY too high on the driver from the factory. The VREF was 1.7 volts, and it needed to be around .5 for the motor I was using. As I set the VREF to the appropriate voltage, the motor started to spin as it should and stopped hissing.

I know this post is old, but I hope that this helps someone else. Pololu has a great video (and documentation in general) for setting the appropriate voltage on most of their drivers on the product page here: [DRV8825 Stepper Motor Driver Carrier, High Current][1].

  [1]: https://www.pololu.com/product/2133


body:
im just looking for how to send/ write date to pc over serial port from arduino..vice versa.

I have few Question to ask after taking so much time and couldn't figure it out myself. I hope you guys can guid me please.

First, i found i can use Serial.println() function to send some data then, on the pc side, it just checks and reads the port (/dev/tty..). But, how does this process actually work under the hood? So, if you use serial.println() it knows about where to write?

Second i also found it's something to do with UART communication.. But, inside Hardware.cpp file, i couldn't find any function call to the one for UART.

Third there is the code like extern HardwareSerial Serial; Then where is the definition of this Serial?

Fourth There seem to have ring buffer for serial buffer. So, when data is being sent then, what and who fill the data into this buffer inside Hardware.cpp?

please, forgive my silly question.. i'm just so curious about this..

title: how does serial port communication work under the hood?

Answers: 2

body:
Serial.println knows where to write because Serial is an object. On boards with more than one port there will also be a Serial1,Serial2,etc. Each object corresponds to a port.

The ring buffers are filled from interrupts. When a new byte comes in, it triggers an interrupt that puts the byte in the buffer. When a byte is finished sending it triggers another interrupt that reads the next byte from the buffer and sends it.

Somewhere there is a source file that sets up the UART. It's full of writing special values to registers and low level things like that. I'm not sure what files things are defined in, but if you use the search feature on github there is tons of interesting stuff.

body:
The first question already got a perfectly good answer. I am answering the other ones.

> i couldn't find any function call to the one for UART.

There are no "UART functions" in the MCU. The UART is controlled by reading and writing into special registers. These come by names like `UCSR0A`, `UCSR0B`, `UCSR0C` (USART 0 Control and Status Registers A, B and C), `UBRR0L`, `UBRR0H` (Low and High bytes of the USART 0 Baud Rate Register) and `UDR0` (USART 0 Data Register). These registers are all referenced in HardwareSerial.cpp. You can check the datasheet for their meaning.

> where is the definition of this Serial?

In HardwareSerial.cpp, by the end of the file, right after the comment "Preinstantiate Objects".

> There seem to have ring buffer for serial buffer. So, when data is being sent then, what and who fill the data into this buffer inside Hardware.cpp?

There are actually _two_ ring buffers: the receive buffer (`_rx_buffer`) is filled by an interrupt service routine and is emptied by you calling `Serial.read()`. The transmit buffer (`_tx_buffer`) is filled by you calling `Serial.write()`, `Serial.print()` or `Serial.println()` (the line `_tx_buffer->buffer[_tx_buffer->head] = c;` in `HardwareSerial::write()`), and is emptied by an interrupt service routine.

These interrupt service routines are defined in HardwareSerial.cpp. They start with lines like `ISR(SOMETHING_vect)`. They are triggered by the hardware UART. The transmit ISR is triggered when the UART is ready to accept a new byte to transmit (when it is done transmitting byte _n_, it starts transmitting byte _n_+1 and is ready to accept byte _n_+2 in its TX buffer). The receive ISR is triggered when a new byte has been received.

> when does it get initialised?

When you call `Serial.begin()`.


body:
I have an Arduino GSM Shield mounted on an Arduino Uno. Can I stack this [GPS shield][1] above Arduino GSM shield? Will there be any pin configuration problem?

In GSM Shield hardware pin’s configuraton are as below:

    0 - Not connected
    1 - Not connected
    2 - GSM Rx
    3 - GSM Tx
    7 - Modem reset

If there is any problem, how can it be solved? I would be happy if there are any alternatives for the GPS shield.

----

### Addendum

The [schematic of the Arduino GSM shield][2]:
![schematic of the Arduino GSM shield][3]

The [schematic of the SparkFun GPS shield][4]:
![schematic of the SparkFun GPS shield][5]

  [1]: https://www.sparkfun.com/products/10709#comment-5366048bce395fa40e8b4567
  [2]: http://arduino.cc/en/uploads/Main/arduino-gsm-shield-schematic.pdf
  [3]: https://i.stack.imgur.com/7ttFF.png
  [4]: https://cdn.sparkfun.com/datasheets/Dev/Arduino/Shields/GPSShield-v16.pdf
  [5]: https://i.stack.imgur.com/zZUxI.png

title: Arduino shield stacking

Answers: 3

body:
From [the shield description][1], the TX and RX of the GPS are mapped on pins 2 & 3, like your GSM, so you'll have to change that.

I'm using Adafruit GPS + flash card shield, which is a bit cheaper (and uses pins 7&8).

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

body:
![enter image description here][1]
<sup>*Photo by [John Boxall](http://tronixstuff.com/)*</sup>

Which pins do they use?
-----------------------

To determine if two shields are compatible, you have to read the specifications of both shields.

The best source for this information is the data sheets supplied with the shields. However there is also this [Shield List](http://shieldlist.org/)

Can you reassign pins?
----------------------

Some shields provide a means to alter which pins are used for communications. This can take the form of a switch or a jumper - either pull-off or solder-bridge type. (the GPS shield in the question has jumpers).

Where the shields do not support pin-reassignment or provides insufficient flexibility, to work-around incompatibilities you can use an in-between shield designed for the purpose.

[here](https://www.sparkfun.com/products/11002) is one example:

> You hear it all the time in the Arduino community, “will this shield work with my other shield?.” I think we’ve all been disappointed to find that two of our favorite shields compete for control of a digital pin here or a serial pin there. While there are sometimes some clever workarounds from elegant code modifications to aggressive ‘greenwiring,’ Mayhew Labs may have come up with the simplest solution thus far: The Go-Between Shield.

Are any alternatives for the foo shield
----

I notice that Arduino.cc now point people to the list referenced above. They used to have their [own list](http://playground.arduino.cc/Main/SimilarBoards#goShie).

Product recommendations are off-topic here but, obviously, you can [search](https://www.google.com/search?q=gps+shield)

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

body:
This answer does not directly address the pin conflict issue, but rather skirts around it.

I have been looking into this same issue for over a month now and have come to the conclusion that the best option is to either [purchase][1], for around $30:

![SIM908 Shield][2]

 or [make][3], for around $20 (+$60 for the modules)

![Modular SIM908/900 shield][4]

 a shield that uses the [SIM908][5]. The SIM908 comes with both GPRS/GSM functionality, and GPS functionality, whereas the SIM900 only has GPRS/GSM. Now, there is no longer an issue with pin conflicts, as instead of two separate shields, only one is required.

The only disadvantage is that if you already have a GPRS/GSM shield, then that purchase will become redundant.

As an aside there is an alternative of a *3G* (**WCDMA** and **HSPA**) and GPS, using both assisted-mobile (A-GPS) and mobile-based (S-GPS) modes, combined shield, from [Cooking Hacks][6]. A bit more pricey though, at $160.

  [1]: http://www.ebay.com/itm/GSM-Phone-Module-GSM-GSM-GPRS-Arduino-Shield-Based-on-Quad-band-SIM908-Module-/251665851830
  [2]: https://i.stack.imgur.com/1yOw5.jpg
  [3]: http://www.open-electronics.org/gsm-gps-shield-for-arduino/
  [4]: https://i.stack.imgur.com/sEc4n.jpg
  [5]: http://wm.sim.com/producten.aspx?id=1024
  [6]: http://www.cooking-hacks.com/documentation/tutorials/arduino-3g-gprs-gsm-gps


body:
I am communicating with the Web server's database via Arduino GSM shield + GPRS connectivity

    void loop()
    {
      if (client.connect(server, port))
         {
           .......
          }
      else
         {
          Serial.println("Server not found");
          }
      delay(1000);
    }

The first time when the loop() runs in the serial port, the code works perfectly and stores in my server's db. The second time when the loop() runs after some delay, It is unable to connect to the server and results "server not found" . I don't know what is the problem.

Please let me know if there is a way to connect continuously. Thank you

title: client.connect() fails except the first time

Answers: 3

body:
You have to disconnect before being able to connect again otherwise the controller will crash due to memory starvation. Every connect you do takes some memory to register state information. Not sure of the exact commands involved, but it'd look a bit like this:

       if (client.connect(server, port))
         {
           .......
           client.disconnect( .... );
          }
      else
    ........

Alternatively you can check if you are already connected, and only do a reconnect when necessary, but I don't know which library you are using, let alone if there is a proper check available in it.

body:
    void loop()
    {
     if (client.connect(server, port))
     {
       .......

       client.stop();
      }

     else
     {
      Serial.println("Server not found");
      }
     delay(1000);
     }

body:
If possible, do a check, if it's still connected with the server. Close the connection when work is done. You might also keep using the open connection, just try whatever works best for you.

But avoid opening a second connection, when you still have an open one. As an example:

    void loop()
    {
        if(!client.connected())
        {
            if (client.connect(server, port))
            {
                ...
                client.disconnect();
            }
            else
                Serial.println("Server not found");
        }
        else
            client.disconnect();
        delay(1000);
    }


body:
So, when searching for a way to play audio files through the Arduino, I came across this site: [How to play WAV audio files with Arduino Uno and MicroSD card][1]

This seems like a really good library (although I haven't had the time to really play around with it yet). Has anyone used this before, and, if so, is it a good library to use, or do you know of better ones out there which you would recommend?

  [1]: http://maxoffsky.com/maxoffsky-blog/how-to-play-wav-audio-files-with-arduino-uno-and-microsd-card/

title: Playing audio files with sine wave from arduino

Answers: 1

body:
I used some time ago the TMRPCM library that the tutorial you linked used and I was very satisfied.

It doesn't take too much space and it has some really unique and neat features like the possibility to use two speakers instead of one to reproduce stereo audio (Unfortunately you need a more powerful AVR IC, surely not an UNO board/328 IC for this feature if you don't want to occur in bad reproduction)

From [GitHub's wiki][1]:

> All 328 based boards: Arduino Uno, Nano, Duemilanove, etc
>
> Mega Types: 1280, 2560, etc
>
> No Due support currently.

You can only have WAV files on the SD but they can be very large (other libraries limit you to a specific maximum size/duration) and you need to connect the SD to the arduino via SPI (as far as I know it is the only way to communicate directly with an SD card).

Also, you will need to convert the files to 8 bit WAV (so it's faster and easier for the arduino to reproduce the sound) with sample rate from 8 to 32khz, mono audio.

Be careful just because you'll need to power the SD with 3.3 volts otherwise you'll fry the entire card.

> Most of the extra features require more memory, more program space, and in some cases, more processing power for playback Some of them are still being fine tuned. Please keep this in mind when enabling these features.

If you want to take a look, [go to this page][2] for more informations on the advanced features

A last thing that I have to say is that the functions are really straightforward:

    TMRpcm audio;
    audio.play("filename");    plays a file
    audio.play("filename",30); plays a file starting at 30 seconds into the track
    audio.speakerPin = 11;     set to 5,6,11 or 46 for Mega, 9 for Uno, Nano, etc.
    audio.disable();           disables the timer on output pin and stops the music
    audio.stopPlayback();      stops the music, but leaves the timer running
    audio.isPlaying();         returns 1 if music playing, 0 if not
    audio.pause();             pauses/unpauses playback
    audio.quality(1);          Set 1 for 2x oversampling
    audio.volume(0);           1(up) or 0(down) to control volume
    audio.setVolume(0);        0 to 7. Set volume level
    audio.loop(1);             0 or 1. Can be changed during playback for full control of looping.

  [1]: https://github.com/TMRh20/TMRpcm/wiki
  [2]: https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features