body:
I'm using `sprintf` to use a format specifier `myTemplate` with some strings. The result will then be written to Serial. Although the sketch compiles fine, it does not write any thing to the serial, nothing is seen in the Serial monitor.

Is `sprintf` being used wrongly here?

 char* result;
 char* myTemplate;

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

 void loop() {
     myTemplate = "Welcome %s. You have slept %s times";
     sprintf(result, myTemplate, "Jane", "many");
     Serial.println(result);
     Serial.println("hello");

 }

----------

When I try the follwing sketch and write something to the Serial monitor, I receive gibberish echoed back to me!  Why is this?

**Sketch**

 char received;
 char* message = "";

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

 void loop() {

     // Echos back
     if(Serial.available() > 0) {
         received = Serial.read();
         Serial.println(message);

         if(received == '\n') {
             message = "";
         }  else {
             message += received;
         }

     }
 }

title: Nothng Written to Serial when using sprintf

Answers: 1

body:
When you use `sprintf()`, you need to have some space allocated for it to write the result to. At the moment, you're just passing an uninitialised pointer (`result`), meaning the behaviour of `sprintf()` is undefined. It might appear to work under some circumstances, but not others (and even if it did seem to work, it could have some nasty side effects on other parts of your code).

The simplest approach is to allocate a static `char` buffer. You need to be sure it's big enough to contain all of the text you want it to store though (plus an extra null character at the end).

For example:

    char* myTemplate = "";
    char result[64] = {0};

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

    void loop() {
        myTemplate = "Welcome %s. You have slept %s times";

        sprintf(result, myTemplate, "Jane", "many");
        Serial.println(result);
        Serial.println("hello");
    }

As a side note, it's usually a good idea to initialise your variables. This is especially true for pointers.


body:
I have an Arduino Uno R3. I have a paddlewheel waterspeed sensor that I use on an ISR on pin 2. The power supply is approximately 8v stepped down to 4.92v with a circuit yanked from the phone charger. I have also tried this with the arduino 5v.

The pin returns the correct values with digitalRead(), so it's cycling between 1 and 0.

The ISR works fine on pin3. Why does it work on pin 3 and not pin 2 ISR?

    void itest() {
        Serial.println( "test" );
    }

    void setup() {
        attachInterrupt(0, itest, FALLING);
    }

title: Arduino Uno R3 ISR does not work on pin 2?

Answers: 1

body: never use Serial inside an interrupt handler, increment a (volatile) variable and print it in the loop().


body:
I am sending a list of servo positions via the serial connection to the arduino in the following format

    1:90&2:80&3:180

Which would be parsed as:

`servoId : Position & servoId : Position & servoId : Position`

How would I split these values up, and convert them to an integer?

title: How do I split an incoming string?

Answers: 12

body:
You can use [`Stream.readStringUntil(terminator)`][1] passing a different terminator for each part.

On each part you then call [`String.toInt`][2]

  [1]: http://arduino.cc/en/Reference/StreamReadStringUntil
  [2]: http://arduino.cc/en/Reference/StringToInt

body:
You could do something like the following, but please take into account several things:

If you use ```readStringUntil()```, it will wait until it receives the character or timeouts. Thus, with your current string, the last position will last a little longer, as it has to wait. You can add a trailing ```&``` to avoid this timout. You can easily check this behavior in your monitor, try to send the string with and without the extra ```&``` and you will see such timeout delay.

You actually do not need the servo index, you can just send your string of positions, and get the servo index by the value position in the string, something like: ```90&80&180&```. If you use the servo index, maybe you want to check it (convert to ```int```, and then match the loop index i) to ensure that nothing went wrong with your message.

You have to check that the returning string from ```readStringUntil``` is not empty. If the function timeouts, you didn't receive enough data, and thus any attempt to extract your ```int``` values will produce strange results.

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

    void loop() {
     for(int i=1; i<=3; i++) {
      String servo = Serial.readStringUntil(':');
      if(servo != ""){
       //here you could check the servo number
       String pos = Serial.readStringUntil('&');
       int int_pos=pos.toInt();
       Serial.println("Pos");
       Serial.println(int_pos);
      }
     }
    }

body:
Contrarily to other answers, I'd rather stay away from `String` for the following reasons:

- dynamic memory usage (that may quickly lead to **heap fragmentation** and **memory exhaustion**)
- **quite slow** due to construction/destruction/assignment operators

In an embedded environment like Arduino (even for a Mega that has more SRAM), I'd rather use **standard C functions**:

 - [`strchr()`][1]: search for a character in a C string (i.e. `char *`)
 - [`strtok()`][2]: splits a C string into substrings, based on a separator character
 - [`atoi()`][3]: converts a C string to an `int`

That would lead to the following code sample:

<!-- language: c -->

    // Calculate based on max input size expected for one command
    #define INPUT_SIZE 30
    ...

    // Get next command from Serial (add 1 for final 0)
    char input[INPUT_SIZE + 1];
    byte size = Serial.readBytes(input, INPUT_SIZE);
    // Add the final 0 to end the C string
    input[size] = 0;

    // Read each command pair
    char* command = strtok(input, "&");
    while (command != 0)
    {
        // Split the command in two values
        char* separator = strchr(command, ':');
        if (separator != 0)
        {
            // Actually split the string in 2: replace ':' with 0
            *separator = 0;
            int servoId = atoi(command);
            ++separator;
            int position = atoi(separator);

            // Do something with servoId and position
        }
        // Find the next command in input string
        command = strtok(0, "&");
    }

The advantage here is that no dynamic memory allocation takes place; you can even declare `input` as a local variable inside a function that would read the commands and execute them; once the function is returned the size occupied by `input` (in the stack) is recovered.

  [1]: http://www.cplusplus.com/reference/cstring/strchr/
  [2]: http://www.cplusplus.com/reference/cstring/strtok/
  [3]: http://www.cplusplus.com/reference/cstdlib/atoi/

body:
This function can be used to separate a string into pieces based on what the separating character is.

    String xval = getValue(myString, ':', 0);
    String yval = getValue(myString, ':', 1);

    Serial.println("Y:" + yval);
    Serial.print("X:" + xval);

Convert String to int

    int xvalue = xvalue.toInt(xval);
    int yvalue = yvalue.toInt(yval);

This Chunk of code takes a string and separates it based on a given character and     returns
The item between the separating character

    String getValue(String data, char separator, int index)
    {
        int found = 0;
        int strIndex[] = { 0, -1 };
        int maxIndex = data.length() - 1;

        for (int i = 0; i <= maxIndex && found <= index; i++) {
            if (data.charAt(i) == separator || i == maxIndex) {
                found++;
                strIndex[0] = strIndex[1] + 1;
                strIndex[1] = (i == maxIndex) ? i+1 : i;
            }
        }
        return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
    }

body:
 String getValue(String data, char separator, int index)
 {
  int maxIndex = data.length() - 1;
  int j = 0;
  String chunkVal = "";

  for (int i = 0; i <= maxIndex && j <= index; i++)
  {
   chunkVal.concat(data[i]);

   if (data[i] == separator)
   {
    j++;

    if (j > index)
    {
     chunkVal.trim();
     return chunkVal;
    }

    chunkVal = "";
   }
   else if ((i == maxIndex) && (j < index)) {
    chunkVal = "";
    return chunkVal;
   }
  }
 }

body:
**See example at:**
https://github.com/BenTommyE/Arduino_getStringPartByNr

    // splitting a string and return the part nr index split by separator
    String getStringPartByNr(String data, char separator, int index) {
        int stringData = 0;        //variable to count data part nr
        String dataPart = "";      //variable to hole the return text

        for(int i = 0; i<data.length()-1; i++) {    //Walk through the text one letter at a time
            if(data[i]==separator) {
                //Count the number of times separator character appears in the text
                stringData++;
            } else if(stringData==index) {
                //get the text when separator is the rignt one
                dataPart.concat(data[i]);
            } else if(stringData>index) {
                //return text and stop if the next separator appears - to save CPU-time
                return dataPart;
                break;
            }
        }
        //return text if this is the last part
        return dataPart;
    }

body:
Simplest solution is to use [sscanf()][1].

      int id1, id2, id3;
      int pos1, pos2, pos3;
      char* buf = "1:90&2:80&3:180";
      int n = sscanf(buf, "%d:%d&%d:%d&%d:%d", &id1, &pos1, &id2, &pos2, &id3, &pos3);
      Serial.print(F("n="));
      Serial.println(n);
      Serial.print(F("id1="));
      Serial.print(id1);
      Serial.print(F(", pos1="));
      Serial.println(pos1);
      Serial.print(F("id2="));
      Serial.print(id2);
      Serial.print(F(", pos2="));
      Serial.println(pos2);
      Serial.print(F("id3="));
      Serial.print(id3);
      Serial.print(F(", pos3="));
      Serial.println(pos3);

This give the following output:

    n=6
    id1=1, pos1=90
    id2=2, pos2=80
    id3=3, pos3=180

Cheers!

  [1]: http://www.cplusplus.com/reference/cstdio/scanf/

body:
Here is **Arduino** method to split a String as answer to the question ["How to split a string in substring?"](https://arduino.stackexchange.com/questions/31643/how-to-split-a-string-in-substring) declared as a duplicate of the present question.

The objective of the solution is to parse a series of **GPS** positions logged into a **SD card** file. Instead of having a String received from `Serial`, the String is read from file.

The function is `StringSplit()` parse a String `sLine = "1.12345,4.56789,hello"` to 3 Strings `sParams[0]="1.12345"`, `sParams[1]="4.56789"` & `sParams[2]="hello"`.

 1. `String sInput`: the input lines to be parsed,
 2. `char cDelim`: the delimiter character between parameters,
 3. `String sParams[]`: the output array of parameters,
 4. `int iMaxParams`: the maximum number of parameters,
 5. Output `int`: the number of parsed parameters,

The function is based on `String::indexOf()` and `String::substring()` :

    int StringSplit(String sInput, char cDelim, String sParams[], int iMaxParams)
    {
     int iParamCount = 0;
     int iPosDelim, iPosStart = 0;

     do {
            // Searching the delimiter using indexOf()
      iPosDelim = sInput.indexOf(cDelim,iPosStart);
      if (iPosDelim > (iPosStart+1)) {
                // Adding a new parameter using substring()
       sParams[iParamCount] = sInput.substring(iPosStart,iPosDelim-1);
       iParamCount++;
                // Checking the number of parameters
       if (iParamCount >= iMaxParams) {
        return (iParamCount);
       }
       iPosStart = iPosDelim + 1;
      }
     } while (iPosDelim >= 0);
     if (iParamCount < iMaxParams) {
            // Adding the last parameter as the end of the line
      sParams[iParamCount] = sInput.substring(iPosStart);
      iParamCount++;
     }

     return (iParamCount);
    }

And the usage is really simple:

 String sParams[3];
 int iCount, i;
 String sLine;

    // reading the line from file
 sLine = readLine();
    // parse only if exists
 if (sLine.length() > 0) {
        // parse the line
  iCount = StringSplit(sLine,',',sParams,3);
  // print the extracted paramters
  for(i=0;i<iCount;i++) {
   Serial.print(sParams[i]);
  }
        Serial.println("");
 }

body:
    char str[] = "1:90&2:80&3:180";     // test sample serial input from servo
    int servoId;
    int position;

    char* p = str;
    while (sscanf(p, "%d:%d", &servoId, &position) == 2)
    {
        // process servoId, position here
        //
        while (*p && *p++ != '&');   // to next id/pos pair
    }

body:
*jfpoilpret* provided great [answer][1] for parsing serial command on Arduino. However Attiny85 doesn't have bidirectional serial - SoftwareSerial has to be used. This is how you port same code for Attiny85

<!-- language: c -->

    #include <SoftwareSerial.h>

    // Calculate based on max input size expected for one command
    #define INPUT_SIZE 30

    // Initialize SoftwareSerial
    SoftwareSerial mySerial(3, 4); // RX=PB3, TX=PB4

    // Parameter for receiving Serial command (add 1 for final 0)
    char input[INPUT_SIZE + 1];

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

    void loop() {
      // We need this counter to simulate Serial.readBytes which SoftwareSerial lacks
      int key = 0;

      // Start receiving command from Serial
      while (mySerial.available()) {
        delay(3);  // Delay to allow buffer to fill, code gets unstable on Attiny85 without this for some reason
        // Don't read more characters than defined
        if (key < INPUT_SIZE && mySerial.available()) {
          input[key] = mySerial.read();
          key += 1;
        }
      }

      if (key > 0) {
        // Add the final 0 to end the C string
        input[key] = 0;

        // Read each command pair
        char* command = strtok(input, "&");
        while (command != 0)
        {
          // Split the command in two values
          char* separator = strchr(command, ':');
          if (separator != 0)
          {
            // Actually split the string in 2: replace ':' with 0
            *separator = 0;
            int servoId = atoi(command);
            ++separator;
            int position = atoi(separator);
          }
          // Find the next command in input string
          command = strtok(0, "&");
        }
      }
    }

Attiny85 schematics for pin numbers
[![enter image description here][2]][2]

Sketch compiles into:

    Sketch uses 2244 bytes (27%) of program storage space. Maximum is 8192 bytes.
    Global variables use 161 bytes (31%) of dynamic memory, leaving 351 bytes for local variables. Maximum is 512 bytes.

So there is plenty of space and memory for the rest of code

  [1]: https://arduino.stackexchange.com/a/1033/43756
  [2]: https://i.stack.imgur.com/IxwmX.png

body:
    void setup() {
    Serial.begin(9600);
    char str[] ="1:90&2:80";
    char * pch;
    pch = strtok(str,"&");
    printf ("%s\n",pch);

    pch = strtok(NULL,"&"); //pch=next value
    printf ("%s\n",pch);
    }
    void loop(){}

body:
It's not an answer to your question but it may be useful for someone. If your string has a specific prefix, then you can use simply `startsWith` and `substring`. E.g.

    void loop ()
      if(Serial.available()){
        command = Serial.readStringUntil('\n');
        Serial.println("Received command: " + command);
        if(command.startsWith("height")) {
          Serial.println(command.substring(7));
        }
      }
    }

And then send `height 10` what will extract `10`.


body:
I built a simple clock using a 4 digits 7 segments LCD display. I display one digit at a time, switching on and off very quicky and cycling through digits.

Everything is ok, but I used 8 + 4 = 12 arduino pins. I need 2 more pins for other features and I don't want to use 0 and 1 as I need onboard programming features of Arduino Mini.

I used I2C for RTC clock, I could add some interface here (like a PCF8574) and get some pins from here. But I'd like a different (and more educational, for me) approach.

Is there an IC that sends an HIGH output on one of four output pins driven by 2 input pins? I need this:

    IN     OUT
    P0 P1  D0 D1 D2 D3
    0  0   1  0  0  0
    0  1   0  1  0  0
    1  0   0  0  1  0
    1  1   0  0  0  1

This way I can connect OUT to digit selection and spare 2 pins.

Thanks for your hints.

title: Save some arduino pins when driving a 4 digits 7 segments display

Answers: 4

body:
A 2-to-4 line decoder should do what you need. I've used a [74HC139][1] with Arduino before, which contains two decoders in a 16-pin DIP.

There are lots of other options though. In the past, I've used an 8 bit serial-to-parallel shift register ([74HC595][2]) to control a 7 segment display. It effectively lets you control 8 (or more) outputs using only 3 pins on your microcontroller. You have to be careful of power requirements though. Most shift registers aren't able to drive such a display directly, but I was able to incorporate transistors quite easily to get around that.

  [1]: http://www.fairchildsemi.com/ds/74/74VHC139.pdf
  [2]: https://www.sparkfun.com/datasheets/IC/SN74HC595.pdf

body:
An [I2C IO expander][1] might be your best bet.  If your existing I2C device uses a different address, you may be able to put both devices on the same I2C bus.  You would then use 0 additional pins compared to your current design.

  [1]: http://www.digikey.com/product-detail/en/MCP23017-E/SP/MCP23017-E/SP-ND/894272 "I2C"

body:
I know it's not what you asked, but you're using a lot of pins, why not try streamlining them and go to an I2C backpack? [This one from adafruit][1] includes a single 4x7 segment display.

given your comment, another option would be an [I2C/SPI 7 Segment driver][2]. ([datasheet][3]).

new edit: Actually, when I posted the above 7 segment driver, this is the one I was thinking of. I don't know why I didn't find this the first time.

[max7219/7221 datasheet][4] and [digikey source][5]:

  [1]: http://www.adafruit.com/products/879
  [2]: http://uk.farnell.com/nxp/saa1064-n2/ic-led-driver-4dgt-i2c-24dip/dp/1627002
  [3]: http://www.fortito.mx/wp-content/uploads/technical/SAA1064.pdf
  [4]: http://www.maximintegrated.com/datasheet/index.mvp/id/1339
  [5]: http://www.digikey.com.au/product-search/en?vendor=0&keywords=max7219+|+max7221

body:
Are you using your analog pins?  Did you know [they can be used as digital pins][1]?

> The analog pins can be used identically to the digital pins, using the aliases A0 (for analog input 0), A1, etc. For example, the code would look like this to set analog pin 0 to an output, and to set it HIGH:
>
>     pinMode(A0, OUTPUT);
>     digitalWrite(A0, HIGH);

This is your best bet if you aren't using all your analog pins.

  [1]: http://arduino.cc/en/Tutorial/AnalogInputPins


body:
Following [this guide][1], it says to include a library in the C++ Linker called `m`. What is this for?

Specifically, [Your second Arduino project][2].

4) **Configure project**

5th dot point:
> AVR C++ Linker -> Libraries: Under libraries, add arduino_core and m (in that order). Under path, add the path to the correct core library, e.g. "`${workspace_loc:/arduino_core/328P_16MHz}`"

  [1]: http://playground.arduino.cc/Code/Eclipse#.UzgDN_nEKG4
  [2]: http://playground.arduino.cc/Code/Eclipse#YourSecondArduinoProject

title: What is the library m in C++ linker?

Answers: 1

body: The m library is the "math" library. You have to link with it in most flavours of gnu compilers (it is typically not required in other, as it is included in the standard lib) when using functions and stuff from the header file "math.h".


body:
I'm trying to upgrade firmware on my wifi shield by following the [upgrade instructions for Mac](http://arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading). I was wondering what this means?:

> Connect a jumper on the J3 connector, that put the shield in the programming mode. Then connect the USB cable to the shield USB mini socket

**How can I do this?**

title: updating firmware on arduino wifi shield

Answers: 2

body: A "jumper" is a little piece of metal (or a 0-ohm resistor) that connects two pads or pins together. So, create an electrical connection across J3 ("DFU programming jumper" in all the pictures). You will then be able to program the shield via USB.

body:
The jumper is only neccesary if your device is not R3 (revision 3)
Be carefully if you connect the shield and your computer does not
recognice the port.
You gonna need a driver in the link below there are all the steps
include other links to download software as Flip 3.4.7 who has
the executable batchisp which one you can made the changes
read the web site:

http://www.dfrobot.com/community/?p=3760

and extra information about that in official site of arduino
WiFi Shield Firmware Upgrading

there you gonna have an idea how to do it.

for me was more clear as in this site describe everything
and also teach to probe if there is an update
having sucess in the process to installing something it
could be as a question answered with non the specific
thing you need.

http://www.binarytaskforce.com/Weblog/2013/09/21/arduino-wifi-firmware-update/

I am also in the process to update my device if I will have success
I will write to how I do it.
At the moment reading a bunch of differents forums beacuse arduino team itself
appearently had some troubles to provided a guided how to do it sucessfully.


body:
At this stage, my finalized design includes Arduino Nano 3.0, a breakout board and a few electrical components on a breadboard.

Will there be an appreciable cost savings from not buying a ready-made Arduino? The Arduino Nano clone being used costs $17.20.

And is it a good idea if everything is soldered on to a custom fabricated PCB board, including the components of Arduino Nano 3.0? The PCB board will cost around $10 at the quantities I'm starting with.

title: Building Arduino Nano from components

Answers: 1

body:
You can probably do a lot better than $17 but not much better than $8:

http://www.ebay.com/itm/Mini-USB-Nano-V3-0-ATmega328P-5V-Micro-controller-Board-For-Arduino-compatible-/130977189883?pt=LH_DefaultDomain_0&hash=item1e7ed94ffb

If you don't need USB, you can use a Pro Mini and they go for about $4 and that's really hard to beat.


body:
Are there any i2c LCD screens that are larger than 2004 characters and larger than 4.8 x 2.7 x 1.2 inches in dimensions?

I have the [Sainsmart 2004 LCD][1] but it can't display all the information that I need. Maybe a 20x8 character screen? Because the screen will be viewed from a distance of about 50cm, the screen size should be at least 5" in diagonal.

![enter image description here][2]

  [1]: https://www.sainsmart.com/products/20x4-iic-i2c-twi-lcd-module
  [2]: https://i.stack.imgur.com/X6vHl.png

title: LCDs larger than 20x04 and 5" diagonal

Answers: 3

body:
Naked displays... search e.g. Ebay for "40x4 lcd" (maybe enable "worldwide" search)...

...naked... so not i2c ... but Arduino libs for these displays exist (e.g.: [liquidcrystal440][1]), so add an Arduino-Pro or such and you can have i2c... basically they are two 40x2 displays on the same spi bus selected by different chip select lines...

  [1]: https://code.google.com/p/liquidcrystal440/

body: The 44780 display chip used by these devices has 80 bytes of storage, which is why you can scroll the 2x16 side to side to show up to 40 characters per line. however 4x20 is 80 and that's the limit of the chip.

body:
There are ST7920 based displays which may come close to what you are looking for. They have a similar parallel (4 or 8 bit) interface to the HD44780 based displays (as you have been using), but also support a 3-wire SPI-like interface.

A quick google found the datasheet here:
https://www.lcd-module.de/eng/pdf/zubehoer/st7920_chinese.pdf

They have both graphics and text modes, and most of the displays appear to have 128x64 pixels, giving 16x8 characters assuming 8x8 font, although it appears the native text font is 16x8 pixels.

While it might be more complicated to use these in graphics mode, they are probably the closest to the HD44780 based displays in appearance (large monochrome pixels), unlike other large displays which will probably have more (smaller) pixels than you need.

See also https://playground.arduino.cc/Code/LCD12864


body:
I am connecting my Arduino to my Cubieboard that is running Android.

I tested this originally with my android tablet and USB cable. This worked successfully for the most part using the firmata kit but I don't want to use firmata.

I want a basic function library written in Java for use with Unity (eg [Library Tutorial Video][1]) to connect to the Arduino via the USB serial port connection much like a connection with my Windows computer.

**I'd like basic command functions like:**

 - Connect / Open
 - Write
 - Read
 - Flush
 - Close

I was thinking maybe of using this library [here][2] but I am unsure how to go about this. I know similar discussion have already taken place on the forum claiming it may not be possible, but it is very clear that it is. It has been done many times. All I need to do is send strings with serial after finding the Arduino's COM port and reading from the serial.

  [1]: https://www.dropbox.com/s/i1mera8850cp6u8/Creating a Simple Unity plugin to Android.mp4
  [2]: https://github.com/mik3y/usb-serial-for-android

title: How to create a serial communication connection between Cubieboard running Android and Arduino

Answers: 2

body:
Using the library you linked should be a simple case of downloading the library's jar file from https://github.com/mik3y/usb-serial-for-android/releases and adding it as a reference/library/dependency (I forget what eclipse calls them) in your eclipse project.

Then of course providing you connect with the right baud rates and so on it should work.

body:
Totally insane thought here but.....

Have you tried writing a chrome App to talk to your Arduino?

I did it on the Mac - had chrome monitoring things happening on the network and sending Serial Commands to the Arduino over USB.

You can find samples in the Chrome samples / docs

https://developer.chrome.com/apps/serial


body:
This is a follow on question from https://arduino.stackexchange.com/questions/1002/how-to-reduce-serial-speed-on-arduino-bootloader-optiboot-and-on-the-ide

I did manage recompile optiboot bootloader to work at 57600 bps and uploaded it to a couple of ATmega328-PUs. I just changed the `BAUD_RATE` to `57600L` in Makefile and recompiled it.

They worked just fine with my [Arduino Single Sided Serial (Severino)](http://arduino.cc/en/Main/ArduinoBoardSerialSingleSided3) and a couple of custom standalone Arduino boards with FTDI-like header.

However, I couldn't program the same MCUs using my Arduino Uno R3. When I try to upload a sketch, avrdude just sits there waiting for a response that doesn't come. The output I got is something like this:

    avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "C:\Users\Ricardo\arduino-1.0.5\hardware/tools/avr/etc/avrdude.conf"

             Using Port                    : \\.\COM3
             Using Programmer              : arduino
             Overriding Baud Rate          : 57600
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Recv:
    avrdude: stk500_getsync(): not in sync: resp=0x00

    avrdude done.  Thank you.

Would that have anything to do with the 2nd MCU that acts as the USB driver on the Uno - the [ATmega16U2](http://www.atmel.com/devices/atmega16u2.aspx)? Do I have to patch it, too?

So, my questions are:

**1. Why my recompiled optiboot didn't work with my Arduino Uno R3?**

**2. What can I do to check what's wrong with the upload process using my new bootloader?**

title: Why my Arduino Uno R3 doesn't work with a recompiled optiboot with BAUD_RATE=57600

Answers: 1

body:
Chris Stratton's comments helped me find a workaround for my problem. It looks like the version of optiboot I was working with (see [source-code here](http://pastebin.com/d8NUirfZ)) doesn't work properly at 57600 BAUD with Arduino Uno without modifications (that I don't know how to make). So I compiled the bootloader with 76800 BAUD, configured the IDE accordingly, and all my boards started to work fine with it.

It is still unclear to me the reason I one can't use 57600 BAUD, but I'm too pragmatic and too little knowledgeable to go after the true answer. So, I'll take Chris' word for it. He said this:

> Basically, 57600 does not divide in 16 MHz nicely when the 8x or 16x oversampling of the hardware UART is taken into account. My gut feeling is that different implementation are using different approximations. If they used the same approximation then even if "wrong" things would be basically fine (especially as the hardware design is similar), but if they are are off in opposite directions it could be unreliable. If you post the exact bootloader source you used we can see for sure - some optiboot source I just looked at seems to actually be using a software UART for 57600.

That's the end of it for me.


body:
I'd always thought Arduino was a microcontroller platform but the actual microcontroller is an AVR chip made by Atmel, or something like that made by someone else, based on a RISC ISA, and Arduino is usually used to refer to the whole circuit board powered by this AVR chip. Is my understanding correct?

What's the difference/relationship between Arduino and AVR?

Answers: 6

body:
The Arduino is an AVR processor running special code that lets you use the Arduino environment.

AVR's can be used by themselves with some additional supporting components.

Arduino is a combination of both AVR(chip) and breadboard.

AVR is a single chip, and would require a breadboard.

body:
Arduino is a prototyping board, and the term "Arduino" is also used to refer to the IDE and library on the PC side, and the whole ecosystem.
AVR is the architecture (developed by Atmel) of the microcontroller chip used in all official 8-bit boards, and almost all clones.
Arduino UNO and 2009, the most used boards, use the AtMega328P chip.

Many times, Arduino is used to quickly test some idea, sensor, and circuitry, then a stand-alone board is built around the AtMega chip, as it cost 1/10 of the Arduino board, soldered circuit on a stripboard or on a custom PCB are more reitable, and can be optimized on some aspect, like power usage, space occupied, high current/voltage, and so on.

Newest and advanced Arduino board use a different chip with a very different architecture; the Arduino Yun uses a SAM plus a classic AVR, the Due uses an ARM (same architecture used by many smartphones), the Galileo use an x86 (like a classic single-core cpu).

body:
[Arduino is a set of open-sourced hardware- and software specifications, originally conceived as a students' platform.][1] I would add that the specifications, though openly available, are distributed under various public licenses.

There are "official" Arduino boards made by an Italian company of the same name, but as the board designs are open-sourced, there are lots of good (and a few "less good") variants from other sources.

AVR refers to the line of MCUs manufactured by Atmel and used in the original designs. Atmel was acquired in 2016 by Microchip Technology, who continue to manufacture the AVR devices.

Some of the more recent Arduino designs use more capable processors from other chip manufacturers, but many still use the Atmel/Microchip AVR processors. The smaller AVRs' relative simplicity (ATtiny & ATmega, f/ex) make them ideal for quickly designing/building boards and software for less demanding applications and for learning about programming and digital controls.

  [1]: https://en.wikipedia.org/wiki/Arduino#History

body: The Arduino tools and ecosystem supports processors other than just Atmel AVR chips.  For instance the Arduino Due uses an ARM Cortex-M3 processor.

body:
Arduino is really a common set of code that makes using the dev boards they sell accessible to wide range of user base.

Arduino is basically an IDE that uses the C/C++ language and a set of classes that are adaptable to common set of hardware, predominantly Atmel and mostly AVR although as people have mentioned already the Arduino boards are becoming increasingly more powerful. But is amazing how much you can do with the ATmega328p.

You don't have to use the Arduino IDE to program your board and in fact, I tend to use Atmel Studio myself or Notepad++. You can get a plug-in for Atmel Studio 6.2 and above that allows you to create sketches and upload them to most Arduino boards.

body:
Although the previous answers are technically correct, I think there is currently a shift in the meaning of "Arduino".

When the original Arduino boards were released they were head and shoulders better than the competition, especially when looking at the cost vs performance tradeoff.

But this is no longer the case. Boards based around the ESP8266 and ESP32 chips are cheaper and far more powerful than the Atmel chips. Also, the AVR IDE environment has been extended to support these chips. And to further confuse the issue this "Arduinio" forum has almost 2000 questions tagged ESP8266 and around 850 tagged ESP32.

So expect changes. They are already happening. Will "Arduino" come to mean any chip supported by the IDE? Will this forum move to a more generic name like IOT? I really don't know.


body:
I have Code for Mod bus Library as below. I have Gone through lots of forum. How to assign device ID, slave address, length using below library function:

    #include <SimpleModbusSlave.h>
    #define  LED 9
    enum
    {

      ADC_VAL,
      PWM_VAL,
      HOLDING_REGS_SIZE // leave this one
    };

    unsigned int holdingRegs[HOLDING_REGS_SIZE];
    void setup()
    {
      modbus_configure(&Serial, 9600, SERIAL_8N2, 1, 2, HOLDING_REGS_SIZE, holdingRegs);
      pinMode(LED, OUTPUT);
    }

    void loop()
    {
      modbus_update();
      holdingRegs[ADC_VAL] = analogRead(A0); // update data to be read by the master to adjust the PWM
      analogWrite(LED, holdingRegs[PWM_VAL]>>2); // constrain adc value from the arduino master to 255
    }

I am getting Error has.

    SimpleModbusSlaveArduino.cpp: In function 'void setup()':
    SimpleModbusSlaveArduino:79: error: 'SERIAL_8N2' was not declared in this scope

![Error message for IDE][1]

I have  made changes in the lib as in forum. but I found no value read by my software.

Master sending below request on read mode. But not receiving anything.

    12:31:02.953: Com8, Baud Rate: 9600, Data Bits: 8 Bits, Parity: None, Stop Bits: 1 Stop Bit
    12:31:02.953: Echoback: On, RTS Control: On, Transmit Delay: 5 ms, Response Delay: 1000 ms
    12:31:02.953: Read Holding Register(s), Repeat Loop
    12:31:02.953: Device Address: 01h, Register: 0000h
    12:31:02.953: |-> Read Register: 0000h
    12:31:02.968: -> [01h] [0Dh] [00h] [00h] [00h] [01h] [CBh] [EDh]

![my softawre][2]
[CHANGES MADE IN AS IN FORUM MENTIONED][3]

  [2]: https://i.stack.imgur.com/rJSz8.jpg
  [3]: http://forum.arduino.cc/index.php?topic=176142.0

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

title: Modbus Protocol Compile Error

Answers: 2

body:
Not sure where you got the library from, but if it's from this [github repo][1], you're using it wrong.

The function prototype for `modbus_configure` is:

    void modbus_configure(long baud, byte _slaveID, byte _TxEnablePin, unsigned int _holdingRegsSize, unsigned char _lowLatency);

The [example file][2] shows how to use it correctly

    modbus_configure(115200, 1, 2, TOTAL_REGS_SIZE);

  [1]: https://github.com/thibs0/EWC2013-Greenhouse-demo/tree/master/Arduino/libraries/SimpleModbusSlave
  [2]: https://github.com/thibs0/EWC2013-Greenhouse-demo/blob/master/Arduino/libraries/SimpleModbusSlave/examples/SimpleModbusSlaveExample/SimpleModbusSlaveExample.ino

body:
In your first example the error is that SERIAL_8N2 is not declared. maybe you are using an old Arduino IDE? try latest 1.0.x or 1.5.x

in the second case TOTAL_REGS_SIZE is a pointer to int, while the function expect a char. Without code is hard to tell what is wrong and how, but in your first code it should be

    modbus_configure(115200, 1, 2, HOLDING_REGS_SIZE);

also because you are not passing a reference to the array, you have to pass a pointer pointing the current element in the update function

    modbus_update(holdingRegs[i]);
    i++


body:
Is there a way to get a DateTime object from a unix timestamp and hour offset? I want to be able to print a formatted string, for example `Wed Apr 02 17:15:06 2014`.

I have:

 1. A unix timestamp: `1396451852`.
 2. An offset from my hour zone, `+1` hour.

Note: I get the timestamp from an internet service and want to make the conversion in the Arduino.

title: Can I get a Datetime object from a unix timestamp?

Answers: 2

body:
The [Arduino Time Library][1] looks like it can do it. Or have a look at the strftime() function from unix and unix-oid environments. There is [source to strftime() here][2]. It's pretty large but you can probably cut it down considerably to just the format parts you need.

  [1]: http://playground.arduino.cc/Code/Time
  [2]: http://www.jbox.dk/sanos/source/lib/strftime.c.html

body:
The seconds since (UNIX) epoch relies on a [database](https://en.wikipedia.org/wiki/Tz_database).

> New editions of the database and code are published as changes warrant, usually several times per year.

Your options can:

- Reduce the timezone database to the timezone you are actually interested in;
- Don't forget about daylight savings time for you specific timezone;
- The leap years are well known too and reasonably easy to program;
- The leap seconds are decided upon usually only couple months before they are introduced and therefore cannot be accounted for in an algorithm.

Conclusion
-
- So can you convert epoch to a time/date format? Yes.
- Will it be accurate? It'll drift away over time (months or years)

Advise
-
If you retrieve epoch from an Internet service, why not use (another?) webserver that has the full timezone database available to convert it to accurate date/time, or 'synchronize' against every once in a while?


body:
I'm trying to understand how to fully use the COMPB vector ISR of Timer0 on the ATMega328 (standard Arduino core). I realize it will make delay() and millis() not work but that's ok by me. I've setup some test code that *should* output a 244Hz signal on D4 and 488Hz on D5 (note, this is running at 8MHz). But D5 (COMPB) is always what D4 (COMPA) is. Any thoughts? Code below:

    #include <avr/interrupt.h>

    volatile bool stateA = false;
    ISR(TIMER0_COMPA_vect)
    {
     if (stateA)
      PORTD |= _BV(PIND4);
     else
      PORTD &= ~(_BV(PIND4));

     stateA = !stateA;
    }

    volatile bool stateB = false;
    ISR(TIMER0_COMPB_vect)
    {
     if (stateB)
      PORTD |= _BV(PIND5);
     else
      PORTD &= ~(_BV(PIND5));

     stateB = !stateB;
    }

    void setup()
    {
     DDRD |= _BV(PIND4) | _BV(PIND5);

     //set timer0 interrupt at 2kHz
     TCCR0A = 0;// set entire TCCR2A register to 0
     TCCR0B = 0;// same for TCCR2B
     TCNT0 = 0;//initialize counter value to 0
     // set compare match register for 2khz increments
     OCR0A = 255;//244Hz
     OCR0B = 127;//488Hz
     // turn on CTC mode
     TCCR0A |= (1 << WGM01);
     // Set CS01 and CS00 bits for 64 prescaler
     TCCR0B |= (1 << CS01) | (1 << CS00);
     // enable timer compare interrupt
     TIMSK0 |= (1 << OCIE0B) | (1 << OCIE0A);

     interrupts();

    }

**Update:** After thinking about it, I'm realizing that it's not that I need two separate frequencies (though I just kinda wanted to know how, so this is good stuff) but I just need two separate interrupts, only using Timer0 (1 & 2 are already in use elsewhere). They can be the same frequency, most likely. I probably *could* put all the functionality I need in the same TIMER0_COMPA_vect, however I was trying to use that in a library I was writing and was trying to keep the functionality separate... this may not be possible.

title: Using TIMER0_COMPB_vect

Answers: 4

body:
Your code doesn't do what you think it does. The timer always runs at 244Hz, and OCR0B only matches twice per period, causing it to have the same frequency but a different phase. What you need to do is set OC0B on compare match and clear it in the overflow ISR. OCR0A you can simply set to toggle on match.

    TCCR0A = _BV(COM0A0) | _BV(COM0B1) | _BV(COM0B0) | _BV(WGM01);
    TIMSK0 |= _BV(OCIE0A);

     ...

    ISR(TIMER0_COMPA_vect)
    {
      PORTB &= ~_BV(PD5);
    }

Also, OC0A is D6, not D4.

body:
I think your code did not set `TIMSK0` properly.

Instead of:

    TIMSK0 |= (1 << OCIE0B) | (1 << OCIE0A);

You should use:

    TIMSK0 = (1 << OCIE0B) | (1 << OCIE0A);

Why? Because `TIMSK0` is already initialized by Arduino libraries before your `setup()` is called.

If you take a look at `hardware/arduino/cores/arduino/wiring.c` and search for the `init()` function, you will see that it contains the following lines:

     // enable timer 0 overflow interrupt
    #if defined(TIMSK) && defined(TOIE0)
     sbi(TIMSK, TOIE0);
    #elif defined(TIMSK0) && defined(TOIE0)
     sbi(TIMSK0, TOIE0);
    #else
     #error Timer 0 overflow interrupt not set correctly
    #endif

With these lines, the `TOIE0` bit of `TIMSK0` is set, but your `setup()` does not clear it.

body:
Actually, after reading the ATmega328P datasheet again, I am not sure that you can use both `OCR0A` and `OCR0B` in normal timer mode.

In particular, since you use CTC mode, I think that `TCNT0` will be cleared every time its value reaches `OCR0A` i.e. 127.

Since you need 244Hz and 488Hz (exactly twice 244Hz), I think you can operate with only one of `OCR0A` or `OCRB0` and do the work in one ISR only:

    #include <avr/interrupt.h>

    volatile bool setBothPins = false;
    ISR(TIMER0_COMPA_vect)
    {
        if (setBothPins)
            // D4 is changed only once (244Hz)for every 2 changes of D5 (488Hz)
            PORTD ^= _BV(PIND4);
        PORTD ^= _BV(PIND5);

        setBothPins = !setBothPins;
    }

    void setup()
    {
        DDRD |= _BV(PIND4) | _BV(PIND5);

        //set timer0 interrupt at 2kHz
        TCCR0A = 0;// set entire TCCR2A register to 0
        TCCR0B = 0;// same for TCCR2B
        TCNT0 = 0;//initialize counter value to 0
        // set compare match register for 2khz increments
        OCR0A = 127;//488Hz
        // turn on CTC mode
        TCCR0A |= (1 << WGM01);
        // Set CS01 and CS00 bits for 64 prescaler
        TCCR0B |= (1 << CS01) | (1 << CS00);
        // enable timer compare interrupt
        TIMSK0 = (1 << OCIE0A);

        interrupts();
    }

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


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

title: Connecting to network with wifi shield

Answers: 2

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.


body:
I am not able to receive data. I am able to send data from master but am not getting any response. This program uploaded successfully. I have below setup to monitor data from Modbus.

I have included code for Modbus protocol below.

Also, can someone suggest me the link to download modbus slave config library without any error along with wiring diagram

    11:42:17.000: Device Address: 01h, Register: 000Dh
    11:42:17.000: |-> Read Register: 000Dh
    11:42:17.015: -> [01h] [0Dh] [00h] [0Dh] [00h] [01h] [08h] [7Ch]

![MYsetup][1]

    #include <modbus.h>
    #include <modbusDevice.h>
    #include <modbusRegBank.h>
    #include <modbusSlave.h>

    /*
    This example code shows a quick and dirty way to get an
    arduino to talk to a modbus master device with a
    device ID of 1 at 9600 baud.
    */

    //Setup the brewtrollers register bank
    //All of the data accumulated will be stored here
    modbusDevice regBank;
    //Create the modbus slave protocol handler
    modbusSlave slave;

    void setup()
    {

    //Assign the modbus device ID.
      regBank.setId(1);

    /*
    modbus registers follow the following format
    00001-09999  Digital Outputs, A master device can read and write to these registers
    10001-19999  Digital Inputs, A master device can only read the values from these registers
    30001-39999  Analog Inputs, A master device can only read the values from these registers
    40001-49999  Analog Outputs, A master device can read and write to these registers

    Analog values are 16 bit unsigned words stored with a range of 0-32767
    Digital values are stored as bytes, a zero value is OFF and any nonzer value is ON

    It is best to configure registers of like type into contiguous blocks.  this
    allows for more efficient register lookup and and reduces the number of messages
    required by the master to retrieve the data
    */

    //Add Digital Output registers 00001-00016 to the register bank
      regBank.add(1);
      regBank.add(2);
      regBank.add(3);
      regBank.add(4);
      regBank.add(5);
      regBank.add(6);
      regBank.add(7);
      regBank.add(8);
      regBank.add(9);
      regBank.add(10);
      regBank.add(11);
      regBank.add(12);
      regBank.add(13);
      regBank.add(14);
      regBank.add(15);
      regBank.add(16);

    //Add Digital Input registers 10001-10008 to the register bank
      regBank.add(10001);
      regBank.add(10002);
      regBank.add(10003);
      regBank.add(10004);
      regBank.add(10005);
      regBank.add(10006);
      regBank.add(10007);
      regBank.add(10008);

    //Add Analog Input registers 30001-10010 to the register bank
      regBank.add(30001);
      regBank.add(30002);
      regBank.add(30003);
      regBank.add(30004);
      regBank.add(30005);
      regBank.add(30006);
      regBank.add(30007);
      regBank.add(30008);
      regBank.add(30009);
      regBank.add(30010);

    //Add Analog Output registers 40001-40020 to the register bank
      regBank.add(40001);
      regBank.add(40002);
      regBank.add(40003);
      regBank.add(40004);
      regBank.add(40005);
      regBank.add(40006);
      regBank.add(40007);
      regBank.add(40008);
      regBank.add(40009);
      regBank.add(40010);
      regBank.add(40011);
      regBank.add(40012);
      regBank.add(40013);
      regBank.add(40014);
      regBank.add(40015);
      regBank.add(40016);
      regBank.add(40017);
      regBank.add(40018);
      regBank.add(40019);
      regBank.add(40020);

    /*
    Assign the modbus device object to the protocol handler
    This is where the protocol handler will look to read and write
    register data.  Currently, a modbus slave protocol handler may
    only have one device assigned to it.
    */
      slave._device = &regBank;

    // Initialize the serial port for coms at 9600 baud
      slave.setBaud(9600);
    }

    void loop()
    {
    //put some data into the registers
      regBank.set(1, 1);
      regBank.set(2, 1);
      regBank.set(3, 0);
      regBank.set(4, 1);
      regBank.set(5, 1);
      regBank.set(6, 0);
      regBank.set(7, 1);
      regBank.set(8, 0);

      regBank.set(10001, 1);
      regBank.set(10002, 1);
      regBank.set(10003, 1);
      regBank.set(10004, 1);
      regBank.set(10005, 0);
      regBank.set(10006, 0);
      regBank.set(10007, 0);
      regBank.set(10008, 0);

      regBank.set(30001,1);
      regBank.set(30002,2);
      regBank.set(30003,3);
      regBank.set(30004,4);
      regBank.set(30005,5);
      regBank.set(30006,6);
      regBank.set(30007,7);
      regBank.set(30008,8);
      regBank.set(30009,9);
      regBank.set(30010,10);

      regBank.set(40001,1);
      regBank.set(40002,2);
      regBank.set(40003,2);
      regBank.set(40004,4);
      regBank.set(40005,5);
      regBank.set(40006,6);
      regBank.set(40007,7);
      regBank.set(40008,8);
      regBank.set(40009,9);
      regBank.set(40010,10);

     while(1)
      {
        //put a random number into registers 1, 10001, 30001 and 40001
        regBank.set(1, (byte) random(0, 2));
        regBank.set(10001, (byte) random(0, 2));
        regBank.set(30001, (word) random(0, 32767));
        regBank.set(40001, (word) random(0, 32767));

         slave.run();
      }
    }

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

title: MODbus response for configure data

Answers: 0


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

title: Modifying serial message for Adafruit NFC/RFID card

Answers: 1

body:
had to simply modify PrintHex in
Adafruit_NFCShield_I2C.h

to accept an additional argument


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

title: Pass variable in a URL

Answers: 3

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


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

title: Change Options for the AVR Programmer via Arduino IDE

Answers: 1

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


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

title: Arduino Lego Robot

Answers: 1

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


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

title: Response of Modbus Protocol

Answers: 1

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


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

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

Answers: 2

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.