text:
What is the point of D0-D3 on LCD?
The Arduino LiquidCrystal library has 4 constructors with different arguments:
LiquidCrystal(rs, enable, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d4, d5, d6, d7)
LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)

The following comments are stated for the constructor arguments:

[...] d0, d1, d2, and d3 are optional; if omitted, the LCD will be controlled using only the four data lines (d4, d5, d6, d7).

What is the point of d0-d3 if they are not needed? Will they decrease the response time?

That type of LCD has two main modes of operation: 4-bit mode which uses 4 data pins (d4-d7), and 8-bit mode which uses all 8 data pins (d0-d7).
4-bit mode has the advantage of requiring fewer output pins on your Arduino. However, it means your sketch needs to send each command/character as two separate batches of 4-bits (one after the other). This is handled for you automatically by the LiquidCrystal library, so you won't need any extra complexity in your code. However, it does mean that your sketch requires roughly double the number of processor cycles to send anything to the LCD.
In contrast, 8-bit mode sends each command/character as a single batch of 8-bits. That simply means it technically runs a little faster.
With that said, a person looking at the display probably won't see a significant speed difference most of the time, as it still goes very quickly. The main impact will be on the microcontroller (the Arduino in this case). If it can use the faster 8-bit mode then it can devote a little more processing time to other things. That can be particularly helpful for timing-critical applications.

With that said, a person looking at the display probably won't see a significant speed difference most of the time, as it still goes very quickly. Which isn’t usually a problem since many modules (especially cheap Chinese ones like the ones on eBay) tend to have low refresh rates, so you can't update them too fast without them turning into a blurry, unreadable mess anyway.

The answer is on the same page as the quote you mentioned (I have highlighted the important statement):

Creates a variable of type LiquidCrystal. The display can be controlled using 4 or 8 data lines. If the former, omit the pin numbers for d0 to d3 and leave those lines unconnected. The RW pin can be tied to ground instead of connected to a pin on the Arduino; if so, omit it from this function's parameters.

It turns out that the Hitachi HD44780 LCD display can work in 4-bit or 8-bit modes.

Yes, it says it can be controlled using both 4 and 8 data lines. But what is the point of using 8 if you only need 4? I mean, isn't there any advantage of using 8 over 4? Why waste 4 data lines if it's of no use?

Using 8 bits mode is a bit faster on Arduino side and simpler (less code). But in general, it is not really worth it, in comparison to sparing 4 output pins.

@jfpoilpret It's worth it if you have four extra output pins...

@annon can you be more concrete about HOW it is worth to use 8 pins mode? Concrete experiment values?

@jfpoilpret As stated in Peter's answer, it gives a little more processing time to the chip. If you have four extra pins, go ahead and add it. If it would require it to be much bigger/more expensive, it's not really worth it.

The presence of those pins is a requirement of the technique that had to be used to interface the LCD to the microprocessors that were available back when the HD44780U controller chip was developed.
Single chip microcontrollers as we know them were still in the future and the LCD had to be interfaced to the 8-bit microprocessor chips of the times using the same techniques as any other 8-bit I/O or memory device which was an 8-bit bus.


text:
How to reduce serial speed on Arduino bootloader (optiboot) and on the IDE?
I'm debugging a couple of RS232-to-TTL converter boards that I'm trying to use to program my Arduinos and one thing I would like to try would be to reduce the upload serial speed from 115200 to 19200.
How do I do that?
I imagine that there's a setting that can be easily changed on the Arduino IDE preferences. But where is it? But then the bootloader speed would have to match that? How do I change the serial upload speed on optiboot, too?

On Arduino IDE side, the upload speed is coded in hardware/arduino/boards.txt
uno.upload.speed=115200
...

for every kind of board; you cannot change it directly from the IDE (that would be too dangerous as that value must match the expected speed for the actual bootloader of every board).
Now as per the optiboot loader side, the upload speed is defined in BAUD_RATE macro, in optiboot.c:
/* set the UART baud rate defaults */
#ifndef BAUD_RATE
#if F_CPU >= 8000000L
#define BAUD_RATE   115200L // Highest rate Avrdude win32 will support
#elsif F_CPU >= 1000000L
#define BAUD_RATE   9600L   // 19200 also supported, but with significant error
#elsif F_CPU >= 128000L
#define BAUD_RATE   4800L   // Good for 128kHz internal RC
#else
#define BAUD_RATE 1200L     // Good even at 32768Hz
#endif
#endif

So I guess you can:

#define BAUD_RATE 19200 before that block of code
recompile the optiboot loader
upload your own new bootloader version
update uno.upload.speed accordingly in boards.txt
check it on the usual blink sketch and cross your fingers :-)

Please note that this kind of task is not for beginners, you need to know what you're doing.
Also note that I disclaim any responsibility if you get unable to upload programs to your Arduino afterwards!

This isn't going to "fry" your arduino. At worst, you'd wind up with a ATmega with a
damaged boot loader, which would just mean you'd need to re-program it again via ICSP.

Then say you could render your arduino unrecoverable without a proper programmer. "Fry" implies actual hardware damage, not just mis-configuration that makes recovery involved.

no proprer progrqammer is needed, you can use ftdi/8u2 chip on-board with bit-bang mode.

Tried it and it worked great! Well, the Uno didn't like the optiboot running on 56200 bps (not sure why), but the Severino and my custom boards with serial FTDI-like programming headers all worked. I also couldn't compile the optiboot slower than that (tried 19200) because other compile errors, but that's ok. I used Arduino IDE 1.0.5 and followed the instructions on .\hardware\arduino\bootloaders\optiboot\README.TXT and didn't have to install anything beyond the IDE. Nice!!

And that solved the problem with my RS232-to-TTL converter board. It worked ok with 56200 bps. Thanks much!!

source: Stack Exchange

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

sort: votes


text:
Can the Arduino Uno become an AVR programmer and use the ICSP header to program the target board
The Arduino Uno has an ICSP header that I imagine is for programming the board using a separate ICSP programmer. That is, its ICSP header turn the board into a target.
Can one use that same ICSP to program other boards, turning the Arduino Uno effectively into a ICSP AVR programmer? How?
I'm assuming that the target boards would also be Arduinos and wanted the Uno to program them using the Arduino IDE. Is that possible?
Reading the AVR In-System Programming Application Note it looks to me that the only issue would be to make the programmer (the Arduino Uno) control the target board reset line. I've seen something like that in ArduinoISP sketch, but in that sketch, the target reset is controlled by port D10. But one could program the reset line to be an output, right? So could we change the ArduinoISP sketch to use its own reset line as output to control the target board reset line? If not, why not?

First of all, as configured, the RESET pin can not be used as an output pin. In order to use it as an I/O pin, you would have to program the RSTDISBL fuse. But once you do that, as jippie said, it becomes near-impossible to reprogram your Arduino (if you have the socketed through hole variety of the MCU, you could pull it out and put it into a high voltage programmer; in all other cases, it's effectively impossible).
So in theory, you can use the ICSP header the way you suggest. In practice, it's under almost any conceivable circumstance a terrible idea.

I recommend going out and buying an AVR Dragon - costs aroud $US50. That gives you ISCP programming plus debugwire debugging (using the Atmel Studio IDE).

Atmel Studio only runs on Windows. That's fine if you have Windows, not so great if you are using Linux or Mac.

To answer my own question, just to report that I found something close to what I was looking for, which I link and describe briefly below.
Gammon Software Solutions forum - Atmega Bootloader Programmer - Programming Cable
On that page, the author suggest that we cut pin 5 from the 6-pin ICSP programming cable, solder a pin to it, and wire it to pin D10. Like so:

Then, you can load the Arduino Uno with the ArduinoISP sketch and program the target board as usual.

Yes you can program the Arduino's reset input pin as an output and use that to program another AVR, but you can no longer program your Arduino as that relies on the controller being reset through its own reset pin.
Coming to think about it, I am not sure how the other devices (like the USB controller) responds to being reset by Arduino's controller itself. It resets the USB controller which may or may not reset the connection to the computer, possibly loosing data. With the USB controller being reset, GPIO-pins D0 and D1 (the serial interface between PC and Arduino's AVR) may corrupt the datastream.

In the R3, the nRESET line of the USB controller is not connected to the nRESET line of the main MCU, but only to its own ISP connector. Cutting a trace will disconnect the nRESET line of the main MCU, and jumpering a pair of pads ("RESET EN") will reenable it.

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


text:
Client or WiFiClient wrapper for adafruit CC3000 wifi
I have a CC3000 wifi module from adafruit that is working OK. Now, I am trying to use it together with an external service, which code requires me to pass a Client (from Arduino SDK) reference, but the Adafruit_CC3000_Client does not inherit from Client nor WifiClient.
I am looking for an appropiate wrapper, but unable to find one. Does anyone know about such wrapper?

write it yourself, extends the Client class and override its method to call CC3000 method :)

Yes, as I didnt get any answers, I have started to do so, but it is a little tricky, I will post the answer when I am able to get it working properly.

As I didn't get any answer, and further search for an existing solution failed, I decided to roll my own. The class header is very straightforward, I decided to go for single inheritance and composition of Adafruit_CC3000_Client:
class CC3000Client: public WiFiClient {
public:
    CC3000Client(Adafruit_CC3000& cc, Stream& stream=Serial);
    virtual ~CC3000Client();

    virtual int connect(IPAddress ip, uint16_t port);
    virtual int connect(const char *host, uint16_t port);
    virtual uint8_t connected();
    virtual int available();
    virtual void stop();
    virtual void flush();
    virtual int peek();
    virtual int read();
    virtual size_t write(uint8_t v);
    virtual size_t write(const uint8_t *buf, size_t size);
    virtual int read(uint8_t *buf, size_t size);
    virtual operator bool();

private:
    Adafruit_CC3000& cc3000;
    Adafruit_CC3000_Client client;
    bool peeked;
    int peeked_byte;
    Stream& stream;
};

The implementation is a bit tricky (or I didn't manage to find a better way), as the Adafruit client does not have peek() functionality, so this wrapper class have to implement it.
CC3000Client::CC3000Client(Adafruit_CC3000& cc, Stream& stre) :
        cc3000(cc), peeked(false), stream(stre), peeked_byte(0) {
}
CC3000Client::~CC3000Client() {
}

int CC3000Client::connect(IPAddress ip, uint16_t port) {
    client = cc3000.connectTCP((uint32_t) ip, port);
    peeked = false;
    if (client.connected())
        return 1;
    return 0;
}
int CC3000Client::connect(const char *host, uint16_t port) {
    uint32_t ip = 0;
    if (!cc3000.getHostByName((char*) host, &ip)) {
        stream.println(F("Couldn't resolve!"));
        return 0;
    }
    client = cc3000.connectTCP(ip, port);
    peeked = false;
    if (client.connected()) {
        return 1;
    }
    return 0;
}
uint8_t CC3000Client::connected() {
    return (uint8_t) client.connected();
}
int CC3000Client::available() {
    if(peeked)
        return 1;
    return (int) client.available();
}
void CC3000Client::stop() {
    peeked = false;
    flush();
    while (client.connected()){
        client.close();
        delay(10);
    }
}
void CC3000Client::flush() {
    peeked = false;
    while (connected() && available())
        read();
}
int CC3000Client::peek() {
    if (!peeked) {
        if (available()) {
            peeked_byte = read();
            peeked = true;
        } else
            return -1;
    }
    return peeked_byte;

}
int CC3000Client::read() {
    if (peeked) {
        peeked = false;
        return peeked_byte;
    }
    return (int) client.read();
}
size_t CC3000Client::write(uint8_t v) {
    return (size_t) client.write(v);
}
size_t CC3000Client::write(const uint8_t *buf, size_t size) {
    return client.write(buf, size);
}
int CC3000Client::read(uint8_t *buf, size_t size) {
    if(peeked){
        buf[0]=peeked_byte;
        peeked=false;
        return client.read(buf+1, size-1);
    }
    return client.read(buf, size);
}
CC3000Client::operator bool() {
    stream.println("Error, bool() not implemented");
    return true;
}

Both files are available here, if you are using biicode all you have to do in your code is to put an include like the following and run "bii find", that will also retrieve and install the cc3000 library:
#include "diego/ardunet/cc3000client.h"

I have used and tested it with a simple http_get call (also here) and with the temboo service, and it has worked OK for sending emails from a Gmail account from an Arduino Mega2560 connected to the CC3000. This temboo service uses via the SDK Client interface most methods of this wrapper, but the bool() operator and the CC3000Client::write(const uint8_t *buf, size_t size) method.


text:
Nothng Written to Serial when using sprintf
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;
        }

    }
}

Where do you actually allocate any memory to result?

define 'gibberish'. Can you give some examples of what you are receiving? Have you got the monitor on 9600 as well? You realise you're Serial.printing message before you're allocating your read to it? And that at the end of the read there is possibly a new line which clears your message anyway, so it's never going to be seen

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.

Unfortunately it isn't quite always good to initialize them. Initializing them (or leaving them with the default value) will add prologue code to set/clear them even if the original value is never used; to prevent this declare the variable as being uninitialized, e.g. char *result __attribute__ ((section (".noinit")));. See the "Memory Sections" section of the AVR Libc documentation for details.

Thank you. When I try to empty out message using message="", I get the error in the (updated) question. Whats the proper way to clear a buffer?

@Nyxynyx: Why do you need to clear it?

@IgnacioVazquez-Abrams I updated the code in the question to show why I'm clearing it, thanks!

Oh boy... Unfortunately string handling in C is not quite as simple as you try to make it. Consider using string or String instead.

@IgnacioVazquez-Abrams It does work with String, but I'm reading lots of tips about how String is dynamically allocated and will encounter errors after some time.

Handling C strings is a bit out of scope for this site. Consider reading through C string questions on Stack Overflow for some insight on how they work.


text:
Arduino Uno R3 ISR does not work on pin 2?
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);
}

Have you compared the disassembled code when using each pin?

Can you show us the code of the ISR and how you registered it?

Where do you set pinMode() of pin 2 to INPUT?

@jfpoilpret it doesn't need pinMode() and the ISR is hidden by the arduino code in the attachInterrupt

I hope you haven't forgotten to change attachInterrupt(0,itest,FALLING); to attachinterrupt(1,itest,FALLING);

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


text:
How do I split an incoming string?
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?

i have slave(arduino uno) send string via serial 30;12.4;1
and 1 master (esp8266) recive string
i want in master have seperated data like
30
12.4
1
and save it in micro sd card

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(): search for a character in a C string (i.e. char *)
strtok(): splits a C string into substrings, based on a separator character
atoi(): converts a C string to an int

That would lead to the following code sample:
// 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.

Hadn't thought of the memory issue.  this is great.

Excellent. My answer was very "arduino" based and using typical arduino SDK functions which a novel user could be more used to, but this answer is what should be done for "production" systems. In general, try to escape from dynamic memory allocation in embedded systems.

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 = xval.toInt();
int yvalue = yval.toInt();

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

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

This seems like a very good solution thank you.  The example clears it up perfectly

What if we had an undefined number of servo inputs?  in my example there was 3.  But what if sometimes it was more, or less.  Can you offer any suggestion for handling such a scenario

Sure: There are two possibilities. 1. Send first the number of servos: 3:val1&val2&val3&, read such number prior to starting the loop. 2. Use a different terminator to indicate you have no more servos, loop until you find it: val1&val2&val3&#, for example.

Glad this solution helped you, @ValrikRobot, could you please validate the answer if it was useful?

or you can just remove the for, and so the code will just work any time you send a command.

You can use Stream.readStringUntil(terminator) passing a different terminator for each part.
On each part you then call String.toInt

Simplest solution is to use sscanf().
  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!

It is not working for serial.read()... any idea why? I get the following error: invalid conversion from 'int' to 'char*' [-fpermissive]

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

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

That's was good. That's was perfect!!!

jfpoilpret provided great answer 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
#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

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

How to read from serial on an ATtiny85 isn't really part of the question.

Sorry for diverging from question, but community and resources available for Attiny is way smaller than for Arduino. People like me looking for answers use Arduino keyword and sometimes get into very tricky situations as implementing Arduino code onto Attiny is not always trivial. Had to convert original code to work on Attiny, tested it working and decided to share it

This site is in Q&A format. Answers should answer the question. Yours just adds something that's unrelated to it.

Here is Arduino method to split a String as answer to the question "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".

String sInput: the input lines to be parsed,
char cDelim: the delimiter character between parameters,
String sParams[]: the output array of parameters,
int iMaxParams: the maximum number of parameters,
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("");
}

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
}

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

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.

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


text:
Save some arduino pins when driving a 4 digits 7 segments display
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.

A 2-to-4 line decoder should do what you need. I've used a 74HC139 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) 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.

I already have transistors for driving digits as there could be up to 8 segments lit (7 segments + dot). I guess I need to add 74HC139 before transistors and let it operate with low current. Thanks for your precious hint!

With 74HC595 solution I would need a transistor per segment, right? This could become complex with 32 transistors. I'd go for 74HC139 solution.

@Ghigo - Since you're only displaying one digit at a time, you should only need 8 transistors for the segments.

In this case I need to put 74HC595 after transistors. Some current will flow there. From datasheet I see 20mA is the limit when switching. Is this correct?

@Ghigo - You can connect the Arduino directly to the 595 without any difficulty. The transistors should go between that and the display. Each output on the 595 can usually only manage around 6mA on its own at 5V.

I think you'll neeed 4 additional transistors (in addition to the 8 first ones, one per segment): one for each digit common cathode (or anode, based on your displays), as for a chip, sourcing current is the same as sinking current, which means you may fry the circuit on the other end of the LED...

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 includes a single 4x7 segment display.
given your comment, another option would be an I2C/SPI 7 Segment driver. (datasheet).
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 and digikey source:

Thanks for the hint. My display is bigger than this and I wanted a more educational approach. I would like to keep display driver part directly on Arduino as I already have implemented automatic brightness control with a photoresistor and some lines of code.

@Ghigo I just posted an update for a 7 segment driver that may be of use as well.

It says no longer manufactured, but there are clones. Interesting approach.

I don't know why I posted that first driver, that's not the one I have here. I have one of these on a breakout board with 8 x 7 segment displays. Works a treat!

Are you using your analog pins?  Did you know they can be used as digital pins?

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.

Inreresting. I have 2 unused analog pins I can try to use them for display as I require a pwm pin. Never tried this

+1 for referencing them by their analog assignment (A0) instead of digital (14) et al which isn't always correct.

An I2C IO expander 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.

Just noticed you've already considered this approach - I'm gonna leave this here anyway for other folks reading too speedily.


text:
What is the library m in C++ linker?
Following this guide, it says to include a library in the C++ Linker called m. What is this for?
Specifically, Your second Arduino project.
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}"

Bewared of this tutorial that seems quite old and is probably not uptodate now. Note that if you want to use Eclipse, I'd suggest to take a look at this plugin: http://eclipse.baeyens.it/ I use it everyday (currently using 1.2.5.5 as I have not yet installed Arduino IDE 1.5).

@jfpoilpret Is that using the compiler shipped with the Arduino I DE? I actually decided not to use Arduino and go for full fledged C...

Yes it uses the AVR tools that come installed with Arduino IDE. But you can do full-fledged C or C++ with it if you want as it does not perform default #includes like Arduino IDE.

@jfpoilpret Do you have access to strings and vectors?

I haven't checked that but I'd rather stay away from STL and involved dynamic memory allocations for embedded development.

Also I'm not sure if AVR tools support templates as required for STL usage.

@jfpoilpret You can use at least strings in the Arduino IDE, which is one of the many reasons why I'm moving to C instead...

Standard C++ also supports the same kind of string class (maybe the same? I have not checked)

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

Is this a library that the compiler knows where is by itself?

Yes, it is enough to indicate "-lm" as an option to the compiler-linker. No necessity to indicate -L(pathToLib).


text:
updating firmware on arduino wifi shield
I'm trying to upgrade firmware on my wifi shield by following the upgrade instructions for Mac. 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?

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.

Ok so on the wifi shield i just place the cap over the DFU programming pin (the one that comes with the shield)? Like shown on this picture http://www.dfrobot.com/community/how-to-upgrade-arduino-wifi-shield-firmware-on-windows.html

That would be the one.

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.


text:
Building Arduino Nano from components
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.

You should also consider if you actually need all the components the Nano has.

http://www.digikey.com/product-search/en/integrated-circuits-ics/embedded-microcontrollers/2556109?k=atmega328&quantity=1 http://www.digikey.com/product-search/en/integrated-circuits-ics/embedded-microcontrollers/2556109?k=atmega168&quantity=1

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.


text:
LCDs larger than 20x04 and 5" diagonal
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 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.

Short answer: No. Long answer: No, but you can fake it.

@IgnacioVazquez-Abrams Fake it, as in use multiple LCDs over i2c? Are 20x04 LCDs as large as they get?

As in configure a MCU with a font table as a I2C slave and hook it up to a graphical LCD.

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

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.

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

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


text:
How to create a serial communication connection between Cubieboard running Android and Arduino
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) 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 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.

is your Cubieboard using adroid? what does "java eclipse" means? java is a language, eclipse is an ide, i think you have a bit of confusion.
Many times they say it not possible as many phone does NOT have an USB HOST, but only USB SLAVE. Cubie should have a master.
Java's library used by arduino ide are RXTX(old) and JSSC(use that)

Of course yes.  I did get it a little confused.  I need to access the serial port connected to arduino.  Could you give a bit of information on the JSSC?

Ive been looking at the documentation at https://code.google.com/p/java-simple-serial-connector/wiki/jSSC_examples and im not seeing any android support, am i being a little naive?

JSSC does not support Andorid. i was thinking you was running Linux on the cubie.. Then the library you linked is the way to go

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.

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

Do you know if this will run on the poster's embedded board, under their current operating system, and have access to the serial devices?


text:
Why my Arduino Uno R3 doesn't work with a recompiled optiboot with BAUD_RATE=57600
This is a follow on question from 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) 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? 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?

What do you mean by "you couldn't program the same MCUs using your Uno R3" ?  Are you trying to use the Arduino as an ISP to program something else?  Are you putting a chip already loaded with this bootloader into your R3 and trying to talk to it there?

@ChrisStratton - It's the 2nd option. I burn the modified bootloader into an MCU (using my Uno as ISP), then I remove the ISP circuitry, put that MCU with the modified bootloader into the Uno R3 socket and try to upload a sketch using regular serial programming via USB. The Uno doesn't respond to an upload operation with the MCU with the modified bootloader in the UNO (as its main MCU).

Can you try this with some other custom baud rate than 57600?  Apparently this is special cased in the USB serial firmware; perhaps you should compare to the calculation in your bootloader.  See https://github.com/arduino/Arduino/blob/master/hardware/arduino/firmwares/atmegaxxu2/arduino-usbserial/Arduino-usbserial.c#L209

@ChrisStratton - I couldn't compile the bootloader with any speed below 57600. I started to get compiler errors that I couldn't fix easily. Maybe I should post that problem as a separate question and try harder now that you think there's a way out.

@ChrisStratton - Did you notice I'm using ATmega328-PU and not the more common pico-power version ATmega328P-PU? Does it matter?

@ChrisStratton - OH BOY!! WHAT ARE THE ODDS??? It worked at 76800!! Many thanks! Just got this new message avrdude: serial_baud_lookup(): Using non-standard baud rate: 76800 but other than that, uploading now works fine. Post your comment as an answer and I'll accept it.

@ChrisStratton - So, what's so special about 57600 baud?

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.

@Chris here's the source-code for the optiboot I've used. It's from Arduino IDE 1.0.5 for Windows:  http://pastebin.com/d8NUirfZ

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

Note I did not say you cannot use 57600, though it seems you may have to modify one end to give them a more closely matching approximation of it.  Since the serial blocks on the two chips are similar, this should be fairly straightforward.  The problem is the software which configures the similar registers in each is fairly different.

@ChrisStratton - Ok. I tried to edit my answer to match what you said, but feel free to edit it yourself if you think you can express it better.


text:
What's the difference/relationship between Arduino and AVR?
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?

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

Arduino is a set of open-sourced hardware- and software specifications, originally conceived as a students' platform. 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.

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.

For the record, you can use the Arduino environment for many AVR chips without any special code. The only extra thing you need is an AVR programmer which could be a $40, official Atmel one, or a $5 USPASP programmer, or even another Arduino running the ArduinoISP sketch.

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.

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

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.


text:
Modbus Protocol Compile Error
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

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]

CHANGES MADE IN AS IN FORUM MENTIONED

Are you using the Uno or the Mega? Someone mentioned the Due, is that what you're using? You have both tags, but that doesn't make much sense IMO.

Not sure where you got the library from, but if it's from this github repo, 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 shows how to use it correctly
modbus_configure(115200, 1, 2, TOTAL_REGS_SIZE);

I tried already it is not working. i have pasted Error for your library

All those errors are, again, with using the library. Read the error carefully and look at the appropriate part of your code. Other than re-stating the error, I can't help you unless you show code.

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

As u said downaded v 1.5 now. But error is same error

seems like you are using an arduino DUE, witch is not explicitly supported by the lib.


text:
Can I get a Datetime object from a unix timestamp?
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:

A unix timestamp: 1396451852.
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.

To clarify: You have a unix time-stamp on your arduino and you want to make the conversion there? Could the supplier of the timestamp instead provide the formatted string?

Yes! i get this unix time-stamp from internet.

The seconds since (UNIX) epoch relies on a 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?

+1 For letting me know that leap seconds exist AND for the great answer.

The Arduino Time Library 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. It's pretty large but you can probably cut it down considerably to just the format parts you need.


text:
Using TIMER0_COMPB_vect
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.

You could optimize your code a little bit by replacing if (stateA) ... with PORTD ^= _BV(PIND4); (exclusive or of this bit) and removing those volatile state variables.

I don't see the point why you would need 2 interrupts at the same frequency, you can do your stuff in the same ISR.

Because some of the stuff is in a library and I want to keep it separate from other logic

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.

Your code doesn't seem to match what you are saying to do... could you maybe clarify a little?

CTC resets the timer when it matches OCR0A. We set COM0A[1:0] to 0b01 in order to tell OC0A to toggle. For OC0B we set it in the middle of the timer (COM0B[1:0]=0b11, OCR0B ~= OCR0A/2) period, and then clear it at the end (via the ISR). This gives it twice the frequency of OC0A.

Sorry, but some code would be really helpful, I'm still a bit lost.

The code I gave integrates directly into the code you already have, simply replace the assignment to TCCR0A as well as the whole ISR.

As well as the overflow interrupt enable that I just added (since you won't have the Arduino libraries to do it for you).

Aaaand because I wasn't thinking, it didn't occur to me that a match on OCR0A would happen at the same time as an overflow, so I've changed the ISR used. It should now compile against the Arduino libraries.

So... I was thinking about my code some more and I don't have to have them running at two different frequencies. I really just need to separate interrupts. Does that make any of this easier?

@AdamHaile: You don't even need two interrupts, you just need OC0B to toggle twice as often as OC0A. My code takes advantage of the timer hardware to do just that, rather than doing it all in interrupts.

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.

This shouldn't actually interfere though. Timer 0 overflow is only for the Arduino timing functions.

That's what I thought, but I think it is still preferrable to ensure you set all Timer0 registers properly. Timer functions are a bit complex and you may be bitten by some strange behavior you did not expect, if you don't care for it.

See update above

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

Just checked it on my UNO, seems to work fine (with double frequencies, as the UNO runs on 16MHz).

See update above

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


text:
Connecting to network with wifi shield
I just bought a WiFi shield and I cannot connect to my wireless network (WPA2).

I used the sketch from the Arduino site 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?

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

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.


text:
MODbus response for configure data
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]

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

Does that mean your other question is resolved? If so, you should mark an accepted answer.

Nope that also not resolved. I am getting issue which being not solved yet. Since code is different and also problem associated with it is different so i posted here

maybe you switched TX and RX?


text:
Modifying serial message for Adafruit NFC/RFID card
Using an Uno configured with an Adafruit RFID-NFC shield to send the UID values to a desktop game I am building.
Works fine. However, in addition to just the UID, I need to send 1 additional value, lets call it 'game choice'. This can be one of 3 values. This is just the relevant code. Can any experts suggest how I might modify the following to send this additional value?
/**************************************************************************/
#include <Wire.h>
#include <Adafruit_NFCShield_I2C.h>

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

Adafruit_NFCShield_I2C nfc(IRQ, RESET);

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

  nfc.begin();

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

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

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

  if (success) {

   nfc.PrintHex(uid, uidLength );
}
}

Could you elaborate on what you want to send, from where and to whom? Its not entirely clear.

The message is sent obviously whenever a user scans their tag over 1 of 3 possible scan targets(game choices). This 'game choice' value would be hardcoded. The receiving end is a desktop Adobe AIR application. Using the ArduinoConnector native Extension https://code.google.com/p/as3-arduino-connector/

so 3 arduinos+3 shields, 1 used for each choice and COM port

had to simply modify PrintHex in
Adafruit_NFCShield_I2C.h
to accept an additional argument

Could you explain a bit more on what you changed (show relevant code)? The answer in its current form isn't very useful to others having the same issue.


text:
Pass variable in a URL
I am working on code where I am able to manually enter the value in the URL to let the PHP code save it in the database, but I'm unsure how to do it with a variable in a loop running. This is the URL:
student.cs.hioa.no/~s180343/updatedb.php?verdi=25

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

  // Initialize Serial
  Serial.begin(9600);

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

  // run various example processes

}

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

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

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

What do you mean by "manually entering" do you want to do subsequent curls as: verdi=25, verdi=26...?

If that's the case take a look to string appender

yes! hthwen. I want to do it in a loop so you can put a variable in verdi=$variable

Please note that duplicates (or close variants) of this question were also cross-posted to Stack Overflow and EE.SE. Cross-posting is against Stack Exchange policy, so they have been migrated/merged where possible. Some variations in question information have been lost in this process.

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.

String myUrl = "student.cs.hioa.no/~s180343/updatedb.php?verdi=" + verdi;
is wrong, you can't concatenate array of char (pointer to char) to a int, you'll get erratic result.
you need to do concatenation: solution 1:
String myUrl = "student.cs.hioa.no/~s180343/updatedb.php?verdi=";
myUrl += verdi;
that mean: string(array of char) is casted to String(object) and then verdi is concatenated to the String objcet; or
String myUrl = String("student.cs.hioa.no/~s180343/updatedb.php?verdi=") + String(verdi);

@lesto you're right. I fixed it.

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

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


text:
Change Options for the AVR Programmer via Arduino IDE
I want to program an ATtiny through the Arduino IDE. I have a somehow strange programmer. But I can upload via avrdude by

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

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

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

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

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:

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).
Switch to Arduino IDE 1.5 and follow Federico's answer :-)
Use another IDE, something that deserves the IDE name. I use Eclipse with this Arduino plugin and it works fine for me. As a bonus, avrdude support seems better as you can see on the screenshot below:


text:
Arduino Lego Robot
I'm currently developing a Lego Robot, the mindstorm series to be specific. I want to replace the lego NXT brick with an arduino, maybe an intel galileo in the future. How do I establish connections from the arduino with the lego sensors? Also, I would like some input on any cool features that I can add to this robot. This robot is to be seen as a human companion. Thanks in advance.
An example of a sensor i would like to use is here : http://www.hitechnic.com/cgi-bin/commerce.cgi?preadd=action&key=NIS1070
How do I interface this with an arduino?

Looks like they use I2C so you just have to look at the pinout and then hook it up to the I2C pins on the Arduino. http://www.dexterindustries.com/howto/connect-the-arduino-and-the-lego-mindstorms-together/

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

NXShield-Dx
Bricktronics shield

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