Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arduino By Example
Arduino By Example

Arduino By Example: Design and build fantastic projects and devices using the Arduino platform

By Adith Jagadish Boloor , Adith Jagdish Boloor
$48.99
Book Sep 2015 242 pages 1st Edition
eBook
$39.99 $27.98
Print
$48.99
Subscription
$15.99 Monthly
eBook
$39.99 $27.98
Print
$48.99
Subscription
$15.99 Monthly

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Sep 14, 2015
Length 242 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781785289088
Category :
Table of content icon View table of contents Preview book icon Preview Book

Arduino By Example

Chapter 1. Getting Started with Arduino

Hello there! If you are reading this book right now, it means that you've taken your first step to make fascinating projects using Arduinos. This chapter will teach you how to set up an Arduino and write your first Arduino code.

You'll be in good hands whilst you learn some of the basics aspects of coding using the Arduino platform; this will allow you to build almost anything including robots, home automation systems, touch interfaces, sensory systems, and so on. Firstly, you will learn how to install the powerful Arduino software, then set that up, followed by hooking up your Arduino board and, after making sure that everything is fine and well, you will write your first code! Once you are comfortable with that, we will modify the code to make it do something more, which is often what Arduino coders do. We do not just create completely new programs; often we build on what has been done before, to make it better and more suited to our objectives. The contents of this chapter are divided into the following topics:

  • Prerequisites

  • Setting up

  • Hello World

  • Summary

Prerequisites


Well, you can't jump onto a horse without putting on a saddle first, can you? This section will cover what components you need to start coding on an Arduino. These can be purchased from your favorite electrical hobby store or simply ordered online.

Materials needed

  • 1x Arduino-compatible board such as an Arduino UNO

  • 1x USB cable A to B

  • 2x LEDs

  • 2x 330Ω resistors

  • A mini breadboard

  • 5x male-to-male jumper wires

Note

The UNO can be substituted for any other Arduino board (Mega, Leonardo, and so on) for most of the projects. These boards have their own extra features. For example, the Mega has almost double the number of I/O (input/output) pins for added functionality. The Leonardo has a feature that enables it to control the keyboard and mouse of your computer.

Setting up


This topic involves downloading the Arduino software, installing the drivers, hooking up the Arduino, and understanding the IDE menus.

Downloading and installing the software

Arduino is open source-oriented. This means all the software is free to use non-commercially. Go to http://arduino.cc/en/Main/Software and download the latest version for your specific operating system. If you are using a Mac, make sure you choose the right Java version; similarly on Linux, download the 32-or 64-bit version according to your computer.

Arduino download page

Windows

Once you have downloaded the setup file, run it. If it asks for administrator privileges, allow it. Install it in its default location (C:\Program Files\Arduino or C:\Program Files (x86)\Arduino). Create a new folder in this location and rename it My Codes or something where you can conveniently store all your programs.

Mac OS X

Once the ZIP file has finished downloading, double-click to expand it. Copy the Arduino application to the Applications folder. You won't have to install additional drivers to make the Arduino work since we will be using only the Arduino UNO and MEGA throughout the book. You're all set.

If you didn't get anything to work, go to https://www.arduino.cc/en/guide/macOSX.

Linux (Ubuntu 12.04 and above)

Once you have downloaded the latest version of Arduino from the preceding link, install the compiler and the library packages using the following command:

sudo apt-get update && sudo apt-get install arduino arduino-core

If you are using a different version of Linux, this official Arduino walkthrough at http://playground.arduino.cc/Learning/Linux will help you out.

Connecting the Arduino


It is time to hook up the Arduino board. Plug in the respective USB terminals to the USB cable and the tiny LEDs on the Arduino should begin to flash.

Arduino UNO plugged in

If the LEDs didn't turn on, ensure that the USB port on your computer is functioning and make sure the cable isn't faulty. If it still does not light up, there is something wrong with your board and you should get it checked.

Windows

The computer will begin to install the drivers for the Arduino by itself. If it does not succeed, do the following:

  1. Open Device Manager.

  2. Click on Ports (COM & LPT).

  3. Right-click on Unknown Device and select Properties.

  4. Click on Install Driver and choose browse files on the computer.

  5. Choose the drivers folder in the previously installed Arduino folder.

The computer should say that your Arduino UNO (USB) has been successfully installed on COM port (xx). Here xx refers to a single or double digit number. If this message didn't pop up, go back to the Device Manager and check if it has been installed under COM ports.

Arduino UNO COM port

Remember the (COMxx) port that the Arduino UNO was installed on.

Mac OS X

If you are using Mac OS, a dialog box will tell you that a new network interface has been detected. Click Network Preferences and select Apply. Even though the Arduino board may show up as Not Configured, it should be working perfectly.

Linux

You are ready to go.

The serial ports for Mac OS and Linux will be obtained once the Arduino software has been launched.

The Arduino IDE

The Arduino software, commonly referred to as the Arduino IDE (Integrated Development Environment), is something that you will become really familiar with as you progress through this book. The IDE for Windows, Mac OS, and Linux is almost identical. Now let's look at some of the highlights of this software.

Arduino IDE

This is the window that you will see when you first start up the IDE. The tick/check mark verifies that your code's syntax is correct. The arrow pointing right is the button that uploads the code to the board and checks if the code has been changed since the last upload or verification. The magnifying glass is the Serial Monitor. This is used to input text or output debugging statements or sensor values.

Examples of Arduino

All Arduino programmers start by using one of these examples. Even after mastering Arduino, you will still return here to find examples to use.

Arduino tools

The screenshot shows the tools that are available in the Arduino IDE. The Board option opens up all the different boards that the software supports.

Hello World


The easiest way to start working with Arduinos begins here. You'll learn how to output print statements. The Arduino uses a Serial Monitor for displaying information such as print statements, sensor data, and the like. This is a very powerful tool for debugging long codes. Now for your first code!

Writing a simple print statement

Open up the Arduino IDE and copy the following code into a new sketch:

void setup() {
Serial.begin(9600);
Serial.println("Hello World!");
}

void loop() {
}

Open Tools | Board and choose Arduino UNO, as shown in the following screenshot:

Open Tools | Port and choose the appropriate port (remember the previous COM xx number? select that), as shown in the following screenshot. For Mac and Linux users, once you have connected the Arduino board, going to Tools | Serial Port will give you a list of ports. The Arduino is typically something like /dev/tty.usbmodem12345 where 12345 will be different.

Selecting the Port

Finally, hit the Upload button. If everything is fine, the LEDs on the Arduino should start flickering as the code is uploaded to the Arduino. The code will then have uploaded to the Arduino.

To see what you have accomplished, click on the Serial Monitor button on the right side and switch the baud rate on the Serial Monitor window to 9600.

You should see your message Hello World! waiting for you there.

LED blink


That wasn't too bad but it isn't cool enough. This little section will enlighten you, literally.

Open up a new sketch.

Go to File | Examples | 01. Basics | Blink.

Blink example

Before we upload the code, we need to make sure of one more thing. Remember the LED that we spoke about in the prerequisites? Let's learn a bit about it before plugging it in, as shown in the following image:

LED basics

We will make use of it now. Plug in the LED such that the longer leg goes into pin 13 and the shorter leg goes into the GND pin, as in the following:

LED blink setup (Fritzing)

Note

This diagram is made using software called Fritzing. This software will be used in future projects to make it cleaner to see and easier to understand as compared to a photograph with all the wires running around. Fritzing is open source software which you can learn more about at www.fritzing.org.

Arduino LED setup

Upload the code. Your LED will start blinking, as shown in the following image.

A lit up LED

Isn't it just fascinating? You just programmed your first hardware. There's no stopping you now. Before advancing to the next chapter, let's see what the code does and what happens when you change it.

This is the blink example code that you just used:

/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
  
This example code is in the public domain.
*/

//Pin 13 has an LED connected on most Arduino boards.
//give it a name:
int led = 13;

//the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

//the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

We have three major sections in this code. This format will be used for most of the projects in the book.

int led = 13;

This line simply stores the numerical PIN value onto a variable called led.

void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

This is the setup function. Here is where you tell the Arduino what is connected on each used pin. In this case, we tell the Arduino that there is an output device (LED) on pin 13.

void loop() {
digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
delay(1000);               // wait for a second
digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
delay(1000);               // wait for a second
}

This is the loop function. It tells the Arduino to keep repeating whatever is inside it in a sequence. The digitalWrite command is like a switch that can be turned ON (HIGH) or OFF (LOW). The delay(1000) function simply makes the Arduino wait for a second before heading to the next line.

If you wanted to add another LED, you'd need some additional tools and some changes to the code. This is the setup that you want to create.

Connecting two LEDs to an Arduino

If this is your first time using a breadboard, take some time to make sure all the connections are in the right place. The colors of the wires don't matter. However, GND is denoted using a black wire and VCC/5V/PWR is denoted with a red wire. The two resistors, each connected in series (acting like a connecting wire itself) with the LEDs, limit the current flowing to the LEDs, making sure they don't blow up.

As before, create a new sketch and paste in the following code:

/*
Double Blink
Turns on and off two LEDs alternatively for one second each repeatedly.

This example code is in the public domain.
*/

int led1 = 12;
int led2 = 13;

void setup() {
// initialize the digital pins as an output.
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);

// turn off LEDs before loop begins
digitalWrite(led1, LOW);   // turn the LED off (LOW is the voltage level)
digitalWrite(led2, LOW);   // turn the LED off (LOW is the voltage level)
}

//the loop routine runs over and over again forever:
void loop() {
digitalWrite(led1, HIGH);   // turn the LED on (HIGH is the voltage level)
digitalWrite(led2, LOW);    // turn the LED off (LOW is the voltage level)
delay(1000);                // wait for a second
digitalWrite(led1, LOW);    // turn the LED off (LOW is the voltage level)
digitalWrite(led2, HIGH);   // turn the LED on (HIGH is the voltage level)
delay(1000);                // wait for a second
}

Once again, make sure the connections are made properly, especially the positive LEDs (the longer one to OUTPUT PIN) and the negative (the shorter to the GND) terminals. Save the code as DoubleBlink.ino. Now, if you make any changes to it, you can always retrieve the backup.

Upload the code. 3… 2… 1… And there you have it, an alternating LED blink cycle created purely with the Arduino. You can try changing the delay to see its effects.

For the sake of completeness, I would like to mention that you could take this mini-project further by using a battery to power the system and decorate your desk/room/house. More on how to power the Arduino will be covered in subsequent chapters.

Summary


You have now completed the basic introduction to the world of Arduino. In short, you have successfully set up your Arduino and have written your first code. You also learned how to modify the existing code to create something new, making it more suitable for your specific needs. This methodology will be applied repeatedly while programming, because almost all the code available is open source and it saves time and energy.

In the next chapter, we will look into sensors and displays. You will build a digital ruler that you can use to measure short distances. It will consist of an ultrasound sensor to compute distance and a small LCD screen to display it. Additionally, we will look at safely powering the Arduino board using a battery so that you are not dependent on your computer for USB power every time.

Left arrow icon Right arrow icon

Key benefits

What you will learn

Understand and utilize the capabilities of the Arduino Integrate sensors to gather environmental data and display this information in meaningful ways Add modules such as Bluetooth and WiFi that allow the Arduino to communicate and send data between devices Create simple servers to allow communication to occur Build automated projects including robots while learning complex algorithms to mimic biological locomotion Implement error handling to make programs easier to debug and look more professional Integrate powerful programming tools and software such as Python and Processing to broaden the scope of what the Arduino can achieve Practice and learn basic programming etiquette

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Sep 14, 2015
Length 242 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781785289088
Category :

Table of Contents

18 Chapters
Arduino by Example Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
Acknowledgements Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Getting Started with Arduino Chevron down icon Chevron up icon
Digital Ruler Chevron down icon Chevron up icon
Converting Finger Gestures to Text Chevron down icon Chevron up icon
Burglar Alarm – Part 1 Chevron down icon Chevron up icon
Burglar Alarm – Part 2 Chevron down icon Chevron up icon
Home Automation – Part 1 Chevron down icon Chevron up icon
Home Automation – Part 2 Chevron down icon Chevron up icon
Robot Dog – Part 1 Chevron down icon Chevron up icon
Robot Dog – Part 2 Chevron down icon Chevron up icon
Robot Dog – Part 3 Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela