body:
It *is* possible to use the Timer0 compare interrupts without affecting the `millis()` and `micros()` functions. Simply set the compare interrupts to occur at 1/3rd and 2/3rds of the overflow period. That way they won't conflict with each other because there will be some time between each of the three interrupts (overflow, compare A and compare B). You can't change the frequency though because that would change the update of `millis()` and `micros()`. Instead, you could use software *post*-scalers within the ISRs, something like this:

```c++
volatile bool     isr_t0a_flag = false;
volatile uint32_t isr_t0a_delta_time = 0;
#define           TIMER_0_COMPARE_A_POST_SCALER 50

volatile bool     isr_t0b_flag = false;
volatile uint32_t isr_t0b_delta_time = 0;
#define           TIMER_0_COMPARE_B_POST_SCALER 100

void setup()
{
  Serial.begin(115200);
  Serial.print("\n\n");

  // Find out what Timer0 has been initialised to.
  Serial.println(TCCR0A);  // 3 = Fast PWM mode with a fixed timeout of 255.
  Serial.println(TCCR0B);  // 3 = 64 prescaler.
  Serial.println(OCR0A);   // 0
  Serial.println(OCR0B);   // 0
  Serial.println(TIMSK0);  // 1 = Timer overflow interrupt enabled for millis()/micros().
  Serial.print("\n\n");

  cli(); // Disable interrupts.

  //
  // Set Timer0 compare interrupts
  //
  // Clock frequency     = 16 MHz
  // Prescaler           = 64
  // Timeout             = 255
  //
  // Overflow interrupt frequency = 16 MHz / 64 / (255 + 1) = 977 Hz (1024 us)
  // Overflow interrupt frequency =  8 MHz / 64 / (255 + 1) = 488 Hz (2048 us)
  //
  OCR0A  = 85;              // Set 1/3rd phase shift for compare A.
  OCR0B  = 171;             // Set 2/3rds phase shift for compare B.
  TIMSK0 |= (1 << OCIE0A);  // Enable compare A interrupt.
  TIMSK0 |= (1 << OCIE0B);  // Enable compare B interrupt.

  sei(); // Enable interrupts.

  // Verification.
  Serial.println(TCCR0A);  // 3   = Fast PWM mode with a fixed timeout of 255.
  Serial.println(TCCR0B);  // 3   = 64 prescaler.
  Serial.println(OCR0A);   // 85  = 1/3rd phase shift for compare A.
  Serial.println(OCR0B);   // 171 = 2/3rds phase shift for compare B.
  Serial.println(TIMSK0);  // 7   = All 3 interrupts enabled.
  Serial.print("\n\n");
}

void loop()
{
  uint32_t t0a_delta_time = 0;
  uint32_t t0b_delta_time = 0;

  ////////////////////////////
  // BEGIN CRITICAL SECTION

  cli();  // Disable interupts.

  bool t0a_flag = isr_t0a_flag;
  if (t0a_flag)
  {
    t0a_delta_time = isr_t0a_delta_time;
    isr_t0a_flag = false;
  }

  bool t0b_flag = isr_t0b_flag;
  if (t0b_flag)
  {
    t0b_delta_time = isr_t0b_delta_time;
    isr_t0b_flag = false;
  }

  sei();  // Enable interrupts.

  // END CRITICAL SECTION
  ////////////////////////////

  if (t0a_flag)
  {
    Serial.print("T0a ");
    Serial.println(t0a_delta_time);
  }

  if (t0b_flag)
  {
    Serial.print("T0b ");
    Serial.println(t0b_delta_time);
  }
}

ISR(TIMER0_COMPA_vect)
{
  static byte count = 0;
  count++;
  if (count >= TIMER_0_COMPARE_A_POST_SCALER)
  {
    count = 0;
    static uint32_t previous_time = 0;
    uint32_t time = micros();
    uint32_t delta_time = time - previous_time;
    previous_time = time;
    isr_t0a_delta_time = delta_time;
    isr_t0a_flag = true;
  }
}

ISR(TIMER0_COMPB_vect)
{
  static byte count = 0;
  count++;
  if (count >= TIMER_0_COMPARE_B_POST_SCALER)
  {
    count = 0;
    static uint32_t previous_time = 0;
    uint32_t time = micros();
    uint32_t delta_time = time - previous_time;
    previous_time = time;
    isr_t0b_delta_time = delta_time;
    isr_t0b_flag = true;
  }
}
```


sender: user

message:
Connecting to network with wifi shield

I just bought a WiFi shield and I cannot connect to my wireless network (WPA2).

- I used the [sketch from the Arduino site](http://arduino.cc/en/Tutorial/ConnectWithWPA) for connecting to WPA network and put my SSID and password on but it doesn't connect (I know the credentials are correct as I used my phone to connect with these WiFi credentials).
- When I read the serial monitor it just keeps trying to connect. The WiFi-shield board error light is red
- I checked my network settings and my block level is at is lowest (NAT only).

**Why can't I connect?**

sender: assistant

body:
In the loop:

    // attempt to connect to Wifi network:
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network:
        status = WiFi.begin(ssid, pass);

        // wait 10 seconds for connection:
        delay(10000);
      }

Can you add ``Serial.print(status);`` before the delay so you can see if any of these arise:

 * WL_IDLE_STATUS = 0
 * WL_NO_SSID_AVAIL
 * WL_CONNECT_FAILED
 * WL_CONNECTION_LOST
 * WL_DISCONNECTED

They are defined in ``wl_definitions.h``


body: I was facing the same issue using the Feather M0 board from Adafruit. After updating the Arduino IDE as well as the IDE's libraries and firmware, I was able to connect to WiFi.


message:
Modifying serial message for Adafruit NFC/RFID card

Using an Uno configured with an Adafruit RFID-NFC shield to send the UID values to a desktop game I am building.

Works fine. However, in addition to just the UID, I need to send 1 additional value, lets call it 'game choice'. This can be one of 3 values. This is just the relevant code. Can any experts suggest how I might modify the following to send this additional value?

    /**************************************************************************/
    #include <Wire.h>
    #include <Adafruit_NFCShield_I2C.h>

    #define IRQ   (2)
    #define RESET (3)  // Not connected by default on the NFC Shield

    Adafruit_NFCShield_I2C nfc(IRQ, RESET);

    void setup(void) {
      Serial.begin(115200);
      Serial.println("Hello!");

      nfc.begin();

      uint32_t versiondata = nfc.getFirmwareVersion();
      if (! versiondata) {
        Serial.print("Didn't find PN53x board");
        while (1); // halt
      }
      // Got ok data, print it out!
      Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
      Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
      Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

      // configure board to read RFID tags
      nfc.SAMConfig();

      Serial.println("init");
    }
    void loop(void) {
      uint8_t success;
      uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
      uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
      int nfcDEC;
      success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

      if (success) {

       nfc.PrintHex(uid, uidLength );
    }
    }

body:
had to simply modify PrintHex in
Adafruit_NFCShield_I2C.h

to accept an additional argument


message:
Pass variable in a URL

I am working on code where I am able to manually enter the value in the URL to let the PHP code save it in the database, but I'm unsure how to do it with a variable in a loop running. This is the URL:

    student.cs.hioa.no/~s180343/updatedb.php?verdi=25

Code:

    void setup() {
      // Initialize Bridge
      Bridge.begin();

      // Initialize Serial
      Serial.begin(9600);

      // Wait until a Serial Monitor is connected.
      while (!Serial);
      Serial.println("Ready");

      // run various example processes

    }

    void loop() {
       runCurl();
       delay(10000);
    }

    void runCurl() {
      // Launch "curl" command and get Arduino ascii art logo from the network
      // curl is command line program for transferring data using different internet protocols
      Process p;        // Create a process and call it "p"
      p.begin("curl");  // Process that launch the "curl" command
      p.addParameter("student.cs.hioa.no/~s180343/updatedb.php?verdi=25"); // Add the URL parameter to "curl"
      p.run();      // Run the process and wait for its termination

      // A process output can be read with the stream methods
      while (p.available()>0) {
        char c = p.read();
        Serial.print(c);
      }
      // Ensure the last bit of data is sent.
      Serial.flush();
    }

body:
You can pass in a variable into a function. Something like this:

    void runCurl(int verdi) {
        ...
        String myUrl = "student.cs.hioa.no/~s180343/updatedb.php?verdi=";
        myUrl += verdi;
        p.addParameter(myUrl);
        ...
    }

You call the function like this, now:

    runCurl(1);
    runCurl(2);
    runCurl(someVar);

and so on. Since it's already in your main `loop()` function, you just need to set pass in a different number based on whatever it is you're trying to do.


body:
first of all, you declare your `buffer` as a string of 50 characters, but

    student.cs.hioa.no/~s180343/updatedb.php?verdi=

is already 48, and you start your value at 1200 and increments over that, so basically

    sprintf (buffer, "student.cs.hioa.no/~s180343/updatedb.php?verdi=%d", val)

will create a buffer of 53 characters (52 characters + `\0`).

Secondly, it's always a better idea to give the *full* URL to a program such as curl, as it might work but may give unexpected results as well if you do not provide the protocol… `curl` could legally assume you want `ftp` or `gopher` to access that address!

    http://student.cs.hioa.no/~s180343/updatedb.php?verdi=%d

Third, here's how you setup and use your `val` variable:

    int val=1200;
    sprintf (…, "…", val);
    val++;

so once you've reached `32767` your int is overflowing, getting back to `-32,768`.

Oh, and by the way, it is good practice on a Q&A site such as Stack Overflow to actually *ask* a question and say what your problem is. All my hints here are insights based on reading your flawed code.

HTH


body:
Alright. I'm assuming you mean that you need the last part of the url varied from, say 1 to 100. Like Java, Processing, and, by extension, Arduino, allow you to add an integer to a String to get a String. I haven't tested this out, but it should work:

    #include <Process.h>
    #define MIN 0
    #define MAX 100

    int i;

    void setup() {
      i = MIN;

      // Initialize Bridge
      Bridge.begin();

      // Initialize Serial
      Serial.begin(9600);

      // Wait until a Serial Monitor is connected.
      while (!Serial);
      Serial.println("Ready");

      // run various example processes

    }

    void loop() {
       if (i<=MAX) {
         runCurl();
         i = i+1;
       }
       delay(10000);
    }

    void runCurl() {
      // Launch "curl" command and get Arduino ascii art logo from the network
      // curl is command line program for transferring data using different internet protocols
      Process p;        // Create a process and call it "p"
      p.begin("curl");  // Process that launch the "curl" command
      String myUrl = "student.cs.hioa.no/~s180343/updatedb.php?verdi=";
      p.addParameter(myUrl+i); // Add the URL parameter to "curl"
      p.run();      // Run the process and wait for its termination

      // A process output can be read with the stream methods
      while (p.available()>0) {
        char c = p.read();
        Serial.print(c);
      }
      // Ensure the last bit of data is sent.
      Serial.flush();
    }


message:
Change Options for the AVR Programmer via Arduino IDE

I want to program an ATtiny through the Arduino IDE. I have a somehow strange programmer. But I can upload via avrdude by

>avrdude -p attiny13 -P /dev/cu.usbmodemfa131     -c stk500v2    -F -B20 -U flash:w:programm.hex

It took a while to figure out that I had to slow the baud rate via the -B20 switch. If I try to upload via the arduino 1.0.5 IDE avrdude is executed as follows.

> /Applications/Adafruit Arduino 1.0.5.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -C/Applications/Adafruit Arduino 1.0.5.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -pattiny13 -cstk500v1 -P/dev/tty.usbmodemfa131 -Uflash:w:/var/folders/9t/5jldfq752fs1x74_rhn2plz80000gn/T/build7680201613426497544.tmp/attinytest.cpp.hex:i

My question is, how can I change the preferences such that I have control over the avrdude parameters? Say I want to add a -B20 switch and change stk500v1 to stk500v2.

body:
**Short answer**: I'm afraid you can't do it with Arduino IDE 1.0.5.

**Long answer**:

First of all, be aware that `-B20` does not specify the baud rate but the bitclock period (in us); this is specific to `stk500v2` programmer.

Normally, enabling your programmer should only be a matter of adding it to the list of programmers known by Arduino IDE; that list can be found in `hardware/arduino/programmers.txt`. You would then append the following lines at the end of this file:

    strangeprogrammer.name=Somehow Strange Programmer
    strangeprogrammer.communication=serial
    strangeprogrammer.protocol=stk500v2
    strangeprogrammer.force=true
    strangeprogrammer.speed=?????

However, the problem here is that Arduino IDE does not seem to be able to use flag `-B` (bitclock period) but only flag `-b` (baud rate) which value is set to whatever you will put to `strangeprogrammer.speed`.

At least that's what I could find out by inspecting Arduino IDE source code: `AvrdudeUploader.java` never adds that flag to the `avrdude` command-line :-(

That means your options are:

1. Rebuild the Arduino IDE 1.0 on your own after modifying `AvrdudeUploader.java` to support `-B` flag; code should be quite easy (about 2 more lines of Java code).

2. Switch to Arduino IDE 1.5 and follow [Federico's answer][1] :-)

3. Use another IDE, something that deserves the **IDE** name. I use Eclipse with this [Arduino plugin][2] and it works fine for me. As a bonus, avrdude support seems better as you can see on the screenshot below:

![enter image description here][3]

  [1]: https://arduino.stackexchange.com/questions/1075/change-options-for-the-avr-programmer-via-arduino-ide/1077#1077
  [2]: http://eclipse.baeyens.it/UsethePlugin.html
  [3]: https://i.stack.imgur.com/gUqsS.png


message:
Arduino Lego Robot

I'm currently developing a Lego Robot, the mindstorm series to be specific. I want to replace the lego NXT brick with an arduino, maybe an intel galileo in the future. How do I establish connections from the arduino with the lego sensors? Also, I would like some input on any cool features that I can add to this robot. This robot is to be seen as a human companion. Thanks in advance.

An example of a sensor i would like to use is here : http://www.hitechnic.com/cgi-bin/commerce.cgi?preadd=action&key=NIS1070

How do I interface this with an arduino?

body:
Doing a quick search on google you can find a couple of shields designed for that purpose:

 * [NXShield-Dx][1]
 * [Bricktronics shield][2]

Second one is allows less motor connections but it's cheaper and has a [book][3] written by the designers

  [1]: http://www.robotshop.com/en/arduino-lego-mindstorms-shield-nxshield-d.html
  [2]: https://store.wayneandlayne.com/products/bricktronics-shield-kit.html
  [3]: http://shop.oreilly.com/product/0636920024316.do


message:
Response of Modbus Protocol

I have the below code. This code is successfully compiling and uploading, but I am not getting any response from Slave. What do I need to do?

![Error message][1]

![Connection diagram][2]

Some time data being received from Slave (I get this error):
![error2][3]

My main code:

    #define ID  1
    /*static float ARDUINO_ANALOG_SCALING = 0.00488758;
    static float Ydegree;
    static int Sensor_Value;
    float Yvoltage;

    */

    Modbus slave(ID, 0, 0);
    boolean led;
    int8_t state = 0;
    unsigned long tempus;
    // data array for modbus network sharing
    uint16_t au16data[9];
    float latitude=13.08;

    void setup() {
      pinMode(13, OUTPUT);
      slave.begin( 19200 );
      tempus = millis() + 100;
      digitalWrite(13, HIGH );
    }

    void loop() {

      state = slave.poll( au16data, 9 );
      if (state > 4) {
        tempus = millis() + 50;
        digitalWrite(13, HIGH);
      }
      if (millis() > tempus) digitalWrite(13, LOW );

      au16data[4] = analogRead(0);
      au16data[5] = analogRead(1);

      au16data[6] = slave.getInCnt();
      au16data[7] = slave.getOutCnt();
      au16data[8] = slave.getErrCnt();
    }

Modbus code:

    #define  MAX_BUFFER  64
    typedef struct {
      uint8_t u8id;          /*!< slave address between 1 and 247. 0 means broadcast */
      uint8_t u8fct;         /*!< function code: 1, 2, 3, 4, 5, 6, 15 or 16 */
      uint16_t u16RegAdd;    /*!< address of the first register to access at slave/s */
      uint16_t u16CoilsNo;   /*!< number of coils or registers to access */
      uint16_t *au16reg;     /*!< pointer to memory image in master */
    }
    modbus_t;

    enum {
      RESPONSE_SIZE = 6,
      EXCEPTION_SIZE = 3,
      CHECKSUM_SIZE = 2
    };

    enum MESSAGE {
      ID = 0,
      FUNC,
      ADD_HI,
      ADD_LO,
      NB_HI,
      NB_LO,
      BYTE_CNT
    };

    enum MB_FC {
      MB_FC_NONE                     = 0,   /*!< null operator */
      MB_FC_READ_COILS               = 1, /*!< FCT=1 -> read coils or digital outputs */
      MB_FC_READ_DISCRETE_INPUT      = 2, /*!< FCT=2 -> read digital inputs */
      MB_FC_READ_REGISTERS           = 3, /*!< FCT=3 -> read registers or analog outputs */
      MB_FC_READ_INPUT_REGISTER      = 4, /*!< FCT=4 -> read analog inputs */
      MB_FC_WRITE_COIL               = 5, /*!< FCT=5 -> write single coil or output */
      MB_FC_WRITE_REGISTER           = 6, /*!< FCT=6 -> write single register */
      MB_FC_WRITE_MULTIPLE_COILS     = 15, /*!< FCT=15 -> write multiple coils or outputs */
      MB_FC_WRITE_MULTIPLE_REGISTERS = 16 /*!< FCT=16 -> write multiple registers */
    };

    enum COM_STATES {
      COM_IDLE                     = 0,
      COM_WAITING                  = 1

    };

    enum ERR_LIST {
      ERR_NOT_MASTER                = -1,
      ERR_POLLING                   = -2,
      ERR_BUFF_OVERFLOW             = -3,
      ERR_BAD_CRC                   = -4,
      ERR_EXCEPTION                 = -5
    };

    enum {
      NO_REPLY = 255,    /*!< */
      EXC_FUNC_CODE = 1,  /*!< Function code not available */
      EXC_ADDR_RANGE = 2,   /*!< Address beyond available space for Modbus registers */
      EXC_REGS_QUANT = 3,    /*!< Coils or registers number beyond the available space */
      EXC_EXECUTE = 4    /*!< */
    };

    const unsigned char fctsupported[] = {
      MB_FC_READ_COILS,
      MB_FC_READ_DISCRETE_INPUT,
      MB_FC_READ_REGISTERS,
      MB_FC_READ_INPUT_REGISTER,
      MB_FC_WRITE_COIL,
      MB_FC_WRITE_REGISTER,
      MB_FC_WRITE_MULTIPLE_COILS,
      MB_FC_WRITE_MULTIPLE_REGISTERS
    };

    #define T35  5

    class Modbus {
    private:
      HardwareSerial *port; //!< Pointer to Serial class object
      uint8_t u8id; //!<0=master, 1..247=slave number
      uint8_t u8serno; //!<serial port: 0-Serial, 1..3-Serial1..Serial3
      uint8_t u8txenpin; //!<flow control pin: 0=USB or RS-232 mode, >0=RS-485 mode
      uint8_t u8state;
      uint8_t au8Buffer[MAX_BUFFER];
      uint8_t u8BufferSize;
      uint8_t u8lastRec;
      uint16_t *au16regs;
      uint16_t u16InCnt, u16OutCnt, u16errCnt;
      uint16_t u16timeOut;
      uint32_t u32time, u32timeOut;
      uint8_t u8regsize;

      void init(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin);
      void sendTxBuffer(); // transmit buffer to serial port
      int8_t getRxBuffer(); // get serial buffer contents
      uint16_t calcCRC(uint8_t u8length); // get CRC from au8Buffer until u8length
      uint8_t validateAnswer();
      uint8_t validateRequest(); // validate master request
      void get_FC1(); // *** only master ***
      void get_FC3(); // *** only master ***
      int8_t process_FC1( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
      int8_t process_FC3( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
      int8_t process_FC5( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
      int8_t process_FC6( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
      int8_t process_FC15( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
      int8_t process_FC16( uint16_t *regs, uint8_t u8size ); //!< *** only slave ***
      void buildException( uint8_t u8exception ); // build exception message

    public:
      Modbus(); // !< Default Constructor
      Modbus(uint8_t u8id, uint8_t u8serno); // !< Constructor
      Modbus(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin); // !< Full Constructor
      void begin(long u32speed);
      void begin();
      void setTimeOut( uint16_t u16timeout); //!< write communication watch-dog timer
      uint16_t getTimeOut(); //!< get communication watch-dog timer value
      boolean getTimeOutState(); //!< get communication watch-dog timer state
      int8_t query( modbus_t telegram ); //!< only for master
      int8_t poll(); //!< cyclic poll for master
      int8_t poll( uint16_t *regs, uint8_t u8size ); //!< cyclic poll for slave
      uint16_t getInCnt(); //!< number of incoming messages
      uint16_t getOutCnt(); //!< number of outcoming messages
      uint16_t getErrCnt(); //!< error counter
      uint8_t getID(); //!< get slave ID between 1 and 247
      uint8_t getState();
      uint8_t getLastError(); //!< get last error message
      void setID( uint8_t u8id ); //!< write new ID for the slave
      void end(); //!< finish any communication and release serial communication port
    };

    Modbus::Modbus() {
      init(0, 0, 0);
    }

    Modbus::Modbus(uint8_t u8id, uint8_t u8serno) {
      init(u8id, u8serno, 0);
    }

    Modbus::Modbus(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin) {
      init(u8id, u8serno, u8txenpin);
    }

    void Modbus::begin(long u32speed) {

      switch ( u8serno ) {
    #if defined(UBRR1H)
      case 1:
        port = &Serial1;
        break;
    #endif

    #if defined(UBRR2H)
      case 2:
        port = &Serial2;
        break;
    #endif

    #if defined(UBRR3H)
      case 3:
        port = &Serial3;
        break;
    #endif
      case 0:
      default:
        port = &Serial;
        break;
      }

      // port->begin(u32speed, u8config);
      port->begin(u32speed);
      if (u8txenpin > 1) { // pin 0 & pin 1 are reserved for RX/TX
        // return RS485 transceiver to transmit mode
        pinMode(u8txenpin, OUTPUT);
        digitalWrite(u8txenpin, LOW);
      }

      port->flush();
      u8lastRec = u8BufferSize = 0;
      u16InCnt = u16OutCnt = u16errCnt = 0;
    }

    void Modbus::begin() {
      begin(19200);
    }

    void Modbus::setID( uint8_t u8id) {
      if (( u8id != 0) && (u8id <= 247)) {
        this->u8id = u8id;
      }
    }

    uint8_t Modbus::getID() {
      return this->u8id;
    }

    void Modbus::setTimeOut( uint16_t u16timeOut) {
      this->u16timeOut = u16timeOut;
    }

    boolean Modbus::getTimeOutState() {
      return (millis() > u32timeOut);
    }

    uint16_t Modbus::getInCnt() {
      return u16InCnt;
    }

    uint16_t Modbus::getOutCnt() {
      return u16OutCnt;
    }

    uint16_t Modbus::getErrCnt() {
      return u16errCnt;
    }

    uint8_t Modbus::getState() {
      return u8state;
    }

    int8_t Modbus::query( modbus_t telegram ) {
      uint8_t u8regsno, u8bytesno;
      if (u8id != 0) return -2;
      if (u8state != COM_IDLE) return -1;

      if ((telegram.u8id == 0) || (telegram.u8id > 247)) return -3;

      au16regs = telegram.au16reg;

      // telegram header
      au8Buffer[ ID ]         = telegram.u8id;
      au8Buffer[ FUNC ]       = telegram.u8fct;
      au8Buffer[ ADD_HI ]     = highByte(telegram.u16RegAdd );
      au8Buffer[ ADD_LO ]     = lowByte( telegram.u16RegAdd );

      switch ( telegram.u8fct ) {
      case MB_FC_READ_COILS:
      case MB_FC_READ_DISCRETE_INPUT:
      case MB_FC_READ_REGISTERS:
      case MB_FC_READ_INPUT_REGISTER:
        au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
        au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
        u8BufferSize = 6;
        break;
      case MB_FC_WRITE_COIL:
        au8Buffer[ NB_HI ]      = ((au16regs[0] > 0) ? 0xff : 0);
        au8Buffer[ NB_LO ]      = 0;
        u8BufferSize = 6;
        break;
      case MB_FC_WRITE_REGISTER:
        au8Buffer[ NB_HI ]      = highByte(au16regs[0]);
        au8Buffer[ NB_LO ]      = lowByte(au16regs[0]);
        u8BufferSize = 6;
        break;
      case MB_FC_WRITE_MULTIPLE_COILS:
        u8regsno = telegram.u16CoilsNo / 16;
        u8bytesno = u8regsno * 2;
        if ((telegram.u16CoilsNo % 16) != 0) {
          u8bytesno++;
          u8regsno++;
        }

        au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
        au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
        au8Buffer[ NB_LO + 1 ]    = u8bytesno;
        u8BufferSize = 7;

        u8regsno = u8bytesno = 0; // now auxiliary registers
        for (uint16_t i = 0; i < telegram.u16CoilsNo; i++) {

        }
        break;

      case MB_FC_WRITE_MULTIPLE_REGISTERS:
        au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
        au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
        au8Buffer[ NB_LO + 1 ]    = (uint8_t) ( telegram.u16CoilsNo * 2 );
        u8BufferSize = 7;

        for (uint16_t i = 0; i < telegram.u16CoilsNo; i++) {
          au8Buffer[ u8BufferSize ] = highByte( au16regs[ i ] );
          u8BufferSize++;
          au8Buffer[ u8BufferSize ] = lowByte( au16regs[ i ] );
          u8BufferSize++;
        }
        break;
      }

      sendTxBuffer();
      u8state = COM_WAITING;
      return 0;
    }

    int8_t Modbus::poll() {
      // check if there is any incoming frame
      uint8_t u8current = port->available();

      if (millis() > u32timeOut) {
        u8state = COM_IDLE;
        u16errCnt++;
        return 0;
      }

      if (u8current == 0) return 0;

      // check T35 after frame end or still no frame end
      if (u8current != u8lastRec) {
        u8lastRec = u8current;
        u32time = millis() + T35;
        return 0;
      }
      if (millis() < u32time) return 0;

      // transfer Serial buffer frame to auBuffer
      u8lastRec = 0;
      int8_t i8state = getRxBuffer();
      if (i8state < 7) {
        u8state = COM_IDLE;
        u16errCnt++;
        return i8state;
      }

      // validate message: id, CRC, FCT, exception
      uint8_t u8exception = validateAnswer();
      if (u8exception != 0) {
        u8state = COM_IDLE;
        return u8exception;
      }

      // process answer
      switch ( au8Buffer[ FUNC ] ) {
      case MB_FC_READ_COILS:
      case MB_FC_READ_DISCRETE_INPUT:
        // call get_FC1 to transfer the incoming message to au16regs buffer
        get_FC1( );
        break;
      case MB_FC_READ_INPUT_REGISTER:
      case MB_FC_READ_REGISTERS :
        // call get_FC3 to transfer the incoming message to au16regs buffer
        get_FC3( );
        break;
      case MB_FC_WRITE_COIL:
      case MB_FC_WRITE_REGISTER :
      case MB_FC_WRITE_MULTIPLE_COILS:
      case MB_FC_WRITE_MULTIPLE_REGISTERS :
        // nothing to do
        break;
      default:
        break;
      }
      u8state = COM_IDLE;
      return u8BufferSize;
    }

    int8_t Modbus::poll( uint16_t *regs, uint8_t u8size ) {

      au16regs = regs;
      u8regsize = u8size;

      // check if there is any incoming frame
      uint8_t u8current = port->available();
      if (u8current == 0) return 0;

      // check T35 after frame end or still no frame end
      if (u8current != u8lastRec) {
        u8lastRec = u8current;
        u32time = millis() + T35;
        return 0;
      }
      if (millis() < u32time) return 0;

      u8lastRec = 0;
      int8_t i8state = getRxBuffer();
      if (i8state < 7) return i8state;

      // check slave id
      if (au8Buffer[ ID ] != u8id) return 0;

      // validate message: CRC, FCT, address and size
      uint8_t u8exception = validateRequest();
      if (u8exception > 0) {
        if (u8exception != NO_REPLY) {
          buildException( u8exception );
          sendTxBuffer();
        }
        return u8exception;
      }

      u32timeOut = millis() + long(u16timeOut);

      // process message
      switch ( au8Buffer[ FUNC ] ) {
      case MB_FC_READ_COILS:
      case MB_FC_READ_DISCRETE_INPUT:
        return process_FC1( regs, u8size );
        break;
      case MB_FC_READ_INPUT_REGISTER:
      case MB_FC_READ_REGISTERS :
        return process_FC3( regs, u8size );
        break;
      case MB_FC_WRITE_COIL:
        return process_FC5( regs, u8size );
        break;
      case MB_FC_WRITE_REGISTER :
        return process_FC6( regs, u8size );
        break;
      case MB_FC_WRITE_MULTIPLE_COILS:
        return process_FC15( regs, u8size );
        break;
      case MB_FC_WRITE_MULTIPLE_REGISTERS :
        return process_FC16( regs, u8size );
        break;
      default:
        break;
      }
    }

    /* _____PRIVATE FUNCTIONS_____________________________________________________ */

    void Modbus::init(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin) {
      this->u8id = u8id;
      this->u8serno = (u8serno > 3) ? 0 : u8serno;
      this->u8txenpin = u8txenpin;
      this->u16timeOut = 1000;
    }

    int8_t Modbus::getRxBuffer() {
      boolean bBuffOverflow = false;

      if (u8txenpin > 1) digitalWrite( u8txenpin, LOW );

      u8BufferSize = 0;
      while ( port->available() ) {
        au8Buffer[ u8BufferSize ] = port->read();
        u8BufferSize ++;

        if (u8BufferSize >= MAX_BUFFER) bBuffOverflow = true;
      }
      u16InCnt++;

      if (bBuffOverflow) {
        u16errCnt++;
        return ERR_BUFF_OVERFLOW;
      }
      return u8BufferSize;
    }

    void Modbus::sendTxBuffer() {
      uint8_t i = 0;

      // append CRC to message
      uint16_t u16crc = calcCRC( u8BufferSize );
      au8Buffer[ u8BufferSize ] = u16crc >> 8;
      u8BufferSize++;
      au8Buffer[ u8BufferSize ] = u16crc & 0x00ff;
      u8BufferSize++;

      // set RS485 transceiver to transmit mode
      if (u8txenpin > 1) {
        switch ( u8serno ) {
    #if defined(UBRR1H)
        case 1:
          UCSR1A = UCSR1A | (1 << TXC1);
          break;
    #endif

    #if defined(UBRR2H)
        case 2:
          UCSR2A = UCSR2A | (1 << TXC2);
          break;
    #endif

    #if defined(UBRR3H)
        case 3:
          UCSR3A = UCSR3A | (1 << TXC3);
          break;
    #endif
        case 0:
        default:
          UCSR0A = UCSR0A | (1 << TXC0);
          break;
        }
        digitalWrite( u8txenpin, HIGH );
      }

      // transfer buffer to serial line
      port->write( au8Buffer, u8BufferSize );

      // keep RS485 transceiver in transmit mode as long as sending
      if (u8txenpin > 1) {
        switch ( u8serno ) {
    #if defined(UBRR1H)
        case 1:
          while (!(UCSR1A & (1 << TXC1)));
          break;
    #endif

    #if defined(UBRR2H)
        case 2:
          while (!(UCSR2A & (1 << TXC2)));
          break;
    #endif

    #if defined(UBRR3H)
        case 3:
          while (!(UCSR3A & (1 << TXC3)));
          break;
    #endif
        case 0:
        default:
          while (!(UCSR0A & (1 << TXC0)));
          break;
        }

        // return RS485 transceiver to receive mode
        digitalWrite( u8txenpin, LOW );
      }
      port->flush();
      u8BufferSize = 0;

      // set time-out for master
      u32timeOut = millis() + (unsigned long) u16timeOut;

      // increase message counter
      u16OutCnt++;
    }

    /**
     * @brief
     * This method calculates CRC
     *
     * @return uint16_t calculated CRC value for the message
     * @ingroup buffer
     */
    uint16_t Modbus::calcCRC(uint8_t u8length) {
      unsigned int temp, temp2, flag;
      temp = 0xFFFF;
      for (unsigned char i = 0; i < u8length; i++) {
        temp = temp ^ au8Buffer[i];
        for (unsigned char j = 1; j <= 8; j++) {
          flag = temp & 0x0001;
          temp >>= 1;
          if (flag)
            temp ^= 0xA001;
        }
      }
      // Reverse byte order.
      temp2 = temp >> 8;
      temp = (temp << 8) | temp2;
      temp &= 0xFFFF;
      // the returned value is already swapped
      // crcLo byte is first & crcHi byte is last
      return temp;
    }

    uint8_t Modbus::validateRequest() {
      // check message crc vs calculated crc
      uint16_t u16MsgCRC =
        ((au8Buffer[u8BufferSize - 2] << 8)
        | au8Buffer[u8BufferSize - 1]); // combine the crc Low & High bytes
      if ( calcCRC( u8BufferSize - 2 ) != u16MsgCRC ) {
        u16errCnt ++;
        return NO_REPLY;
      }

      // check fct code
      boolean isSupported = false;
      for (uint8_t i = 0; i < sizeof( fctsupported ); i++) {
        if (fctsupported[i] == au8Buffer[FUNC]) {
          isSupported = 1;
          break;
        }
      }
      if (!isSupported) {
        u16errCnt ++;
        return EXC_FUNC_CODE;
      }

      // check start address & nb range
      uint16_t u16regs = 0;
      uint8_t u8regs;
      switch ( au8Buffer[ FUNC ] ) {
      case MB_FC_READ_COILS:
      case MB_FC_READ_DISCRETE_INPUT:
      case MB_FC_WRITE_MULTIPLE_COILS:
        u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]) / 16;
        u16regs += word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ]) / 16;
        u8regs = (uint8_t) u16regs;
        if (u8regs > u8regsize) return EXC_ADDR_RANGE;
        break;
      case MB_FC_WRITE_COIL:
        u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]) / 16;
        u8regs = (uint8_t) u16regs;
        if (u8regs > u8regsize) return EXC_ADDR_RANGE;
        break;
      case MB_FC_WRITE_REGISTER :
        u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]);
        u8regs = (uint8_t) u16regs;
        if (u8regs > u8regsize) return EXC_ADDR_RANGE;
        break;
      case MB_FC_READ_REGISTERS :
      case MB_FC_READ_INPUT_REGISTER :
      case MB_FC_WRITE_MULTIPLE_REGISTERS :
        u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]);
        u16regs += word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ]);
        u8regs = (uint8_t) u16regs;
        if (u8regs > u8regsize) return EXC_ADDR_RANGE;
        break;
      }
      return 0; // OK, no exception code thrown
    }

    uint8_t Modbus::validateAnswer() {
      // check message crc vs calculated crc
      uint16_t u16MsgCRC =
        ((au8Buffer[u8BufferSize - 2] << 8)
        | au8Buffer[u8BufferSize - 1]); // combine the crc Low & High bytes
      if ( calcCRC( u8BufferSize - 2 ) != u16MsgCRC ) {
        u16errCnt ++;
        return NO_REPLY;
      }

      // check exception
      if ((au8Buffer[ FUNC ] & 0x80) != 0) {
        u16errCnt ++;
        return ERR_EXCEPTION;
      }

      // check fct code
      boolean isSupported = false;
      for (uint8_t i = 0; i < sizeof( fctsupported ); i++) {
        if (fctsupported[i] == au8Buffer[FUNC]) {
          isSupported = 1;
          break;
        }
      }
      if (!isSupported) {
        u16errCnt ++;
        return EXC_FUNC_CODE;
      }

      return 0; // OK, no exception code thrown
    }

    void Modbus::buildException( uint8_t u8exception ) {
      uint8_t u8func = au8Buffer[ FUNC ];  // get the original FUNC code

      au8Buffer[ ID ]      = u8id;
      au8Buffer[ FUNC ]    = u8func + 0x80;
      au8Buffer[ 2 ]       = u8exception;
      u8BufferSize         = EXCEPTION_SIZE;
    }

    void Modbus::get_FC1() {
      uint8_t u8byte, i;
      u8byte = 0;

      // check the answer length
      boolean bEvenOdd =
        ( au8Buffer[ ADD_HI ] % 2 == 0) ?
      false :
      true;

      uint8_t u8WordsNo =
        ( !bEvenOdd ) ?
      au8Buffer[ ADD_HI ] / 2 :
      au8Buffer[ ADD_HI ] / 2 + 1;

      for (i = 0; i < u8WordsNo; i++) {
        au16regs[ i ] = word(
        au8Buffer[ u8byte ],
        au8Buffer[ u8byte + 1 ]);
        u8byte += 2;
      }

      // cut last byte
      if (bEvenOdd) {
        au16regs[ u8WordsNo - 1 ] &= 0xff00;
      }
    }

    void Modbus::get_FC3() {
      uint8_t u8byte, i;
      u8byte = 3;

      for (i = 0; i < au8Buffer[ 2 ] / 2; i++) {
        au16regs[ i ] = word(
        au8Buffer[ u8byte ],
        au8Buffer[ u8byte + 1 ]);
        u8byte += 2;
      }
    }

    int8_t Modbus::process_FC1( uint16_t *regs, uint8_t u8size ) {
      uint8_t u8currentRegister, u8currentBit, u8bytesno, u8bitsno;
      uint8_t u8CopyBufferSize;
      uint16_t u16currentCoil, u16coil;

      // get the first and last coil from the message
      uint16_t u16StartCoil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
      uint16_t u16Coilno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

      // put the number of bytes in the outcoming message
      u8bytesno = (uint8_t) (u16Coilno / 8);
      if (u16Coilno % 8 != 0) u8bytesno ++;
      au8Buffer[ ADD_HI ]  = u8bytesno;
      u8BufferSize         = ADD_LO;

      // read each coil from the register map and put its value inside the outcoming message
      u8bitsno = 0;

      for (u16currentCoil = 0; u16currentCoil < u16Coilno; u16currentCoil++) {
        u16coil = u16StartCoil + u16currentCoil;
        u8currentRegister = (uint8_t) (u16coil / 16);
        u8currentBit = (uint8_t) (u16coil % 16);

        bitWrite(
        au8Buffer[ u8BufferSize ],
        u8bitsno,
        bitRead( regs[ u8currentRegister ], u8currentBit ) );
        u8bitsno ++;

        if (u8bitsno > 7) {
          u8bitsno = 0;
          u8BufferSize++;
        }
      }

      // send outcoming message
      if (u16Coilno % 8 != 0) u8BufferSize ++;
      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();
      return u8CopyBufferSize;
    }

    int8_t Modbus::process_FC3( uint16_t *regs, uint8_t u8size ) {

      uint8_t u8StartAdd = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
      uint8_t u8regsno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );
      uint8_t u8CopyBufferSize;
      uint8_t i;

      au8Buffer[ 2 ]       = u8regsno * 2;
      u8BufferSize         = 3;

      for (i = u8StartAdd; i < u8StartAdd + u8regsno; i++) {
        au8Buffer[ u8BufferSize ] = highByte(regs[i]);
        u8BufferSize++;
        au8Buffer[ u8BufferSize ] = lowByte(regs[i]);
        u8BufferSize++;
      }
      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();

      return u8CopyBufferSize;
    }

    int8_t Modbus::process_FC5( uint16_t *regs, uint8_t u8size ) {
      uint8_t u8currentRegister, u8currentBit;
      uint8_t u8CopyBufferSize;
      uint16_t u16coil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );

      // point to the register and its bit
      u8currentRegister = (uint8_t) (u16coil / 16);
      u8currentBit = (uint8_t) (u16coil % 16);

      // write to coil
      bitWrite(
      regs[ u8currentRegister ],
      u8currentBit,
      au8Buffer[ NB_HI ] == 0xff );

      // send answer to master
      u8BufferSize = 6;
      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();

      return u8CopyBufferSize;

    }

    int8_t Modbus::process_FC6( uint16_t *regs, uint8_t u8size ) {

      uint8_t u8add = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
      uint8_t u8CopyBufferSize;
      uint16_t u16val = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

      regs[ u8add ] = u16val;

      // keep the same header
      u8BufferSize         = RESPONSE_SIZE;

      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();

      return u8CopyBufferSize;
    }

    int8_t Modbus::process_FC15( uint16_t *regs, uint8_t u8size ) {
      uint8_t u8currentRegister, u8currentBit, u8frameByte, u8bitsno;
      uint8_t u8CopyBufferSize;
      uint16_t u16currentCoil, u16coil;
      boolean bTemp;

      // get the first and last coil from the message
      uint16_t u16StartCoil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
      uint16_t u16Coilno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

      // read each coil from the register map and put its value inside the outcoming message
      u8bitsno = 0;
      u8frameByte = 7;
      for (u16currentCoil = 0; u16currentCoil < u16Coilno; u16currentCoil++) {

        u16coil = u16StartCoil + u16currentCoil;
        u8currentRegister = (uint8_t) (u16coil / 16);
        u8currentBit = (uint8_t) (u16coil % 16);

        bTemp = bitRead(
        au8Buffer[ u8frameByte ],
        u8bitsno );

        bitWrite(
        regs[ u8currentRegister ],
        u8currentBit,
        bTemp );

        u8bitsno ++;

        if (u8bitsno > 7) {
          u8bitsno = 0;
          u8frameByte++;
        }
      }

      // send outcoming message
      // it's just a copy of the incomping frame until 6th byte
      u8BufferSize         = 6;
      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();
      return u8CopyBufferSize;
    }

    int8_t Modbus::process_FC16( uint16_t *regs, uint8_t u8size ) {
      uint8_t u8func = au8Buffer[ FUNC ];  // get the original FUNC code
      uint8_t u8StartAdd = au8Buffer[ ADD_HI ] << 8 | au8Buffer[ ADD_LO ];
      uint8_t u8regsno = au8Buffer[ NB_HI ] << 8 | au8Buffer[ NB_LO ];
      uint8_t u8CopyBufferSize;
      uint8_t i;
      uint16_t temp;

      // build header
      au8Buffer[ NB_HI ]   = 0;
      au8Buffer[ NB_LO ]   = u8regsno;
      u8BufferSize         = RESPONSE_SIZE;

      // write registers
      for (i = 0; i < u8regsno; i++) {
        temp = word(
        au8Buffer[ (BYTE_CNT + 1) + i * 2 ],
        au8Buffer[ (BYTE_CNT + 2) + i * 2 ]);

        regs[ u8StartAdd + i ] = temp;
      }
      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();

      return u8CopyBufferSize;
    }

  [1]: https://i.stack.imgur.com/eglU2.jpg
  [2]: https://i.stack.imgur.com/bphiY.png
  [3]: https://i.stack.imgur.com/wwfhW.jpg

body:
My testing indicates that the slave **is** responding. I made up a master from <http://playground.arduino.cc/Code/ModbusMaster> and tested it:

[![Modbus response][1]][1]

* Channel 0 is master to slave.
* Channel 1 is slave to master.

Zooming in:

[![Modbus response 2][2]][2]

  [1]: https://i.stack.imgur.com/fKKFq.png
  [2]: https://i.stack.imgur.com/mEgz6.png


message:
How do I use Arduino and node.js?

I am new to Arduino, however I have experience in web development, lately I have been using, meteor js and the mean stack for different projects. However, I am open to trying any language for development.

What I am trying to do is build a simple application to control the LED on the Arduino over the web.

I am working with another person, and the Arduino will be behind a firewall so I am not sure how to access it via the internet. I do have access to an Arduino Uun that I can use for testing at home which does have linio connected via bridge, which I don't quite understand what that does.

I've also heard of [this](https://www.yaler.net/), but would like to stay away from third party builds as much as possible if I can do it myself.

Whats the common way to do this with an Arduino behind a firewall? How do I do this with a Arduino Yun? Is it easier with a Yun?

body:
first of all you need to have clear what you need to do.
Arduino UNO is just a microcontroller with a serial (over USB) connection.
To make your arduino accessible from the internet, it need to be connected with the internet, or to have something that act like a bridge.
You can use an ethernet shield, a wifi shiled, or a YUN witch is an arduino UNO + a micro linux with has ethernet and wifi (programmable in phyton, or the chip can command the linux sending command to bash shell using the special bridge library)
You can even connect arduin on the pc by usb and create a bridge program, or, if your firewall/router is a unlocked linux/similar, you can use it.

How many option, and we event startint to decide how o talk with it. As you want to use node.sj, you can use socket or get/post.
Using socket is faster, lighter, and can create a pull connection, and js wil be a requisite. With get/post you don't even need js, pure html form will do.

then, after you decided witch sistem you like (arduino as http server or plain socket) you can open the corresponding port on the firewall/nat. but is just the last part


body:
I am working on similar project that uses internet to communicate with external device (mobile). I am reading data from sensors and passing them over the web with web sockets. I am using Arduino Yun for this project and Spacebrew (for web sockets communication). It's very interesting approach but quite a challenge in some cases. You will probably run into asynchronous/synchronous problem, which in my case lead me to running some Python scripts on Yun triggered from Processing code. I am currently running Spacebrew server on my VPN, so I can connect my Yun left at home and use my iphone from everywhere to get the readings.

It's also worth mentioning Yun comes with pre-installed Temboo library, which is great starting point for web communication. The configuration is really easy and quick. You will also find official documentation very handy and easy to understand. It's really great starting point for experimenting with web-like applications integrated with Arduino Yun.

### Spacebrew ###

 - <http://docs.spacebrew.cc/>

   Spacebrew is an open, dynamically re-routable software toolkit for choreographing interactive spaces. Or, in other words, a simple way to connect interactive things to one another. Every element you hook up to the system can subscribe to, and publish data feeds.

 - <http://github.com/Spacebrew/pySpacebrew>

   This repo contains the Spacebrew Library for Python along with documentation and example apps.

 - <http://github.com/julioterra/yunSpacebrew>

   The Spacebrew Yun library features two main components - a set of python scripts that run on the linino, and a library that runs on the atmel chip. You find there information how to install both of these components so that you can connect to Spacebrew from an Arduino sketch.

### Temboo ###

Yun has also build in Temboo library, it's a great way to start experimenting, once you prove the concept you can start narrowing your environment and moving away if you don't want to use 3rd parties software.

 - <http://www.temboo.com/arduino>

   The Temboo Library makes it easy to connect to over 100 web-based resources and services with Processing. Currently you can find libraries for Android, Arduino, iOS, Java, Node.js, PHP, Processing, Python, REST API, Ruby, Twyla

### Node.js ###

You can also run node.js on the Yun itself, here's good article and some packages ready to install:

 - <http://giorgiocefaro.com/blog/installing-node-js-on-arduino-yun>
 - <https://github.com/giorrrgio/nodejs-linino>

   This is an openwrt package for node. It probably only works on mips (not mipsel, or arm). It runs an outdated v8 as well.

### What is Bridge library for Arduino Yun? ###

You also asked about Bridge library. As you know Yun has two processors on board, one is running your Processing code, the other one has Linux on it (Linino). Bridge basically simplifies communication between them so they can "talk" to eachother, more information here:

 - <http://arduino.cc/en/Reference/YunBridgeLibrary>

   (Taken from arduino.cc documentation:)

   The Arduino Yún has two processors on board. One is an ATmega32U4 like on the Arduino Leonardo. The other is an Atheros 9331, running Linux and the OpenWRT wireless stack, which enables the board to connect to WiFi and Ethernet networks. It is possible to call programs or custom scripts on the Linux system through the Arduino to connect with various internet services.

   The Bridge library simplifies communication between the ATmega32U4 and the AR9331. It inherits from Stream, and many of the methods should be familiar from Serial and other derivatives of Stream.

   Bridge commands from the 32U4 are interpreted by Python on the AR9331. Its role is to execute programs on the GNU/Linux side when asked by Arduino, provide a shared storage space for sharing data like sensor readings between the Arduino and the Internet, and receiving commands from the Internet and passing them directly to the Arduino.

   Bridge allows communication in both directions, acting as an interface to the the Linino command line.

### Where to start? ###

I would start with Temboo if I were you, it's a great learning curve and quite simple step to start. You will also learn and understand how the board works and how you can communicate with "external world". Once you have proof of concept, start experimenting with different libraries and improving the approach. Perhaps you will find Spacebrew more handy later or even discover different solutions.


message:
Parse JSON with arduino to turn on LED

Hi i'm trying to parse JSON resposne from webserver in my arduino in order to turn on and off a LED light. I'm using the wifi client repeating example to make a get request to my server:

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

Here is what I get printed back from the serial port

    connecting...
    HTTP/1.1 200 OK
    Date: Sun, 06 Apr 2014 01:14:37 GMT
    Server: Apache
    X-Powered-By: PHP/5.5.10
    Cache-Control: no-cache
    X-Frame-Options: SAMEORIGIN
    Set-Cookie: expires=Sun, 06-Apr-2014 03:14:37 GMT; Max-Age=7200; path=/; httponly
    Connection: close
    Transfer-Encoding: chunked
    Content-Type: application/json

    19
    {"lightstatus":"on"}
    0

How do i parse the JSON portion of this response only so that I can use it to control my LED?

Thanks

body:
I'm aware of a few JSON parsing libraries for Arduino.

* [aJSON][1]
* [Arduino JSON Parser][2]
* [JSON Arduino][3]

I've never used any of these but I did do some simple JSON parsing in a project I'm working on so I'll show you how I did that.

NOTE: I'm reading serial data using the software serial library. You'll need to change this code to work for you. This will only work on very simple JSON strings. It's *very* limited but if that's all you're parsing then it'll work.

Example of JSON response from server:

    {"id":"TEST1","lat":"38.56050207","lng":"-121.42158374","total":"3","available":"2"}

First, only read data between curly braces.

    String response = "";
    bool begin = false;
    while (SIM900.available() || !begin) {

        char in = SIM900.read();

        if (in == '{') {
            begin = true;
        }

        if (begin) response += (in);

        if (in == '}') {
            break;
        }

        delay(1);
    }

This code reads data one byte at a time and once it gets an open brace, it starts saving it into `response`. When it gets a closing brace, it ends it. So here's a clear limitation, you can only have one set of opening/closing braces in your string.

Once I have the string, I use `indexOf` and `substring` to extract relevant information:

    start = response.indexOf("id\":\"") + 5;
    end = start + 5;
    nodeId = response.substring(start, end);

This code sets `start` to the beginning of `id":"` + 5 characters in the string. It's +5 because that's how long `id":"` is. So `start` points to `TEST1` in the JSON string. In my system, the ID is always going to be 5 characters long so end is `start + 5`. I then use `substring` to extract that.

Again, before anyone starts down voting me for this horrible solution: if you know exactly what you're working with, and understand the limitations of this code, then this is not a bad solution. It's a solution that gets the job done.

  [1]: https://github.com/interactive-matter/aJson
  [2]: https://github.com/bblanchon/ArduinoJsonParser
  [3]: https://github.com/not404/json-arduino


body:
I have programmed a class that will receive char by char the JSON document. It only will store in memory a few bytes for known JSON structure using a state machine and the results you need. So you can query the class for the results you want and will process the JSON.

Its ideal for your purpose. I have used for connecting to a weather service that returns a json:

    static const char* queries[] = { "list.0.deg", "list.0.weather.0.main"};
    StreamJsonReader jsonreader(queries, 2); // 2 queries
    while(char c  =  read()){
          jsonreader.process_char(c);
    }

    cout << jsonreader.results[0] << endl;
    cout << jsonreader.results[1] << endl;

Check this blog post I just wrote: http://web.biicode.com/blog/big-json-on-arduino.

Source code is [here][1] in Biicode.

  [1]: https://www.biicode.com/lasote/blocks/lasote/stream_json_reader/branches/master


body:
I wrote a parser for the PIC that has very low ram use because it works directly with char pointers and does not build a tree structure. If you ask to get item N of a list, it gives you an actual pointer into the direct JSON file right at the start of item N of the list. Then you can ask what type of object the pointer represents, etc. It's buggy and doesn't support floats and I think has a few other limitations(twas a long time ago) but it's all on github:https://github.com/EternityForest/OpenFortune-fortune-like-text-generator
You'll need to look in libfortune which is part of the C version.


body:
I wrote a simple JSON-RPC library (on top of aJson) with example of how to turn a led on with JSON-RPC procedure call:

 - Code: https://github.com/cloud-rocket/arduino-json-rpc
 - Documentation: http://www.cloud-rocket.com/2014/03/serial-json-rpc-server-arduino/


message:
Extend battery life with a power-controlling microcontroller?

[This article][1] describes a method to extend the battery life: use a low-power controller to switch on the Arduino only when needed. The author states that this method uses considerably less power than using Arduino's sleep mode.

Are there downsides to this approach? Which variant should I build?(The [TPS61240 variant][2] seems to use something from Circuits@Home that's not available anymore.) **I'd appreciate schematics or links to detailed instructions.**

Background: I'm building a sensor device that's in an environment with no mains power supply. The sensor should wake up eg. hourly, read eg. a temperature sensor, possibly send an SMS and then go back to sleep.

  [1]: http://alanbmitchell.wordpress.com/2011/10/09/design-of-the-extended-battery-life-power-controller-for-the-arduino/
  [2]: http://alanbmitchell.wordpress.com/2011/11/07/arduino-power-controller-with-texas-instruments’-tps61240/

body:
Switching off power to the board only makes sense if you're using a full Arduino. Once you strip the Arduino down to the bare MCU and decoupling capacitors (or start with a basic breakout board instead), disabling unused peripherals and sleeping the CPU has much more of an effect since you no longer need to supply power to an external monitor chip.

Naturally this may involve creating your own board for the MCU. Fortunately Atmel has the basics of that covered.


message:
Measuring resistance conceptually and in code?

How would I measure resistance over a certain length? In this case the resistance is variable.

What I have in my head is that you would output a certain amount of current from one pin, and measure how much comes back from the other.

I'm not sure if this would work, or how to implement it in code.

I've seen [this forum post](http://forum.arduino.cc/index.php/topic,21614.0.html), but it's not making much sense to me.

How can I measure resistance?

body:
you cant control current output to a pin BUT you know a pin output 5V (if using a 5V a arduino, 3.3v in other case).

Then what you need is a know resistence resitor, so you can set up a [voltage divider][1] and then read the resulting voltage with an analogRead. That give you a 10bit precision value that you can easily translate to a voltage, and then use the formula on the linked page to find R1 or R2 (depends on how you wired up your know resistor)

  [1]: http://en.wikipedia.org/wiki/Voltage_divider


message:
How do I connect a PS4 controller connected to an Arduino that's connected to a laptop to another Arduino?

My high school is entering an ROV competition and for next year's competition we want to try and set it up so that we can control it using a PS4 controller. I have done research and found [this][1] shield for Arduino and [this][2] library that allows you to connect it to an Arduino. I plan to then connect the Arduino to a computer via USB and then send each button press to a Processing program via serial. Would it then be possible to send this from Processing to another Arduino out of the laptop? I'm just wondering how feasible this project is.

We initially had just a single Arduino at the top with the Ethernet shield and took inputs from standard joystick potentiometers. We want to add in using the PS4 controller this year for easier control. We found the USB Host Shield that gives us that capability, but uses the same pins as the Ethernet shield. So we added another Arduino, connecting the laptop as the bridge also allows to have a GUI. The Ethernet is wired, by the way. We need the laptop, it's not just for a bridge.

  [1]: http://www.circuitsathome.com/products-page/arduino-shields/usb-host-shield-2-0-for-arduino-assembled
  [2]: https://github.com/felis/USB_Host_Shield_2.0

body:
this is possible, but the processig bridge can add a lot of delay if not correctly handled, also wifi has a low range, almost 100m by default hardware.

zigbee module has better range (xbee pro are up to 1km) and are microcontroller friendly, you use the as you are using a serial, they will hide their complexity once you set them up, and this can be done by PC.

That mens less code, that mena less error and more ram/flash/cpu so you can do a smarter robot :)

 zigbee use the serial protocol to communicate, exactly as you do with the pc. Also arduino can use, with the library SoftSerial, any pin as Serial. So you can keep the HardwareSerial to communicate with pc, and any 2 free pin to communicate with the xbee. So you can use the arduino stand alone, only with the controller, and when needed connect the pc. Then arduino can act as a bridge between xbee and pc, so pc can excange data with the rover. But even without pc your project will be fun.
The same apply for bluetoot or 400/800mhz rxtx module, but not for wifi shield


body:
**This project is very simple.** As I understand it, this is your setup:

    +–––––––––––––––––––––––––––––––––––––––––+
    |                                         |
    |  Arduino 1-––––––––––-PS4 Controller    |
    |  |                 (W. Shield attached) |
    |  |USB                                   |
    |  |                                      |
    |  Computer                               |
    |  |                                      |
    |  |[Wireless]                            |
    |  |                                      |
    |  Arduino 2                              |
    |                                         |
    +–––––––––––––––––––––––––––––––––––––––––+
*[Made with ASCIIFlow](http://asciiflow.com)*

If you have a very small range (I'd say 10-20 feet max), I recommend using Bluetooth. The [HC 06 Bluetooth module looks like a good choice](http://www.amazon.com/Arduino-Wireless-Bluetooth-Transceiver-Module/dp/B0093XAV4U/ref=sr_1_1?ie=UTF8&qid=1396918346&sr=8-1&keywords=hc+06+bluetooth+arduino). There's also a less powerful HC05 if I remember correctly. I had one once but accidentally destroyed it before I could connect with a bad soldering job :). The one linked on Amazon luckily comes with a "backplane" already soldered so you just need to attach 5V, GND, and the TX/RX pins to the Arduino, accordingly. Then, you can select the BT module (wherever it appears on your OS; search online for this) and then you can connect to it and add the password 1234. After that, it should function like a normal COM port.

You would connect this to the HC06 to Arduino 2, and wirelessly the HC06 to the computer. The computer would then be connected to Arduino 1, who would receive the PS4 signals, with the shield. You would use Processing to receive the PS4 signals and to send data to the second Arduino board. I'm not an expert on Processing, but I found [this serial library](https://www.processing.org/reference/libraries/serial/Serial.html).

I ***do not*** recommend using Xbee because one Arduino needs to talk to the computer and the other at the same time. That's not practical with the way it's set up on most boards. The OP would need another UART connection, even so the Xbee and the USB to UART chip use the same pins on all standard boards.


message:
Controlling LED from web server

I have a LED attached to my Arduino wifi shield that I want to control from my PHP web server.  In terms of communication, should I

1. Make my Arduino a web server and then communicate with PHP web server via HTTP

2. Make my Arduino a web client and receive commands from my PHP web service.  I would parse the JSON response

Also my other question is should I communicate with JSON between my PHP web server or is there a better way to send commands to my LED light?

body: There's no need for either PHP or JSON. Simply detect when one of two URLs (say, `/led/on` and `/led/off`) has been accessed on the Arduino's web server, change the LED state, and return a 204 response.


body:
The REST protocol is ideal for this and there's a nice Sketch already written, called RESTduino on Github:
[https://github.com/jjg/RESTduino][1]

Basically (and loosely) REST treats a URL as a command.  Quoting from the RESTduino doc's:

"To turn on the LED attached to pin #9 (currently case sensitive!):

    http://192.168.1.177/9/HIGH

This will set the pin to the HIGH state and the LED should light. Next try this:

     http://192.168.1.177/100

This will use PWM to illuminate the LED at around 50% brightness (valid PWM values are 0-255)."

  [1]: https://github.com/jjg/RESTduino


message:
How to send an email with Arduino and a WiFi shield?

I want to make my Arduino connect via WiFi and then send an email. The idea is very simple, but the problem is that I've never worked with those protocols and other things before. I just wanted something that's already premade, so I would just change the information.

Is there a library or a function that sends the email?

If someone could help me to understand, so I can make it myself, that would be the best.

body:
What you're looking for is a **SMTP (Simple Mail Transport Protocol) library**. A Google search finds 2 for the Arduino:

- SMTPClient

  This seems to be a minimal-capability SMTP-only library that piggybacks on top of a connection library.

- FullIP

  This seems to be a full IP package for the Arduino that works with select network devices which includes SMTP capability.


body:
You actually present 2 issues here, which can be handled separately:

- You are concerned about having a WiFi, not an Ethernet shield. This doesnt affect at all for sending emails or any other network stuff. When you have internet connection, it is almost transparent from the programming side. So I recommend first to try your wifi shield connection and configuration as a separate problem, with a more simple task, as a simple HTTP_GET to a known web page. A function like this might help, assuming that you have an instance of WiFiClient (which is a Client), that has been connected (with connect) to the URL and port 80:

        void http_get(Client& www, char website[], char webpage[], int timeout, Stream& stream) {
            if (www.connected()) {
                int n = www.print("GET ");
                www.print(webpage);
                www.print(" HTTP/1.1\r\n");
                www.print("Host: ");
                www.print(website);
                www.print("\r\n");
                www.print("\r\n");
            } else {
                stream.println(F("Connection failed get"));
                return;
            }

            /* Read data until either the connection is closed, or the idle timeout is reached. */
            unsigned long lastRead = millis();
            while (www.connected() && (millis() - lastRead < timeout)) {
                while (www.available()) {
                    char c = www.read();
                    stream.print(c);
                    lastRead = millis();
                }
            }
        }

- The second problem is that you want to send an email. One you have a connection, it doesnt matter if it is wifi or wired. The above recommended libraries (SMTPClient, FullIP) will directly connect to your provider (e.g. gmail) and will request your gmail password, something that is not secure over non secure connections (and those libraries do not seem to provide secure layer), so personally I am not comfortable with that option. I have been using the [temboo][1] service, that allows to send emails, and I have found it to be quite convenient and simple. Furthermore, they also have many other services. The service stores your gmail or whatever provider credentials, and you access the service via a Secret Key and App Password they provide. While this keys might not be fully secure to be sent via non secure layers, at least it only compromises your app in the cloud application, which you might simply manage, and not your full email account. (Disclaimer: I have no relation with temboo, and there might be other similar services for this task, e.g. [Carriots][2], I simply say that I have used them with success for this task and feel it is relatively simple). Your code using temboo, could be something like:

  TembooChoreo choreo(client); // your WiFiClient object

  // Set Temboo account credentials
  choreo.setAccountName(temboo_account);
  choreo.setAppKeyName(temboo_app);
  choreo.setAppKey(temboo_app_key);

  // credential is the name of your gmail profile in temboo
  choreo.setCredential(credential);
  choreo.addInput("MessageBody", body);
  choreo.addInput("Subject", subject);
  choreo.addInput("ToAddress", address);

  //Identify the Choreo to run
  choreo.setChoreo("/Library/Google/Gmail/SendEmail");

  choreo.run();
  choreo.close();

  [1]: http://www.temboo.com
  [2]: https://www.carriots.com/documentation/arduino


body: There may be a problem with sending Email from Arduino, but not where you are expecting it. SMTP protocol is super simple, even Arduino can handle it. But you will need SMTP server somewhere that will talk to your Arduino. SSL connections (as on Gmail) are out of consideration (code to handle the encryption would be too much for Arduino) so you'd have to find mail provider that provides plain SMTP - and there aren't many. If you will set up one yourself, say on your home PC with static IP address, it would be an invitation for spammers and a guaranteed way to get your IP blacklisted by Spamhaus. My advice would be to have Python, PHP or Perl script hosted somewhere that will handle HTTP POST requests from your Arduino and do Email sending. It is safer and simpler.


body:
Sending gmail via SMTP from an Arduino is completely feasible. I am doing it from an Arduino MKR WIFI 1010 using the WIFINina library. I'm  pretty sure that my solution will work on any of the SAMD based Arduinos.

There is a bit o "setting up" to do, but it's not hard.

Check out my solution on my [gitlab repo][1].

Be sure to do the config BEFORE trying to execute the code...
Good luck!
GF

  [1]: https://gitlab.com/gratefulfrog/arduino-wifinina-gmail-smtp


body:
The simplest way to send email from Arduino is to make HTTP request to IFTTT. See [Arduino - IFTTT][1]

  [1]: https://arduinogetstarted.com/tutorials/arduino-ifttt


message:
How can I communicate Raspberry Pi and Arduino (in both ways) using a 10-15m distance wires?

I am starting a personal project of home automation and I have a raspberry pi and an arduino Uno board.

I want communicate raspberry pi and my arduino where my raspberry should be able to write and read signals to and from arduino.

The distance between them I think its going to be something around 10 to 15 meters.

What do I need for it? what kind of wires or other components I'll need to achieve my goal? I repeat: I do not want to communicate raspberry pi and arduino wirelessly.

Thanks!

body:
for length such as this, you should be using protocols that are designed for length, such as:

 * UART,
 * CAN,
 * Ethernet

for UART, you can't of course use a direct connection between the two boards, you need to upgrade the connection and wiring to either rs232 or rs485, using a driver between the arduino pins and the cable.

Though, the simplest solution would be to plug the Arduino on the Raspberry Pi using a lengthy USB cable (or more likely 3 five meters cable), which should work fine as long as you only do serial communication. The USB 2.0 limitation of 5 meters are for "hi-speed" connections, which is not our concern for simple serial data communication.

HTH


message:
Can anyone explain how to use MPL sensor with Arduino MEGA?

I am trying to connect a MPL3115A2 Altitude/Pressure/Temp Sensor Breakout which I bought from Hobbytronics to my Arduino Mega. What I had in mind was (Breakout -> Arduino):

`3.3V -> 3.3 V`
`GND -> GND`
`SDA -> A4`
`SCL -> A5`

The information which I've found so far is very conflicting and I'm not sure whether or not I should be using pull-up or in-line resistors, and if so, what value?

The code which the product page links to also differs, with one stating that the Wire library is unsafe to use with a 3.3V rated sensor due to the internal pull-ups, but the other code uses the Wire library?

If anyone could advise me on how best to use this sensor without frying it, it would be much appreciated!

 - Product information
 - Code

body:
Since the device is 3.3V and the Arduino is 5V, you *will* need a I2C level converter such as the TCA9517. Simply supply the Mega side with 5V and the device side with 3.3V and attach 4.7kohm pull-ups to 5V on the Mega side, and it will convert both SDA and SCL for you. You won't need pull-ups on the device side since it includes pull-ups on the board.

For I1 and I2 (push-pull outputs) you can use either normal level converters or you can use a SN74LVC2G07 along with the pull-ups found on the Mega inputs.


message:
How to program a CAN-BUS Arduino shield to control car windows?

My project is to control car windows using voice recognition. I have successfully controlled some LEDs using the EasyVR Arduino shield using and Arduino MEGA. Now I want to take control of the windows using the CAN-BUS arduino shield.

Because the car that I own doesn't have an OBD-II connector, I am using two Arduinos with two CAN-BUS Arduino shields making one a sender and the other a receiver. How can I program the CAN-BUS Arduino shield to make a simulation of the car's windows?

CAN-BUS shield that I am using: https://www.sparkfun.com/products/10039

Arduino Mega: https://www.sparkfun.com/products/11061

body:
What model car do you have?  Most cars do not have the ability to control power windows from the car computer.  Late model cars will have the ability to control the window motors using bidirectional functions on a scan tool.  On any car, the window motors have two wires, if one wire is given power and one ground it will spin if you switch the wire that gets power with the wire that gets ground it spin in the opposite direction.  In my experience the way power windows work are both wires are ground while the switch is in the neutral position and by flipping the switch the switch will disconnect one of the grounds and replace it with a power.  Find a wiring diagram for your car, and look at how the windows are controlled.

Get a 2 relay breakout board such as this one (make sure you check the current ratings):
http://www.amazon.com/SainSmart-2-CH-2-Channel-Relay-Module/dp/B0057OC6D8/ref=sr_1_1?ie=UTF8&qid=1400730995&sr=8-1&keywords=arduino+relay+12v

Connect the ground wire to the normally closed (when no power is applied to the relay this is connected to the output wire) side of both relays and the 12v power to the normally open (when power is applied to the relay this is connected to the output wire)side of both relays.

In order to control the relay breakout board you choose one io pin per relay and set it as an output, then connect those pins to the corresponding pin on the breakout board. Set one of the pins to high (you apply power to one relay) the motor now has a power and a ground connection, set the opposite pin high to spin the other way.

I would place this in the driver side door underneath the window master switches because you can have access to every windows wires as they come out of the master switch.

Some late model cars will have a different set up than the one described, but the window motor will only have two wires (it is just a brushed DC motor) just find the window motor and hookup there.

I hope this helps.


message:
Creating a wireless remote

I am trying to create a wireless remote control to control a servo motor via Bluetooth. What all do I need to establish this? I did some research and found the following:

[Tinyduino][1]

[Bluetooth low energy shield][2]

  [1]: https://tiny-circuits.com/products/tinyduino/
  [2]: https://tiny-circuits.com/shop/tinyshield-bluetooth-le/

Would these be enough (in addition to the servo motor) to establish my needs? Any advice on how I would go about coding this? I can research on the specifics but hints on functions to use would be greatly appreciated. Thanks!

I need to be able to control the system wirelessly (may it be Bluetooth or whatever) through a remote control. This remote control could be a push button system or an app on the phone. I do not have this designed yet. I do not know how to make iPhone apps so the best solution for me would be a simple push button on/off switch that can wirelessly tell the servo motor to either turn 90º clockwise or counterclockwise.

The RFDuino suggestion is very helpful, thank you for that. Can anyone recommend a push-button switch (small) that can wirelessly transmit the signal to the servo motor on the device? I hope this clears things up. Thanks!

body:
I would also check out [RFDuino][1].

Basically it's a finger-tip sized, Arduino compatible, wireless enabled microcontroller, low cost enough to leave in all of your projects.

The RFduino runs Arduino code and can do everything an Arduino can.

  [1]: http://www.rfduino.com/


message:
Calibrate Watchdog Timer

Is there any good way to calibrate the watchdog timer? I'm trying to use it as a time source, even when asleep, but it's woefully inaccurate. Some simple testing showed it loosing 2 minutes every *hour*!

body:
Not only is it uncalibrateable, but it's actually pretty rubbish (as you've discovered). If you check the datasheet you'll see that it can vary between about 109kHz and 119kHz, even though its nominal frequency is 128kHz.

With the ATmegaXX8(A/P) you can reconfigure the system to run its CPU off the internal RC oscillator and timer 2 from a crystal across TOSC1/TOSC2 (pins 9/10 [DIP] or 7/8 [TQFP]) by setting ASSR[6:5] to 0b01 and changing the CKSEL[3:0] fuse bits to 0b0010. Take careful note of the warning on AS2 in the datasheet though. If you want to use a watch crystal instead of prescaling the existing crystal on an Arduino board then you'll need some soldering skill as well.

If you need crystal accuracy for the CPU as well then you'll need to move up to an AVR family that has a separate asynchronous timer that can be supplied with a watch crystal, such as the ATmegaXX4(P) (Sanguino) or ATmegaXXX0 (Mega/Mega 2560).


message:
Faster GPS update rate for parser

I really hope somebody can help me.

I need help making my code receive updates faster to the parser...I need the received GPS coordinates (Latitude and Longitude) to update 5 or more times a second, currently it locks when stationary. Can somebody help?

code:

    #include <TinyGPS.h>

    /* This sample code demonstrates the normal use of a TinyGPS object.
       It requires the use of SoftwareSerial, and assumes that you have a
       4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
    */

    TinyGPS gps;
    //SoftwareSerial ss(4, 3);

    static void smartdelay(unsigned long ms);
    static void print_float(float val, float invalid, int len, int prec);
    static void print_int(unsigned long val, unsigned long invalid, int len);
    static void print_date(TinyGPS &gps);
    static void print_str(const char *str, int len);
    //double getCurrentLatitude();
    //double getCurrentLongitude();

    //double cLatitude = 0.0;
    //double cLongitude = 0.0;
    //
    //double getCurrentLatitude(){
    //  return cLatitude;
    //}
    //
    //double getCurrentLongitude(){
    //  return cLongitude;
    //}

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

    //  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
    //  Serial.println();
    //  Serial.println("Sats HDOP Latitude      Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
    //  Serial.println("          (deg)         (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
    //  Serial.println("------------------------------------------------------------------------------------------------------------------------------------------");

      Serial1.begin(9600);
    }

    void loop()
    {
      double flat, flon = 0.0000000000000;
      unsigned long age, date, time, chars = 0;
      unsigned short sentences = 0, failed = 0;
      //static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

    //  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
    //  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
      gps.f_get_position(&flat, &flon, &age);
    //  gps.f_get_position(&cLatitude,&cLongitude, &age);

      //print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);
      //print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);

      float lati = (float)flat;
      float longi = (float)flon;

      Serial.print("     ");
      Serial.print(lati, 8);
      Serial.print(" ");
      Serial.print(longi, 8);
      smartdelay(0);
      //cLatitude = flat;
      //cLongitude = flon;
    //  print_float(getCurrentLatitude(), TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);
    //  print_float(getCurrentLongitude(), TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);

    //  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
    //  print_date(gps);
    //  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
    //  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
    //  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
    //  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
    //  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
    //  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
    //  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);
    //
    //  gps.stats(&chars, &sentences, &failed);
    //  print_int(chars, 0xFFFFFFFF, 6);
    //  print_int(sentences, 0xFFFFFFFF, 10);
    //  print_int(failed, 0xFFFFFFFF, 9);

      Serial.println();

      smartdelay(1000);
    }

    static void smartdelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (Serial1.available())
          gps.encode(Serial1.read());
      } while (millis() - start < ms);
    }

    static void print_float(float val, float invalid, int len, int prec)
    {
      if (val == invalid)
      {
        while (len-- > 1)
          Serial.print('*');
        Serial.print(' ');
      }
      else
      {
        Serial.print(val, prec);
        int vi = abs((int)val);
        int flen = prec + (val < 0.0 ? 2 : 1); // . and -
        flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
        for (int i=flen; i<len; ++i)
          Serial.print(' ');
      }
      smartdelay(0);
    }

    /*
        If data is invalid, print out *******
        otherwise print out buffer
    */
    static void print_int(unsigned long val, unsigned long invalid, int len)
    {
      char sz[32];
      if (val == invalid)
        strcpy(sz, "*******");
      else
        sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
        sz[i] = ' ';
      if (len > 0)
        sz[len-1] = ' ';
      Serial.print(sz);
      smartdelay(0);
    }

    static void print_date(TinyGPS &gps)
    {
      int year;
      byte month, day, hour, minute, second, hundredths;
      unsigned long age;
      gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
      if (age == TinyGPS::GPS_INVALID_AGE)
        Serial.print("********** ******** ");
      else
      {
        char sz[32];
        sprintf(sz, "d/d/d d:d:d ",
            month, day, year, hour, minute, second);
        Serial.print(sz);
      }
      print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
      smartdelay(0);
    }

    static void print_str(const char *str, int len)
    {
      int slen = strlen(str);
      for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
      smartdelay(0);
    }

body:
I assume you're using TinyGPS which I sourced from https://github.com/mikalhart/TinyGPS

I've recently done a similar thing - just trying to get the gps to work and give me as much data as possible.

The code I used to do this is here:

 #include "TinyGPS.h"

 #define GPS_BAUD 115200
 #define PC_BAUD 115200

 TinyGPS gps;

 int led1 = 13;

 long lat, lon;

 unsigned long fix_age, time, date, speed, course;

 unsigned long chars;
 unsigned short sentences, failed_checksum;

 void setup()
 {
   pinMode(led1, OUTPUT);
   Serial1.begin(GPS_BAUD);
   Serial.begin(PC_BAUD);
   Serial1.println("");
   Serial1.println("Initializing");
   Serial1.println("");
   digitalWrite(led1, HIGH);
   delay(2000);
   digitalWrite(led1, LOW);
   delay(500);
 }

 void loop()
 {
   while(Serial1.available()){
  if(gps.encode(Serial1.read())){
    digitalWrite(led1, HIGH);
    gps.get_position(&lat, &lon, &fix_age);
    gps.get_datetime(&date, &time);
    Serial1.println("");
    Serial1.println("Lat: " + String(lat));
    Serial1.println("Lon: " + String(lon));
    delay(3000);
    gps.stats(&chars, &sentences, &failed_checksum);
    Serial1.println("Chars: " + String(chars));
    Serial1.println("Sents: " + String(sentences));
    delay(1000);
    Serial1.println("Fails: " + String(failed_checksum));
    Serial1.println("");
    delay(1000);
  }
  Serial1.print(".");
   }
 }

I was using an Arduino Mega 2560, but I think you have the same Serial ports on your Due. I connected the TX pin of my GPS ( can't remember the model but I think it was a 10Hz version of this: https://www.sparkfun.com/products/9891 ) to Serial1's RX and I used a small serial 2 row LCD display to output which was connected to Serial1's TX, hence I was using serial1 for both transmitting and receiving. If you remove the delays from the code above the data is read and then written back as fast as possible and while I never measured how many fixes I was seeing per second I'm fairly sure there were at least 5.

The code you want is probably something like this:

 #include "TinyGPS.h"

 #define GPS_BAUD 115200
 #define PC_BAUD 115200

 TinyGPS gps;

 int led1 = 13;

 long lat, lon;

 unsigned long fix_age, time, date, speed, course;

 unsigned long chars;
 unsigned short sentences, failed_checksum;

 void setup()
 {
   pinMode(led1, OUTPUT);
   Serial1.begin(GPS_BAUD);
   Serial.begin(PC_BAUD);
   Serial1.println("");
   Serial1.println("Initializing");
   Serial1.println("");
   digitalWrite(led1, HIGH);
   delay(2000);
   digitalWrite(led1, LOW);
   delay(500);
 }

 void loop()
 {
   while(Serial1.available()){
  if(gps.encode(Serial1.read())){
    digitalWrite(led1, HIGH);
    gps.get_position(&lat, &lon, &fix_age);
    gps.get_datetime(&date, &time);
    Serial.print("    ");
    Serial.print(lat);
    Serial.print(" ");
    Serial.print(long);
  }
   }
 }

As commented by @connor-wolf above you will probably need to change the baud-rate of your communications up because otherwise you the limit of the amount of information you can send/receive per second is probably too low. The baud rate must also match the baud rate of your GPS device. Some GPS devices have an adjustable baud rate.

------

A quick google turned up an average NMEA sentence length of 60 bytes and if I recall correctly you may have 2 or 3 sentences to each fix? (I think the extra sentences contain extra info like satellite counts, and stuff). So assume you need 180 bytes per fix and you want at least 5 fixes per second that would be 900 bytes. In baud that is 900x8 = 7200. So assuming my estimations above are accurate or overestimated then you have enough bandwidth.

I'm not sure however if the Micro transmits/receives over serial while running the other instructions in your code - I would assume not to be safe but it's worth some research. Therefore you have to account for the time the micro spends transmitting and interpreting the data as time in the second that it can't spend receiving the data. Therefore I would suggest that doubling or even tripling the data rate would be a good idea. (as you can see from my example I just set it to as high as the GPS would go.)

Anyway. I hope all that helps.

P.S please forgive if I've used the wrong terminology for fixes/sentences or whatever


message:
Using SD card shield on Arduino Due

I have a Seeed Studio SD card shield (V3) that I am trying to use on my Arduino Due. I am having trouble using the SD examples that come with the Arduino IDE.

They worked fine on my Arduino Uno by setting `chipSelect` to `SS`. Below is the code I used for the Arduino Uno. It is the same as the `CardInfo.ino` in the examples section under SD (except for the `chipSelect`).

CardInfo.ino
<!-- language-all: lang-cpp -->
    /*
      SD card test

     This example shows how use the utility libraries on which the'
     SD library is based in order to get info about your SD card.
     Very useful for testing a card when you're not sure whether its working or not.

     The circuit:
      * SD card attached to SPI bus as follows:
     ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
     ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
     ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
     ** CS - depends on your SD card shield or module.
       Pin 4 used here for consistency with other Arduino examples

     created  28 Mar 2011
     by Limor Fried
     modified 9 Apr 2012
     by Tom Igoe
    */

    // include the SD library:
    #include <SPI.h>
    #include <SD.h>

    // set up variables using the SD utility library functions:
    Sd2Card card;
    SdVolume volume;
    SdFile root;

    // change this to match your SD shield or module;
    // Arduino Ethernet shield: pin 4
    // Adafruit SD shields and modules: pin 10
    // Sparkfun SD shield: pin 8
    const int chipSelect = SS; //CHANGE HERE!!!!!!!!

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.print("\nInitializing SD card...");
      // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
      // Note that even if it's not used as the CS pin, the hardware SS pin
      // (10 on most Arduino boards, 53 on the Mega) must be left as an output
      // or the SD library functions will not work.
      pinMode(10, OUTPUT);     // change this to 53 on a mega

      // we'll use the initialization code from the utility libraries
      // since we're just testing if the card is working!
      if (!card.init(SPI_HALF_SPEED, chipSelect)) {
        Serial.println("initialization failed. Things to check:");
        Serial.println("* is a card is inserted?");
        Serial.println("* Is your wiring correct?");
        Serial.println("* did you change the chipSelect pin to match your shield or module?");
        return;
      } else {
        Serial.println("Wiring is correct and a card is present.");
      }

      // print the type of card
      Serial.print("\nCard type: ");
      switch (card.type()) {
        case SD_CARD_TYPE_SD1:
          Serial.println("SD1");
          break;
        case SD_CARD_TYPE_SD2:
          Serial.println("SD2");
          break;
        case SD_CARD_TYPE_SDHC:
          Serial.println("SDHC");
          break;
        default:
          Serial.println("Unknown");
      }

      // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
      if (!volume.init(card)) {
        Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
        return;
      }

      // print the type and size of the first FAT-type volume
      uint32_t volumesize;
      Serial.print("\nVolume type is FAT");
      Serial.println(volume.fatType(), DEC);
      Serial.println();

      volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
      volumesize *= volume.clusterCount();       // we'll have a lot of clusters
      volumesize *= 512;                            // SD card blocks are always 512 bytes
      Serial.print("Volume size (bytes): ");
      Serial.println(volumesize);
      Serial.print("Volume size (Kbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);
      Serial.print("Volume size (Mbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);

      Serial.println("\nFiles found on the card (name, date and size in bytes): ");
      root.openRoot(volume);

      // list all files in the card with date and size
      root.ls(LS_R | LS_DATE | LS_SIZE);
    }

    void loop(void) {

    }

Here is a picture of my setup:

![Due with SD card shield][1]

###tl;dr

How do I make this shield work on my Due?

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

body:
![Due Pin description](https://www.theengineeringprojects.com/wp-content/uploads/2018/09/introduction-to-arduino-due-2-1.png)

Looking at the pin configuration, the SPI pins are not in the same location as the UNO. Remove the Shield from Due and use cables to connect to the SPI pins


message:
Mic input and Speaker output using arduino

I am trying to make a small project. Firstly, I want to record voice using a small microphone(electret) for the time button is pressed and on releasing the button, the speaker of my laptop should output the recorded voice or a speaker attached to the arduino should output.

**Note: I don't want to use any shield to do so. Simply Arduino**

body:
Microphone input is easy (ADC). Speaker output is easy (PWM). Both have many, many examples strewn across the Internet.

What happens in between is *not*, and will require external components. You will need at the very least somewhere to store the samples between record and playback. Investigate SPI SRAM large enough to store all the required samples at your chosen sample rate (8 kS/s should be high enough for human speech).


message:
Why am I getting "fatal error: SoftwareSerial.h: No such file or directory"

I downloaded the Adafruit_GPS library from Adafruit and I'm trying to compile the example code (due_parsing) but I can't seem to get past this silly error:

    In file included from due_parsing.ino:15:

    /Users/haddad/Documents/Arduino/libraries/Adafruit_GPS/Adafruit_GPS.h:24: fatal error: SoftwareSerial.h: No such file or directory
    compilation terminated.

This is the location in the example Arduino Sketch where `SoftwareSerial.h` is mentioned:

    #ifdef __AVR__
      #include <SoftwareSerial.h>
    #endif

I noticed it's around an `ifdef` guard, so shouldn't it not even matter that I don't have this library?

I went into the .h and .cpp files and commented out the where it called `SoftwareSerial.h`, but I'm still getting that above error.

Does anybody know how to fix this?
I am using Arduino IDE v1.5.5

----------

Update:

I didn't put the library in the library direct on my mac but I'm now getting tons of errors, all the errors are with `SoftwareSerial.cpp`. Is anybody else having similar issues when you go to compile?

body:
According to your comment:

> after commenting out those ifdef guards, it worked

I would say that is a bug in the **Adafruit_GPS** library.

As a matter of fact, the **DUE** is not using the **AVR** architecture (it uses **ARM**), that explains why `#ifdef __AVR__` in `Adafruit_GPS.h` never passes; but then something else should be done specifically for the DUE (missing `#else` or `#elif`).

After checking on *github*, there is an [issue][1] open for that; unfortunately, as of April 2014, it has not moved for 10 months.

Your best guess would be to go there and try to "reactivate" this issue.

  [1]: https://github.com/adafruit/Adafruit-GPS-Library/issues/14


body: So I went into the interface file (.h) and removed all references to AVR and then went into (.cpp) and removed all references to AVR there as well. It now seems to be working, although sometimes it says "Not supported Architecture ARM" during compilation...very weird


body:
this is a "bug" in the arduino IDE pre-compilation process.
If you turn on the compiling verbositi in thge precerences menu, you will see that arduino has copied all file (with a rater "stupid" code that just look for include) into a temp folder (wiring lib are not copied, but the below still aplly). Until here, ugly but still fine.

Then, it will -force- compilation of every "included" file, one by one, the facto bypassing the #ifdef.. and this is why you get that problem.

Solution is to heavy change the ide so it will force compilation only in the main, and let the compiler include and compile needed libraries.

I still have no idea why every file is forced, but a change like this is really heavy and break-old-code prone..

Newest IDE to bypass this problem (and also some other problem, like depeency) use a "config" file that will tell the IDE if use the AVR or ARM or x86 library, probabily this file is missing and the ide see te lib as only AVR by default.

Double check if it is really usable on DUE