text:
Understanding the relationship of Pulse and Stepper RPM
This may be a better question for the Physics StackExchange 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

I wonder if this generates a proper pulse. It needs a delay after digitalWrite(PIN, LOW);

There's definitely a clock dependent granularity and additional delay among other potential problems.  For steady rotation, consider using a hardware timer to drive a pin, or failing that trigger an interrupt so that at least the overall rate remains constant.  There should be a fixed factor of step rate as long as the system is operating properly, but there will be both a rate and am acceleration at which it starts skipping steps, especially under load or resonance.

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.

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


text:
Is it possible to transmit Longitude and Latitude via RF433MHz?
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.

Welcome AdiT! I've seen you posted the same question at EE.SE. I would like to let you know that cross-posting across SE sites is not generally a good idea. See this post for more details.

@Ricardo Okay I'm sorry, I didn't know it :)

That's ok. It's just a minor sin :D I just really wanted to let you know. Let's just wait for some answers.

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.

I want to use RF because of I want a longer range. Therefore I'm not using WiFi. I don't understand what do you mean with this "if you manually wired it (3.3V)"? What should I manually wired?

@AdiT Edited post a bit. I meant manually wiring the Xbee module as opposed to a shield to save space/reduce weight. By the way, Xbee is RF. You can get several different distance ranges of Xbee to suit your needs.

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.

You have a point. How else is it possible to transmit the data to smartphone?

@AdiT bluetooth for one

source: Stack Exchange

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

sort: votes


text:
Multiple definition of '__vector_36' (intterupts)
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. 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).
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;
  }
}

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.

I was hoping to prevent editing of core libraries, but I guess there's no other option... Thanks :)

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.

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


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

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:

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?

Although I haven't looked at the source myself, in these types of situations they usually use interrupt timer 1, 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.

(source: bansky.net)

(Source)
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.

So it essentially simulates PWM? What is the point of the digital pins with PWM channels then?

@user1265 More or less... it's using the timers that drive PWM. As far as the point of PWM, IIRC the ATmega328 has circuitry to make PWM more efficient.

@user1265, hardware PWM is "free", i.e. it does not affect the performance of the rest of your program at all (it just ties up a timer, or at least part thereof). Servicing interrupt routines for emulated PWM is comparatively costly. However, in this case, the PWM frequency is only about 50Hz, so this is not overly tragic (Standard Arduino PWM frequency is 31/62kHz, doing PWM for e.g. lighting applications at 50Hz would probably be rather flickery).

What is the point of the digital pins with PWM channels then? - you can get much higher frequencies (up to 8 MHz) and very precise duty cycles. This isn't possible when you are relying upon an interrupt to do this for you.

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


text:
Arduino Uno + Ardumoto + BT robot works from USB but not from baterries
My Arduino UNO board is part of a small robot 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.
I do not have the actual code that is on my Arduino. It must be similar to the code on this page, since I am using their Android app for BT communication with my robot, and it works on USB power supply.

Do you have anything in your code that says while (!Serial); inside setup()?

what happens when you plug in the battery plug? any LEDS on the arduino light up?

Does the basic "blink" example work? If not, then it's hardware. Otherwise, software. A few other things: is battery providing enough current and charged fully? Check both of these with a multimeter. Are you positive that all connections are correct (VIN and ground) and there are no loose connections?

on usb everything works, on bateries dead silence not even a led. to test the basic blink I guess I must replace the current program. I was hoping that I can diagnose the power somehow be fore it bridges with the USB source since that works. Batteries and plug are fine, I only measured the voltage, 7.8 should be ideal right?

Stupid question but you sure the polarity is correct?  The power led should at least light up...  Also, are you using the VIN pin are the power jack... goes to the same place...

Do you have more data about your batteries, and are they fully charged? The current that batteries can provide is super important due to the motors that are part of your circuit.

tx I tried to answer your questions (see the update).

Measure the voltage of your batteries when the led's blink (motor should turn). If you see a significant voltage drop then your batteries are not providing enough current. You can also test this with a dummy load (resistor s should do).

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.

The motor shield also contains the bluetooth slot and everything is powered through Arduino UNO, either through USB or batteries. I only measured the voltage on the source, but I will try to verify the intensity details at the batteries as well as the Arduino output pins.


text:
Arduino Yún console clear
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?

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

authors: webknjaz -- Слава Україні


text:
Communication with two XBee's and Arduinos over serial
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.

I've seen a few posts that include the SoftwareSerial library. Could this help?

Have you tested the modules with X-CTU's terminal to see if you can send something from one module to the other? That would help determining if you have ahardware problem, a configuration problem or a software problem.

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.

I removed the wrong information abou routers.

Yeah I did try that, I ended up just resetting the firmware back to factory settings and only changed the pan ID. For some reason that worked so I guess that's all I had to do.. Thanks for the reply though.


text:
Arduino Serial Communication
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?

My first thought would be that the port speed and settings change back to defaults when you close the IDEs Serial monitor?

This really should go back to stackoverflow, as the problem is with not using the desktop serial configuration APIs.  Basically, you need to set a variety of serial port settings in a compatible way - when you (somewhat dangerously) "share" the port you inherit those set by the serial monitor, until it sets them back on exit.  You may be able to use a command line stty program to discover how the serial monitor is setting the port.

How are you opening the serial port when you communicate "through terminal" ?  It's application dependant whether the serial port settings are restored to their original state when the port is closed.  From your result it seems like the Arduino IDE is restoring them (which is best practise).

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!


text:
Can Arduino Mega2560 Use this 24VDC Relay?
Can a Arduino MEGA 2560 R3 provide enough current out of its pin to activate the Songle srd-24vdc-sl-c relay? Will powering the Arduino with an external power supply help?

Please avoid proving links (for the datasheet) that will require people to download and run an executable for viewing, it's the open door for virus and spams! I have found the same datasheet as PDF here: http://www.datasheet4u.com/download_new.php?id=720559

possible duplicate of How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino?

I don't consider this question a duplicate as the problem here is voltage-related in fact. However, the solutions may be similar.

As I know there is a 5Vdc one from the same manufacturer....

The 5V relay is a better/simpler option, but still requires an extra transistor (and flyback diode) to switch the relay current.

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 transistor between the Arduino pin and the relay. A MOSFET is often used in so-called Solid State Relay (SSR) 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 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.

No, a MOSFET is never called an SSR, these are entirely different devices. A MOSFET has no galvanic separation between input and "output".

Well according to wikipedia (http://en.wikipedia.org/wiki/Solid-state_relay), it's not obvious an SSR has to provide galvanic separation. Also, it mentions a "A SSR based on a single MOSFET, ..., works well for DC loads.". I think we might argue about it, but I admit that provided SSR examples don't look like MOSFET :-) I'll update my answer.

I had a chat at EE.SE and apparently a single MOSFET called SSR is uncommon, but it does sometimes appear in literature.


text:
Getting the contacts/ storing contacts to SIM card
I have the GSM shield and is there any ways to get the stored contacts on the SIM card? It seems that the GSM library 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).

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

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.
#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()
{

}


text:
IR controlled light dimmer
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????

Need to provide some code, libraries and description of the IO used. It is likely that is a conflict.

Add links to the circuit diagram and spec sheet of both zero crossing detector and IR-receiver.

Without looking at the code, it seems like you have a loop somewhere and the code can't get pass that loop at the right time so an event isn't registered by the code and it's "missed."

Can you clarify the sentence "my IR receiver stops working and zero crossing interrupt is not detected": how do you know that concretely, did you add some traces to show what happens?

www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit..study this instructable, I successfully implement IR remote and Light dimming by following his second option which doesn't use interrupt..

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.

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.

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


text:
How to write makefile-compatible sketches?
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 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 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.

Thus question is way beyond my knowledge, but some things you'd have to consider is the include of the Arduino.h file. Incorporating the bootloader; and whatever else. I'll be following this question :)

I'd suggest you take a look at Arduino-CMake (https://github.com/queezythegreat/arduino-cmake).

http://inotool.org/

You can't write a "program" that is considered valid by both the IDE and G++ directly unless you're willing to make a number of sacrifices. Deal with Ino.

Found my answer here, in the comments of the attached makefile.

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.

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

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.
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: Classes and objects: how many and which file types do I actually need to use them?


text:
Sketches not uploading to Micro from Ubuntu 14.04
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.

I just successfully compiled and uploaded the blink sketch to a Mega on 14.04, so the update shouldn't be an issue. Are you using the correct serial interface and board type?

Unplug Arduino; type sudo dmesg -c; clear. Plug in Arduino, wait a couple seconds, then type dmesg and copy the output into your question. Also add the output for lsusb to your question.

@jippie how do you determine the correct serial interface?

It is in the dmesg output that you get when following above hint.

@jippie thanks for helping. not near the board at this time but i'll try and comment in a bit

lsusb is also useful (you may need to apt-get it first). It lists all currently connected USB devices. You should see the arduino there when you connect it (it may be called "FTDI Device" (the serial interface device) though)..

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.

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.


text:
Simple Script controlled by Raspberry not working
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).

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.

Have you also tried other rates that worked (or not) between 9600 and 115200 bauds?

That is weird. Anyone know why that's happening?


text:
Reverse turning of Stepper motor
I have a stepper motor connected to my Arduino like this using the ULN2003A Darlington Array:

(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.

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

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
}

Thanks about the semicolon, I was copying out my code in a rush. Also, I've tried a negative number of steps but it doesn't work.

@user12321 I'm not quite sure. Does it compile? This page says that a negative number will go the other way. All I can say is to make sure you copied all of the code right. I can't tell what "doesn't work" means.

Well it compiles and runs but carries on rotating in the same direction

I found the solution at the here: forum.arduino.cc/index.php?PHPSESSID=kvi8dt2b5en5hhk02dlmjrotl5&topic=143276.msg109779#msg109779. I had the wires the wrong way round.

@user Does the negative work then?

Yeah, it works like a dream!


text:
Adding devices makes I2C read 0
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.

The best way to diagnose I2C problems is to look at the signals with a scope. Then you can see whether the slaves are acknowledging the master's commands, check each sensor address and all. Can you do that and post the shot? Also, schematics would help a lot.

Another guess is that maybe you should remove one set of pullups from one of the boards. But that would probably damage it, so think carefully about it.

@Ricardo unforunately, I'm in high school and don't have access to a scope. can I ask how removing a set of pullups might resolve the issue?

Well, I was just guessing. As I said, without a scope, there's no way of knowing what's going on. But I read somewhere that each I2C module comes with its own set of pullups. Then, if you place too many of them on a bus, their resistance will divide up, changing the optimal pullup value. So, someone suggested that the modules should come without the pullups, so that one would calculate the optimal pullup resistance of the set of modules and solder it up in one of them (closer to the master I guess).

Somebody else said that it's easier to ship the modules with the pullups and then remove some of them if you combine several modules.

Here it is, the discussion is in this answer to a question of mine. Look at the 3rd comment from the top.

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

OP said it worked with one device


text:
Arduino 1 can somehow support 32-bit audio?
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?

32 bit is high end audio electronics, don't expect to breadboard that with an Arduino at your desk at home. 16 bits is already a serious challenge, even in a professinal setting.

A processor can handle larger numbers one bit or word at a time, though you will soon hit the limit of the number of useful operations per second.  32 bits for a single audio channel is wasteful; limits of physics mean no circuit can be built without a noise level that would make many of them meaningless

First of all,what is the point of this? I'm afraid this is a XY question. 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:

(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.

The tl;dr is right on.  It's not a 10 bit data bus, it's a 10 bit ADC, so the additional bits go 'missing'  before your code ever sees them.  On the other hand, 10bit music might sound 4 times better than most chiptunes :)

@AShelly I'm pretty used to Bose products when I listen to music, so it sounds horrible IMHO :-)

thanks for your reply
I was talking to put an external buffer which "splits" the 32 bits into four groups of 10 and a buffer at the end that joins the 4 groups.
Or as you say, a 32-bit adc from outside, if I used it, arduino still could handle the computing power required to keep 4/5 digital filters together without any problems?

@Mario It really depends on what you're doing with the audio and how often you want to sample. If you don't mind sampling three times a second with external ADC and write directly after, you'll be fine. If you want to have 500 frames using a Uno and a 32 bit ADC and do complex computations, not so good. I'd recommend if you use a 32 bit ADC (not required, but significantly better quality), to use the Arduino Due since it has a 32 bit chip and a better architecture all around.

there is no such thing as a 32-bit adc!


text:
Processing Input
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.

What part are you having problems with? Sending data to Arduino from Processing or parsing data on the Arduino? Your question is very vague. Read up on http://arduino.cc/en/reference/serial

What exactly are you trying to accomplish in your project?  Please be more specific.

I want to enter a pass through processing and if its correct i want to trigger a pin.

Should it be the PC or the arduino which checks the password?  What happens if someone uses their own pc program instead of yours?

Arduino should have to contain the password

What have you done so far? Do you already have the PC-side app (with the password form)? How do you intend to connect the PC to your Arduino: serial/USB, or something else?

If you want the Arduino to contain the password, then a simple solution would be to put all the program logic there - generate a prompt, read input, check it, act on the result.  At that point the PC program can simply be any terminal emulator, written in processing or anything else.

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.

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


text:
Debugging my Stepper Motor Driver circuit
I'm using the Pololu DRV8825 Stepper Motor Driver to control a NEMA 17 Steppermotor with an Arduino Uno.  According to the Pololu website, the circuit should be wired as follows:

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

The Arduino (microcontroller) is powered by a USB cable connected to the computer
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.
I'm using a 9V battery to power the motor.
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

I double checked to make sure that connected stepper wires pairs are properly connected to the "A" pins and "B" pins on the driver.
I tried reversing the A1-A2 pair and B1-B2 pair in all possible combinations.  All combinations produce the same result as above.
I tried increasing the motor power supply to 12V (8 alkaline AA batteries).  The same result occurs.
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).
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:

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?

The direction of the pins shouldn't matter.. it's just saying it may be hard to turn the trimpot with the black plastic part of the headers right up against it so it recommends doing it the way you did it.

@sachleen I presume the trimpot is that tiny circular part that looks like a screw.  Do I need to turn it to adjust the current draw?  If so, how can I tell exactly how much current I'm actually getting?

Yeah it's the circular thing in the top-left of the bottom image (component side up). Not sure if you need to change it. Read the "Current limiting" section of the pololu.com to see how to see what kind of current its drawing.

@sachleen:  Ok. I see.  It says "to measure the current running through a single motor coil without clocking the STEP input".   But I'm not sure what "without clocking the STEP input" means... Do you understand what that means?

I've never used a stepper so I might have no idea what I'm talking about. buuut... See where you do digitalWrite(stp, HIGH); and low? that's clocking it. I think it wants you to leave it high.

I think you should also add digitalWrite(dir, LOW); in your setup(), I don't think it will change anything but it's preferrable to enforce the value you want at the beginning.

Have you tried your circuit without batteries but using a "better" power supply (eg some wall-wart 9V 2A)? That would allow you to ensure this is not a power issue (or the opposite).

This question doesn't really have much of anything to do with arduino, and would be more likely to receive knowledgeable input on EE stackexchange.

@ChrisStratton:  I know.  I was debating posting it there or here.  I wasn't sure if the issue was the arduino sketch, the electrical circuit, or something else.  After the responses, it appears now that the problem is most likely the power supply.  Do you recommend that I delete the question here and repost on the EE SE site?

I don't think it should be deleted, but migration would be a good idea.

Sure, @chrisStratton.  Go ahead and migrate it.

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.

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.

I just tried increasing the delay time to 1000ms (1 second), and still no change in behavior.  I guess I'll have to try batteries that can provide higher amperage.  I looked up my AA batteries and found that they provide about 900 milliamp-hours.  Should I look for batteries that provide at least 1700 milliamp-hours (corresponding to the 1.7amp current draw from the stepper motor)?

@Paul No, this is a common misconception. A mAH means that it has the capacity to release that much power, not that it can release that all at once. Since it's hard to tell the maximum current on most one-time batteries, I'd recommend getting a 9.6V rechargeable "RC battery" that can provide 1.8+A (amps, not amp hours). They can get a bit costly, but you need that much power. Advice: don't try adding rechargeable batteries in series. They're highly dangerous if not perfectly "balanced!"

Please stop giving mistaken advice about batteries.  Most cells can supply a current many times their mAh rating, by a factor of 10 or more (the C rating).  "Balance" is largely a charging concern, and primarily with lithium chemistries - something neither a 9.6v RC pack nor individual 1.2 - 1.5v AA cells utilize.

There is already a 100uF cap shown on the circuit, so why mentioneing that adding a cap is needed?

@Chris By balanced I meant that if you combine two slightly different lithium batteries they can be highly dangerous. From what I can tell, the OP is using standard AA alkaline batteries which I am positive that one can't support two amps at a time. Even if it could, it most likely wont last twenty minutes because of voltage loss in the battery. There is no chip to manage voltage loss. The OP hasn't specified the battery composition they are using, either, so it may be able to supply enough current, if charged enough.

@jfpoilpret Oops, didn't notice that. However, it can't hurt to leave it in there. :)

@AnnonomusPenguin: I am using alkaline batteries.  Perhaps switching to lithium would work better?  I've heard that they can provide more amps...

Do not use lithium - there are real concerns though not quite as erroneously described here.  Alkaline AA's can easily supply 2 amps, though only for a bit less than an hour.  You really should use a power supply.

@Chris Please ping the person you are talking to with @Username so they will get pinged. Anyway, can one AA supply 2A? You have to remember in series that the voltage characteristics are added, but the current characteristics are those of only one battery. I'm concerned that one AA won't be able to provide 1.5V 1.8A, which is what the OP needs.

@Paul Like others have pointed out, the best route as far as I know to debug this further is to get a power supply that can for sure supply the right amount of electricity. You could also use an old PSU for this purpose...

@AnnonomusPenguin - a single AA cell can in fact provide several amps.  One of the real problems with specialist sites such as this is that topics get diverted to a backwater where there's a shortage of actual knowledge and a lot of mistaken information. Also, if you are going to make site usage recommendations, you could start by using someone's actual username in your @ notification - otherwise, you depend on the automatic notification to those in the preceding posts.

@Chris I stand corrected, I must be buying cheap batteries :) Anyway, you only need the first three letters for a ping.

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).

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.

No, you are mistaken.  A common ground is absolutely necessary for this to function, and if you are not getting one there you are probably getting one through the AC wiring.  Whatever cause your overheating was a different issue.  What you have posted here is bad advice.


text:
how does serial port communication work under the hood?
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..

See chapter 19 of the datasheet.

Stackexchange sites are for specific, individual questions.  Please edit your post to ask a single question which can have a specific answer - preferably one you are left with after reading the documentation.

You might find this interesting about buffers on both sides of a Nano connected to a Raspian system running a Python data logger, using just a regular USB programming cable between the two:
https://arduino.stackexchange.com/questions/11710/does-data-came-on-serial-port-store-for-some-time

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.

Thank you for reply. now that i know serial is an object then when does it get initialised ? And, when the interrupts happens, then somehow the code for that interrupt knows about Serial object so that i can play with that ring buffer ?

While there is an interrupt for "transmit complete," that's not the one most libraries would be using to fill the ring buffer. Instead they'd use the "USART Data Register Empty" interrupt to indicate that you can load a new values in the transmit register, which holds the next byte that will be sent after the USART has finished sending the current byte in the shift register. In other words, the interrupt happens when the MCU starts sending a byte, which may be important in some applications. (Section 24.7.3 of the datasheet.)

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().

Note that if the IDE is on a Raspbian, HardwareSerial.cp is located at /usr/share/arduino/hardware/arduino/cores/arduino - go into HardwareSerial.cpp and look at where it detects it has more than 1000 bytes of memory (The Rpi has 2048) and that is where the ring buffer setting is 64.  I haven't found any need to expand it, but it can be done.