55
Arduino III Internet of ings

Arduino III: Internet of Things

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Arduino III: Internet of Things

Arduino IIIInternet ofThings

Page 2: Arduino III: Internet of Things

Synthesis Lectures onDigitalCircuits and Systems

EditorMitchell A.Thornton, SouthernMethodist University

The Synthesis Lectures on Digital Circuits and Systems series is comprised of 50- to 100-page bookstargeted for audience members with a wide-ranging background. The Lectures include topics thatare of interest to students, professionals, and researchers in the area of design and analysis of digitalcircuits and systems. Each Lecture is self-contained and focuses on the background informationrequired to understand the subject matter and practical case studies that illustrate applications. Theformat of a Lecture is structured such that each will be devoted to a specific topic in digital circuitsand systems rather than a larger overview of several topics such as that found in a comprehensivehandbook. The Lectures cover both well-established areas as well as newly developed or emergingmaterial in digital circuits and systems design and analysis.

Arduino III: Internet of ThingsSteven F. Barrett2021

Arduino II: SystemsSteven F. Barrett2020

Arduino I: Getting StartedSteven F. Barrett2020

Index Generation FunctionsTsutomu Sasao2019

Microchip AVR® Microcontroller Primer: Programming and Interfacing, Third EditionSteven F. Barrett and Daniel J. Pack2019

Microcontroller Programming and Interfacing with Texas Instruments MSP430FR2433and MSP430FR5994 – Part II, Second EditionSteven F. Barrett and Daniel J. Pack2019

Page 3: Arduino III: Internet of Things

iiiMicrocontroller Programming and Interfacing with Texas Instruments MSP430FR2433and MSP430FR5994 – Part I, Second EditionSteven F. Barrett and Daniel J. Pack2019

Synthesis of Quantum Circuits vs. Synthesis of Classical Reversible CircuitsAlexis De Vos, Stijn De Baerdemacker, and Yvan Van Rentergen2018

Boolean Differential CalculusBernd Steinbach and Christian Posthoff2017

Embedded Systems Design with Texas Instruments MSP432 32-bit ProcessorDung Dang, Daniel J. Pack, and Steven F. Barrett2016

Fundamentals of Electronics: Book 4 Oscillators and Advanced Electronics TopicsThomas F. Schubert and Ernest M. Kim2016

Fundamentals of Electronics: Book 3 Active Filters and Amplifier FrequencyThomas F. Schubert and Ernest M. Kim2016

Bad to the Bone: Crafting Electronic Systems with BeagleBone and BeagleBone Black,Second EditionSteven F. Barrett and Jason Kridner2015

Fundamentals of Electronics: Book 2 Amplifiers: Analysis and DesignThomas F. Schubert and Ernest M. Kim2015

Fundamentals of Electronics: Book 1 Electronic Devices and Circuit ApplicationsThomas F. Schubert and Ernest M. Kim2015

Applications of Zero-Suppressed Decision DiagramsTsutomu Sasao and Jon T. Butler2014

Modeling Digital Switching Circuits with Linear AlgebraMitchell A. Thornton2014

Page 4: Arduino III: Internet of Things

ivArduino Microcontroller Processing for Everyone! Third EditionSteven F. Barrett2013

Boolean Differential EquationsBernd Steinbach and Christian Posthoff2013

Bad to the Bone: Crafting Electronic Systems with BeagleBone and BeagleBone BlackSteven F. Barrett and Jason Kridner2013

Introduction to Noise-Resilient ComputingS.N. Yanushkevich, S. Kasai, G. Tangim, A.H. Tran, T. Mohamed, and V.P. Shmerko2013

Atmel AVR Microcontroller Primer: Programming and Interfacing, Second EditionSteven F. Barrett and Daniel J. Pack2012

Representation of Multiple-Valued Logic FunctionsRadomir S. Stankovic, Jaakko T. Astola, and Claudio Moraga2012

Arduino Microcontroller: Processing for Everyone! Second EditionSteven F. Barrett2012

Advanced Circuit Simulation Using Multisim WorkbenchDavid Báez-López, Félix E. Guerrero-Castro, and Ofelia Delfina Cervantes-Villagómez2012

Circuit Analysis with MultisimDavid Báez-López and Félix E. Guerrero-Castro2011

Microcontroller Programming and Interfacing Texas Instruments MSP430, Part ISteven F. Barrett and Daniel J. Pack2011

Microcontroller Programming and Interfacing Texas Instruments MSP430, Part IISteven F. Barrett and Daniel J. Pack2011

Pragmatic Electrical Engineering: Systems and InstrumentsWilliam Eccles2011

Page 5: Arduino III: Internet of Things

vPragmatic Electrical Engineering: FundamentalsWilliam Eccles2011

Introduction to Embedded Systems: Using ANSI C and the Arduino DevelopmentEnvironmentDavid J. Russell2010

Arduino Microcontroller: Processing for Everyone! Part IISteven F. Barrett2010

Arduino Microcontroller Processing for Everyone! Part ISteven F. Barrett2010

Digital System Verification: A Combined Formal Methods and Simulation FrameworkLun Li and Mitchell A. Thornton2010

Progress in Applications of Boolean FunctionsTsutomu Sasao and Jon T. Butler2009

Embedded Systems Design with the Atmel AVR Microcontroller: Part IISteven F. Barrett2009

Embedded Systems Design with the Atmel AVR Microcontroller: Part ISteven F. Barrett2009

Embedded Systems Interfacing for Engineers using the Freescale HCS08 MicrocontrollerII: Digital and Analog Hardware InterfacingDouglas H. Summerville2009

Designing Asynchronous Circuits using NULL Convention Logic (NCL)Scott C. Smith and JiaDi2009

Embedded Systems Interfacing for Engineers using the Freescale HCS08 MicrocontrollerI: Assembly Language ProgrammingDouglas H.Summerville2009

Page 6: Arduino III: Internet of Things

viDeveloping Embedded Software using DaVinci & OMAP TechnologyB.I. (Raj) Pawate2009

Mismatch and Noise in Modern IC ProcessesAndrew Marshall2009

Asynchronous Sequential Machine Design and Analysis: A Comprehensive Developmentof the Design and Analysis of Clock-Independent State Machines and SystemsRichard F. Tinder2009

An Introduction to Logic Circuit TestingParag K. Lala2008

Pragmatic PowerWilliam J. Eccles2008

Multiple Valued Logic: Concepts and RepresentationsD. Michael Miller and Mitchell A. Thornton2007

Finite State Machine Datapath Design, Optimization, and ImplementationJustin Davis and Robert Reese2007

Atmel AVR Microcontroller Primer: Programming and InterfacingSteven F. Barrett and Daniel J. Pack2007

Pragmatic LogicWilliam J. Eccles2007

PSpice for Filters and Transmission LinesPaul Tobin2007

PSpice for Digital Signal ProcessingPaul Tobin2007

Page 7: Arduino III: Internet of Things

viiPSpice for Analog Communications EngineeringPaul Tobin2007

PSpice for Digital Communications EngineeringPaul Tobin2007

PSpice for Circuit Theory and Electronic DevicesPaul Tobin2007

Pragmatic Circuits: DC and Time DomainWilliam J. Eccles2006

Pragmatic Circuits: Frequency DomainWilliam J. Eccles2006

Pragmatic Circuits: Signals and FiltersWilliam J. Eccles2006

High-Speed Digital System DesignJustin Davis2006

Introduction to Logic Synthesis using Verilog HDLRobert B.Reese and Mitchell A.Thornton2006

Microcontrollers Fundamentals for Engineers and ScientistsSteven F. Barrett and Daniel J. Pack2006

Page 8: Arduino III: Internet of Things

Copyright © 2021 by Morgan & Claypool

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted inany form or by anymeans—electronic, mechanical, photocopy, recording, or any other except for brief quotationsin printed reviews, without the prior permission of the publisher.

Arduino III: Internet of Things

Steven F. Barrett

www.morganclaypool.com

ISBN: 9781636390833 paperbackISBN: 9781636390840 ebookISBN: 9781636390857 hardcover

DOI 10.2200/S01077ED1V03Y202102DCS060

A Publication in the Morgan & Claypool Publishers seriesSYNTHESIS LECTURES ON DIGITAL CIRCUITS AND SYSTEMS

Lecture #60Series Editor: Mitchell A. Thornton, Southern Methodist UniversitySeries ISSNPrint 1932-3166 Electronic 1932-3174

Page 9: Arduino III: Internet of Things

Arduino IIIInternet ofThings

Steven F. BarrettUniversity of Wyoming, Laramie, WY

SYNTHESIS LECTURES ON DIGITAL CIRCUITS AND SYSTEMS #60

CM&

cLaypoolMorgan publishers&

Page 10: Arduino III: Internet of Things

x

ABSTRACTThis book is about the Arduino microcontroller and the Arduino concept. The visionary Ar-duino team of Massimo Banzi, David Cuartielles, Tom Igoe, Gianluca Martino, and DavidMellis launched a new innovation in microcontroller hardware in 2005, the concept of open-source hardware. Their approach was to openly share details of microcontroller-based hardwaredesign platforms to stimulate the sharing of ideas and promote innovation. This concept hasbeen popular in the software world for many years. In June 2019, Joel Claypool and I met toplan the fourth edition of Arduino Microcontroller Processing for Everyone! Our goal has been toprovide an accessible book on the rapidly evolving world of Arduino for a wide variety of audi-ences including students of the fine arts, middle and senior high school students, engineeringdesign students, and practicing scientists and engineers. To make the book even more accessibleto better serve our readers, we decided to change our approach and provide a series of smallervolumes. Each volume is written to a specific audience. This book, Arduino III: Internet ofThings,explores Arduino applications in the fascinating and rapidly evolving world of the Internet ofThings. Arduino I: Getting Started provides an introduction to the Arduino concept. Arduino II:Systems, is a detailed treatment of the ATmega328 processor and an introduction to C program-ming and microcontroller-based systems design.

KEYWORDSArduino microcontroller, Arduino UNO R3, Internet of Things, IoT, MKR 1000,MKR1010, greenhouse, weather stat

Page 11: Arduino III: Internet of Things

xi

ContentsPreface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv

Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix

1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 The Big Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.3 Arduino Quick Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.3.1 Quick Start Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.3.2 Arduino Development Environment Overview . . . . . . . . . . . . . . . . . . . 41.3.3 Sketchbook Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.3.4 Arduino Software, Libraries, and Language References . . . . . . . . . . . . 51.3.5 Writing an Arduino Sketch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1.4 Arduino UNO R3 Processing Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.5 Arduino UNO R3 Open Source Schematic . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.6 Arduino UNO R3 Host Processor–The ATmega328 . . . . . . . . . . . . . . . . . . . . 10

1.6.1 ATmega328 Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141.6.2 ATmega328 Port System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.6.3 ATmega328 Internal Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

1.7 Interfacing to Other Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181.8 Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201.10 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201.11 Chapter Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2 The Internet and IoT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232.2 A Big Picture of the Internet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242.3 Brief History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262.4 Internet Protocol Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282.5 Internet Addressing Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

Page 12: Arduino III: Internet of Things

xii2.5.1 IPv4 Header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302.5.2 CIDR Addressing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312.5.3 IPv6 Header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322.5.4 MAC Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342.5.5 DNS and URL Addressing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

2.6 Internet Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352.7 Cybersecurity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352.8 Internet of Things (IoT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382.9 Information Technology vs. Operational Technology . . . . . . . . . . . . . . . . . . . 392.10 Operational Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402.11 IoT Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422.12 IoT Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442.13 Industrial Internet of Things (IIoT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442.14 IoT and IIoT Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442.15 Application 1: Exploration of the Ethernet . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452.16 Application 2: Exploration with the Arduino Oplà IoT Kit . . . . . . . . . . . . . . 482.17 Application 3: Exploration of the MKR WiFi 1010 with the Ethernet . . . . . 502.18 Application 4: Exploration of the Arduino UNO WiFi Rev 2 with the

Ethernet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502.19 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512.20 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512.21 Chapter Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

3 Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553.2 Serial Communications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563.3 Serial Communication Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573.4 Near Field Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593.5 Serial USART . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

3.5.1 System Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623.5.2 Programming in Arduino . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663.5.3 System Operation and Programming in C . . . . . . . . . . . . . . . . . . . . . 67

3.6 Serial Peripheral Interface (SPI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793.6.1 SPI Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803.6.2 Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803.6.3 SPI Programming in the Arduino Development Environment . . . . . 82

Page 13: Arduino III: Internet of Things

xiii3.6.4 SPI Programming in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 833.6.5 Example: LED Strip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

3.7 Two-Wire Serial Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913.7.1 TWI Programming Arduino Development Environment . . . . . . . . . 933.7.2 TWI Programming in C–TWI Compatible LCD . . . . . . . . . . . . . . . 93

3.8 Radio Frequency (RF) Communications Theory . . . . . . . . . . . . . . . . . . . . . . 1053.9 Bluetooth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

3.9.1 BT Hardware and Communications . . . . . . . . . . . . . . . . . . . . . . . . . 1083.10 Zigbee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

3.10.1 Sparkfun XBee3 Wireless Kit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1123.11 Cellular Microcontroller Communications . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

3.11.1 Adafruit 2G FONA 800 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1163.11.2 Sparkfun LTE Shield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

3.12 Application: Near Field Communications (NFC) . . . . . . . . . . . . . . . . . . . . . 1193.13 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1253.14 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1253.15 Chapter Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

4 Application: IoTGreenhouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1294.1 Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1294.2 Aside: Local vs. Remote Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1294.3 Greenhouse Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1314.4 Greenhouse Instrumentation System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1324.5 Solar Power System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1324.6 Weather Station . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

4.6.1 Structure Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1364.6.2 Circuit Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1374.6.3 Bottom-Up Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1394.6.4 UML Activity Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1544.6.5 Microcontroller Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1544.6.6 Final Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

4.7 Greenhouse Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1724.8 Application: Exploration with MKR IoT Bundle . . . . . . . . . . . . . . . . . . . . . 2014.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2054.10 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2054.11 Chapter Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

Page 14: Arduino III: Internet of Things

xiv

A Programming the ATmega328 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209A.1 ISP Hardware and Software Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209A.2 ImageCraft JumpStart C for AVR Compiler Download, Installation, and

ATmega328 Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209A.3 Atmel Studio Download, Installation, and ATmega328 Programming . . . . . 211

Author’s Biography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

Page 15: Arduino III: Internet of Things

xv

PrefaceThis book is about the Arduino microcontroller and the Arduino concept. The visionary Ar-duino team of Massimo Banzi, David Cuartielles, Tom Igoe, Gianluca Martino, and DavidMellis launched a new innovation in microcontroller hardware in 2005, the concept of open-source hardware. Their approach was to openly share details of microcontroller-based hardwaredesign platforms to stimulate the sharing of ideas and promote innovation. This concept hasbeen popular in the software world for many years. In June 2019, Joel Claypool and I met toplan the fourth edition of Arduino Microcontroller Processing for Everyone! Our goal has been toprovide an accessible book on the rapidly evolving world of Arduino for a wide variety of audi-ences including students of the fine arts, middle and senior high school students, engineeringdesign students, and practicing scientists and engineers. To make the book even more accessibleto better serve our readers, we decided to change our approach and provide a series of smallervolumes. Each volume is written to a specific audience. This book, Arduino III: Internet ofThings,explores Arduino applications in the fascinating and rapidly evolving world of the Internet ofThings (IoT). Arduino I: Getting Started provides an introduction to the Arduino concept. Ar-duino II: Systems is a detailed treatment of the ATmega328 processor and an introduction to Cprogramming and microcontroller-based systems design.

APPROACHOFTHEBOOKThe goal of this book series is to provide a thorough introduction to the Arduino UNO R3 andinterfacing to different peripherals, a detailed exploration of the ATmega328, and the embeddedsystems design process, and Arduino applications in the IoT using the Arduino MKR 1000 andMKR 1010, as shown in Figure 1. We try very hard to strike a good balance between theory andpractical information. The theory is important to understand some of the underlying concepts.We also think it is important to provide multiple, practical examples they may be adapted forother projects.

This book, Arduino III: the Internet of Things, explores Arduino applications in the IoT.The phrase “Internet of Things” or “IoT” is attributed to Kevin Ashton in a 1999 presentationdescribing supply chain initiatives [Hanes].1 Generally speaking, IoT is about connecting ob-jects via the internet to accomplish specific tasks. A closely related concept is cyber-physicalsystems (CPS) or the integration of computer and physical processes. Although IoT and CPSoriginated in different communities, they share many of the same techniques and concepts.A National Institute of Standards and Technology (NIST) study acknowledges the “emerging

1Hanes D., G. Salgueiro, P. Grossetete, R. Barton, J. Henry (2017) IoT Fundamentals–Networking Technologies, Protocols,and Use Cases for the Internet of Things, Cisco Press.

Page 16: Arduino III: Internet of Things

xvi PREFACE

Arduino I: Getting Started

Getting startedArduino platformsPower and interfacingSystem examples

Arduino II: Systems

Getting startedProgrammingAnalog-to-digital conversionTiming subsystemSerial communication subsystemInterrupt subsystemEmbedded systems design

Arduino III: Internet of !ings

Getting startedInternetInternet of !ings (IoT)ConnectivityApplication: Greenhouse

Figure 1: Arduino book series.

consensus around the equivalence of CPS and IoT concepts [Greer].”2 We do the same in thisbook and primarily use the term “IoT” to refer to both.

The book builds upon the foundation of the first two volumes. The reader should have asolid grounding in the Arduino UNO R3, the Arduino Development Environment, and writingArduino sketches. For completeness we have provided prerequisite information in Chapter 1.Chapter 1 provides a brief review of some of Arduino concepts and introduces the MicrochipATmega328. This is the processor hosted onboard the Arduino UNO R3.

Chapter 2 provides an introduction to the fascinating world of the internet. In planningthis chapter, a concept map was constructed of the internet. The concept map allows one todiagram and provide organization and relationship between related concepts. It is a good toolto take a large concept, such as the internet, and break it into smaller, related topics. From theconcept map, the chapter outline was developed. The concept map of the internet developed forChapter 2 is provided in Figure 2. The concept map is not unique or complete. It may evolveover time to take into account emerging concepts.

Chapter 2 also provides an introduction to the IoT and CPS. It provides a brief introduc-tion to the IoT and CPS concepts and then describes enabling technologies, a simplified IoTarchitecture, the related topics of Information Technology (IT), and Operational Technology(OT), and explores the Industrial Internet of Things (IIoT). IIoT is a rapidly emerging conceptin many areas of agriculture, energy, food production, manufacturing, mining, transportation,and many other industries (Hanes [5]).

Chapter 3 explores the multiple methods a microcontroller may be connected to anotherdevice to share information and tasks. The chapter begins with an overview of techniques basedon range and a tutorial on serial communication concepts. Specific connection techniques arethen discussed including Near Field Communication (NFC); short-range, hardwire, serial com-munication systems (UART, SPI, I2C); and radio frequency (RF) connection techniques in-cluding BlueTooth, ZigBee, Ethernet, and connection via the cellular phone network.

2Greer, C., M. Burns, D. Wollman, E. Griffor (2019) Cyber–Physical Systems and Internet of Things, NIST Special Pub-lications 1900–202, National Institute of Standards and Technology, U.S. Department of Commerce.

Page 17: Arduino III: Internet of Things

PREFACE xvii

ConnectivityMicro-

controller

Emergingconcepts

Applicationareas

Cyber-security

Connectivityto internet

Internet

Internethardware

IPaddress

Operation Networks

Ethernet

Repeater

AgricultureEnergy - electricity - gas - oilFood productionManufacturingMiningRetailTelecomTransportationWater

Router Bridge Gateway

Internetof

�ings(IoT)

ControllerArea

Network(CAN)

WideArea

Network(WAN)

LocalArea

Network(LAN)

PersonalArea Networks

(PAN)(ZigBee)

Internetof

�ings(IoT)

Sensors

Actuators

Shields

XbeeIR remote

VGA cameraEthernet

RFIDuino

UARTSPII2C

CANBluetooth

NFCRFIDZigBee

:

Cellularphone

network

Sensor/actuatorinterface

Figure 2: Internet concept map.

Page 18: Arduino III: Internet of Things

xviii PREFACEChapter 4 applies the information from the previous chapters in the design and con-

struction of an instrumented greenhouse. Although the application is specifically geared to-ward a greenhouse, the multiple examples provided of equipping an Arduino UNO R3 and aMKR 1000 with sensors and control devices may be applied to a wide variety of projects.

Steven F. BarrettLaramie, Wyoming, March 2021

Page 19: Arduino III: Internet of Things

xix

AcknowledgmentsA number of people have made this book possible. I would like to thank Massimo Banzi of theArduino design team for his support and encouragement in writing the first edition of this book:Arduino Microcontroller: Processing for Everyone! In 2005, Joel Claypool of Morgan & ClaypoolPublishers, invited Daniel Pack and I to write a book on microcontrollers for his new series titled“Synthesis Lectures on Digital Circuits and Systems.” The result was the book MicrocontrollersFundamentals for Engineers and Scientists. Since then we have been regular contributors to theseries. Our goal has been to provide the fundamental concepts common to all microcontrollersand then apply the concepts to the specific microcontroller under discussion. We believe thatonce you have mastered these fundamental concepts, they are easily transportable to differentprocessors. As withmany other projects, Joel has provided his publishing expertise to convert ourfinal draft into a finished product. We thank him for his support on this project and many others.He has provided many novice writers the opportunity to become published authors. His visionand expertise in the publishing world made this book possible. We also thank Dr. C.L. Tondoof T&T TechWorks, Inc. and his staff for working their magic to convert our final draft into abeautiful book.

I would also like to thank Sparkfun, Adafruit, DFRobot, and Microchip for their permis-sion to use images of their products and copyrighted material throughout the text series. SeveralMicrochip acknowledgments are in order.

• This book contains copyrighted material of Microchip Technology Incorporated repli-cated with permission. All rights reserved. No further replications may be made with-out Microchip Technology Inc.’s prior written consent.

• Arduino III: Internet of Things is an independent publication and is not affiliated with,nor has it been authorized, sponsored, or otherwise approved by Microchip.

I would like to dedicate this book to my close friend Dr. Daniel Pack, Ph.D., P.E. In 2000,Daniel suggested that we might write a book together on microcontrollers. I had always wantedto write a book but I thought that’s what other people did. With Daniel’s encouragement wewrote that first book (and several more since then). Daniel is a good father, good son, goodhusband, brilliant engineer, great leader, has a work ethic that is second to none, and is a goodfriend. To you, good friend, I dedicate this book. I know that we will write many more together.

Page 20: Arduino III: Internet of Things

xx ACKNOWLEDGMENTSIt is hard to believe we have been writing together for 20C years. Finally, I would like to thankmy wife and best friend of many years, Cindy.

Steven F. BarrettLaramie, Wyoming, March 2021

Page 21: Arduino III: Internet of Things

1

C H A P T E R 1

Getting StartedObjectives: After reading this chapter, the reader should be able to do the following.

• Successfully download and execute a simple program using the Arduino DevelopmentEnvironment (ADE).

• Describe the key features of the ADE.

• Name and describe the different features aboard the Arduino UNO R3 processorboard.

• Discuss the features and functions of the Microchip ATmega328.

1.1 OVERVIEWWelcome to the world of Arduino!1 The Arduino concept of open-source hardware was devel-oped by the visionary Arduino team of Massimo Banzi, David Cuartilles, Tom Igoe, GianlucaMartino, and David Mellis in Ivrea, Italy. The team’s goal was to develop a line of easy-to-usemicrocontroller hardware and software such that processing power would be readily available toeveryone.

We assume you have a solid footing in the Arduino UNO R3, the ADE, interfacingtechniques, and Arduino sketch writing. The chapter begins with a brief review of some of theseconcepts.

We use a top-down design approach. We begin with the “big picture” of the chapter. Wethen discuss the ADE and how it may be used to quickly develop a program (sketch) for theArduino UNO R3. We then provide an overview of the hardware features of the Arduino UNOR3 evaluation board which hosts the Microchip ATmega328 processor.

1.2 THEBIGPICTUREMost microcontrollers are programmed with some variant of the C programming language.The C programming language provides a nice balance between the programmer’s control ofthe microcontroller hardware and time efficiency in program writing. As an alternative, theADE provides a user-friendly interface to quickly develop a program, transform the program

1This chapter is included with permission from Arduino I: Getting Started for completeness and to allow each seriesvolume to be independent.

Page 22: Arduino III: Internet of Things

2 1. GETTINGSTARTED

USB

Option 1Arduino UNO R3

Option 2ISP programming

of ATmega328 chip

Option 3ISP programming

of Arduino UNO R3

Arduino UNO R3

6-wireISP ribbon

cableMicrochip AVR

Dragon

Compiler

Computer

Assembler

filename.cfilename.h

filename.asm

filename.hexfilename.eep

C compiler

Arduino Development Environment

Arduino DevelopmentEnvironment

orC compiler

filename.hexfilename.eep

Figure 1.1: Programming the Arduino processor board. (Arduino illustrations used with per-mission of the Arduino Team (CC BY-NC-SA) [www.arduino.cc]. Microchip AVR Dragonillustration used with permission of Microchip, Incorporated [www.microchip.com].)

to machine code, and then load the machine code into the Arduino processor in several simplesteps, as shown in Figure 1.1.

The first version of the ADE was released in August 2005. It was developed at the In-teraction Design Institute in Ivrea, Italy to allow students the ability to quickly put processingpower to use in a wide variety of projects. Since that time, updated versions incorporating newfeatures have been released on a regular basis [www.arduino.cc].

At its most fundamental level, the ADE is a user-friendly interface to allow one to quicklywrite, load, and execute code on a microcontroller. A barebones program need only consist ofa setup() and loop() function. The ADE adds the other required pieces such as header files andthe main program construct. The ADE is written in Java and has its origins in the Processorprogramming language and the Wiring Project [www.arduino.cc].

Page 23: Arduino III: Internet of Things

1.3. ARDUINOQUICK START 3The ADE is hosted on a laptop or personal computer (PC). Once the Arduino program,

referred to as a sketch, is written; it is verified and uploaded to the Arduino UNO R3 evaluationboard. Alternatively, a program may be written in C using a compiler. The compiled code canbe uploaded to the Arduino UNO R3 using a programming pod such as the Microchip AVRDragon.

1.3 ARDUINOQUICK STARTTo get started using an Arduino-based platform, you will need the following hardware andsoftware:

• an Arduino-based hardware processing platform,

• the appropriate interface cable from the host PC or laptop to the Arduino platform,

• an Arduino compatible power supply, and

• the Arduino software.

Interface cable. The Arduino UNO R3 connects to the host laptop or PC via a USB cable(type A male to type B female).

Power supply. The Arduino processing boards may be powered from the USB port duringproject development. However, it is highly recommended that an external power supply be em-ployed. This will allow developing projects beyond the limited electrical current capability of theUSB port. For the UNO R3 platform, Arduino [www.arduino.cc] recommends a power sup-ply from 7–12 VDC with a 2.1 mm center positive plug. A power supply of this type is readilyavailable from a number of electronic parts supply companies. For example, the Jameco #133891power supply is a 9 VDC model rated at 300 mA and equipped with a 2.1 mm center positiveplug. It is available for under US$10. The UNO has an onboard voltage regulators that maintainthe incoming power supply voltage to a stable 5 VDC.

1.3.1 QUICK STARTGUIDEThe ADE may be downloaded from the Arduino website’s front page at www.arduino.cc. Ver-sions are available for Windows, Mac OS X, and Linux. Provided below is a quick start step-by-step approach to blink an onboard LED.

• Download the ADE from www.arduino.cc.

• Connect the Arduino UNO R3 processing board to the host computer via a USB cable(A male to B male).

• Start the ADE.

Page 24: Arduino III: Internet of Things

4 1. GETTINGSTARTED• Under the Tools tab select the type of evaluation Board you are using and the Port

that it is connected to.

• Type the following program.

//***************************************************************#define LED_PIN 13

void setup(){pinMode(LED_PIN, OUTPUT);}

void loop(){digitalWrite(LED_PIN, HIGH);delay(500); //delay specified in msdigitalWrite(LED_PIN, LOW);delay(500);}//***************************************************************

• Upload and execute the program by asserting the “Upload” (right arrow) button.

• The onboard LED should blink at one second intervals.

With the ADE downloaded and exercised, let’s take a closer look at its features.

1.3.2 ARDUINODEVELOPMENTENVIRONMENTOVERVIEWThe ADE is illustrated in Figure 1.2. The ADE contains a text editor, a message area for dis-playing status, a text console, a tool bar of common functions, and an extensive menuing system.The ADE also provides a user-friendly interface to the Arduino processor board which allowsfor a quick upload of code. This is possible because the Arduino processing boards are equippedwith a bootloader program.

A close-up of the Arduino toolbar is provided in Figure 1.3. The toolbar provides sin-gle button access to the more commonly used menu features. Most of the features are self-explanatory. As described in the previous section, the “Upload” button compiles your code anduploads it to theArduino processing board.The “SerialMonitor” button opens the serial monitorfeature. The serial monitor feature allows text data to be sent to and received from the Arduinoprocessing board.

Page 25: Arduino III: Internet of Things

1.3. ARDUINOQUICK START 5

sketch_may15a Arduino 1.8.12

File Edit Sketch Tools Help

+ –

sketch_may15a

Figure 1.2: Arduino Development Environment [www.arduino.cc].

Open

Save

Opens serial monitor

Verify—checks for errors

Upload

Creates new sketch +

Figure 1.3: Arduino Development Environment buttons.

1.3.3 SKETCHBOOKCONCEPTIn keeping with a hardware and software platform for students of the arts, the Arduino envi-ronment employs the concept of a sketchbook. An artist maintains their works in progress in asketchbook. Similarly, programs are maintained within a sketchbook in the Arduino environ-ment. Furthermore, we refer to individual programs as sketches. An individual sketch withinthe sketchbook may be accessed via the Sketchbook entry under the File tab.

1.3.4 ARDUINOSOFTWARE, LIBRARIES, ANDLANGUAGEREFERENCES

The ADE has a number of built-in features. Some of the features may be directly accessed via theADE drop-down toolbar illustrated in Figure 1.2. Provided in Figure 1.4 is a handy reference to

Page 26: Arduino III: Internet of Things

6 1. GETTINGSTARTED

Menu

File- New- Open- Open Recent- Sketchbook- Examples- Close- Save- Save As- Page Setup- Print- Preferences- Quit

Edit- Undo- Redo- Cut- Copy- Copy for Forum- Copy as HTML- Paste- Select All- Go to line...- Comment/ Uncomment- Increase Indent- Decrease Indent- Increase Font Size- Decrease Font Size- Find- Find Next- Find Previous

Sketch- Verify/Compile- Upload- Upload Using Programmer- Export Compiled Binary- Show Sketch Folder- Include Library- Add File

Tools- Auto Format- Archive Sketch- Fix Encoding & Reload- Merge Libraries- Serial Monitor- Serial Plotter- WiFi101/ WiFi NINA Firmware Updater- Board: xxx- Port- Get Board Info- Programmer: xxx- Burn Bootloader

Help- Getting Started- Environment- Troubleshooting- Reference

- Galileo Help- Getting Started- Troubleshooting

- Edison Help- Getting Started- Troubleshooting

- Find in Reference- Frequently Asked Questions- Visit Arduino.cc- About Arduino

Figure 1.4: Arduino Development Environment menu [www.arduino.cc].

show the available features. The toolbar provides a wide variety of features to compose, compile,load, and execute a sketch.

1.3.5 WRITINGANARDUINOSKETCHThe basic format of the Arduino sketch consists of a “setup” and a “loop” function. The setupfunction is executed once at the beginning of the program. It is used to configure pins, declarevariables and constants, etc. The loop function will execute sequentially step-by-step. Whenthe end of the loop function is reached it will automatically return to the first step of the loopfunction and execute again. This goes on continuously until the program is stopped.

//*******************************************************************void setup()

{//place setup code here}

void loop(){

Page 27: Arduino III: Internet of Things

1.3. ARDUINOQUICK START 7

//main code steps are provided here::

}//*******************************************************************

Example 1.1 Let’s revisit the sketch provided earlier in the chapter.

//*******************************************************************#define LED_PIN 13 //name pin 13 LED_PIN

void setup(){pinMode(LED_PIN, OUTPUT); //set pin to output}

void loop(){digitalWrite(LED_PIN, HIGH); //write pin to logic highdelay(500); //delay specified in msdigitalWrite(LED_PIN, LOW); //write to logic lowdelay(500); //delay specified in ms}//*******************************************************************

In the first line the #define statement links the designator “LED_PIN” to pin 13 on theArduino processor board. In the setup function, LED_PIN is designated as an output pin. Recallthe setup function is only executed once. The program then enters the loop function that isexecuted sequentially step-by-step and continuously repeated. In this example, the LED_PINis first set to logic high to illuminate the LED onboard the Arduino processing board. A 500-msdelay then occurs. The LED_PIN is then set low. A 500-ms delay then occurs. The sequencethen repeats.

Even themost complicated sketches follow the basic format of the setup function followedby the loop function. To aid in the development of more complicated sketches, the ADE hasmany built-in features that may be divided into the areas of structure, variables, and functions.The structure and variable features follow rules similar to the C programming language. The

Page 28: Arduino III: Internet of Things

8 1. GETTINGSTARTED

Arduino Functions

Digital I/OpinMode( )digitalWrite( )digitalRead( )

Analog I/OanalogReference( )analogRead( )analogWrite( ) (PWM)

Advanced I/Otone( )notone( )shiftOut( )shiftIn( )pulseIn( )

Timemillis( )micros( )delay( )delayMicroseconds( )

Mathmin( )max( )abs( )constrain( )map( )pow( )sqrt( )

CommunicationSerial( )Stream( )

External InterruptsattachInterrupt( )detachInterrupt( )

Interruptsinterrupts( )noInterrupts( )

Bits and ByteslowByte( )highByte( )bitRead( )bitWrite( )bitSet( )bitClear( )bit( )

Random NumbersrandomSeed( )random( )

Trigonometrysin( )cos( )tan( )

Figure 1.5: Arduino Development Environment functions [www.arduino.cc].

built-in functions consists of a set of pre-defined activities useful to the programmer. Thesebuilt-in functions are summarized in Figure 1.5.

There are many program examples available to allow the user to quickly construct a sketch.These programs are summarized in Figure 1.6. Complete documentation for these programs isavailable at the Arduino homepage [www.arduino.cc]. This documentation is easily accessiblevia the Help tab on the Arduino Development Environment toolbar. This documentation willnot be repeated here. With the Arduino open-source concept, users throughout the world areconstantly adding new built-in features. As new features are added, they are released in futureADE versions. As anArduino user, you toomay add to this collection of useful tools.Throughoutthe remainder of the book we use both the ADE to program the Arduino UNO R3 and severalother Arduino-based products. In the next section we get acquainted with the features of theUNO R3.

1.4 ARDUINOUNOR3 PROCESSINGBOARD

The Arduino UNO R3 processing board is illustrated in Figure 1.7. Working clockwise fromthe left, the board is equipped with a USB connector to allow programming the processor froma host PC or laptop. The board may also be programmed using In System Programming (ISP)

Page 29: Arduino III: Internet of Things

1.4. ARDUINOUNOR3 PROCESSINGBOARD 9

Arduino EnvironmentBuilt-in Programs

Digital Input/Output- Blink (under Basics)- Blink without delay- Button- Debounce- Digital Input Pullup- State Change Detection-Tone Keyboard- Tone Melody- Tone Multiple- Tone Pitch Follower

Analog Input/Output- Analog InOut Serial- Analog Input- Analog Write Mega- Calibration- Fading- Smoothing

Control Structures- Array- For loop interation- If statement conditional- Switch case- Switch case 2- While statement conditional

Sensors- ADX3xx accelerometer- Knock detector- Memsic2125 two-axis accelerometer- Ping ultrasonic range finder

Communication- ASCII Table- Dimmer- Graph- MIDI- MultiSerial- Physical pixel- Read ASCII String- Serial call response- Serial call response ASCII- Serial Event- Serial Passthrough- Virtual color mixer

Multiple Libraries- Strings- USB- LCD- Robot Control- Robot Motor- SD card- Servo- Stepper :

Figure 1.6: Arduino Development Environment built-in features [www.arduino.cc].

techniques. A six-pin ISP programming connector is on the opposite side of the board from theUSB connector.

The board is equipped with a USB-to-serial converter to allow compatibility between thehost PC and the serial communications systems aboard the Microchip ATmega328 processor.The UNO R3 is also equipped with several small surface mount light-emitting diodes (LEDs)to indicate serial transmission (TX) and reception (RX) and an extra LED for project use. Theheader strip at the top of the board provides access for an analog reference signal, pulse widthmodulation (PWM) signals, digital input/output (I/O), and serial communications. The headerstrip at the bottom of the board provides analog inputs for the analog-to-digital (ADC) systemand power supply terminals. Finally, the external power supply connector is provided at thebottom-left corner of the board. The top and bottom header strips conveniently mate with anArduino shield to extend the features of the Arduino host processor.

Page 30: Arduino III: Internet of Things

10 1. GETTINGSTARTED

LED powerindictor

LED

TX LEDUSB-to-serial

converter

Switch

USBconnector

(to PC)

Power supplyconnector

(7-12 VDC)

Power supplyterminals

Analoginputs

Timebase

RX LED

Seria

l com

m

Analo

g re

fere

nce

PWM

ISP programmingconnector

Digital I/O

Figure 1.7: Arduino UNO R3 layout. (Figure adapted and used with permission of ArduinoTeam (CC BY-NC-SA) [www.arduino.cc].)

1.5 ARDUINOUNOR3OPENSOURCE SCHEMATIC

The entire line of Arduino products is based on the visionary concept of open-source hardwareand software. That is, hardware and software developments are openly shared among users tostimulate new ideas and advance the Arduino concept. In keeping with the Arduino concept,the Arduino team openly shares the schematic of the Arduino UNO R3 processing board. SeeFigure 1.8.

1.6 ARDUINOUNOR3HOSTPROCESSOR–THEATMEGA328

The host processor for the Arduino UNO R3 is the Microchip ATmega328. The “328” is a28 pin, 8-bit microcontroller. The architecture is based on the Reduced Instruction Set Com-puter (RISC) concept which allows the processor to complete 20 million instructions per second(MIPS) when operating at 20 MHz. The “328” is equipped with a wide variety of features asshown in Figure 1.9. The pin out diagram and block diagram for this processor are provided inFigures 1.10 and 1.11. The features may be conveniently categorized into the following systems:

Page 31: Arduino III: Internet of Things

1.6. ARDUINOUNOR3HOSTPROCESSOR—THEATMEGA328 11

Figu

re1.

8:A

rdui

noU

NO

R3op

enso

urce

sche

mat

ic.(F

igur

eada

pted

and

used

with

perm

issio

nof

theA

rdui

noTe

am(C

CBY

-NC

-SA

)[ww

w.ar

duin

o.cc

].)

Page 32: Arduino III: Internet of Things

12 1. GETTINGSTARTED

Arduino UNO R3

hosted on the ATmega328

Memory System- 32K byte, ISP programmable flash- 1K byte, byte addressable EEPROM- 2K byte RAM

Timer System- Two 8-bit timer/counter- One 16-bit timer/counter- Six PWM channels

Analog-to-digitalconverter- 6 channel 10-bit ADC (PDIP)

Serial Communications- Serial USART- Serial peripheral interface- Two wire interface (TWI)

Port System- 14 digital I/O pins -- 6 provide PWM- 6 analog input pins

Interrupt System- 26 total interrupts- 2 external pin interrupts

Figure 1.9: Arduino UNO R3 systems.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

PC5 (ADC5/SCL/PCINT13)

PC4 (ADC4/SDA/PCINT12)

PC3 (ADC3/PCINT11)

PC2 (ADC2/PCINT10)

PC1 (ADC1/PCINT9)

PC0 (ADC0/PCINT8)

GND

AREF

AVCC

PB5 (SCK/PCINT5)

PB4 (MISO/PCINT4)

PB3 (MOSI/OC2A/PCINT3)

PB2 (SS/OC1B/PCINT2)

PB1 (OC1A/PCINT1)

28

27

26

25

24

23

22

21

20

19

18

17

16

15

(PCINT14/RESET) PC6

(PCINT16/RXD) PD0

(PCINT17/TXD) PD1

(PCINT18/INT0) PD2

(PCINT19/OC2B/INT1) PD3

(PCINT20/XCK/T0) PD4

VCC

GND

(PCINT6/XTAL1/TOSC1) PB6

(PCINT7/XTAL2/TOSC2) PB7

(PCINT21/OC0B/T1) PD5

(PCINT22/OC0A/AIN0) PD6

(PCINT23/AIN1) PD7

(PCINT0/CLKO/ICP1) PB0

Figure 1.10: ATmega328 pin out. (Figure used with permission of Microchip, Incorporated[www.microchip.com].)

Page 33: Arduino III: Internet of Things

1.6. ARDUINOUNOR3HOSTPROCESSOR—THEATMEGA328 13

Watchdogtimer

Watchdogoscillator

debugWIRE

PROGRAMLOGIC

Flash

CPU

SRAM

EEPROM

DA

TA

BU

S

8bit T/C 0

8bit T/C 2

USART 0

PORT D (8)

16bit T/C 1

Analogcomp.

SPI

PORT B (8)

A/D conv.

TWI

RESET

AVCC

AREF

GND

2

6

GND VCC

PD[0..7] PB[0..7] PC[0..6] ADC[6..7]

XTAL[1..2]

PORT C (7)

Oscillatorcircuits/

clockgeneration

Powersupervision

POR/BOD andRESET

Internalbandgap

Figure 1.11: ATmega328 block diagram. (Figure used with permission of Microchip, Incorpo-rated [www.microchip.com].)

Page 34: Arduino III: Internet of Things

14 1. GETTINGSTARTED• memory system,

• port system,

• timer system,

• analog-to-digital converter (ADC),

• interrupt system, and

• serial communications.

1.6.1 ATMEGA328MEMORYThe ATmega328 is equipped with three main memory sections: flash electrically erasable pro-grammable read only memory (EEPROM), static random access memory (SRAM), and byte-addressable EEPROM. We discuss each memory component in turn.

ATmega328 In – System Programmable Flash EEPROMBulk programmable flash EEPROM is used to store programs. It can be erased and programmedas a single unit. Also, should a program require a large table of constants, it may be includedas a global variable within a program and programmed into flash EEPROM with the rest ofthe program. Flash EEPROM is nonvolatile meaning memory contents are retained even whenmicrocontroller power is lost. The ATmega328 is equipped with 32K bytes of onboard repro-grammable flash memory. This memory component is organized into 16K locations with 16 bitsat each location.

ATmega328 Byte – Addressable EEPROMByte-addressable EEPROM memory is used to permanently store and recall variables duringprogram execution. It too is nonvolatile. It is especially useful for logging system malfunctionsand fault data during program execution. It is also useful for storing data that must be retainedduring a power failure but might need to be changed periodically. Examples where this typeof memory is used are found in applications to store system parameters, electronic lock combi-nations, and automatic garage door electronic unlock sequences. The ATmega328 is equippedwith 1024 bytes of byte-addressable EEPROM.

ATmega328 Static RandomAccessMemory (SRAM)Static RAM memory is volatile. That is, if the microcontroller loses power, the contents ofSRAM memory are lost. It can be written to and read from during program execution. TheATmega328 is equipped with 2K bytes of SRAM. A small portion of the SRAM is set aside forthe general-purpose registers used by the processor and also for the input/output and peripheralsubsystems aboard the microcontroller. A header file provides the link between register names

Page 35: Arduino III: Internet of Things

1.6. ARDUINOUNOR3HOSTPROCESSOR—THEATMEGA328 15

Port x Data Register – PORTx

7 0

Port x Data Direction Register – DDRx

7 0

Port x Input Pins Address – PINx

(a) Port associated registers

(b) Port pin configuration

x: Port designator (B, C, D) n: Pin designator (0–7)

7

DDxn

0

0

1

1

PORTxn

0

1

0

1

Pullup

No

Yes

No

No

Comment

Tri-state (Hi-Z)

Source current if externally pulled low

Output low (sink)

Output high (source)

I/O

Input

Input

Output

Output

0

Figure 1.12: ATmega328 port configuration registers [www.microchip.com].

used in a program and their physical description and location in memory. During program exe-cution, RAM is used to store global variables, support dynamic memory allocation of variables,and to provide a location for the stack.

1.6.2 ATMEGA328 PORT SYSTEMThe Microchip ATmega328 is equipped with three, 8-bit general purpose, digital input/output(I/O) ports designated PORTB (8 bits, PORTB[7:0]), PORTC (7 bits, PORTC[6:0]), andPORTD (8 bits, PORTD[7:0]). As shown in Figure 1.12, each port has three registers associ-ated with it:

• Data Register PORTx—used to write output data to the port,

• Data Direction Register DDRx—used to set a specific port pin to either output (1) orinput (0), and

Page 36: Arduino III: Internet of Things

16 1. GETTINGSTARTED• Input Pin Address PINx—used to read input data from the port.

Figure 1.12b describes the settings required to configure a specific port pin to either inputor output. If selected for input, the pin may be selected for either an input pin or to operate inthe high impedance (Hi-Z) mode. If selected for output, the pin may be further configured foreither logic low or logic high.

Port pins are usually configured at the beginning of a program for either input or out-put and their initial values are then set. Usually, all eight pins for a given port are configuredsimultaneously.

1.6.3 ATMEGA328 INTERNAL SYSTEMSIn this section, we provide a brief overview of the internal features of the ATmega328. It shouldbe emphasized that these features are the internal systems contained within the confines ofthe microcontroller chip. These built-in features allow complex and sophisticated tasks to beaccomplished by the microcontroller.

ATmega328 Time BaseThe microcontroller is a complex synchronous state machine. It responds to program steps in asequential manner as dictated by a user-written program.Themicrocontroller sequences througha predictable fetc-decode-execute sequence. Each unique assembly language program instruc-tion issues a series of signals to control the microcontroller hardware to accomplish instructionrelated operations.

The speed at which a microcontroller sequences through these actions is controlled by aprecise time base called the clock. The clock source is routed throughout the microcontroller toprovide a time base for all peripheral subsystems. The ATmega328 may be clocked internallyusing a user-selectable resistor capacitor (RC) time base or it may be clocked externally. TheRC internal time base is selected using programmable fuse bits. You may choose from severaldifferent internal fixed clock operating frequencies.

To provide for a wider range of frequency selections an external time source may be used.The external time sources, in order of increasing accuracy and stability, are an external RC net-work, a ceramic resonator, or a crystal oscillator. The system designer chooses the time basefrequency and clock source device appropriate for the application at hand. Generally speak-ing, if the microcontroller will be interfaced to external peripheral devices either a ceramic res-onator or a crystal oscillator should be used as a time base. Both are available in a wide varietyof operating frequencies. The maximum operating frequency of the ATmega328P is 20 MHz[www.microchip.com].

ATmega328 Timing SubsystemThe ATmega328 is equipped with a complement of timers which allows the user to generate aprecision output signal, measure the characteristics (period, duty cycle, frequency) of an incom-

Page 37: Arduino III: Internet of Things

1.6. ARDUINOUNOR3HOSTPROCESSOR—THEATMEGA328 17ing digital signal, or count external events. Specifically, the ATmega328 is equipped with two8-bit timer/counters and one 16-bit counter.

PulseWidthModulation ChannelsA pulse width modulated (PWM) signal is characterized by a fixed frequency and a varyingduty cycle. Duty cycle is the percentage of time a repetitive signal is logic high during the signalperiod. It may be formally expressed as:

duty cycleŒ%� D .on time=period/ � .100%/:

The ATmega328 is equipped with four PWM channels. The PWM channels coupledwith the flexibility of dividing the time base down to different PWM subsystem clock sourcefrequencies allows the user to generate a wide variety of PWM signals: from relatively high-frequency low-duty cycle signals to relatively low-frequency high-duty cycle signals.

PWM signals are used in a wide variety of applications including controlling the positionof a servo motor and controlling the speed of a DC motor.

ATmega328 Serial CommunicationsThe ATmega328 is equipped with a variety of different serial communication subsystems includ-ing the Universal Synchronous and Asynchronous Serial Receiver and Transmitter (USART),the serial peripheral interface (SPI), and the Two-wire Serial Interface (TWI). What these sys-tems have in common is the serial transmission of data. In a serial communications transmission,serial data is sent a single bit at a time from transmitter to receiver. The serial communicationsubsystems are typically used to add and communicate with additional peripheral devices.

ATmega328 Serial USART The serial USART may be used for full-duplex (two-way) com-munication between a receiver and transmitter. This is accomplished by equipping the AT-mega328 with independent hardware for the transmitter and receiver. The USART is typicallyused for asynchronous communication. That is, there is not a common clock between the trans-mitter and receiver to keep them synchronized with one another. To maintain synchronizationbetween the transmitter and receiver, framing start and stop bits are used at the beginning andend of each data byte in a transmission sequence.

The ATmega328 USART is quite flexible. It has the capability to be set to different datatransmission rates known as the Baud (bits per second) rate. The USART may also be set fordata bit widths of 5–9 bits with one or two stop bits. Furthermore, the ATmega328 is equippedwith a hardware-generated parity bit (even or odd) and parity check hardware at the receiver. Asingle parity bit allows for the detection of a single bit error within a byte of data. The USARTmay also be configured to operate in a synchronous mode.

ATmega328 Serial Peripheral Interface (SPI) The ATmega328 Serial Peripheral Interface(SPI) can also be used for two-way serial communication between a transmitter and a receiver.

Page 38: Arduino III: Internet of Things

18 1. GETTINGSTARTEDIn the SPI system, the transmitter and receiver share a common clock source. This requires anadditional clock line between the transmitter and receiver but allows for higher data transmissionrates as compared to the USART.

The SPI may be viewed as a synchronous 16-bit shift register with an 8-bit half residingin the transmitter and the other 8-bit half residing in the receiver. The transmitter is designatedthe master since it is providing the synchronizing clock source between the transmitter and thereceiver. The receiver is designated as the slave.

ATmega328 Two-wire Serial Interface (TWI) The TWI subsystem allows the system de-signer to network related devices (microcontrollers, transducers, displays, memory storage, etc.)together into a system using a two-wire interconnecting scheme. The TWI allows a maximum of128 devices to be interconnected. Each device has its own unique address and may both transmitand receive over the two-wire bus at frequencies up to 400 kHz. This allows the device to freelyexchange information with other devices in the network within a small area.

ATmega328 Analog to Digital Converter (ADC)The ATmega328 is equipped with an eight-channel analog to digital converter (ADC) subsys-tem. The ADC converts an analog signal from the outside world into a binary representationsuitable for use by the microcontroller. The ATmega328 ADC has 10-bit resolution. This meansthat an analog voltage between 0 and 5 V will be encoded into one of 1024 binary representa-tions between .000/16 and .3FF/16. This provides the ATmega328 with a voltage resolution ofapproximately 4.88 mV.

ATmega328 InterruptsThe normal execution of a program follows a specific sequence of instructions. However, some-times this normal sequence of events must be interrupted to respond to high priority faults andstatus both inside and outside the microcontroller. When these higher priority events occur, themicrocontroller suspends normal operation and executes event specific actions contained withinan interrupt service routine (ISR). Once the higher priority event has been serviced by the ISR,the microcontroller returns and continues processing the normal program.

The ATmega328 is equipped with a complement of 26 interrupt sources. Two of the in-terrupts are provided for external interrupt sources while the remaining interrupts support theefficient operation of peripheral subsystems aboard the microcontroller.

1.7 INTERFACINGTOOTHERDEVICESChapter 3 “Arduino Power and Interfacing” of Arduino I: Getting Started introduces the ex-tremely important concept of microcontroller interfacing. Anytime an input or an output deviceis connected to a microcontroller, the interface between the device and the microcontroller mustbe carefully analyzed and designed. This will ensure the microcontroller will continue to oper-

Page 39: Arduino III: Internet of Things

1.8. APPLICATION 19

Plantaccessroad

Plant accessvehicle detector(tact switch)

Busy highway

Figure 1.13: Intersection.

ate within specified parameters. Should the microcontroller be operated outside its operationalenvelope; erratic, unpredictable, and an unreliable system may result.

1.8 APPLICATIONInexpensive hardware may be used as a first prototype of more complex systems. In this exercisewe use LEDs and switches to develop a first prototype of a traffic control system.

Scenario.A busy two-lane highway exits from the south side of a small community. Nearthe city’s edge is a manufacturing plant that runs three 8 hour shifts. The entrance to the plant isvia a small road intersecting the busy highway. Develop and test an algorithm to control a trafficlight at the intersection of the busy highway and plant access road. Normally, the busy highwaywill have priority for through traffic.However, at shift changeover timewindows, vehicles exitingthe plant will be allowed access to the highway.

Model the intersection light using LEDs. A vehicle ready for exit on the plant access roadis indicated using a tact momentary switch, as shown in Figure 1.13.

Page 40: Arduino III: Internet of Things

20 1. GETTINGSTARTED• Part 1. Develop an Arduino sketch to control the traffic lights at the intersection.

• Part 2. Develop a control algorithm for the intersection of two, 2-lane busy streetswithin a city. Provide for pedestrian crosswalks.

1.9 SUMMARYThe goal of this chapter was to provide an introduction and tutorial on the Arduino UNO R3.We used a top-down design approach. We began with the “big picture” of the chapter followedby an overview of the ADE and the subsystems aboard the ATmega328.

1.10 REFERENCES[1] Arduino homepage. www.arduino.cc

[2] Microchip ATmega328 PB AVR Microcontroller with Core Independent Peripherals and PicoPower Technology DS40001906C, Microchip Technology Incorporation, 2018. www.microchip.com

1.11 CHAPTERPROBLEMS1.1. Describe the steps in writing a sketch and executing it on an Arduino UNO R3 pro-

cessing board.

1.2. What is the serial monitor feature used for in the Arduino Development Environment?

1.3. Describe what variables are required and returned and the basic function of the followingbuilt-in Arduino functions: Blink, Analog Input.

1.4. Sketch a block diagram of the ATmega328 and its associated systems. Describe thefunction of each system.

1.5. Describe the different types of memory components within the ATmega328. Describeapplications for each memory type.

1.6. Describe the three different register types associated with each port.

1.7. How may the features of the Arduino UNO R3 be extended?

1.8. Discuss different options for the ATmega328 time base. What are the advantages anddisadvantages of each type? Construct a summary table.

1.9. Discuss the three types of serial communication systems aboard the ATmega328. Re-search an application for each system.

Page 41: Arduino III: Internet of Things

1.11. CHAPTERPROBLEMS 211.10. What is the difference between an ADC and DAC. Which one is aboard the AT-

mega328?

1.11. How does the Arduino UNO R3 receive power? Describe in detail.

1.12. What is the time base for the Arduino UNO R3? At what frequency does it operate?How many clock pulses per second does the time base provide? What is the time be-tween pulses?

1.13. What is meant by the term open source?

1.14. What is the maximum operating frequency of the ATmega328? What is the lowestoperating frequency of the ATmega328?

1.15. What is the range of operating voltages that may be applied to the ATmega328?

Page 42: Arduino III: Internet of Things
Page 43: Arduino III: Internet of Things

23

C H A P T E R 2

The Internet and IoTObjectives: After reading this chapter, the reader should be able to do the following.

• Describe how data is routed and exchanged via the internet.

• Summarize significant events in internet development.

• Describe protocol stacks used in internet message processing.

• Define different methods of device addressing employed within the internet.

• Define the function of key internet hardware components.

• Summarize the differences between network configurations.

• Summarize threats to safe and secure internet operations.

• Provide a definition for the Internet of Things (IoT) concept.

• Provide an IoT feature list.

• Define Information Technology (IT) and Operational Technology (OT).

• Describe the features of a programmable logic controller (PLC) based OT system.

• Provide a working definition of the Industrial Internet of Things (IIoT).

• Describe how IoT concepts are employed within a specific industry.

• Sketch an IoT model and describe the relationship between “things” and applications.

2.1 OVERVIEWWelcome to the world of the internet! This chapter provides a condensed overview of internetoperation and history. We begin with a big picture overview of the internet followed by a briefreview of internet development. We then take a closer look at selected internet topics includingprotocols, addressing techniques, different network configurations, threats to internet security,and threat countermeasures. Admittedly, the treatment of these topics is brief. We discuss in-ternet concepts related to our exploration of the IoT. We then discuss IoT concept applicationsin the industrial world of the IIoT. For additional details, the interested reader is referred to theexcellent references at the end of the chapter used to compile the information presented here.

Page 44: Arduino III: Internet of Things

24 2. THE INTERNETAND IoT

Cloud

Cable/DSL modem

Protocols::Optical or cable links

Radio frequency (RF) links

WiFi router

Home or small businesssystem

Laptop

Phone

Figure 2.1: Internet at home or a small business configuration.

2.2 A BIG PICTUREOFTHE INTERNETFrom its early beginnings in the late 1960s to today, the internet has become ubiquitous (foundeverywhere) in every facet of our lives. A few examples where the internet has become prevalentinclude industry, agriculture, energy production, education, healthcare, entertainment, manu-facturing, retail, communications, and many other areas (Hanes [5]).

Many (including the author) take a safe, secure, and reliable internet for granted. Portionsof the internet, consisting of a global network of interconnected computers, are referred to as the“cloud.” In this section we examine connections between computers that comprise the internetin a home and work environment and then examine what is inside the cloud.

Figure 2.1 provides a typical internet connection found in a home or small business such asa cafe or small store. A cable or digital subscriber line (DSL) modulator/demodulator (modem)provides a connection to the internet. The cable/DSL modem is provided by an Internet ServiceProvider (ISP) when you subscribe to their internet connection service. The connection betweenthe cable/DSL modem and the ISP provider may be a combination of copper cable, optical fiber,and wireless radio frequency connection links.

With internet service available via the cable/DSL modem, a WiFi router is used to es-tablish a wireless local area network (WLAN) within your home or small business. The WLAN

Page 45: Arduino III: Internet of Things

2.2. A BIG PICTUREOFTHE INTERNET 25

Cloud

Protocols::

Protocols::

Protocols::

Optical or cable links

Radio frequency (RF) links

WiFi

LaptopPersonal computer Personal computer

Local area network

Local areanetwork

. . . . . .

Phone

Router and firewall

Hub

Servers- DNS- DHCP- SQL

Hub

Bridge

Business system

Figure 2.2: Internet at a large business or university.

serves as an internet access point to a broader area using radio frequency (RF) signals operatingat 2.5 or 5 GHz. The link between the cable/DSL modem to the WiFi router is via a cable.Wireless devices such as a cell phone or a laptop within range of the WiFi router are able toaccess the internet with proper credentials (i.e., WLAN password and ISP subscription). TheWiFi router range may be extended using a WiFi range extender.

Internet service typically found in a larger business or a university is shown in Figure 2.2.Internet service is provided to the organization via an ISP. Connection is made to the ISP viaa firewall. The firewall provides protection from internet hazards outside the organization. Itmay also be used to limit outgoing information from the organization (e.g., sensitive companyinformation, classified material, etc.). There is also a router at the organization portal. It is usedto route internet message traffic to its next destination.

Individual computers are provided access to the internet via a cabled connection to a hub.The hub is used to connect computers into a local area network (LAN) sharing the same locationor similar function such as an academic department or company section.Multiple LANs are thenconnected via a bridge. The bridge will also provide connection to a series of local servers suchas a Domain Name System (DNS) server, a Dynamic Host Configuration Protocol (DHCP)

Page 46: Arduino III: Internet of Things

26 2. THE INTERNETAND IoTserver, a Structured Query Language (SQL) database server, and a mail server (among others).WiFi access may also be provided by a WiFi router as previously described.

Figure 2.3 shows the configuration of the internet cloud. The cloud contains the globalconnection of multiple internet service providers. Regional internet service providers share in-ternet traffic via a metropolitan area exchange (MAE). The regional network ISPs connect to anetwork service provider who are in turn connected to other network service providers via net-work access points. Connectivity across the globe is provided by submarine optical fiber cablesspanning the oceans. Internet access may be provided to remote areas via balloon borne networkaccess points (Loon [11]).1 The overall result is a global network of interconnected computersfor the open exchange of information.

Aside from the internet hardware components, there are internet protocols and applica-tions used to insure reliable and compatible communications from one location to another. Asan example, when you are checking your favorite news website or sending an e-mail to a friend,the specific application you are using along with the computer’s operating system has built infeatures to interact with the internet to accomplish your desired task.

The application and the operating system apply the different layer activities to transmitinformation over the internet. For example, the e-mail message you are sending is broken intopackets of information, provided source, and destination IP addresses, and converted to an elec-tronic signal. The packets are then routed to the destination computer via a series of internethops directed by routers along the path. At the destination the received packets are reassembledand the protocol steps are applied in reverse order.

2.3 BRIEFHISTORYThe internet started as a United States government project in the late 1960s. The AdvancedResearch Projects Agency (ARPA) sponsored a project to interconnect four computers at dif-ferent locations to share resources as shown in Figure 2.4. The resulting network was dubbedARPANET.

From this early start additional computers were added and evolved into the Defense Ad-vanced Research Projects Network or DARPANET. In the mid-1980s the National ScienceFoundation established NSFNET. The early government sponsored programs were the first In-ternet Service Providers. Commercial providers joined in the late 1980s with full commercialcontrol of the internet by 1995. The Internet Society (ISOC) was established in 1992 to assureall people globally benefit from the internet (Levine [10]).

From this basic understanding of internet operation and history, we spend the remainderof the chapter taking a more detailed view of selected topics necessary for our investigation ofthe IoT.

1January 2021 news releases indicate the Loon system may be phased out.

Page 47: Arduino III: Internet of Things

2.3. BRIEFHISTORY 27

Ground coverage

Balloon-borne

networkaccess

Fiber opticsubmarine cables

across oceanto differentcontinents

Protocols::

Protocols::

Protocols::

Optical or cable links

Radio frequency (RF) links

WiFi

Laptop

Protocols::

Laptop

Personal computer Personal computer

Local area network

Local areanetwork

. . . . . .

. . .. . . . . . . . .

Phone

Router and firewall

Hub

Servers- DNS- DHCP- SQL

Hub

Bridge

Business system

Cable/DSL modem

WiFi router

Home or small business system

Phone

Networkservice

provider

Networkservice

provider

Networkservice

providerNetworkaccesspoint

Networkaccesspoint

Networkaccesspoint

MAEMAE

Networkservice

providerRegionalinternetservice

provider

Regionalinternetservice

provider

Regionalinternetservice

provider

Figure 2.3: The cloud.

Page 48: Arduino III: Internet of Things

28 2. THE INTERNETAND IoT

Stanford Research InstituteStanford, CA

University of CaliforniaSanta Barbara, CA

University of UtahSalt Lake City, UT

University of CaliforniaLos Angeles, CA

Figure 2.4: ARPANET.

2.4 INTERNETPROTOCOLMODELS

There are two differentmodels of protocol stacks commonly used within the internet community.A protocol is a standardized set of rules and procedures. The layered protocol models provideguidelines on how data is processed within applications and prepared for transmission over theinternet. Both protocols were developed in the early 1980s.

The International Organization for Standardization (ISO) developed the seven layeredOpen Systems Internet protocol stack ISO/OSI reference model shown in Figure 2.5a. Theadjacent layers interact with one another in a given system while similar layers interact with oneanother in different systems.

The transmission control protocol/internet (TCP/IP) maps into several layers of the OSImodel as shown in Figure 2.5a. Figure 2.5b shows the four layers of the TCP/IP model: appli-cation, transport, internet, and link layer.

The data to be shared with another computer resides within the application layer. Thedata is divided into packets. As the data packet is processed through each layer of the sendingcomputer, additional header and footer information is appended to the data payload. The IPaddress allows the sender and receiver to find one another on the internet (Leiden [9], Lowe [12],and Null [14]).

Page 49: Arduino III: Internet of Things

2.5. INTERNETADDRESSINGTECHNIQUES 29

Application

Presentation

Session

Transport

Network

Data link

Physical

FTP, HTTP,Telnet, SMTP, …

TCP/IP

OSI

TCP

IP

(a) Comparison of the OSI protocol stack model to the TCP/IP protocol stack model

(b) TCP/IP protocol for sender and receiver interaction

Application

Transport

Internet

Link

Application

Transport

Internet

Link

Sender Receiver

Data

UDPdata

UDPheader

Frameheader

Framefooter

IPheader

IP data

Frame data

Internet

Figure 2.5: OSI vs. TCP/IP (Leiden [9], Lowe [12], and Null [14]).

2.5 INTERNETADDRESSINGTECHNIQUES

In this section we discuss the importance of and techniques used to address network assets. Webegin with IP addressing and packet headers. There are two different versions of the IP header:IPv4 and IPv6, as shown in Figure 2.6.

Page 50: Arduino III: Internet of Things

30 2. THE INTERNETAND IoT

0

0 Network(7 bits) Host (24 bits)

Class A network

1 2 3

byte 0 byte 1

Service typeVersion Headerlength Datagram length

Header checksum

Source IP address

Destination IP address

IP options (10 to 40 bytes) with padding

Data

(a) IPv4 diagram

(b) IP address format IPv4,expressed as 32-bit, decimal dotted notation

Packet identification

Time to live(TTL)

Protocolnumber

Fragment offsetFlags

byte 2 byte 3

4 5 6 7

0 1 2 3

byte 0 byte 1 byte 2

xxx.xxx.xxx.xxx

(d) IP address format IPv6,expressed as 128-bit, hexadecimal colon notation

hhhh:hhhh:hhhh:hhhh:hhhh:hhhh:hhhh:hhhh

byte 3

4 5 6 7

0 1 2 3

byte 0 byte 1

Version Trafficclass Flow label

Source IP address

Destination IP address

Data

(c) IPv6 diagram

Payload length Next header Hop limit

byte 2 byte 3

4 5 6 7

10 Network (14 bits) Host (16 bits)

Class B network

110 Network (21 bits) Host (8 bits)

Class C network

Figure 2.6: IPv4 and IPv6 (Leiden [9] and Null [14]).

2.5.1 IPv4HEADERThe earlier IPv4 header version consists of 24 bytes followed by the data payload. The overallpacket datagram must be at least 40 bytes. The IPv4 header consists of the following fields:

• Version: IP protocol version. For IPv4 this field is set to .0100/2.

• Header length: specified as 32-bit words.

• Type of service: specifies priority from low (000) to critical (101).

• Total length: specifies total length of the datagram packet in bytes.

Page 51: Arduino III: Internet of Things

2.5. INTERNETADDRESSINGTECHNIQUES 31• Packet ID: the packet is assigned a unique serial number.

• Flags: indicates whether a larger packet can be broken into smaller packets.

• Fragment offset: provides fragment location within packet.

• Time to live: determines number of internet hops are allowed from source to destina-tion.

• Protocol number: indicates the type of protocol associated with the data: 0–reserved,1–internet control message protocol (ICMP), 6–transmission control protocol (TCP),or 17–user datagram protocol (UDP).

• Header checksum: holds the calculated checksum of the header.

• Provides source and destination address of packet. Note each address is 32 bits inlength. A unique address or source ID is provided to each source computer on theinternet. The allocation of addresses is coordinated by the Internet Corporation forAssigned Names and Numbers or ICANN [www.ICANN.org].

• IP options: provides additional control information.

The IPv4 protocol uses the 32-bit IP address configuration as shown in Figure 2.6b. Thefirst several bits of the address indicates the network class: Class A for large networks (0), ClassB for medium-sized networks (10), and Class C for smaller networks (110). The remaining IPaddress bits are partitioned to select a network and a specific host. The IP address is expressedas a 32-bit dotted decimal notation value (xxx.xxx.xxx.xxx). Each byte in the address is specifiedby its decimal equivalent (xxx) and has a value ranging from 0–255 (Hanes [5], Lowe [12], andNull [14]).

2.5.2 CIDRADDRESSINGTo provide additional addressing flexibility a Classless Inter-Domain Routing (CIDR) address-ing scheme was developed. The CIDR scheme provides for flexible subnet addressing within theIPv4 protocol. The format of the CIDR address is provided in Figure 2.7a. A subnet is a smallernetwork within one of the network classes: A, B, or C.

Recall the IPv4 protocol provides for a 32-bit IP address. The CIDR protocol allowsthe address to be partitioned into a number of address bits allocated to identify the networkand the remaining bits allocated to identify a specific host (computer) within the network. Aslash character (/) follows the address with a decimal number. The decimal number indicates thenumber of logic ones in the subnet mask.

In the example provided in Figure 2.7b left an IP address has been partitioned such that 24bits will be used to identify the specific network while the remaining 8 bits will be used to specifya specific computer within the network. This partition allocation results in a subnet mask of

Page 52: Arduino III: Internet of Things

32 2. THE INTERNETAND IoT

xxx.xxx.xxx.xxx/number

Number = leading 1’s in routing mask

(b) CIDR addressing format example

(a) Classless inter-domain routing (CIDR) addressing format

Unique host addresses190.166.2.1

::

190.166.2.255

Subnet mask: 255.255.255.0

2host bits = host addresses

32-bit address

24 leading 1’s

HostNetwork

11111111.11111111.11111111.00000000

xxx.xxx.xxx.xxx/24

HostNetwork

255.255.255.0 Subnet mask

190.166.2.2/24 CIDR IP address

190.166.2.0 Subnet address

Bitwise AND ofsubnet mask withIP address yieldssubnet address

Figure 2.7: CIDR addressing [www.IETF.org].

255.255.255.0 or expressed in separated binary as .11111111:11111111:11111111:00000000/2.Since there are 24 bits in the subnet mask containing leading ones, a =24 is appended to theIP address to communicate the partition information. The 8 bits allocated for host or computeraddressing will provide for 2host bits or 256 unique addresses.

In Figure 2.7b right, the IP address (190.166.2.2./24) has been partitioned into 24 bits forthe subnet address and the other 8 bits for specific computer addressing. This partition resultsin the subnet mask 255.255.255.0. When this mask is logically ANDed with the IP address theresulting subnet address 190.166.2.0 results. The specific computers within the subnet will beaddressed beginning at 190.166.2.1. and ending at 190.166.2.255 [www.IETF.org].

2.5.3 IPv6HEADERIn the mid-1990s, the IPv6 was released by the Internet Engineering Task Force (IETF). TheIPv6 protocol provides for a longer 128-bit IP address space. The different fields within the IPv6header specify the following.

• Version: IP protocol version. For IPv6 this field is set to .0110/2.

Page 53: Arduino III: Internet of Things

2.5. INTERNETADDRESSINGTECHNIQUES 33

Top-level

aggregation

(TLA)

• • •

• • •• • •

• • •

Next-level

aggregation

(NLA)

Site-level

aggregation

(SLA)

Next-level

aggregation

(NLA)

Site-level

aggregation

(SLA)

HostHost

TLA ID: 13 bits

NLA ID: 24 bits

SLA ID: 16 bits

Interface ID: 64 bits

(a) Aggregatable global unicast address

(b) Aggregatable global unicast address format

Prefix001

3 bits

TLA ID

13 bits

Reserved

8 bits

NLA ID

24 bits

SLA ID

16 bits

Interface ID

64 bits

Figure 2.8: IPv6 addressing (Hanes [5], Lowe [12], and Null [14]).

• Traffic class: will specify different priority.

• Flow label: will specify the type of communication in progress.

• Payload length: expressed in bytes

• Next header: specifies if additional header information is provided in the payload.

• Hop limit: will allow up to 256 hops from source to destination.

• Source and destination addresses: 128 bits each.

The IETF developed a logical, methodical method of assigning IPv6 addresses, the Ag-gregatable Global Unicast Address Format, as shown in Figure 2.8. The 128-bit address is parti-

Page 54: Arduino III: Internet of Things

34 2. THE INTERNETAND IoT

b0: 0: globally unique, 1: administered locally

b0: 0: unicast, 1: multicast

Organizational unique identifier (OUI) Network interface controller (NIC) identifier

b7 b1 b0

Figure 2.9: MAC address (Hanes [5], Lowe [12], and Null [14]).

tioned into different fields to specify top, next, and site-level aggregation representing for an ex-ample a country, a company within the country, and networks within the company, respectively.The 64-bit interface ID is a combination of the host device MAC address and information froma nearby router. The 128-bit IPv6 address is specified as eight 16-bit values expressed in hex-adecimal and separated by colons (hhhh:hhhh:hhhh:hhhh: hhhh:hhhh:hhhh:hhhh) (Hanes [5],Lowe [12], and Null [14]).

2.5.4 MACADDRESSThe host device’s Medium Access Control (MAC) address is a 48-bit device specific address asshown in Figure 2.9. The address is partitioned into six different bytes. The address specifies theOrganizational Unique Identifier (OUI) and the Network Interface Controller (NIC) identifier.The NIC provides the interface between the host computer or device and the internet. TheMAC addressing scheme allows each NIC to have a unique address (Hanes [5], Lowe [12], andNull [14]).

2.5.5 DNSANDURLADDRESSINGRather than memorize the IP address for individual networks and computers, descriptive, user-friendly names may be assigned using Domain Name System (DNS) techniques. The DNSserves as a distributed directory of named network assets. The directory is stored on a num-ber of DNS servers throughout the internet. You may apply for a DNS name from a DNSprovider. The provider will determine if the name is available for use. The Internet Corpora-tion for Assigned Names and Numbers (ICANN) coordinates the use of DNS names across theglobe (Shuler [16]).

Page 55: Arduino III: Internet of Things

2.6. INTERNETHARDWARE 35

.com .edu .gov .mil

Root

.net .org

Figure 2.10: Common URL domains (Shuler [16]).

To completely specify the location of a computer on the internet, a Uniform ResourceLocator (URL) address is used. The URL address consists of three parts: the protocol identifier,the DNS name, and the domain name.

A common protocol is “http.” The protocol type is followed by “W ==www:.” The nextportion of theURL address is theDNSname followed by the domain (e.g., .edu, .org, etc.). URLdomains are shown in Figure 2.10. As an example, the website address for the main Arduinosite is: http://www.arduino.cc. The “.cc” is a variant of the “.com.” domain.

2.6 INTERNETHARDWAREWe began the chapter with a brief overview of internet operation. In this section we provide abrief summary of hardware components used tomake the internet operate correctly. Key internetcomponents are summarized in Figure 2.11. For each internet component we provide the CiscoSystems icon to sketch an internet layout diagram.

2.7 CYBERSECURITYOne of my favorite books is the The Once and Future King by T. H. White. It is the tale of theyoung boy, “the Wart,” becoming King Arthur and the many adventures along the way. I haveread this book every several years since I was young. Early in the book, White provides a descrip-tion of the Wart’s guardian’s castle. He describes how the castle is protected from marauders bya moat (deep ditch) filled with water. To get access to the castle, a drawbridge is lowered acrossthe moat and then raised again to secure the castle.2

There are many dangers surrounding a network or a computer on the internet. As shownin Figure 2.12, the dangers are in the form of malicious software (malware) or the nefariousefforts of computer hackers. These dangers and challenges include (Kurose [8], Levine [10],and Lowe [12]):

2T. H. White, The Once and Future King.