Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
21 views75 pages

The Future and IoT Building The Internet of Things

The document discusses the Internet of Things (IoT) and its significance in transforming physical objects into interconnected digital entities that enhance efficiency and productivity. It covers various aspects such as entrepreneurship opportunities, main features of IoT devices, design considerations, and the potential economic impact of IoT. The author emphasizes the importance of innovation and user-friendly design in developing IoT applications and devices.

Uploaded by

h.messas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views75 pages

The Future and IoT Building The Internet of Things

The document discusses the Internet of Things (IoT) and its significance in transforming physical objects into interconnected digital entities that enhance efficiency and productivity. It covers various aspects such as entrepreneurship opportunities, main features of IoT devices, design considerations, and the potential economic impact of IoT. The author emphasizes the importance of innovation and user-friendly design in developing IoT applications and devices.

Uploaded by

h.messas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

The Future and IoT

Building the Internet of Things

By Elliott Dian, M.A.Sc

www.futurentech.com
Table of Contents

INTRODUCTION:
HOW PETER SPENCE BUILT A BUSINESS THROUGH THE INTERNET OF THINGS
CHAPTER 1: WHAT IS IoT?
Why is the internet of things important?
CHAPTER 2: ENTREPRENEURSHIP AND THE BUSINESS OF IoT
Sensor Enablement
Data Analytics
Infrastructure Development
CHAPTER 3: MAIN FEATURES OF IOT DEVICES
CHAPTER 4: DESIGN CONSIDERATIONS
Your End Goal
Security
Features
Size Requirements
Communication with Other devices
CHAPTER 5: HOW IoT OPERATES
Sensors
Actuators
Microcontrollers
CHAPTER 6: HOW DATA FROM SENSORS GET PROCESSED, DECISIONS MADE AND ACTIONS HAPPEN?
Networking and the Internet
Intelligent Analysis
Data acquisition and analysis
CHAPTER 7: SECURITY AND PRIVACY
Susceptibility to hacking
Staggering amounts of data
CHAPTER 8: GETTING STARTED WITH ARDUINO
Arduino hardware and the components
Installing the Arduino
Arduino setup
Programs and build process
Library functions
CHAPTER 9: Introduction to C Programming Language
Setting up your environment
Hello world
Variables
Basic C Operators
Constants
Arithmetic and relational operators
Logical operators
Conditional statements
If and if else
Switch
While and for loops
Functions
CONCLUSION
INTRODUCTION:

HOW PETER SPENCE BUILT A BUSINESS THROUGH THE INTERNET OF


THINGS

The goal of this book is to expose you to the possibilities of building your own smart
gadgets, so that you will be at the forefront of the exciting new concept of IoT.

To get started, I would first like to share with you the story of Peter Spence, a young man
who built an empire based on IoT.

"Not so long ago I was a student in London, completing a Masters in Innovation Design
Engineering. I could have gone for a corporate job, but my goal was to find an idea with the
potential to build a business that could have massive social impact.”

“In my final year, I came up with the idea to inspire tomorrow’s inventors by creating a
product that fuses craft and tech, the feeling of creating with your hands and the power of today’s
technology.”

“The idea was to build app-controlled toys and inventions in seconds. I wanted to make it
so easy, that kids of all ages could animate and program the world around them. It sounded fun,
exciting and that was the beginning of my journey. But how did I transform a student’s idea into
a business? How did I go from my solo project to becoming one of three passionate co-
founders?”

“Initially, I worked on it at university. I created a prototype, which wasn’t perfect, but


what I knew was that everyone who saw and played with it thought it was cool, different and
exciting.”

“That feedback was the driver for me. Upon graduation, I realized I had only just
scratched the surface and it was time to create the dream toy for kids. I knew it wouldn’t be easy,
but as I progress I am more motivated than ever to fulfill my passion."

The Internet of Things has been dubbed the future of technology. It is a computing
concept that refers to a future where everything - device, human, network, physical objects and
so on - has a unique identifier and can communicate over the Internet. In a nutshell, everything
will be linked and each individual item will be able to recognize the others.

When several objects act in unity, they are said to possess "ambient intelligence."
Examples of such include cars, electronic appliances, speaker systems, connected security
systems, vending machines, thermostats, household lighting systems and alarms. But these are
just some of the objects that fall into the wide range of the Internet of Things. We believe that
with the IoT, the future will be a beauty to behold, and we can’t wait for it to get here.

The IoT concept is significant because it turns every physical object into a digital one that
is more superior and can relate to other objects in the environment and database.

Big companies are beginning to recognize this advance in technology and see the value it
can add to them. They are now beginning to invest significant funds into IoT, so that they can
sell even more of their software to customers and harvest much more data in the process.

The IoT is just at the beginning of its life, but it is almost certainly here to stay, develop
and improve. Read on for the first look into a world of possibilities that wasn’t imaginable just a
few years ago.
CHAPTER 1:

WHAT IS IoT?

Why is the internet of things important?

Any devices that is connected to internet except computers, tablets, and cellphones are a
form of IoT. The most important part of the internet of things that makes it different from
conventional devices is that it’s not a standalone piece of device, but it’s connected and could
provide online services. Connected devices is connected people. The internet of things will
increase speed, efficiency, and productivity. Savings in time and resources will occur as a result
of collecting data through numerous devices and analyzing the data. Sensors would free up
humans from routine monitoring tasks and allow for more productive activities.

Before we delve into knowing how it works, it is important for you to understand how it
impacts our lives. This will help you to understand its benefit on our personal lives and the
economic implications it has to offer.

Here are four industry examples you can ponder upon:

the use of data-driven systems makes it easy for municipalities to run their cities more
efficiently

IoT technology makes the dream of having a secure home real. The top two ways it does
is by recognizing your voice and knowing who is at your door

intelligent transport solutions which can help in speeding up traffic flows, optimizing fuel
consumption and saving lives by reducing number of accidents

the use of machine monitoring sensors to diagnose and prioritize maintenance crew
schedules for repair equipment, as well as possibly predict pending maintenance issues

On a personal note, imagine the following two scenarios:

on your way home from work, you get an alert from your refrigerator reminding you that
you are low on milk and thus stop by the store to purchase

you are able to remotely cool or heat your home, and open or close your windows or
doors as you desire

Are you excited yet? This is a whole new world. According to Fortune magazine, "the
internet of things as a communications revolution consisting of billions of devices such as
thermostats, lights, appliances, security systems, health devices, cars and possibly all devices
around us are all connected wirelessly."
CHAPTER 2:

ENTREPRENEURSHIP AND THE BUSINESS OF IoT

“IoT is going to be a multi-billion dollar market in India. We would be able to control and
monitor everything from the smart phone and other intelligent devices like wearables. Any
infrastructure in the future has to be ‘automation ready’ to be energy efficient, secure and offer
better lifestyle and comfort. The company that creates the best platform for IoT will win at the
end rather than just creating products,” says Srihari BT, co-founder & director, Pluggx labs.

IoT is about the future. It’s about connecting everything around the globe, and it’s
everywhere. The revolution of the connected and smart environment has just started. In fact,
Samsung CEO announced at CES 2015 that all Samsung products would be IoT enabled in 2020.
About 90% of Samsung products would be enabled to connect to the internet by 2017.

The foundation of digital transformation is the internet of things. Each thing is a source of
revenue for innovative small companies to big size companies. The economic impact of IoT is
predicted to be $2.7 trillion to $6.2 trillion annually by 2025 according to McKinsey Global
Institute.

So yes, there is an increasing recognition of the business benefits due to connecting


devices to the internet.

As an entrepreneur, you have greater freedom over the next few years to explore and
experiment with new ideas and benefit from the implementation of smart things.

Here are the two major areas that you can explore;

1. Wearable gadgets

The growth of wearable gadgets is moving fast. Many types of different smart wearables
are coming to the market every year such as smart watches, sunglasses, and clothes. They are
convenient and hands-free alternative to your common smartphone or tablet.

For example, in the event of an emergency, a smartwatch wearer can contact pre-set
friends or family members in sequential order (in case the first contacted fails to pick up) with
the press of a button. This makes communication through watch just like speaking through a
phone.

At the moment, there are smart watches that allow parents know the location and
movement of their family members through GPS tracking.

Smart glasses are another example of hands-free smartphone-like wearables.


2. Smart homes and cities

A smart thermostat can use sensors and predictive algorithms to detect when no one is at
home and adjust the temperature accordingly to preserve energy. With time, the smart thermostat
will understand usage patterns in the house. It can then use these learned patterns to either
increase or decrease temperature of the home accordingly.

Nest a smart appliance manufacturer, claim that its smart thermostat can reduce heating
and air conditioning bills by as much as 20%.

Another example is smart appliances. Connected washers and dryers are two major
examples of such smart appliances. These can work with smart meters (already installed by
utility companies) to obtain data on energy prices. Thus, they can delay the cycle’s peak energy
consumption periods.

So, some housework can be offloaded to smart appliances through which expenses on
energy can be reduced, and health can be improved. Floor vacuuming and food -chopping are
two other house chores that can be performed by smart appliances.

When these appliances are empowered with an internet connection, sensors and computing
powers, they can gather data about daily usage patterns and analytics on the internet. So, they
can use the information gathered to schedule their own work routines.

If your question is "where is the business opportunity for me?” the answer is through
investing in IoT business. The key opportunity lies in the accurate delivery of data. If I had to
narrow it down to three, here are the top products and services you should consider providing to
IoT industry;
Sensor Enablement

An IoT device can only be effective if it is fed with good data. There will be continued
demand for the development of sensors for machines, gadgets, and transportation systems.
Data Analytics

Huge amount of real-time data collected by sensors required to be analyzed effectively.


This will be used to provide well-informed recommendations on critical situations and also
boosting business performance.

Though it may be done by in-house staffers and consulting firms at first, with time, these
services will be done by business professionals who have a deep knowledge in a specific skill.
The goal could be increasing revenues, optimizing customer service experience or enhancing
operational efficiencies.
Infrastructure Development

Implementation of the internet of things needs a strong, secure and creative network
infrastructure. To cope with the increased demand, data usage, and new users, more bandwidth
will be required. There will be increased opportunities to deliver and do consulting on network
infrastructure.

In conclusion, through IoT devices, there is a vast opportunity to create unique, practical
and innovative products and services for future consumers.
CHAPTER 3:

MAIN FEATURES OF IOT DEVICES

You may ask yourself what makes IoT devices different than other electronic devices we
normally use such as computers or tablets. IoT devices and computers are substantially different
from one another. In this section, you will discover the differences and the similarities (if any)
between them.

If I had to narrow it down to 4 major differences between them, it would be in areas listed
below:

1. One major difference you need to understand between the two is that the IoT device is
not designed to perform hardcore computations. This responsibility is left to the
computer. The computer is to compute functions and run multiple programs.

2. Computers are made to run general functions - play a game, connect to a camera and
record. Though computers are not the most effective or most efficient at any particular
application, they are good at everything. But IoT devices are specifically made to serve
special purposes. They are made to perform a task or a specific set of related tasks. A
clear example of this is your iPod (if you have one) and your laptop. Though you can
play music on both devices, the iPod is specifically made just for the music alone, while
the laptop can both play music and perform other tasks as well. Since these IoT devices
have a streamlined purpose, they are cheaper than the all-purpose computers.

3. The sensors and actuators used in an IoT device are highly designed to focus on a limited
number of tasks. As an example, strong cameras are required in IoT that detect moving
objects.

4. IoT devices are usually small, easy to transfer and not expensive. They don’t have very
powerful processors, and very small storage compare to computers. Some parts of storage
get filled by an operating system. Therefore, they need a different type of operating
system compare to computers, laptops or cell phones.

However, both of them have one similarity; they serve to improve the experience of the
end user. For example, as a music lover, you want to have a wonderful experience each time you
listen to music. Though the IoT device serves this purpose better than the computer, you can still
listen to music from your computer.
CHAPTER 4:

DESIGN CONSIDERATIONS

It is vital that you fully understand the hardware, software and certification requirements
for your application before you jump on the bandwagon and begin to design because everything
comes down to ease of use. Here are a few questions you need to ask yourself when you are in
the design phase:
Your End Goal

The end goal of your application will help you to determine the required power and
performance levels. For example, will your application be used to track products in a supply
chain, or monitor machines for the product's wear and tear? Or will it be providing real-time data
for control, safety and security purposes? Based on this, you will need to choose the sensors and
actuators such as motion sensors or cameras.

User-Friendly

Announced by Samsung CEO, IoT experience needs to be seamless with the consumers. A
good design is simple and user-friendly; so, users shouldn’t deal with the complexity of the
system. Let the users feel they have the device under control. Complexity should be embedded
inside the device. Any kind of friction in the user experience even if it is something as simple as
changing batteries, will give a user reason to stop using your IoT device. The interface between
the device and users has to be very straight forward and easy to use. This way you welcome all
ranges of consumers to connect with the device.
Security

A very important design requirement is minimum layer of encryption that can make your
application secure. SSL (Secure Socket Layer) and passwords are the basics. For example, if
you’re designing a thing that is used for shopping, an SSL certificate is required to protect online
transactions.
Features

Innovation is the main differentiator of each IoT device. Your device has to add additional
features to the products of existing companies or improve them. Prior to start the design, you
should have an answer for this question; how will your innovation improve the revenue
opportunities?

Seamless Interaction

Devices will be able to speak to each other. Thus, finding a newly connected device
should be as easy as tapping on a device that appears on the interface of the smartphone. If these
integrations are as simple as possible, new users will be eased into the experience.
Size Requirements

One important factor to consider is power consumption demands for your application and
the battery size. You must know the power source for your device. You need to consider how to
preserve power if your IoT device will only be powered by batteries.

The other factor will be the size of the app based on the function your IoT is designed for.
Will this size affect performance? If yes, how? Then you can define the size of hardware
components such as memory or processor.
Communication with Other devices

The total worth of the different IoT systems can be greatly increased if they can be made
to work together. By pairing a few devices, we can collect more accurate data.

For example, it is a well-known fact that sensor data from machines can be used to
monitor and subsequently improve machine performance. However, when these data are
combined with that of other machines, decision makers of such companies can have a complete
view of the operation of the machines in the company.

Multi-Device Support

For the sake of simplicity, IoT solutions should be made to work effectively across an
array of devices owned by people. This helps to maximize the value of the IoT devices. This can
be commonly found in home automation systems. IoT devices such as lights, thermostats, and
door locks are able to communicate and exchange messages to achieve a function.

These are some questions you need to answer in the design phase of your project.
CHAPTER 5:

HOW IoT OPERATES

A combination of hardware and software makes up the internet of things devices. Thus,
when you are in the process of designing an IoT, you need to think about hardware, software,
and how you can design the two to work together. You really need to think about both together
as you're working on any particular project.

In the hardware part of the design, you have the Printed Circuit Board (PCB). PCB
consists of some major components - micro controllers, memories, sensors, actuators. There are
other components of the hardware which are connected together with these major components
such as voltage regulators, inductors, capacitors, and some ports (e.g., USB and power ports) that
all are mounted on the board.

At the center of the hardware is the microcontroller and its major function is to execute
codes. The microcontroller is responsible for controlling sensors and actuators. All components
get soldered onto boards and are connected through copper paths. Here, I’ll explain more about
important hardware components you need to know to understand how IoT operates. They are;

Sensors

Actuators

Microcontrollers
Sensors

The beginning level of hardware is sensors that provide input to the device. It is one major
part of the digital acquisition module used in converting physical signals to digital signals which
the computer understands. These physical signals can be temperature, motion, light, speed,
sound, etc. Sensors are very low power and usually small components. Sensors transfer analog
input into digital data. To convert the data, they only need a very low processing capability.
Therefore, they are very low power components that could operate with small batteries for a long
time.

The type and number of sensors you need will depend on the type of application you are
developing the IoT for. The higher the number of sensors needed, the more the processing power
that will be required.

Also, the required resolution of the sensor will depend on the accuracy of your
measurement.
Actuators

Sensors are used to collect data and actuators reflect based on the received data. The brain
of the system analyses data and decides how to react through actuators. Actuators can simply be
small flashing LED (Light Emitting Diode) lights, speakers, or be more complex like electric
motors.
Microcontrollers

The brain of the device that does all the thinking and calculation is the microcontroller.
Generally speaking, they have the same function as processors in desktops or laptops, but a lot
slower and lower price. They are small programmable components. They get soldered onto
boards and connect to other components through electric paths. Microcontrollers run programs
that we write for a given device. They get input as data from sensors, process the data, make
decisions and provide output by controlling actuators or other components. Common language
programs that used for IoT are C, C++ or embedded C. Most of the time, the program is first
written on another system (a host) like your laptop, then final version gets transferred to
microcontroller after debugging.

The device you have in mind should help you decide on the parameters (for example, size,
voltage, current, and capacity) of each component before you order them.

One way to critically minimize wasting money through buying the wrong hardware
components is through the use of a data sheet. A data sheet represents the basic information
about a hardware component. All electrical parameters such as size, shape, voltage, capacity,
input, and output must be available on the data sheet. It is important for you to understand how to
read these data sheets even if it is at the barest minimum. It will help you understand which
hardware parts you need to create your desired IoT device.

The invention of simplified and ready to use boards boosted the growth of IoT. There is
also open source hardware. The concept is like open source code that anybody has access to it. It
is available hardware schematics that can be integrated into a new system or be updated to create
a new product. This concept accelerated the development and growth of IoT as developers don’t
have to start from the scratch. It is the first step in democratizing electronics.

If you have any projects in mind, there are many available and relatively simple to use
hardware platforms to start with, such as Arduino, Raspberry Pi, LaunchPad, Intel Galileo, Intel
Edison, and Samsung ARTIK. In the last chapter, I use Arduino as an example to review the
main components I explained here.

Arduino is an open-source electronics platform that is mainly used for prototyping or


simple projects. Due to its ease of use and low cost, it is one of the most popular
microcontrollers. There are various types of Arduino boards for different applications. Most
Arduinos share similar components. You can learn more about this in the last chapter.

On the other side of IoT design is the software which runs on the microcontroller. When
you have a new project, the two most important questions you need to ask yourself before
writing the software code are;

What hardware components am I going to need to be able to handle software?

How am I going to connect them together to create the output that I desire?

This is a basic aspect of all design projects. Although it is not rigid regarding execution
since there will be changes along the line. But having a plan gives you the framework to base
your work on.

It is important for you to understand that what you've written cannot be directly processed
by the microcontroller. You need to translate it to microcontroller language. This is what is
known as software translation. So, for the microcontroller to process the data, three steps are
involved;

You will write the code

You will do the translation and

The translation then gets executed.

To program your IoT, there are different types of software for prototyping, professional
programming, data storage, and analysis. Prototyping software helps to develop quick programs
and use it for proof of concept. For example, Arduino software has very simple and user-friendly
interface to start with. Wyliodrin is a cloud based ID that is also a good interface for prototyping
if you’re using your computer. These prototyping interfaces could be the first steps to kick off
your project, but they are not powerful enough for accurate or complicated applications.

For the user-level grade products that are required to be robust and stable, you need
professional programming software. Some examples of these platforms are Eclips, Vim, MBed
(online platform), and Intel XDK.

So far, we were mainly talking about how collecting data. In the next chapter, I’ll more
explain how data gets transferred to cloud and analyzed.
CHAPTER 6:

HOW DATA FROM SENSORS GET PROCESSED, DECISIONS MADE AND


ACTIONS HAPPEN?

In this section, we will discuss how data is processed, transferred to the cloud and
decisions made. The ideal schematic is processing data locally, storing some data locally if it’s
required, and sending valuable data to the cloud through the internet for cloud processing and
cloud storage. Inefficient model is sending all collected data directly to the cloud to process and
make decisions. The drawback of this method is that it puts a big load on the cloud to analyze a
huge amount of irrelevant data. This data can be sorted out in local IoT processors initially.
Networking and the Internet

Since an IoT device needs to be connected to the cloud and thus makes it more powerful to
perform heavy duty computations, the network is an essential part.

The mobile ad hoc network (here on referred to as MANET) is a common network for
IoT.

The MANET is a self-configuring network of mobile devices connected wirelessly. It is


self-configuring in the sense that the hosts in the network configure themselves because devices
are moving around at all times and they change their links to other devices continually. A
MANET can either be independent or connected to the larger internet. But in most cases, it has
to be connected to the internet at some point through an access point.

For devices to be connected, there must be an internet gateway that’s connected to local
processing to transfer data into the network. There are different types of technologies which can
be used based on your applications. For example, Bluetooth, low power Wi-Fi, and regular
Ethernet.

To make communication happens between two or more network enabled devices, network
protocols are required. These protocols are formal standards that consist of rules, procedures, and
formats. There are a series of network protocols for IoT such as CoAP and MQTT that are used
for IoT or machine to machine communication. One common internet protocols that we are
familiar with is HTTP that is a web protocol. However, HTTP is not a suitable protocol for IoT.
Intelligent Analysis

This is the extraction of valuable data from all the data collected by sensors for analysis.
The purpose of this is to collect data from multiple users, analyze the data and provide
predictions. Data can be saved in the cloud for the long term.

This process involves:

Input analysis to preprocess input from sensors and make decisions,

Either store the data locally or output data through actuators,

Send valuable data to the cloud for analysis.

This is considered as an optimized cloud computing system in which not all heavy lifting
computation is done in the cloud. Intel calls it Edge Computing and Cisco named it Fog
Computing, as data processing is done prior to cloud and at the edge of the network.
Data acquisition and analysis

Collected data through sensors can be sent to cloud computing services such as Microsoft
Azure or Xively. Cloud computing service offers you libraries to build, test, deploy and manage
applications through a web interface. So you can use their machine learning and data analytics
algorithm to analyze data on the cloud. This is a powerful tool to simplify your project, as you
don’t have to work on very complex machine learning algorithms and prediction models.
CHAPTER 7:

SECURITY AND PRIVACY

Security and privacy issues are a growing concern for IoT consumers. Afterall, there's
nothing off limits when a consumer's life is connected.

These security and privacy issues are what you'll learn about in this chapter.
Susceptibility to hacking

This is the first problem that developers need to address before the IoT can truly take off.

With enough time and energy, researchers were able to hack into real, on-the-market
devices. This means that hackers can do likewise if not more.

For example, recently, a team of researchers from the University of Michigan and
Microsoft used simple methods to discover excess gaps in the security of smart home platform
that was created by Samsung

Public concern about security could be a major drawback if the device can easily get
hacked. According to a study conducted by the control state of the smart home in 2015, 44% of
Americans are "highly concerned" that their information can be obtained illegally from their
smart homes. Imagine the number of IoT devices that can be around us. They are all built to
make our lives easier, but at the same time they are observing us and can communicate out our
information.
Staggering amounts of data

Since IoT apps and devices collect lots of data about us and distribute such that, the
amount of data that can be generated is infinite. Therefore, this leaves more avenues for hackers
to gain access to private information. Private information may no longer be private

The data being collected on a daily basis are personal information. If any of it is
mistakenly or intentionally revealed, it can be used against such individuals.

For example; an insurance company can accurately calculate your insurance rate if they
have access to the information about your driving habits. This information can be collected by all
the sensors in your car.

Recently German researchers were able to determine what television show someone was
watching at a particular time by 'hijacking' data from his smart meter. So, when consumers use
these connected devices, manufacturers or sometimes hackers could own the information about
you.

How to have true security?

Here is what Jason Porter, AT&T's VP of security solutions said; "securing IoT devices
means more than simply securing the actual devices themselves".

He further said: "Companies also need to build security into software applications and
network connections that link to those devices."
CHAPTER 8:

GETTING STARTED WITH ARDUINO

Maybe you’re curious about what this Arduino thing is or want to build an electronics
projects as a hobby for school or part of your job. Or maybe you have big plans for your startup;
you need to build a prototype to demonstrate in your Kickstarter video or in front of customers
and investors. In this section, I’ll help you start your project with Arduino and develop it further
from here. I’ll give you your first introduction to Arduino microcontroller.

Programming a microcontroller is something that is intimidating to a lot of people. But,


I’ll promise you at the end of this book you’ll have written your first program and you can use
this as the starting point. I will take you through this step by step. I don’t assume you to know
how to code or you have a degree in computer science or electrical engineering. This tutorial will
be as easy as installing a printer.

Arduino is an affordable platform with a lot of resources and incredible infrastructure.


Arduino environment includes IDE, Arduino board and Arduino shields. IDE (Integrated
Development Environment) is the software interface where you can write your code, compile
and upload the code. One big advantage of Arduino IDE is that it’s very simple to use.
Technically, you don’t have to use Arduino IDE, you can use other IDEs like eclipse if you’re
more comfortable using that.

Arduino IDE
Another part of the Arduino system is the add-on boards that are called shields. Arduino
shield is an add-on hardware that you can stack up on top of the board to make more complicated
systems.

Arduino shield

If we consider Arduino board as the motherboard, shields act as daughter boards. This
capability enables you to build complex systems without knowing much about hardware. For
example, you can add an Ethernet controller shield to your Arduino board. This shield has two
main components including Ethernet jack and Ethernet controller chip to manage Ethernet
connection. Adding these components into your system from scratch would be a lot of work of
wiring and reading datasheets. But, now you can simply stack this shield on top of your Arduino
board and press it down through pins going out underneath the shield.
Arduino hardware and the components

Arduino is an open-source electronics platform that is mainly used for prototyping or


simple projects. Due to its ease of use and low cost, it is one of the most popular
microcontrollers. There are various types of Arduino boards for different applications. Most
Arduinos share similar components. What is shown in the picture below is Arduino Uno.

Arduino components

The brain of this board is the big rectangular microcontroller chip (8-bit); it’s mainly from
the ATmega series from ATMEL company. Arduino Uno has an ATmega328. The chip itself
contains the central processing unit (CPU), flash memory, working memory (RAM) and
EEPROM memory. Program instructions that are developed in Arduino software are stored in
flash memory. CPU does all the thinking and controls the board. It fetches program instructions
from flash memory or data from RAM. EEPROM is a non-volatile memory to store a relatively
small amount of data. Non-volatile memories retain data even if the device is turned on an off.
When you write and compile your code, it gets written into ATmega328, and this chip executes
the code. In addition to this processor, there’s another microcontroller (ATmega16U2). This
microcontroller only handles communication with the USB. It translates the data that come in
through the USB to the language that the main microprocessor can understand. Output data gets
translated the same way too. Our codes will not make any changes to this small microprocessor.

Sensors and actuators on Arduino boards are not directly mounted. Instead, there are input
and output pins (I/O pins) that allow you to connect your sensor or actuators. These pins are the
interface of the microcontroller. That’s how it makes the board multipurpose. You could read
information from sensors. For instance, if you want to measure how bright it is in the room, you
can attach a photoresistor to the board or attach a GPS receiver to show the location in the world.

There are two sets of pins on top and bottom of the board, which are all connected to the
microcontroller. On the microcontroller, you can see a number of metal leads sticking out.

Microcontroller pins

These leads are wired through the board through copper traces inside the board to I/O pins.
So, by connecting wires to I/O pins, you can connect sensors and actuators to the
microcontroller. This is how a microcontroller is connected to the outside world. If you want to
access to outside world from microcontroller, you take a wire from your sensors or actuators and
plug it into the holes on the board, then your code can control those devices.

The analog pins as marked on the board can read signals from analog sensors like a
temperature sensor and convert it into digital. Analog pins cannot generate an analog output,
because there is no digital to analog converter inside the board.

The other set of pins beside analog pins are power/reset pins, which are generally outputs.
They have several grounds and power on (5 volt power, 3.3 volt power). When you’re wiring
your circuit and connecting it to your Arduino board, you may take power from 5 volts pin to
your circuit. And also you want to have a common ground between your Arduino board and your
circuit, so you connect the wire from your circuit to one of these ground pins.

On the other side, output pins are mounted on the board to connect with actuators. An
actuator could be a simple blink LED light or an LCD to display the room temperature. These
pins are marked as digital. They can also be used for digital inputs. PWM sign close to digital
pins stands for Pulse-Width Modulation; they are designed to simulate analog output like fading
an LED in and out. Here I’m just scratching the surface of what can be used as input or output in
Arduino; there are so many types of sensors and actuator that can be covered here.

The voltages of the pins can be controlled by the sketch or the code you have developed.
In the code, you can call a function to set the output voltage on the pin. Input pins voltage is
controlled by outside components, and the Arduino can just read the voltage. For instance, if you
use a switch and connect it to the input pins, the input voltage of that specific pins can be read
inside the code. If the switch is off, the voltage will be shown as zero. The other way, if the
switch is on, the voltage will be a number higher than zero like 5 volt.

Every board needs a way to be connected to a power source. An Arduino can be powered
from a wall adapter power supply or a USB port, which is also used to connect the Arduino to
the computer to program it.

The button on the corner of the board is a reset switch. When it’s pressed down, it will
restart the program. Codes will not be deleted by the reset button, because they are stored in non-
volatile flash memory. This switch can be useful when you want to rerun the program multiple
times.
Installing the Arduino

Here are a few things you need to go through this tutorial and run your Arduino.
Obviously, you need an Arduino platform, a USB cable to connect the board to your computer
and program it. USB cable can also be used to power up the board. If you don’t want to connect
Arduino to a computer after the programming is done, you need a power cable. A breadboard is
also required for programming the electronic circuits too, for example, lighting up LEDs or run
speakers. You also need LEDs, resistors, speakers, motors or other types of sensors and actuators
depends on your project.

To program Arduino, we will use IDE, which is a software tool that is used for
programming. In the picture below I’m showing Arduino IDE. As you can see, the main section
is the text editor for writing code. Here is where you type your code in there. Above that is the
menus for commands. Below text editor is the message area where is usually for error messages
when you’re compiling your codes.

IDE sections

C code is a powerful language that is used in a lot of applications. But, for an average user
C code is difficult to start with and requires hours of practicing to develop and run a simple
project. What Arduino does is that it extracts away the difficulties of coding with C and it gives
you Arduino programming environment that is much simpler than C.

The way it does it is that there’s a special piece of firmware (Arduino firmware) that is
loaded onto the microcontroller chip, and you program it in the Arduino programming language,
which we will walk through in this section. This helps you start your project nice and easy
without spending hours learning C or other professional programming languages.

To start with, we’re using Arduino Uno in this tutorial, as it’s the easiest board to get, but
feel free to use many different kinds of Arduino platforms.
Arduino setup

Let’s take a look at how your computer has to be set up to run an Arduino. Start by
navigating to Arduino’s website (www.arduino.cc) to download the open-source programming
environment (IDE). Go to the download section. Download the version for whatever operating
system you’re running on. I’m using Windows as an example here. You could do this on Mac
and Linux as well. What you’re downloading is a zip file. The guide below contains steps to
install the Arduino IDE on a system with Windows.

1) If you haven't already, install 7-Zip, a free archive utility that can be downloaded
at: www.7zip.org.
2) Download the Arduino IDE from the Arduino Software page. Be sure to download the
version for your operating system.
3) Navigate to the folder where you downloaded the Arduino IDE .zip file.
4) Right-click on the .zip file, point to 7-Zip, and select Extract to "arduino-…".

Arduino IDE .zip file

5) Open the extracted folder. You can move this folder to a different location if desired. A
common place is to create a C:\Arduino folder. For this example, we will stick with the
Downloads folder where it was extracted.
6) Double-click arduino.exe. The Arduino IDE opens.
7) Choose Tools > Board > Boards Manager. The Boards Manager opens.
In the list of boards, select your board type:
8) Click Install to install the board definition package for your board. When the installation
process is finished, click OK.
You’re now ready to program your Arduino. Open up the IDE with the board connected to
your computer. When you open it, first you’ll see an empty screen as shown before. You could
start writing your code here. But before that, it’s better to upload one of Arduino’s sample codes
and run it to check your system is running fine. This step is just for a sanity check and also get
you started. I’ll advise you to look at the blink example. This is a very simple program. This
program is designed to blink the onboard LED light on and off. The advantage is that we don’t
need to make any circuitry to connect LEDs. This LED is already mounted on the board, so we
can only focus on the program.

To run the blink program follow the steps below

1) Open the LED blink example sketch by choosing File > Examples > 1.Basics > Blink.

LED Blink sketch

2) Choose Tools > Board, then select your board.


3) The other thing you have to do is to tell the environment which serial port your board
is connected to. Select the serial device of the board from the Tools > Serial
Port menu.

Sometimes there is more than one option there. The easiest way to find what port the
board is using is by disconnecting your board, restarting the IDE, and re-opening the
menu. The entry that disappears should be your board. Reconnect the board, restart the
IDE, and select that serial port. If you don’t see any serial port options there, then the
USB drivers are not installed correctly.

Arduino serial port

4) Once you have selected your COM port, the COM port number is displayed in the
bottom right corner of Arduino. Continue to upload the sketch to your board. Press
the upload button and upload the program. As soon as the uploading is done, the
Arduino starts executing the code. If the LED light beside pin 13 starts blinking, then
you know everything is working.
Programs and build process

An Arduino program is called sketch, which is basically C or C++ programs but much
easier. The build process in Arduino takes the codes you developed in C or C++ and translate it
for Arduino to execute. There are a lot of pre-defined library functions that we simply use, which
makes Arduino very simple and user-friendly. Sketches must have a certain structure that I’ll talk
about it here.

There are certain functions that have to be defined in every sketch. Every sketch has to
have a “setup()” function. The difference between Arduino sketch and C or C++ programs is the
“main()” function where the execution starts. We don’t need to include “main()” function in
Arduino sketch. It’s actually created, but we don’t see it. So, you don’t have to write this
function, you have to write the components of “main()”.

Let’s first start with “setup()”. Every Arduino program has 2 parts; it has a “void setup”
where you set the Arduino up. It’s executed once when the Arduino is powered up. So, it’s used
for initialization purposes such as setting up the interface between the shields and Arduino board
or setting up your pins. It needs to be set up only once at the beginning.

The other part is “void loop”, where you use to repeat a function. Whatever you write in
this loop will happen over and over.
Library functions

We have talked about pins and how they can be used for sensors and actuators. Now we’re
going to talk about how you can control these from your code and what functions you need to
call into your code to use the pins as input and outputs.

Before using I/O pins, we should define it inside the code either it’s an input or output.
Basically, we have to assign it, otherwise, the code picks either one by default. In order to do
that, we can use a function called pinMode (pin, mode) function. Note that capitalization matters;
letter “m” of the word “Mode” has to be capital. The first argument in this function is the number
of the pin you want to write the code for. The number of pins is called on the Arduino Uno
board; digital pins are 0-13 and analog pins are A0-A5. For other boards, you may get more
numbers.

The second argument is the mode which is the I/O mode the pin is set to. There are three
modes; INPUT, OUTPUT, and INPUT_PULLUP; the first and second mode assign the intended
pin to be input or output pin, respectively. The last one makes the pin acts as an input, but it
reverses the polarity. When you drive zero volts on it, or in other words when you drive it low,
you read it as a high or vice versa.

Example:

pinMode(13, OUTPUT) → sets the digital pin 13 as output

Let’s assume we have assigned one of the digital pins as an input pin. Now from the code,
we want to read the value from the sensor. There’s a function for this that’s called
“digitalRead(pin)”. There’s only one argument in the function which is the pin. This function
reads the state of the intended pin and returns its state to either LOW (0 volts) or HIGH (5
volts). We usually use this function in our setup, because we need to set up the state of a pin
only once at the beginning. Se, we do it in the setup loop. This is how we read a pin.

Example:

digitalRead(3) → reads the input pin 3

On the other hand, if want to write to a pin, there’s another function called
“digitalWrite(pin, value)”. This function has two arguments; we have to define which pin we
want to work with and also the value that has to be assigned to it. The value has to be either
LOW (0 volts) or HIGH (5 volts). Assume we want to set pin #5 as LOW and give it zero volts,
we write the function as digitalWrite(5, LOW)

Example:

digitalWrite(13, HIGH) → sets the digital pin 13 on

The functions we described so far in this section are all used for digital pins. On the analog
pins, we can only read their analog data. Remember, we can’t drive analog data. Arduino doesn’t
have digital to analog converter, but it has an analog to digital converter inside the
microcontroller. So, to read analog data, we can use “analogRead(pin)” function to see the
converted digital value in our results. There’s only one argument here, which is the pin, and it
can only be between A0-A5, as it has to be an analog pin. The way the conversion happens is
that the microcontroller reads the analog data and returns an integer from 0 to 1023. 0 represents
0 volts and 1023 represents 5 volts. It also returns numbers in between based on the voltage. If
the voltage is right in between, let’s say 2.5 volts, the value you get in your results will be 512.

Example:

analogRead(3) → reads the input pin 3


Wow, well done! You’re almost done. Now you have good knowledge to begin your project.
This is just the start of your journey.
CHAPTER 9:

Introduction to C Programming Language

The commonly used language in IoT projects is C programming language. If you want to
start with Arduino programs, they are all in C or C++, but basically C.

So, I’m just going to introduce C language here and explain about all the basic constructs
of C. At the end of this chapter, you would be able to write a basic C code. I won't talk about all
of C, as it is a big detailed language. But, I will talk about most of the things that you would ever
need to get started or you could use in an Arduino program.

Our starting example, or the program you always start with when you're learning C is
“hello, world”.

This program just prints “hello, world” to the screen. To get it started, I will describe for
you how you would set up your desktop or laptop environment in order to run these programs.
So let's talk about setting up the environment on a Windows machine, a Mac, or a Linux. The
basic things you need are a text editor and a compiler. Debugger will be needed later too.
Setting up your environment

Text editor can be any text editor; you could use Word if you like, but you generally want
to use a programmer's text editor, one that recognizes programming constructs. There are plenty
of those around. One of them is GNU tools, GNU tools are free and open source. There are the
links where you can get appropriate GNU tools.

- Emacs text editor (www.gnu.org/software/emacs)

- gcc C compiler (www.gnu.org/software/gcc)

- gdb C debugger (www.gnu.org/software/gdb)

GNU tools for programming text editor

You don't have to use these, but they're nice. Emacs text editor is just a text editor where
you can type your code in there. Another popular text editor that is used these days is
Notepad++, which is also a GNU tool. Notepad comes with your machine, but it's also on
www.gnu.org. The text editor, Emacs or NotePad++, they both understand C constructs,
so they'll indent for you properly.

GCC is the compiler and GDB is the debugger that you can download all from the links
here. I’m not going to talk too much about the debugger here, so you don't have to worry about
that.

You can run these on Windows. I would say MacOS and Linux are even easier (MacOS is
based on Linux) because you don't have to install any of these; GCC comes pre-installed on
those platforms. On Windows, you have to do it separately.

Now another way to go rather than using GCC and Emacs is to use another integrated
development environment called Eclipse. You can use anyone you want but Eclipse is a common
tool that is open source.

The difference between these tools is that for example, when I write my code, I do
everything with the command line. I'll go to my text editor, type in the code and save the
file. Then, I'll go to the command line and type in the command.

But a lot of people like to use these IDE's (Integrated Development Environment). Like
the Arduino IDE that packages everything in one tool. So you type the code into the IDE, and in
the same IDE, you click a button that compiles the code, or in Eclipse it's called building the
code. So, people like to use IDEs like Eclipse. It puts all the tools together in one nice GUI
(Graphic User Interface), nice graphic user interface, just like Arduino on IDE.

For working with Eclipse, you need Java Runtime Environments (JRE). You have to have
Java installed on your machine, because the Eclipse IDE is written in Java. You can download it
from http://tinyurl.com/23uo3g or Google it.

Also, besides using Eclipse, you could use Microsoft Visual Studio, but it's not free, you
have to pay money.

If you want to use Emacs, as I said, you have to compile it separately. This is the way I do
it:

I use Emacs as a text editor to write my code such as “Hello word” program. Then I save
this file to a directory. Then I go to the command line which is a different window where there I
compile and run the code. I type GCC in the command line to call the compiler.

gcc hello.c -o hello

GCC gave the name of the program -O and then after the -O (-O is short for output), It
gives the file name that I want the executable to be, I called it “hello”. So after I do that
command, in my local directory, there will be a program, a file called “hello”, and that is my
executable.

In Linnex, If I type LS, it gives me a directory listing. It shows me what's in the directory,
and I see there's a program called Hello.

On a Windows machine, you would type “dir” instead of LS in the command prompt (cmd
window). If you own a Mac, you would also type LS, because it's also a Linux box.
If you open up the terminal you would type LS as well. So I get the directory and I type
./hello. You may think you could just type hello to just run the code, but you have to type “./” to
tell it to look in the local directory. In this example, you type ./hello, it takes the hello program,
runs it, and prints “hello world”.

To sum up, you want to have that whole tool chain installed to start coding. You can use
the GNU tool chain (Emacs, GCC), go with an IDE like Eclipse, use NotePad++ or any other
text editor you want. After you install that whole chain, then you can just take a piece of code,
write it, save it and execute it.
Hello world

Here, I'll break down the “Hello World” program. Just so you can understand exactly
what's going on with the program and how it works. It's a simple program to start with. Here
we'll go through it, piece by piece, so you can understand the code.

Hello world program starts off at the top with an “include” statement. #include < stdio.h>.

Anything with a # in front of it is what's called a compiler directive. It's not really a piece
of code, but it tells a compiler to do something special. Here “include” tells the compiler to
include whatever the file is to the right. So #includes <stdio.h> says take this file stdio.h
and include it right here in the code. So it just basically takes that stdio.h and pastes it to the
beginning of this file.

Now in this case, stdio.h (stands for standard IO) is a standard library that has input/output
functions such as “printf” for printing.

So if you ever want to use printf, you have to include the standard IO library. So this
basically takes the library (the .h file) and includes it at the top.

So, the point here is if you want to use a library, you have to include its header file it at the
top of your code. You can include any number of libraries depending on what type of
coding you're doing, but here we'll stick with the standard library.

Now inside the program, after you've done the “include”, you have the “main()”
function. So there's a function called “main”. In this chapter, I'll talk in more detail about
functions a little bit.
But the main() function is where all the execution starts. Main() marks the beginning of
the code, all execution starts at the main(). When it's time to run the code, it goes to the
beginning of the main() and run from there. So every C program, or C++ program, has to have a
main() function in it.

Now let’s look at curly brackets in our example code.

After the main(), there's an open curly bracket, then there's a little code, and then there's a
closed curly bracket. Curly brackets are used to group statements together. All functions have to
start and end with curly brackets.

The idea here is that if there's a function, like the main(), you could have many
instructions inside your main() function. All of instructions have to be grouped together in curly
brackets. So you have an open curly bracket, then you have all your instructions, and then you
have a close curly bracket. All those instructions in between the curly brackets are part of main.

So whenever you start executing, you execute the main, which means you execute those
instructions one at a time from the top.

In our example code here, inside our main function we have a “printf()”, which is a print
statement. Inside the parenthesis, you put in quotes whatever you want to print and it basically
prints the quote to the screen. In our case, we want to print the phrase “hello world”. So you say
printf() and then in parenthesis, you have quotes hello world, closed quotes.

If you have noticed, there's a semi colon (;) after the print statement. When you put a semi
colon at the end of your statement, C knows that the line has ended. What it means is that the
indentation or spacing don't matter. All C looks at is semicolons.

As an example, let’s say you got a program that is 20 lines long. You can put all those
lines on the same physical line in your text editor and never hitting Return. As long as you put
semicolons between them, C will execute it just fine.

Now, let’s write our code in a different way that does exactly the same thing as the first
main.

So, in quotes in the original main, we said, "hello, world\n".

The “\n” at the end of hello world is a special character that tells the code to go to a new
line. It means that if you didn't put the \n, it wouldn't go to the next line.

For instance, in the program that we have up here, the main right here first prints hello and
then it prints world. But notice that there's no \n in between. What it means is that it'll print hello,
and then on the same line, it will print world, because we didn't put a new line. Then it goes to a
new line, so anything else we print after that would be on the next line.
Variables

In C language, you need variables to write code and we'll talk about variables and how
they can be defined and what they mean. Variables are basically names that represent values in a
program.

Similar to algebraic variables, for example X=5, or X=Y+2, X and Y are the variables. So,
they're names that are substitutes for certain values.

All variables have a type, which must be declared. Type is an important concept in C and
in most languages. The type of a variable basically tells you what kind of data it is going to hold.

For instance, when I define int x in my code.

I'm saying, x is going to be an integer, int is short for integer. Or when I define float y, I'm
saying, y is going to be a floating-point number. In C, real numbers are represented by floating-
point types such as float or double. Any number that has a decimal point in it will be interpreted
by the compiler as a floating-point number. Note that you have to put at least one digit after the
decimal point: 2.0. Integers such as int and char are whole numbers, having no fractional
components, in contrast to real numbers.

You may ask what type of information is held in variables. The type is important, because
it determines how arithmetic is performed, it also determines how much memory is going to be
used to store the variable. Remember, all of these variables have to be stored in memory
somewhere. So the question here is, with a variable like x, how many bytes of space do we need
to store that information? And with y, how many bytes of information? The reason is when the
machine is running, it has to store the information, and it has to know how big the information is
going to be. So, that's what the declarations are for. The table below indicates variable types and
sizes:
So, one thing that type lets you know is how much memory is going to be needed.

Also, the type tells you how arithmetic will be performed? Arithmetic is performed
differently depending on the type of data. If you have an integer type and you want to do
addition, everybody knows how to do integer addition, but floating point addition is a much
more complicated thing. If you want to do floating point addition, here’s what happens inside the
hardware or inside the microprocessor; there's often a floating point unit, a dedicated piece of
hardware, just there to do floating point operations. It is separated than the integer operators, so
you'll have an integer ALU (Arithmetic Logic Unit) which performs integer addition and then
you'll have some floating point unit that does floating point operations. So, depending on the
type, you're going to have to send that data to a different piece of hardware to do the operations
that need to be performed.

So that's why typing is needed; you need to know what type the variables are going to be
and you have to declare the type. So, before you can use x in your program, you have to say “int
x;” somewhere or “float y;”.

There are several types in C; here are the main ones (char, int, float, double). Here, we'll
focus on char and int. When it comes to embedded systems, we try to avoid floats and doubles,
because floating point arithmetic and double are slower and bigger. So, we try to avoid them in
general in embedded systems. Sometimes you may need them, but try to avoid them.

So, an int is typically whatever the word size is, but it could be down to 16. For instance
with an Arduino, an int is 16 bits, but a char ,no matter what platform you're using, is only 1
byte. That's just a standard size. Char is very useful in embedded systems, which I use often by
default.

Floating point and double can be much longer, up to 64 bits and 128.

Variables all have to have names associated with them. Names are just a sequence of
visible characters like x or y. However, there are some limits; for instance, a name has to start
with a non-numerical character.
It is acceptable to have “int testvar1”, because it starts with a letter (t). But you can't have
“int 1testvar”, because it starts with a number (1).

You also can't have any variable names that are C keywords such as if, else, while.

So there are so limits on variable names, but you have wide discretion in what your names
are going to be.
Basic C Operators

In this section, I'll talk about the basic C operators; all the operators that you'd regularly
execute. These operations are basic arithmetic and logical operations, and they are very common
that you see them in all languages.
Constants

You can define constants in your code in a couple of ways, but here I'll talk about
“#define”.

#define is a compiler directive, again it has a hash sign in front of it, so it's a compiler
directive. In the example here I say #define ANSWER 42.

What happened here is that wherever it sees answer in the file, it substitutes that with
42. So, it’s very simple; it just looks around for every time it sees ANSWER and substitutes the
42 in. You can do this with characters. In that case, it was a number, the number 42. You can do
it with character constants as well.

In this case, if you want it to be a character, you have to put the character in single quotes
(‘x’).

Notice that I put the x in single quotes. What it does is, if you put it in single quotes, the
code knows that it's a character and it interprets it as a character. So it interprets it as an ASCII
character or Unicode.

Let me explain what ASCII and Unicode characters are. Every character, either visible
character that you see on your keyboard or an invisible character that you can’t see, are all
mapped to numbers. So, x is 120, y is 121, and so on. They're all mapped to numbers in a table. If
you search for ASCII table, you'll get a table that lists every character and its ASCII code
number. Unicode is the same thing, but it’s a bigger one; ASCII is only eight bits long and
Unicode is 16 bits, so you have a lot more characters. ASCII and Unicode overlap.

So, lowercase x has a certain representation, a certain number, and if you put it in single
quotes, the code will know this is meant to be a character, so I will represent it with its ASCII
value. The code looks it up in the table and stores it.
Some characters are not easy to represent, meaning they're invisible characters. You can
use them in your code as characters, but it is not something we want to necessarily get into here.
Arithmetic and relational operators

C has a set of arithmetic and relational operators. They are standard things such as plus,
minus, times, divide, and all that.

The percent sign (%) is a modulo operator. Modulo is the remainder after division. For
instance, 9 module 2 is equal to 1, because if you do 9 divided by 2 you get 4 and the remainder
is 1. Or 9 module 3 is 0, because there's no remainder, or in other words, zero is the remainder.

++ is an increment. If you want to take a variable like x and increment it, you say x++. If
you want to decrement it, you say x--.

There are also comparator operators, relation operators such as ==. This is something to be
careful of in C and other languages; if you say x=1, that's an assignment. That assigns x to be 1,
but, if you say x ==1, that is a test, and a relational operator. It returns true if x is actually equal
to 1 and false if it's not. So you would use x==1 if you have an if statement.

In the example here, if x is less than 5, do whatever we define. In this case, we're using a
relational operator as a test. So x < 5 returns true or false; true if x is less than 5 and false if it's
not.

Another relational operator is ==; it's a comparison which returns true if the two things
are equal, and false if they're not. These operators are used in if statements and conditionals
commonly.
Logical operators

Logical operators meaning and, or, not. So for instance, && means and, || means or, and !
is a not. So what happens is that these operators treat the arguments as one bit binary value.

For example if we say 1 && 2 (1 and 2), there are two arguments here, 1 and 2. So, &&
operator, treats these two arguments as one, big, binary value. So even though 1 and 2 could be
integers, and have many bits, the operator says you are either true or false, which is 1-bit binary.

And the way it does that is it says if it's a zero, then that's a false, and if it’s anything but
zero, then it’s a true. So if I said one and two, it would say one is true and two is true, and then
true and true is true, so it would return true. Because one and two are both non zero, they're both
considered to be true.

For instance in this statement, if A is equal to one and not B. First thing is if you look at
the && it has two arguments; the left side is A=1, so that's true if A is equal to one, and false
otherwise. Then the right side, the not B is the argument. So, not B is true if B is false. If B is
equal to zero, then not B will be true.

And finally if both of those things are true, if A is equal to one, and B is equal to zero,
then the if statement will evaluate to true and it will execute whatever it's supposed to execute.

So that's how logical operators work; they take the arguments and treat them as either true
or false.
Conditional statements

This section is about conditional operation inside a C program. If you have a program with
no conditionals, that's unusual, but you can have a program with no conditionals, where it just
executes line after line.

But, most of the time in programs, you want to have conditionals. Here what I am going to
explain is how you implement conditionals inside C.
If and if else

The main conditional statement is going to be an if statement. Here I’m showing two
forms of an if statement.

Let's take a look at the conditional statement in picture below.

If expression is true, then execute statement1, else execute statement2.

You'll notice after the word if, there's an expression in parentheses. That expression is
evaluated at run time. If it turns out to be true, then statement1 is executed, otherwise, statement2
is executed and note that you don't have to have a statement2. You could just say if expression
statement1 and leave it at that, no else. Then if the expression is true, it executes statement1,
but if it's not true, it executes nothing and it just moves on to the next statement.

Another way is adding an extension (else if). This is sort of a chain or a series of if
statements. In this structure you say check expression1, then execute statement1, else if
expression2, execute statement2.

You can continue this; you can say else if expression3, execute statement3 and so on. You
could continue that as long as you want, and at the end you typically put an else statement, in this
case, statement3.

So what happens is first it checks expression1, if that's true, then it executes statement1
and it's done with the entire if statement. If that's not true then it goes to the next expression and
checks it. And then if that's not true, it goes to the next. So it goes down the list of expressions
until it hits one that's true. As soon as it hits one that's true, it executes the appropriate statement
and then it exits the if statement. If all else fails it hits the else at the end, which, by the way, the
else is optional. You can just leave out the else if you wanted to.

So, those are two forms of if statements, if and else if.

Here's an example, a conditional example. At the top of the code, we have a main. Then,
we declare an integer x, and we set it equal to 1, which we can do on the same line, int x =
1. Then, if x = 1, which it is, printf("Correct"), otherwise printf("Incorrect"). So that's a typical if
statement.

Now one thing to note about in this if statement is statement1 and statement2. In
statement1 we'll print (“Correct”), and in statement2 will print ("Incorrect"). These two
statements are single statements, so if x = 1 we're executing in this case only one statement. But
you could execute many. There are many cases where you might say look, if x = 1 I want to do
10 statements or something like that. To do that, you have to use curly brackets to group the
statements. Notice here, there are no curly brackets. There's a curly bracket that defines main,
one at the top, one at the bottom, but there are no curly brackets inside the if statement. But if I
wanted to have multiple statements executed, if x = 1, then I would put curly brackets in. So I
would say if x = 1, then I have an open curly bracket, then I have as many statements as I wanted
then I have a closed curly bracket, and then I can say else printf("Incorrect").

So you can have many statements executed on the true or false sides of that if statement,
as long as you group them in curly brackets.
Switch

Switch is another type of conditional branch statement, and it's useful in a lot of cases.

What it does is that it basically takes a variable, some expression, and the expression is
evaluated. So you switch against some expression.

The expression in parenthesis is evaluated, as compared to a set of constant expressions. A


common way to do this is let’s say you have a variable x and you know it's going to be equal
either 0, 1, 2, or 3. Under each condition, you want to do a different thing. So, you could say
switch (x), the expression would be x itself. And then you'd define cases like case1, case2 and
statement1, statement2 and so on. If it matches, if the expression evaluates to 1 and you have a
case1, then statement1 is executed. If you have a case2 and the expression matches that, then
statement2 is executed. Default is optional; if nothing matches, you execute the default. It's like
the else at the end of an if statement. Actually a switch is an alternative to using if and else if.

Here's an example of a switch.

If you notice, there’s a break statement. It's important to use these break statements in the
switch.
Let's say I have my switch x (x is my expression). Notice there are three cases, case 0,
case 1 and case 2. What will happen is x is going to be first matched, compared to 0. If it
matches, then it executes that statement y = 1. But if it doesn't match that, then x is going to be
compared to case 1, and then it's going to be compared to 2.

One thing about a switch is that it will continue execution even if the first case is matched.
It'll go on to the next statement, and execute that also, which may not be desirable. Usually you
want these cases to be mutually exclusive, meaning if x = 0, you execute case 0 and that’s
that. You like them to be separate. But that's not how C is.

In order to make it that way, is using a break statement. Now I've put one in the example.
Normally I would put one break statement in every case, but in this case, I put only one in there.

So let's say if you look at case 1, which is x = 1, if x matches case 1, the code executes y =
2 statement, then after that there's a break.

What a break does in a switch is it says stop right now and do not execute anything else
after this line and it jumps out of the case and out of the switch statement all together. So, it
won't reach to case 2; it'll just skip straight to the end of the switch. It's very common in a switch
statement if you have 3 cases like this, case 0, case 1, case 2 and you put 2 breaks. You'll put a
break at the end of case 0 and a break at the end of case 1. You don’t need a break at the end of
case 2, because it's at the end already.

So be wary of switches when you use them, because if you don't use the break, then if x
matches 0, case 0, then it'll also execute case 1 as if it matched that too, and that can be
confusing sometimes.
While and for loops

Basically looping is doing something over and over again in your code. There are many
times that you want to go through an array and evaluate it. You just do whatever the process is
over and over.

For example in Arduino, whenever you're executing you do it over and over as long as the
Arduino is powered on. So, loops are an important construct, and we'll talk about the different
ways to do loops in C here.

We have two basic kinds of loops, “while” loops and “for” loops. There are three
examples shown here.

The top loop is a “for” loop, and bottom ones are “while” loops. There's a regular “while”
loop on the left, and then on the right, there's a “do while” loop, which has a do at the top and a
while at the bottom.

Generally with any kind of loop, regardless of what kind of loop there is, there's always
going to be some kind of an initialization step, an increment step and a conditional check. So,
every loop has to have some end condition that tells you the loop is done.

You usually don't want to loop forever; maybe you only want to do this thing 100
times. So, you need to be able to check, have I done this 100 times? There's always going to be
some sort of a conditional check associated with a loop, where you check if it has been done a
hundred times or not.

Now the most common way to check a thing like that is to have a variable which just tells
you how many times you've been through the loop. Usually “i” is a typical name for that
variable, an index variable.

If you want to go through a loop a hundred times, at the beginning of the loop, you'll set
that i=0. Then every time you go through the loop you say i++ (incrementing i). Then every
pass of the loop, before you start the loop again, you want to check if i is still less than a hundred
or not.

If i<100, then you do the loop again. But eventually i isn't less than a hundred and you're
through with the loop.

That's what's going to happen if it's a for loop or a while loop, either one.

Often, one simple way for the termination condition is using an index variable and adding
one to it every time, but you can have much more sophisticated conditional checks at the end
for termination, if you want to. The conditional check at a for loop and at a regular while loop is
checked at the beginning of the loop to see if you're done with it.

If you look in a for loop here, expression two (expr2) is the conditional check that you do
it at the top of the loop.

The while loop, the first while loop on the right, expression two (expr2), again, is a
conditional check. If that condition is true, then you execute the loop. If it's false, you skip the
loop and you're done.

Now in the one on the right, expression two (expr2) again is a conditional check,
but notice that it's at the bottom of the loop. So what that means?

The difference with the while loop on the right is that the code always goes through the
loop at least once. Because it doesn't do a check until the end of the first pass of the loop. So, the
difference between those two while loops is just where you do the conditional check; do you do
it at the end of an iterational loop or at the beginning of an iterational loop? The difference
happens with the one where you check at the end means you always have to go through the loop
at least once. But with the one that you check at the beginning, you might not go through it the
first time if the condition isn't true.

Let's look at this while loop as an example.


There's a main statement or a main function at the beginning. First, before we even get
into the while loop, you first define a variable called “i” and set it equal to zero. So i is going to
be our index variable, which tells us how many times we've been through the loop. This is a very
common thing to do in these loops. In this while loop, there’s a statement i<3; what this is going
to do is execute this while loop 3 times.

So i starts off at 0 and then, inside the loop, you'll see, it does a print statement, a printf(),
which prints the variable i. And then it says, i = i +1. So every pass of this loop i is
incremented. The first time through the loop i is equal to zero. The next time through the loop i is
equal to one and then 2 and 3. Then you get back to the top and it says while i<3, but if i = 3 then
that's not true, so it finishes the loop at that point. Therefore, this loop will actually execute three
times; when i is equal to zero, i is equal to one, and i is equal to two. Once i is equal to 3, it exits
the while loop and it doesn't execute a final time.

In this while loop, after the word while in parenthesis, you have the termination condition;
the condition that is checked at the beginning of every pass through the loop.

Now, let’s look at a for loop. This loop right here does the same thing that the while
loop did.

For loop is a little more structured than a while statement. In the parenthesis in front of for,
there are three statements in there separated by semicolons. The middle statement is the
termination condition just like with the while loop, which is i < 3.

In the parenthesis, the first statement is the initialization condition. That tells you what you
want to do just right at the beginning, the first time you start this loop. i = 0, assigning i equal to
zero.

Now notice with the while loop, that wasn't built into the while loop, we had a statement
before the while loop that said i = 0. But with the for loop, that's built right into the for loop.

So, the first statement inside the parentheses is the initialization, then you have the
termination, the second statement, and the third statement is the step, the increment (i++). That
third statement is executed at the end of every loop; every time you execute the loop, it
automatically does i++.

Now notice in the while loop, it’s also incremented, but we had to make it explicit; we had
to write i = i + 1 as a statement inside the loop. With the for loop you don't have to do that. It's
just built into the structure of the for loop.

So, in for loop, the initialization, the termination and the step, they're all built into the for
loop. Unlike with the while loop, where the termination was built into the while loop, but the
initialization step had to be put in separately.

One other thing about break and continue; we looked at break already in the context of the
switch statement, but break is also used in loops. It does a similar thing inside a loop. What a
break does is it just exits the loop. If you ever execute a break, it jumps out of the loop
regardless. So, it’s like an early termination

On the other hand, continue is a little different; when you hit the continue, it doesn't jump
out of the entire loop, it jumps out of that one iteration and moves to the next iteration or goes
back to the top of the loop. So what that effectively does is that everything in the loop after
continue is not executed on that path and the loop goes back to the beginning.
Functions

This lecture will talk about the use of functions in C, which is a very important concept. It
is basically a way of encapsulating a bunch of instructions and giving them a name so you can
refer to them again and again. Functions are commonly used in codes, and we need those for
Arduino too.

A function is a way of encapsulating a group of instructions. That's the main thing it's for.

We have two examples of codes here.

At the top, we have a code with three real instructions plus the definition of variables.
Below that we have another example; a program that does the same thing as the top main.

In the program down below, you have this new function called foo().

Looking above foo(), you see we have defined foo() function (void foo()). That function
called foo does everything that the main did before. In fact, it has basically the same code that
the main had.

We took that same code, we put it into this foo.

Now what happens is, so we've defined that into foo. So we've given a name to those
instructions.

And every time we want to execute that sequence of instructions, we just call foo.

So, these two programs do exactly the same thing. The only difference is that the
instructions in the top version, the instructions that do the work, are in the main directly. In the
bottom, the instructions are in this function foo, and then that function foo is called from the
main. But they do exactly the same thing.
Now, you might ask, what's the benefit of this?

Right off the bat, one benefit is if these operations that foo is doing is done over and over
in your code, rather than copying it over and over into your main, it is much more convenient to
write a function that does those instructions. Then every time you just call that function. Now
notice in my main, when I wanted to execute those instructions, I just called foo(), and it
executed those instructions.

Let’s say foo is something I did 100 times in my code, rather than writing all those
instructions over and over a hundred times, I just call foo a hundred times. So, it just reduces,
and it makes the code simpler and easier to understand.

Another important thing is that the naming of the functions is very important.

Here I'm calling it foo, which means nothing, but when you write these function, you want
to give them names that have meaning. For instance, if the function is taking a derivative, you
would call it derivative. And then by just looking at the name, you can say it's called derivative,
which must be taking a derivative and you wouldn't have to think,

This is much like the advantage that you get from using libraries in Arduino. For example,
when you’re using an ethernet controller, there is a connect function that you need in your code
to connect to the internet. As a programmer, you don't have to know all the details of how
connecting happens. You just call connect and connecting happens.

So, that's basically what a function is. You are grouping a bunch of instructions and giving
them a name so you can reuse them. You can call them over and over again, and it's sort of a
shorthand.

The name is now a shorthand for that sequence of instructions.

There are more aspects to it; functions can take arguments. So data can be passed to a
function. In the example we saw here, no data is passed to foo. Foo has all of its data internally,
as int x, int y and int z, everything is already defined. But, instead of writing void foo(), we can
say void foo(int x, int y). Then later on in the program, wherever we call foo function, we’ll
define what int x and int y are by writing foo(2, 3). This means int x is 2 and int y is 3. So, foo
data ca vary in each part of code.

Now you might say what's the benefit of this? Well, one benefit right off the bat is that
now this foo function is much more generic. We can change x and y if we want to. We can say,
let's call foo (2, 3), or maybe we'll call it (1, 2), and it does the same operation with different
numbers.
There are many cases where you have a function where you want to do the same
thing with different numbers. For instance, you want to average a couple pair of numbers. You
could make a function, average, which averages exactly two numbers, or you could make a
function, average, which takes two arguments and averages whichever arguments you pass. The
second average function makes it a heck of a lot more useful, because now you can call it with
whatever arguments you want. You can use it in a more generic way in other contexts.

This was a crash course on C programming language. It was not a detailed course, but it
should be enough to get you started. The rest is all practicing and working on various projects.
CONCLUSION

Whew – you just learned almost everything you need to know about potential innovations
and the business side of the IoT revolution.

But of course, the magic elves aren't going to take over from here. And that's why you
need to start brainstorming on which aspects of the business where you can come in and more
importantly start taking steps towards achieving your goal as soon as possible.

Now, typically I'd merely encourage you to take action, wish you the best of luck and
cross my fingers for you.

Today I'm going to challenge you to take that first step. Find out what you are interested in
or passionate about. Find out how you can use it in IoT business. You could start from here and
develop it as you move forward.

That's right; you're going to be held accountable. Because this time you won't fail. This
time you're going to get started on becoming an IoT entrepreneur.

Last but not least, thank you for reading this book! If you enjoyed it or found it useful, I’d
be very grateful if you’d post a short review on the Amazon website. Your support really does
make a big difference and I read all the reviews personally, so I can get your feedback and make
this book even better. It will also help other people to make an informed decision about my book.

For more information, please check out my website www.futurentech.com.

Other books by me:

The Future and Bitcoin: A Beginner Guide on Cryptocurrency and Blockchain


Technologies, Investing and Trading, Mining, Wallet

Here’s the link to the book on Amazon.com

https://www.amazon.com/dp/B07B4P1WJ8

Thanks again for your support!

You might also like