Programming Arduino

[Contents] [Download Code] [Arduino 1.0] [Errata] [Screenshots]

ste 600

This book is all about Programming the Arduino. I wrote it to try and respond to the many problems that come up on the Arduino forums about how to program an Arduino. The book does not assume any prior knowledge about programming or experience of electronics.

Contents:

Chapter 1. This is Arduino. An introduction the Arduino hardware, what it is capable of and the various types of Arduino board that are available.
Chapter 2. Getting Started. First experiments with your Arduino board, installing the software, powering it up and uploading your first sketch.
Chapter 3. C Language Basics. The basics of the C language and for complete programming beginners an introduction to programming in general.
Chapter 4. Functions. This chapter explains the key concept of using and writing functions in Arduino sketches. Demonstrated throughout with runnable code examples.
Chapter 5. Arrays and Strings. How to make and use more advanced data structures than simple integer variables. A Morse Code example project is slowly developed to illustrate the concepts being explained.
Chapter 6. Input and Output. How to use the digital and analog inputs and outputs on the Arduino in your programs. A multimeter will be useful to see what is happening on the Arduino’s input output connections.
Chapter 7. The Standard Arduino Library. Making use of the standard Arduino functions that come in the Arduino’s standard library.
Chapter 8. Data Storage. Writing sketches that can save data in EEPROM memory and make use of the Arduino’s built-in Flash memory.
Chapter 9. LCD Displays. Programming with the LCD Shield library to make a simple USB message board example.
Chapter 10. Arduino Ethernet Programming. Making the Arduino behave like a web server, including a little background on HTML and the HTTP protocol.
Chapter 11. C++ and Libraries. Beyond C, looking at adding object-orientation and writing your own Arduino libraries.

Arduino 1.0:

At the start of December 2011 Arduino 1.0 was released. This changed a few things, that have caused two of the sketches in this book not to work.

If you are using Arduino 1.0 and have not used any previous version of Arduino, you need to:

Download the new versions of sketches 10-01 and 10-02 from the Download Code link at the top of this page. The classes Server and Client have been renamed to EthernetServer and EthernetClient.

If you are using Arduino 1.0 and have used Arduino 023 or earlier, you may need to:

get version 1.6 of the Bounce library from http://www.arduino.cc/playground/Code/Bounce

Errata:

Page 3. Figure 1.1 marks one of the mounting holes as being the reset button. The reset button is actually slightly below it and to the left just above the label ‘Reset’ on the board.
Page 4, 2nd paragraph under Power Connections, 3.5V should be 3.3V in list of power pins.

Page 7, 2nd paragraph under The Origins of Arduino, … such clones often have “*dunino” names should be “*duino” names.

Page 19. I state that the serial port is always COM3. This is not the case – usually it is COM4.

page 33 paragraph 6 last sentence. The value returned to use from the call would be the sin of the angle passed as its argument. Should be: The value returned to use from the call would be the sine of the angle passed as its argument.

 

page 36 last paragraph last sentence int ledPin 13; Should be: int ledPin = 13;

Page 40. I say that to convert C to F you ‘to multiply it by 5, divide by 9, and then add 32′. This is the wrong way around. It should say ‘multiply it by 9, divide by 5, and then add 32′

Page 44. The sentence: ‘We used the symbol <, which means less than’ should read: ‘We used the symbol > which means greater than’.

Page 47. Near the top of the page. ‘less than 100′ should read ‘less than 20′.

Page 61. “-” missing on p61 table 4-1 for “long’ types (2,147,483,648 to 2,147,483,647) also on page 61, last sentence of first paragraph in section Other Data Types: “numbers between -32767 and 32768″ should be “numbers between -32768 and 32767″ so that it agrees with Table 4-1.
Page 69, Figure 5-1, the first 6 lines of the output is shown as 200, while only the first 3 lines should be 200 (should be 3 lines of 200, 3 lines of 500, 3 lines of 200 – 9 total output lines, not 12 output lines).

Pg.75. Table 5-2. “D” is shown as “..” should be “-..”

Page 120. The example code for writing a string in Chapter 8 does not write the terminator. It should look like this:

char *test = “Hello”;
int i = 0;
while (test[i] != ‘\0′)
{
EEPROM.write(i, test[i]);
i++;
}
EEPROM.write(i, ‘\0′);

Page 121. There was a semi-colon missing on line 7 of sketch 08-03. This is fixed in the current download of the sketches.
Page 121. Also in this sketch, for (int i = 0; i < 1023; i++) should be: for (int i = 0; i <= 1023; i++). That is <= rather than <. As it stands the sketch would not clear the last byte.
Page 149, 1st Paragraph, “Type the flowing into the sketch …” should be “Type the following into the sketch …”

Page 121. The sentence at the end of the page that says ints and floats are both 16 bits should say that ints are 16 bits and floats 32 bit.

Screen Shots:

Following problems with legibility of some of the screen shots on some eBook readers, here are the images.

F02-01

F02-01

 

F02-02

F02-02

 

F02-03

F02-03

 

F02-04

F02-04

 

F02-05

F02-05

 

F02-06

F02-06

 

F02-07

F02-07

 

F02-08

F02-08

 

F02-09

F02-09

 

F02-10

F02-10

 

F03-02

F03-02

 

F03-03

F03-03

 

F03-04

F03-04

 

F03-05

F03-05

 

F03-06

F03-06

 

F03-07

F03-07

 

F05-01

F05-01

 

F06-02

F06-02

 

F10-03

F10-03

 

F11-01

F11-01

 

F11-02

F11-02

36 thoughts on “Programming Arduino

  1. Wayne Carr

    programming arduino Ch 3 page 42 says: “The arithmetic operators +, -, *, and / have an order of precedence – that is, multiplications are done first, then divisions, then additions and subtractions” That isn’t correct. Multiplication and division are at the same level of precedence and are performed left to right, so “10 / 2 * 6″ has the division first and then the multiplication, not the multiplication first as in the text. The same is true of + and -, but the text there doesn’t claim one of those always happens before the other. References: Microsoft c operator precedence or c operator precedence

  2. admin Post author

    I stand corrected! I think I already have that errata in the list, but thanks for pointing it out. It all helps to make the next edition better. Si.

  3. Pascal Munerot

    Hello,
    I think there is a mistake p119 in the section “Storing a float in EEPROM (Unions)”. A float uses 4 bytes and not just 2. This is confirmed with your book “Next steps …” p34 (4 bytes). So the example should probably map a float to a long and thus write two series of 2 bytes. Perhaps even better would be to use 2 int. Not sure how the endianess comes into play.

    Other than that, the book is excellent. I am also reading “hacking electronics which is very clear”.

    Regards

  4. admin Post author

    You are quite right. Sorry about that. Also if you are enjoying Hacking Electronics, it may interest you to know that we have a kit to support the book now. Si.

  5. Bill Ward

    Hi Simon-

    Thinking P 63, last word of 3d paragraph should be “valuable” or something similarly positive instead of “difficult,” as ‘it’ refers to “All of this ” (good practice) rather than “someone else’s badly formatted sketches.”

    I am reading this and Next Steps. Love your writing style- I wish it had been my dry C++ textbook in college. It’s every bit as instructive and by combining with the Ardiuino functionality, much more interesting and readable.

    -BW

  6. Peter Østergaard

    Paragraph three, line four on page 105 says: “…to link to Android over USB.” I got a little confused as Java is actually the “Android language”, but as this book is not about Android and since Android and Arduino look so much alike (the words), I think this could be a spell checker error.

  7. Rafael Apitz

    Dear Simon, I am following your book on Programming Arduino and so far find it very pleasant and easy to follow even been a unskilled 75 yr old. My main interest is to build a simple portable photometer (led + sample holder + photo-diode). I already finish the prototype and tested it coupling a digital voltmeter to the photo-diode output. It does work fine, quite reproducible readings etc. Then I coupled the output to the analog input on the Arduino Uno board and loaded the 06-9 sketch (I modified the sketch delay to 5 sec). This also works fine, however the max P-D output is .470 V, which is fine for me, but I need at least 4 decimals, which I can not get from the println command (just i.e. 0.46 0.47). Of course if I manually divide the Reading by 204.6 I get i.e. 0.4740 or 0.4669, etc. My question is: What should I modify in the sketch to get printed Volts = 0.XXXXX ?

    Best personal regards,
    Rafael

  8. Dale

    Going thru the Arduino Anroid book and trying get the home automation going. I downloaded HomeAutomation.apk and installed. When running, I get the start screen, but when I click Open Browser, nothing opens in the browser. Guessing there are more files I have to download and store somewhere. Please provide me a few more hints. At this point I’m just trying to get the screens show up on Android, though I know they will not be functioning until the hardware is set up. Thanks.

  9. hongsub hwang

    I’d like to know that you can resolve the 10-02 compilation errors sketch of Programming Arduino Getting Started with Sketches book written by your way.

    #include
    #include
    #include
    #include
    #include
    #include
    #include

    byte mac[]={0xDE,0xAD,0xBE,0xEF,0xFE,0xED};//mac Add
    byte ip[]={191,168,1,30};//ip Add
    EthernetServer server(80);

    int numPins=5;
    int pins[]={3,4,5,6,7};
    int pinState[]={0,0,0,0,0};
    char line1[100];

    void setup()
    {
    for(int i=0; i < numPins; i++)
    {
    pinMode(pins[i], OUTPUT);
    }
    Serial.begin(9600);
    Ethernet.begin(mac, ip);
    server.begin();
    }

    void loop()
    {
    EthernetClient client = server.available();
    if(client)
    {
    while(client.connected())
    {
    readHeader(client);
    if(! pageNameIs("/"))
    {
    client.stop();
    return;
    }
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println();

    client.println("”);
    client.println(“<Output Pins”);
    client.println(“”);
    setValuesFormParams();
    setPinStates();
    for(int i=0; i<numPins; i++)
    {
    writeHTMLforPin(client, i);
    }
    client.println("”);
    client.println(“”);
    client.println(“”);
    client.stop();
    }
    }
    }

    void writeHTMLforPin(Client client, int i)
    {
    client.print(“Pin “);
    client.print(pins[i]);
    client.print(“”);
    client.print(“Off”);
    client.print(“On”);
    client.println(“”);
    }

    void setPinStates()
    {
    for(int i=0;i<numPins;i++)
    {
    digitalWrite(pins[i], pinState[i]);
    }
    }

    void setValuesFromParams()
    {
    for(int i=0; i < numPins; i++)
    {
    pinState[i]=valueOfParam(i + '0');
    }
    }

    void readHeader(Client client)
    {
    char ch;
    int i=0;
    while(ch != '\n')
    {
    if(client.available())
    {
    ch=client.read();
    line1[i]=ch;
    i++;
    }
    }
    line1[i]='';
    Serial.println(line1);
    }

    boolean pageNameIs(char* name)
    {
    int i=4;
    char ch=line1[i];
    while(ch != ' ' && ch != '\n' && ch != '?')
    {
    if(name[i-4] != line1[i])
    {
    return false;
    }
    i++;
    ch=line1[i];
    }
    return true;
    }

    int valueOfParam(char param)
    {
    for(int i=0; i < strlen(line1); i++)
    {
    if(line1[i] == param && line1[i+1] == '=')
    {
    return (line1[i+2] – '0');
    }
    }
    return 0;
    }

    sketch_10-02.ino:12:29: error: cannot declare parameter 'client' to be of abstract type 'Client'
    In file included from C:\Program Files\Arduino\libraries\Ethernet\src/EthernetClient.h:5:0,
    from C:\Program Files\Arduino\libraries\Ethernet\src/Ethernet.h:7,
    from sketch_10-02.ino:3:
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:26:7: note: because the following virtual functions are pure within 'Client':
    class Client : public Stream {
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:31:18: note: virtual size_t Client::write(uint8_t)
    virtual size_t write(uint8_t) =0;
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:32:18: note: virtual size_t Client::write(const uint8_t*, size_t)
    virtual size_t write(const uint8_t *buf, size_t size) =0;
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:33:15: note: virtual int Client::available()
    virtual int available() = 0;
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:34:15: note: virtual int Client::read()
    virtual int read() = 0;
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:36:15: note: virtual int Client::peek()
    virtual int peek() = 0;
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:37:16: note: virtual void Client::flush()
    virtual void flush() = 0;
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:29:15: note: virtual int Client::connect(IPAddress, uint16_t)
    virtual int connect(IPAddress ip, uint16_t port) =0;
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:30:15: note: virtual int Client::connect(const char*, uint16_t)
    virtual int connect(const char *host, uint16_t port) =0;
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:35:15: note: virtual int Client::read(uint8_t*, size_t)
    virtual int read(uint8_t *buf, size_t size) = 0;
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:38:16: note: virtual void Client::stop()
    virtual void stop() = 0;
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:39:19: note: virtual uint8_t Client::connected()
    virtual uint8_t connected() = 0;
    ^
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:40:11: note: virtual Client::operator bool()
    virtual operator bool() = 0;
    ^
    sketch_10-02.ino:15:24: error: cannot declare parameter 'client' to be of abstract type 'Client'
    In file included from C:\Program Files\Arduino\libraries\Ethernet\src/EthernetClient.h:5:0,
    from C:\Program Files\Arduino\libraries\Ethernet\src/Ethernet.h:7,
    from sketch_10-02.ino:3:
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:26:7: note: since type 'Client' has pure virtual functions
    class Client : public Stream {
    ^
    sketch_10-02.ino: In function 'void loop()':
    sketch_10-02.ino:36:24: error: cannot allocate an object of abstract type 'Client'
    In file included from C:\Program Files\Arduino\libraries\Ethernet\src/EthernetClient.h:5:0,
    from C:\Program Files\Arduino\libraries\Ethernet\src/Ethernet.h:7,
    from sketch_10-02.ino:3:
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:26:7: note: since type 'Client' has pure virtual functions
    class Client : public Stream {
    ^
    sketch_10-02.ino:49:27: error: 'setValuesFormParams' was not declared in this scope
    sketch_10-02.ino:53:34: error: cannot allocate an object of abstract type 'Client'
    In file included from C:\Program Files\Arduino\libraries\Ethernet\src/EthernetClient.h:5:0,
    from C:\Program Files\Arduino\libraries\Ethernet\src/Ethernet.h:7,
    from sketch_10-02.ino:3:
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:26:7: note: since type 'Client' has pure virtual functions
    class Client : public Stream {
    ^
    sketch_10-02.ino: At global scope:
    sketch_10-02.ino:63:30: error: cannot declare parameter 'client' to be of abstract type 'Client'
    In file included from C:\Program Files\Arduino\libraries\Ethernet\src/EthernetClient.h:5:0,
    from C:\Program Files\Arduino\libraries\Ethernet\src/Ethernet.h:7,
    from sketch_10-02.ino:3:
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:26:7: note: since type 'Client' has pure virtual functions
    class Client : public Stream {
    ^
    sketch_10-02.ino:101:24: error: cannot declare parameter 'client' to be of abstract type 'Client'
    In file included from C:\Program Files\Arduino\libraries\Ethernet\src/EthernetClient.h:5:0,
    from C:\Program Files\Arduino\libraries\Ethernet\src/Ethernet.h:7,
    from sketch_10-02.ino:3:
    C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Client.h:26:7: note: since type 'Client' has pure virtual functions
    class Client : public Stream {
    ^

  10. admin Post author

    Humm, what happens if you open the browser manually setting the URL to localhost:8080 ?

  11. admin Post author

    Hi, println is not very helpful when it comes to formatting numbers. Also Arduino, in their wisdom failed to implement the ‘float’ part of the standard sprintf C command, so you cannot even do it that way. This thread discusses this: http://forum.arduino.cc/index.php/topic,44262.0.html. Look for about the 6th comment down on the thread for a possible solution.

  12. admin Post author

    This should say Arduino – thanks for that. I have added it t the errata on the books webpage.

  13. Thomas White

    I am considering using your book for an Independent Study at my Technical College, we are supposed to be taking a C++ class but I was able to get my teacher to let a few of us do our own thing. I was wondering what hardware we should purchase to get the most out of your book in class. Thanks in advance!
    laymansnerd

  14. admin Post author

    My ‘Programming Arduino’ book is all about software. You really don’t need anything more than an Arduino Uno to get you started.

  15. David Kemp

    I love the book.
    One little thing: I know it is just supposed to be a toy example, but the “Internet Pins” example looks vulnerable to a buffer overflow attack. Can I suggest you change readHeader() to check for i<100. Possibly a good place to point out to your readers the need for this type of check when interfacing with the big bad world of the web!

  16. Harry T

    I am enjoying working through this book, though I wish I had bought it 2 weeks ago!
    I have had problems with the Flasher.h and Flasher.cpp files in Chapter 11, getting an error warning that WProgram couldn’t be found. It seems a common error that crops up many times on the Arduino help forum. The suggestions posted there suggest that the statements
    #include "WProgram.h"
    should read
    #include "Arduino.h"
    I’ve tried it, and it works.
    A steep learning curve.

  17. peluang bisnis terbaru

    One other thing you can do to make money on the internet iis
    freelance work in various mediums. As frustrating as it may be or get, you must
    never give up. and Do it yyou become another statistic in the industry.
    Add to your day’s shedule until it’s almost Stop.

  18. Anthony

    hi simon bought lots of your books such as (programming Arduino) also (30 Arduino projects) ( Arduino +android ) Great books keep up the good work
    I am looking to make my Arduino with the web shield take a input and send out an email but have come unstuck ? can you help.
    If I use your your project 10-5 from your book programming arduino getting started what do I need to put inplace for it to send out an email to my phone.
    Many Thanks
    Anthony

  19. Shannon Lenz

    Sketch 6-07 is not working for me. I downloaded the bounce files, they are bounce1 and bounce2 not merely bounce as stated in the book. The example file included in the bounce2 folder worked for me but I consistently get error messages in the compiler for Sketch 6-07. It’s frustrating because all the other sketches work fine.
    Best,
    Shannon

  20. Dave Delaney

    Thank you for the updates, but there are so many changes to remember. I have this book on my computer and Kobo reader. Is there an electronic up to date version of the book that can be downloaded?
    It would make things so much easier… seeing you already have the corrections done.

    Thanks;

    Dave

  21. Rick

    Hello,
    I have purchased both the Arduino programming books, but have a question.
    In Programming Arduino Getting Started 10.02 Ethernet control lights/relays I have it up and running just fine, Thank you.
    I have modified mine for 10 relays, however can you suggest how to modify it for more than 10 relays? As it reads the char position 4 (0-9) it seems to be limited to 10 relays. Again thanks for the books.

    Rick

  22. Alexandre Souza

    Comprei o livro Projetos com Arduino e Android. Use seu smartphone ou tablet para controlar o arduino. Simon Monk. Editora bookman.

    O download dos códigos e do softwares usados na automação residencial foram direcionados para o site.

    Preciso dos códigos e softwares para teste dos exemplos do livro.
    Agradeço.

  23. Alexandre Souza

    Boa noite.
    Comprei o livro projetos com arduino e android. Use seu smartphone ou tablet para controlar o arduino. Simon Monk. Editora bookman.

    Preciso dos códigos e dos softwares utilizados nos exemplos do livro. Para testes.

    Agradeço.

  24. www

    Also, they have ruled the market due to their anatomical constructions of shoes that make the
    shoes anti-stress with special shock absorption system.
    Style- Most of us looks at the design and style while buying any item.
    1990′s – Bra became a highlight on women’s wardrobe.

  25. MARCOS BRANCO

    Is there any book showing about arduino emulater (like VBB-VIRTUAL BREADBOARD, QEletroTech, Proteus, etc.)?
    Excelent Books, congratulations Simon!

  26. Peter Gagen

    Hi, I have created a folk and pull in GitHub for your sketch 8-01 Reading your book and trying your examples sent me into a spin. It turns out the way the compliler handles PROGMEM has changed. prog_char and prog_uchar have gone. I will let you judge if I have corrected this correctly. It now seems to work with: (sample shown only)
    PROGMEM const char sZ[] = “–..”;
    PROGMEM const char* const letters[] = {sA, sB, sC, sD, sE, sF, sG, sH, sI, sJ, sK, sL, sM,
    sN, sO, sP, sQ, sR, sS, sT, sU, sV, sW, sX, sY, sZ};
    Hope this helps?

    Pete.

  27. www

    There are hundreds of brands out there manufacturing the shoes.

    The Unitron website includes detailed description of the
    features and benefits from this product. Wearing an elegant UGG boot with tight jeans can give you
    a classy and beautiful look.

  28. zajrzyj

    The brand of Moda in pelle provides extremely stylish, durable and
    comfortable shoes. The world is really shrinking and ideas are
    being shared around the globe at a rapid pace.
    Choose not only from the styles of the shoes but
    also make sure that they ate comfortable.

  29. torebki

    Also, they have ruled the market due to their anatomical constructions
    of shoes that make the shoes anti-stress with special shock absorption system.
    The Unitron website includes detailed description of the features and benefits from this product.
    Fresh pairs of UGG products arrive in latest designs
    and fake boots are replicas of these originals.

  30. potencja

    It is not better to select high-heeled shoe, if you are an obese.
    Media doesn’t really know how to handle it and this was
    never more clear when we saw the Vogue Italia cover for June 2011.

    A new kind of wire mixed with natural fabrics, like cotton,
    provided the perfect adjustment to the body.

  31. Aaron

    In sketch 10-01. I can’t get the web server page to come up. I keep getting an error message: avrdude: ser_open(): can’t open device “\\.\COM3″: The system cannot find the file specified.

  32. David Galloway

    Page 88 second paragraph second sentence “It’s it a 1″ should Be “If it’s a 1″. Love your books got next steps to read next.

    Thanks
    -Dave

  33. James Greally

    Hi Simon,
    Congrats on a great book. I’m a newcomer to arduino and working my way through the “Programming Arduino Getting Started —” book before hopefully (!) going on to your ” 30 Arduino Projects for Evil Genius”. One inconsistency I noticed: the example sketch in the text on P47 for 3_09 has:

    int delayPeriod = 100; while the corresponding sketch 3_09 which I downloaded in the programming_arduino-master has int delayPeriod = 250;

    If the textbook was corrected to agree with the example sketch, this would impact on P48. I think that the 5th line would then read,:” So now each time that loop is run, it will take just a bit more than 500 milliseconds,….”
    Hope this helps.
    Kind regards,
    James

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>