www.it-ebooks.info C Programming for Arduino Learn how to program and use Arduino boards with a series of engaging examples, illustrating each core concept Julien Bayle BIRMINGHAM - MUMBAI www.it-ebooks.info C Programming for Arduino Copyright © 2013 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: May 2013 Production Reference: 1070513 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84951-758-4 www.packtpub.com Cover Image by Asher Wishkerman (a.wishkerman@mpic.de) www.it-ebooks.info Credits Author Julien Bayle Reviewers Darwin Grosse Pradumn Joshi Phillip Mayhew Glenn D. Reuther Steve Spence Acquisition Editor Edward Gordon Erol Staveley Lead Technical Editor Susmita Panda Technical Editors Worrell Lewis Varun Pius Rodrigues Lubna Shaikh Sharvari Baet Copy Editors Laxmi Subramanian Sajeev Raghavan Insiya Morbiwala Brandt D'mello Aditya Nair Alda Paiva Project Coordinator Leena Purkait Proofreaders Claire Cresswell-Lane Martin Diver Indexer Tejal R. Soni Graphics Ronak Dhruv Production Coordinator Pooja Chiplunkar Cover Work Pooja Chiplunkar www.it-ebooks.info About the Author Julien Bayle completed his Master's degree in Biology and Computer Sciences in 2000. After several years working with pure IT system design, he founded Design the Media in early 2010 in order to provide his own courses, training, and tools for art elds. As a digital artist, he has designed some huge new media art installations, such as the permanent exhibition of La Maison des Cinématographies de la Méditerranée (Château de la Buzine) in Marseille, France, in 2011. He has also worked as a new media technology consultant for some private and public entities. As a live AV performer, he plays his cold electronic music right from New York to Marseille where he actually lives. The Arduino framework is one of his rst electronic hardware studies since early 2005, and he also designed the famous protodeck controller with various open source frameworks. As an Art and Technology teacher also certied by Ableton in 2010, he teaches a lot of courses related to the digital audio workstation Ableton Live, the real-time graphical programming framework Max 6, and Processing and Arduino. As a minimalist digital artist, he works at the crossroads between sound, visual, and data. He explores the relationship between sounds and visuals through his immersive AV installations, his live performances, and his released music. His work, often described as "complex, intriguing, and relevant", tries to break classical codes to bring his audience a new vision of our world through his pure digital and real- time-generated stimuli. He's deeply involved in the open source community and loves to share and provide workshops and masterclasses online and on-site too. His personal website is http://julienbayle.net. www.it-ebooks.info Acknowledgement I would like to thank my sweet wife Angela and our daughter Alice for having been my unconditional supporters. Special thanks to our son Max, who was born between the writing of Chapter 11 and Chapter 12! I would also like to thank my two great friends Laurent Boghossian and Denis Laffont because they were there for me all through the course of this huge project with their advices, jokes, and unconditional support. I would like to extend many thanks to two very nice persons and friends whom I asked to review this book for me: Glenn D. Reuther and Darwin Grosse. I thank the following great programmers who coded some libraries that have been used in this book: Marcello Romani (the SimpleTimer library), Juan Hernandez (the ShiftOutX library), Thomas Ouellet Fredericks (the Bounce library), Tim Barrass (the Mozzi library), David A. Mellis from MIT (the PCM library), Michael Margolis and Bill Perry (the glcd-arduino library), and Markku Rossi (Arduino Twitter Library with OAuth Support). I want to thank the creators of the following powerful frameworks used in this book besides the Arduino framework itself: Max 6, Processing, and Fritzing. Lastly, I'd like to hug Massimo Banzi and Arduino's project team for having initiated this great project and inspired us so much. www.it-ebooks.info About the Reviewers Darwin Grosse is the Director of Education and Services with Cycling '74, the developer of the Max media programming system. He is also an Adjunct Professor at the University of Denver, and teaches sonic art, programming, and hardware interface in the Emerging Digital Practices department. Pradumn Joshi is currently pursuing his Bachelor's degree in Electrical Engineering from NIT Surat. He is an avid elocutionist and debate enthusiast, and is also interested in economics, freelance writing, and Western music. His area of technical expertise lies in open source hardware development and embedded systems. Phillip Mayhew is a Bachelor of Science in Computer Science from North Carolina State University. He is the Founder and Managing Principal of Rextency Technologies LLC based in Statesville, North Carolina. His primary expertise is in software application performance testing and monitoring. www.it-ebooks.info Glenn D. Reuther's own personal journey and fascination began with music technology during the 1970s with private lessons in "Electronic Music Theory and Acoustic Physics". He then attended Five Towns College of Music in NY and has been a home studio operator since 1981, playing multiple instruments and designing a few devices for his studio conguration. Since then, he has spent several years with Grumman Aerospace as a Ground and Flight Test Instrumentation Technician, before moving through to the IT eld. Beginning with an education in Computer Operations and Programming, he went on to work as network and system engineer having both Microsoft and Novell certications. After over 10 years at the University of Virginia as Sr. Systems Engineer, he spends much of his spare time working with the current state of music technology. His website is http://lico.drupalgardens.com. He is also the author of "One Complete Revelation", a photo journal of his nine- month trek throughout Europe during the early 90s. I would like to thank the author for his friendship, and I would also like to thank my wonderful wife Alice and son Glenn for their patience, understanding, and support during the editing process of this book. Steve Spence has been a veteran of the IT industry for more than 20 years, specializing in network design and security. Currently he designs microcontroller- based process controls and database-driven websites. He lives off grid and teaches solar and wind power generation workshops. He's a former reghter and rescue squad member, and a current Ham Radio operator. In the past, he's been a technical reviewer of various books on alternative fuels (From the Fryer to the Fuel Tank, Joshua Tickell) and authored DIY alternative energy guides. www.it-ebooks.info www.PacktPub.com Support les, eBooks, discount offers and more You might want to visit www.PacktPub.com for support les and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub les available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why Subscribe? • Fully searchable across every book published by Packt • Copy and paste, print and bookmark content • On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. www.it-ebooks.info Table of Contents Preface 1 Chapter 1: Let's Plug Things 7 What is a microcontroller? 7 Presenting the big Arduino family 8 About hardware prototyping 11 Understanding Arduino software architecture 13 Installing the Arduino development environment (IDE) 15 Installing the IDE 15 How to launch the environment? 16 What does the IDE look like? 16 Installing Arduino drivers 19 Installing drivers for Arduino Uno R3 19 Installing drivers for Arduino Duemilanove, Nano, or Diecimilla 20 What is electricity? 20 Voltage 21 Current and power 21 What are resistors, capacitors, and so on? 22 Wiring things and Fritzing 23 What is Fritzing? 25 Power supply fundamentals 27 Hello LED! 28 What do we want to do exactly? 29 How can I do that using C code? 29 Let's upload the code, at last! 34 Summary 34 www.it-ebooks.info [...]...Table of Contents Chapter 2: First Contact with C An introduction to programming Different programming paradigms Programming style C and C+ +? C is used everywhere Arduino is programmed with C and C+ + The Arduino native library and other libraries Discovering the Arduino native library Other libraries included and not directly provided Some very useful included libraries Some external libraries Checking... 142 Checking an example Processing and Arduino Pushing the button What is a button, a switch? 145 149 150 150 Alternative IDEs and versioning Different types of switches 145 150 A basic circuit 150 The pull-up and pull-down concept 153 Making Arduino and Processing talk 155 Wires 151 The circuit in the real world 151 The pseudocode The code The communication protocol The Processing code The new Arduino. .. Your C Programming and Creating Libraries, is the most advanced chapter of the book It describes some advanced C concepts that can be used to make our code reusable, more efficient, and optimized, through some nice and interesting real-world examples Appendix provides us with details of data types in C programming language, operator precedence in C and C+ +, important Math functions, Taylor series for calculation... transform a pure idea into firmware for Arduino Chapter 3, C Basics—Making You Stronger, enters directly into the C language By learning basics, we learn how to read and write C programs, discovering the datatype, basic structures, and programming blocks Chapter 4, Improving Programming with Functions, Math, and Timing, provides the first few keys to improve our C code, especially by using functions... different concrete examples and compares them to digital pins Max 6 frameworks are introduced in this chapter as one of the ideal companions for Arduino Chapter 7, Talking over Serial, introduces the communication concept, especially by teaching about Serial communication We will learn how to use the Serial communication console as a powerful debugging tool Chapter 8, Designing Visual Output Feedback, talks... futuristic world is full of smart and connected devices Do-it-yourself communities have always been fascinated by the fact that each one could design and build its own smart system, dedicated or not, for specific tasks From small controllers switching on the lights when someone is detected to a smart sofa sending e-mails when we sit on them, cheap electronics projects have become more and more easy to create... Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you [5] www.it-ebooks.info Preface Errata Although we have taken every care to ensure the accuracy of our content, mistakes... to precisely define the project, which is a key to success Then we'll have to sketch a schematic with our Arduino board and our LED; it will dig the question, "How are they connected together?" The firmware programming using C language can directly be started after we have sketched the circuit because, as we'll see later, it is directly related to the hardware This is one of the strong powers of Arduino. .. such as Processing and the Max 6 graphical programming framework C Programming for Arduino will teach you the famous "learning-by-making" way of work that I try to follow in all of my courses from Max 6 to Processing and Ableton Live Lastly, C Programming for Arduino will open new fields of knowledge by looking at the input and output concept, communication and networking, sound synthesis, and reactive... the code if and else conditional structure switch…case…break conditional structure Ternary operator Making smart loops for repetitive tasks for loop structure 86 86 89 91 91 91 Implicit type conversion Explicit type conversion Combining negation and comparisons Playing with increment Using imbricated for loops or two indexes 80 82 84 93 93 while loop structure 95 do…while loop structure 96 Breaking the . content • On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view. to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range. mathematical functions and Arduino 105 Trigonometric C functions in the Arduino core 106 Some prerequisites 106 Trigonometry functions 109 Exponential functions and some others 110 Approaching calculation