You are previewing C Programming for Arduino.
O'Reilly logo
C Programming for Arduino

Book Description

Building your own electronic devices is fascinating fun and this book helps you enter the world of autonomous but connected devices. After an introduction to the Arduino board, you’ll end up learning some skills to surprise yourself.

  • Use Arduino boards in your own electronic hardware & software projects

  • Sense the world by using several sensory components with your Arduino boards

  • Create tangible and reactive interfaces with your computer

  • Discover a world of creative wiring and coding fun!

  • In Detail

    Physical computing allows us to build interactive physical systems by using software & hardware in order to sense and respond to the real world. C Programming for Arduino will show you how to harness powerful capabilities like sensing, feedbacks, programming and even wiring and developing your own autonomous systems.

    C Programming for Arduino contains everything you need to directly start wiring and coding your own electronic project. You’ll learn C and how to code several types of firmware for your Arduino, and then move on to design small typical systems to understand how handling buttons, leds, LCD, network modules and much more.

    After running through C/C++ for the Arduino, you'll learn how to control your software by using real buttons and distance sensors and even discover how you can use your Arduino with the Processing framework so that they work in unison. Advanced coverage includes using Wi-Fi networks and batteries to make your Arduino-based hardware more mobile and flexible without wires. If you want to learn how to build your own electronic devices with powerful open-source technology, then this book is for you.

    Table of Contents

    1. C Programming for Arduino
      1. Table of Contents
      2. C Programming for Arduino
      3. Credits
      4. About the Author
      5. Acknowledgement
      6. About the Reviewers
        1. Support files, eBooks, discount offers and more
          1. Why Subscribe?
          2. Free Access for Packt account holders
      8. Preface
        1. What this book covers
        2. What you need for this book
        3. Who this book is for
        4. Conventions
        5. Reader feedback
        6. Customer support
          1. Downloading the example code
          2. Errata
          3. Piracy
          4. Questions
      9. 1. Let's Plug Things
        1. What is a microcontroller?
        2. Presenting the big Arduino family
        3. About hardware prototyping
        4. Understanding Arduino software architecture
        5. Installing Arduino development environment (IDE)
          1. Installing the IDE
          2. How to launch the environment?
          3. What does the IDE look like?
        6. Installing Arduino drivers
          1. Installing drivers for Arduino Uno R3
          2. Installing drivers for Arduino Duemilanove, Nano, or Diecimilla
        7. What is electricity?
          1. Voltage
          2. Current and power
          3. And what are resistors, capacitors, and so on?
          4. Wiring things and Fritzing
            1. What is Fritzing?
          5. Power supply fundamentals
          6. Hello LED!
            1. What do we want to do exactly?
            2. How can I do that using C code?
              1. Start with a new blank page
              2. Setting up the environment according the board we are using
              3. Let's write the code
            3. Let's upload the code, at last!
        8. Summary
      10. 2. First Contact with C
        1. An introduction to programming
          1. Different programming paradigms
          2. Programming style
        2. C and C++?
          1. C is used everywhere
          2. Arduino is programmed with C and C++
        3. The Arduino native library and other libraries
          1. Discovering the Arduino native library
          2. Other libraries included and not directly provided
            1. Some very useful included libraries
            2. Some external libraries
        4. Checking all basic development steps
        5. Using the serial monitor
          1. Baud rate
          2. Serial communication with Arduino
          3. Serial monitoring
        6. Making the Arduino talk to us
          1. Adding serial communication to Blink250ms
          2. Serial functions in more detail
            1. Serial.begin()
            2. Serial.print() and Serial.println()
          3. Digging a bit…
          4. Talking to the board from the computer
        7. Summary
      11. 3. C Basics – Making You Stronger
        1. Approaching variables and types of data
          1. What is a variable?
          2. What is a type?
            1. The roll over/wrap concept
          3. Declaring and defining variables
            1. Declaring variables
            2. Defining variables
        2. String
          1. String definition is a construction
          2. Using indexes and search inside String
            1. charAt()
            2. indexOf() and lastIndexOf()
            3. startsWith() and endsWith()
          3. Concatenation, extraction, and replacement
            1. Concatenation
              1. Concat()
              2. Using the + operator on strings
            2. Extract and replace
              1. substring() is the extractor
              2. Splitting a string using a separator
              3. Replacement
          4. Other string functions
            1. toCharArray()
            2. toLowerCase() and toUpperCase()
            3. trim()
            4. length()
          5. Testing variables on the board
            1. Some explanations
        3. The scope concept
        4. static, volatile, and const qualifiers
          1. static
          2. volatile
          3. const
        5. Operators, operator structures, and precedence
          1. Arithmetic operators and types
            1. Character types
            2. Numerical types
          2. Condensed notations and precedence
          3. Increment and decrement operators
        6. Types manipulations
          1. Choosing the right type
          2. Implicit and explicit types conversions
            1. Implicit type conversion
            2. Explicit type conversion
        7. Comparing values and Boolean operators
          1. Comparison expressions
          2. Combining comparisons with Boolean operators
            1. Combining negation and comparisons
        8. Adding conditions in the code
          1. if and else conditional structure
            1. Chaining an if…else structure to another if…else structure
            2. if…else structure with combined comparisons expressions
            3. Finding all cases for a conditional structure
          2. switch…case…break conditional structure
          3. Ternary operator
        9. Making smart loops for repetitive tasks
          1. for loop structure
            1. Playing with increment
              1. More complex increments
              2. Decrements are negative increments
            2. Using imbricated for loops or two indexes
          2. while loop structure
          3. do…while loop structure
          4. Breaking the loops
          5. Infinite loops are not your friends
        10. Summary
      12. 4. Improve Programming with Functions, Math, and Timing
        1. Introducing functions
          1. Structure of a function
            1. Creating function prototypes using the Arduino IDE
            2. Header and name of functions
            3. Body and statements of functions
          2. Benefits of using functions
            1. Easier coding and debugging
            2. Better modularity helps reusability
            3. Better readability
        2. C standard mathematical functions and Arduino
          1. Trigonometric C functions in the Arduino core
            1. Some prerequisites
              1. Difference between radians and degrees
              2. Cosine, sine, and tangent
              3. Arccosine, arcsine, and arctangent
            2. Trigonometry functions
          2. Exponential functions and some others
        3. Approaching calculation optimization
          1. The power of the bit shift operation
            1. What are bit operations?
            2. Binary numeral system
              1. Easily converting a binary number to a decimal number
            3. AND, OR, XOR, and NOT operators
              1. AND
              2. OR
              3. XOR
              4. NOT
            4. Bit shift operations
            5. It is all about performance
          2. The switch case labels optimization techniques
            1. Optimizing the range of cases
            2. Optimizing cases according to their frequency
          3. Smaller the scope, the better the board
          4. The Tao of returns
            1. Direct returns concept
            2. Use void if you don't need return
          5. Secrets of lookup tables
            1. Table initialization
            2. Replacing pure calculation with array index operations
          6. Taylor series expansion trick
          7. The Arduino core even provides pointers
        4. Time measure
          1. Does the Arduino board own a watch?
            1. The millis() function
            2. The micros() function
          2. Delay concept and the program flow
            1. What does the program do during the delay?
            2. The polling concept – a special interrupt case
            3. The interrupt handler concept
            4. What is a thread?
            5. A real-life polling library example
              1. Installing an external library
              2. Let's test the code
        5. Summary
      13. 5. Sensing with Digital Inputs
        1. Sensing the world
          1. Sensors provide new capacities
            1. Some types of sensors
          2. Quantity is converted to data
          3. Data has to be perceived
        2. What does digital mean?
          1. Digital and analog concepts
          2. Inputs and outputs of Arduino
        3. Introducing a new friend – Processing
          1. Is Processing a language?
          2. Let's install and launch it
          3. A very familiar IDE
            1. Alternative IDEs and versioning
          4. Checking an example
          5. Processing and Arduino
        4. Pushing the button
          1. What is a button, a switch?
            1. Different types of switches
          2. A basic circuit
            1. Wires
            2. The circuit in the real world
          3. The pull-up and pull-down concept
            1. The pseudocode
            2. The code
          4. Making Arduino and Processing talk
            1. The communication protocol
              1. Protocol requirements
              2. Protocol design
            2. The Processing code
              1. Sketching a pseudocode
              2. Let's write that code
              3. Variable definitions
              4. setup()
              5. draw()
              6. The serialEvent() callback
            3. The new Arduino firmware talk-ready
        5. Playing with multiple buttons
          1. The circuit
          2. The Arduino code
          3. The Processing code
        6. Understanding the debounce concept
          1. What? Who is bouncing?
          2. How to debounce
        7. Summary
      14. 6. Sensing the World – Feeling with Analog Inputs
        1. Sensing analog inputs and continuous values
          1. How many values can we distinguish?
          2. Reading analog inputs
            1. The real purpose of the potentiometer
            2. Changing the blinking delay of an LED with a potentiometer
            3. How to turn the Arduino into a low voltage voltmeter?
              1. Calculating the precision
        2. Introducing Max 6, the graphical programming framework
          1. A brief history of Max/MSP
          2. Global concepts
            1. What is a graphical programming framework?
            2. Max, for the playground
            3. MSP, for sound
            4. Jitter, for visuals
            5. Gen, for a new approach to code generation
            6. Summarizing everything in one table
          3. Installing Max 6
          4. The very first patch
            1. Playing sounds with the patch
        3. Controlling software using hardware
          1. Improving the sequencer and connecting the Arduino
            1. Let's connect the Arduino to Max 6
            2. The serial object in Max 6
            3. Tracing and Debugging easily in Max 6
            4. Understanding Arduino messages in Max 6
            5. What is really sent on the wire?
            6. Extracting only the payload?
            7. ASCII conversions and symbols
            8. Playing with sensors
            9. Measuring distances
            10. Reading a datasheet?
            11. Let's wire things
            12. Coding the firmware
            13. Reading the distance in Max 6
          2. Measuring flexion
            1. Resistance calculations
          3. Sensing almost everything
        4. Multiplexing with a CD4051 multiplexer/demultiplexer
          1. Multiplexing concepts
          2. Multiple multiplexing/demultiplexing techniques
            1. Space-division multiplexing
            2. Frequency-division multiplexing
            3. Time-division multiplexing
          3. The CD4051B analog multiplexer
            1. What is an integrated circuit?
            2. Wiring the CD4051B IC?
              1. Identifying pin number 1
            3. Supplying the IC
            4. Analog I/O series and the common O/I
            5. Selecting the digital pin
        5. Summary
      15. 7. Talking over Serial
        1. Serial communication
          1. Serial and parallel communication
          2. Types and characteristics of serial communications
            1. Synchronous or asynchronous
            2. Duplex mode
            3. Peering and bus
              1. Master and slave buses
            4. Data encoding
        2. Multiple serial interfaces
          1. The powerful Morse code telegraphy ancestor
            1. The famous RS-232
              1. From 25 wires to 3
            2. The elegant I2C
            3. The synchronous SPI
            4. The omnipresent USB
              1. USB system design
              2. USB connectors and cables
              3. FTDI IC converting RS-232 to USB
        3. Summary
      16. 8. Designing Visual Output Feedback
        1. Using LEDs
          1. Different types of LEDs
            1. Monochromatic LEDS
            2. Polychromatic LEDs
          2. Remembering the Hello LED example
          3. Multiple monochromatic LEDs
            1. Two buttons and two LEDs
            2. Control and feedback coupling in interaction design
            3. The coupling firmware
            4. More LEDs?
        2. Multiplexing LEDs
          1. Connecting 75HC595 to Arduino and LEDs
          2. Firmware for shift register handling
            1. Global shift register programming pattern
            2. Playing with chance and random seeds
          3. Daisy chaining multiple 74HC595 shift registers
            1. Linking multiple shift registers
            2. Firmware handling two shift registers and 16 LEDs
            3. Current short considerations
        3. Using RGB LEDs
          1. Some control concepts
          2. Different types of RGB LEDs
          3. Lighting an RGB LED
            1. Red, Green, and Blue light components and colors
            2. Multiple imbricated for() loops
        4. Building LED arrays
          1. A new friend named transistor
          2. The Darlington transistors array, ULN2003
          3. The LED matrix
          4. Cycling and POV
          5. The circuit
          6. The 3 x 3 LED matrix code
        5. Simulating analog outputs with PWM
          1. The pulse-width modulation concept
          2. Dimming an LED
            1. A higher resolution PWM driver component
        6. Quick introduction to LCD
          1. HD44780-compatible LCD display circuit
          2. Displaying some random messages
        7. Summary
      17. 9. Making Things Move and Creating Sounds
        1. Making things vibrate
          1. The piezoelectric sensor
          2. Wiring a vibration motor
          3. Firmware generating vibrations
        2. Higher current driving and transistors
        3. Controlling a servo
          1. When do we need servos?
          2. How to control servos with Arduino
          3. Wiring one servo
          4. Firmware controlling one servo using the Servo library
        4. Multiple servos with external power supply
          1. Three servos and an external power supply
          2. Driving three servos with firmware
        5. Controlling stepper motors
          1. Wiring a unipolar stepper to Arduino
          2. Firmware controlling the stepper motor
        6. Air movement and sounds
          1. What is sound actually?
          2. How to describe sound
          3. Microphones and speakers
          4. Digital and analog domains
            1. How to digitalize sound
            2. How to play digital bits as sounds
          5. How Arduino helps produce sounds
        7. Playing basic sound bits
          1. Wiring the cheapest sound circuit
          2. Playing random tones
        8. Improving the sound engine with Mozzi
          1. Setting up a circuit and Mozzi library
          2. An example sine wave
            1. Oscillators
            2. Wavetables
          3. Frequency modulation of a sine wave
            1. Adding a pot
            2. Upgrading the firmware for input handling
        9. Controlling the sound using envelopes and MIDI
          1. An overview of MIDI
          2. MIDI and OSC libraries for Arduino
          3. Generating envelopes
          4. Implementing envelopes and MIDI
          5. Wiring a MIDI connector to Arduino
        10. Playing audio files with the PCM library
          1. The PCM library
          2. WAV2C – converting your own sample
          3. Wiring the circuit
          4. Other reader libraries
        11. Summary
      18. 10. Some Advanced Techniques
        1. Data storage with EEPROMs
          1. Three native pools of memory on the Arduino boards
            1. Writing and reading with EEPROM core library
          2. External EEPROM wiring
          3. Reading and writing to the EEPROM
        2. Using GPS modules
          1. Wiring the Parallax GPS receiver module
          2. Parsing GPS location data
        3. Arduino, battery, and autonomy
          1. Classic cases of USB power supplying
          2. Supplying external power
            1. Supplying with batteries
          3. Power adapter for Arduino supply
          4. How to calculate current consumption
        4. Drawing on gLCDs
          1. Wiring the device
          2. Demoing the library
          3. Some useful method's families
            1. Global GLCD methods
            2. Drawing methods
            3. Text methods
        5. Using VGA with the Gameduino Shield
        6. Summary
      19. 11. Networking
        1. An overview of networks
          1. Overview of the OSI model
          2. Protocols and communications
          3. Data encapsulation and decapsulation
          4. The roles of each layer
            1. Physical layer
            2. Data link layer
            3. Network layer
            4. Transport layer
            5. Application/Host layers
          5. Some aspects of IP addresses and ports
            1. The IP address
            2. The subnet
            3. The communication port
        2. Wiring Arduino to wired Ethernet
          1. Making Processing and Arduino communicate over Ethernet
            1. Basic wiring
            2. Coding network connectivity implementation in Arduino
            3. Coding a Processing Applet communicating on Ethernet
          2. Some words about TCP
        3. Bluetooth communications
          1. Wiring the Bluetooth module
          2. Coding the firmware and the Processing applet
        4. Playing with Wi-Fi
          1. What is Wi-Fi?
            1. Infrastructure mode
            2. Ad hoc mode
            3. Other modes
          2. The Arduino Wi-Fi shield
          3. Basic Wi-Fi connection without encryption
          4. Arduino Wi-Fi connection using WEP or WPA2
            1. Using WEP with Wi-Fi library
            2. Using WPA2 with Wi-Fi library
          5. Arduino has a (light) web server
        5. Tweeting by pushing a switch
          1. An overview of APIs
          2. Twitters API
          3. Using the Twitter library with OAuth support
            1. Grabbing credentials from Twitter
            2. Coding a firmware connecting to Twitter
        6. Summary
      20. 12. Playing with Max 6 Framework
        1. Communicating easily with Max 6 – the [serial] object
          1. The [serial] object
          2. Selecting the right serial port
          3. Polling system
        2. Parsing and selecting data coming from Arduino
          1. The readAll firmware
          2. The ReadAll Max 6 patch
            1. Requesting data from Arduino
            2. Parsing the received data
            3. Distributing received data and other tricks
              1. Cordless trick
              2. Encapsulation and subpatching
              3. Abstractions and reusability
        3. Creating a sound-level meter with LEDs
          1. The circuit
          2. The Max 6 patch for calculating sound levels
          3. The firmware for reading bytes
        4. Pitch shift effect controlled by hand
          1. The circuit with the sensor and the firmware
          2. The patch for altering the sound and parsing Arduino messages
        5. Summary
      21. 13. Improving your C Programming and Creating Libraries
        1. Programming libraries
          1. The header file
          2. The source file
        2. Creating your own LED-array library
          1. Wiring six LEDs to the board
          2. Creating some nice light patterns
          3. Designing a small LED-pattern library
            1. Writing the LEDpatterns.h header
            2. Writing the LEDpatterns.cpp source
            3. Writing the keyword.txt file
          4. Using the LEDpatterns library
        3. Memory management
        4. Mastering bit shifting
          1. Multiplying/dividing by multiples of 2
          2. Packing multiple data items into bytes
          3. Turning on/off individual bits in a control and port register
        5. Reprogramming the Arduino board
        6. Summary
        7. Conclusion
      22. Index